assembler.scm 107 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880
  1. ;;; Guile bytecode assembler
  2. ;;; Copyright (C) 2001, 2009, 2010, 2012, 2013, 2014, 2015, 2017, 2018 Free Software Foundation, Inc.
  3. ;;;
  4. ;;; This library is free software; you can redistribute it and/or
  5. ;;; modify it under the terms of the GNU Lesser General Public
  6. ;;; License as published by the Free Software Foundation; either
  7. ;;; version 3 of the License, or (at your option) any later version.
  8. ;;;
  9. ;;; This library is distributed in the hope that it will be useful,
  10. ;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  12. ;;; Lesser General Public License for more details.
  13. ;;;
  14. ;;; You should have received a copy of the GNU Lesser General Public
  15. ;;; License along with this library; if not, write to the Free Software
  16. ;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  17. ;;; Commentary:
  18. ;;;
  19. ;;; This module implements an assembler that creates an ELF image from
  20. ;;; bytecode assembly and macro-assembly. The input can be given in
  21. ;;; s-expression form, like ((OP ARG ...) ...). Internally there is a
  22. ;;; procedural interface, the emit-OP procedures, but that is not
  23. ;;; currently exported.
  24. ;;;
  25. ;;; "Primitive instructions" correspond to VM operations. Assemblers
  26. ;;; for primitive instructions are generated programmatically from
  27. ;;; (instruction-list), which itself is derived from the VM sources.
  28. ;;; There are also "macro-instructions" like "label" or "load-constant"
  29. ;;; that expand to 0 or more primitive instructions.
  30. ;;;
  31. ;;; The assembler also handles some higher-level tasks, like creating
  32. ;;; the symbol table, other metadata sections, creating a constant table
  33. ;;; for the whole compilation unit, and writing the dynamic section of
  34. ;;; the ELF file along with the appropriate initialization routines.
  35. ;;;
  36. ;;; Most compilers will want to use the trio of make-assembler,
  37. ;;; emit-text, and link-assembly. That will result in the creation of
  38. ;;; an ELF image as a bytevector, which can then be loaded using
  39. ;;; load-thunk-from-memory, or written to disk as a .go file.
  40. ;;;
  41. ;;; Code:
  42. (define-module (system vm assembler)
  43. #:use-module (system base target)
  44. #:use-module (system base types internal)
  45. #:use-module (system vm dwarf)
  46. #:use-module (system vm elf)
  47. #:use-module (system vm linker)
  48. #:use-module (system syntax internal)
  49. #:use-module (language bytecode)
  50. #:use-module (rnrs bytevectors)
  51. #:use-module (ice-9 binary-ports)
  52. #:use-module (ice-9 vlist)
  53. #:use-module (ice-9 match)
  54. #:use-module (srfi srfi-1)
  55. #:use-module (srfi srfi-4)
  56. #:use-module (srfi srfi-9)
  57. #:use-module (srfi srfi-11)
  58. #:export (make-assembler
  59. (emit-receive* . emit-receive)
  60. (emit-mov* . emit-mov)
  61. (emit-fmov* . emit-fmov)
  62. emit-u64=?
  63. emit-u64<?
  64. emit-u64-imm<?
  65. emit-imm-u64<?
  66. emit-s64-imm=?
  67. emit-s64<?
  68. emit-s64-imm<?
  69. emit-imm-s64<?
  70. emit-f64=?
  71. emit-f64<?
  72. emit-=?
  73. emit-<?
  74. emit-arguments<=?
  75. emit-positional-arguments<=?
  76. emit-immediate-tag=?
  77. emit-heap-tag=?
  78. emit-eq?
  79. emit-heap-numbers-equal?
  80. emit-j
  81. emit-jl
  82. emit-je
  83. emit-jnl
  84. emit-jne
  85. emit-jge
  86. emit-jnge
  87. emit-fixnum?
  88. emit-thob?
  89. emit-pair?
  90. emit-char?
  91. emit-eq-null?
  92. emit-eq-nil?
  93. emit-eq-false?
  94. emit-eq-true?
  95. emit-unspecified?
  96. emit-undefined?
  97. emit-eof-object?
  98. emit-untag-fixnum
  99. emit-tag-fixnum
  100. emit-untag-char
  101. emit-tag-char
  102. emit-throw
  103. (emit-throw/value* . emit-throw/value)
  104. (emit-throw/value+data* . emit-throw/value+data)
  105. emit-struct?
  106. emit-symbol?
  107. emit-variable?
  108. emit-vector?
  109. emit-mutable-vector?
  110. emit-immutable-vector?
  111. emit-weak-vector?
  112. emit-string?
  113. emit-heap-number?
  114. emit-hash-table?
  115. emit-pointer?
  116. emit-fluid?
  117. emit-stringbuf?
  118. emit-dynamic-state?
  119. emit-frame?
  120. emit-keyword?
  121. emit-syntax?
  122. emit-program?
  123. emit-vm-continuation?
  124. emit-bytevector?
  125. emit-weak-set?
  126. emit-weak-table?
  127. emit-array?
  128. emit-bitvector?
  129. emit-port?
  130. emit-smob?
  131. emit-bignum?
  132. emit-flonum?
  133. emit-compnum?
  134. emit-fracnum?
  135. emit-allocate-words
  136. emit-allocate-words/immediate
  137. emit-tagged-allocate-words/immediate
  138. emit-scm-ref
  139. emit-scm-set!
  140. emit-scm-ref/tag
  141. emit-scm-set!/tag
  142. emit-scm-ref/immediate
  143. emit-scm-set!/immediate
  144. emit-tagged-scm-ref/immediate
  145. emit-tagged-scm-set!/immediate
  146. emit-word-ref
  147. emit-word-set!
  148. emit-word-ref/immediate
  149. emit-word-set!/immediate
  150. emit-pointer-ref/immediate
  151. emit-pointer-set!/immediate
  152. emit-tail-pointer-ref/immediate
  153. emit-u8-ref
  154. emit-s8-ref
  155. emit-u16-ref
  156. emit-s16-ref
  157. emit-u32-ref
  158. emit-s32-ref
  159. emit-u64-ref
  160. emit-s64-ref
  161. emit-f32-ref
  162. emit-f64-ref
  163. emit-u8-set!
  164. emit-s8-set!
  165. emit-u16-set!
  166. emit-s16-set!
  167. emit-u32-set!
  168. emit-s32-set!
  169. emit-u64-set!
  170. emit-s64-set!
  171. emit-f32-set!
  172. emit-f64-set!
  173. emit-atomic-scm-ref/immediate
  174. emit-atomic-scm-set!/immediate
  175. emit-atomic-scm-swap!/immediate
  176. emit-atomic-scm-compare-and-swap!/immediate
  177. ;; Intrinsics.
  178. emit-add
  179. emit-add/immediate
  180. emit-sub
  181. emit-sub/immediate
  182. emit-mul
  183. emit-div
  184. emit-quo
  185. emit-rem
  186. emit-mod
  187. emit-logand
  188. emit-logior
  189. emit-logxor
  190. emit-logsub
  191. emit-string-set!
  192. emit-string->number
  193. emit-string->symbol
  194. emit-symbol->keyword
  195. emit-class-of
  196. emit-scm->f64
  197. emit-scm->u64
  198. emit-scm->u64/truncate
  199. emit-scm->s64
  200. emit-u64->scm
  201. emit-s64->scm
  202. emit-wind
  203. emit-unwind
  204. emit-push-fluid
  205. emit-pop-fluid
  206. emit-fluid-ref
  207. emit-fluid-set!
  208. emit-push-dynamic-state
  209. emit-pop-dynamic-state
  210. emit-lsh
  211. emit-rsh
  212. emit-lsh/immediate
  213. emit-rsh/immediate
  214. emit-resolve-module
  215. emit-lookup
  216. emit-define!
  217. emit-current-module
  218. emit-cache-ref
  219. emit-cache-set!
  220. emit-call
  221. emit-call-label
  222. emit-tail-call
  223. emit-tail-call-label
  224. (emit-instrument-entry* . emit-instrument-entry)
  225. (emit-instrument-loop* . emit-instrument-loop)
  226. emit-receive-values
  227. emit-return-values
  228. emit-call/cc
  229. emit-abort
  230. emit-builtin-ref
  231. emit-assert-nargs-ee
  232. emit-assert-nargs-ge
  233. emit-assert-nargs-le
  234. emit-alloc-frame
  235. emit-reset-frame
  236. emit-assert-nargs-ee/locals
  237. emit-bind-kwargs
  238. emit-bind-rest
  239. emit-load-label
  240. emit-resolve
  241. emit-prompt
  242. emit-current-thread
  243. emit-fadd
  244. emit-fsub
  245. emit-fmul
  246. emit-fdiv
  247. emit-uadd
  248. emit-usub
  249. emit-umul
  250. emit-uadd/immediate
  251. emit-usub/immediate
  252. emit-umul/immediate
  253. emit-ulogand
  254. emit-ulogior
  255. emit-ulogxor
  256. emit-ulogsub
  257. emit-ursh
  258. emit-srsh
  259. emit-ulsh
  260. emit-ursh/immediate
  261. emit-srsh/immediate
  262. emit-ulsh/immediate
  263. emit-make-array
  264. emit-load-f64
  265. emit-load-u64
  266. emit-load-s64
  267. emit-handle-interrupts
  268. emit-text
  269. link-assembly))
  270. ;; Like define-inlinable, but only for first-order uses of the defined
  271. ;; routine. Should residualize less code.
  272. (eval-when (expand)
  273. (define-syntax define-inline
  274. (lambda (x)
  275. (syntax-case x ()
  276. ((_ (name arg ...) body ...)
  277. (with-syntax (((temp ...) (generate-temporaries #'(arg ...))))
  278. #`(eval-when (expand)
  279. (define-syntax-rule (name temp ...)
  280. (let ((arg temp) ...)
  281. body ...)))))))))
  282. ;;; Bytecode consists of 32-bit units, often subdivided in some way.
  283. ;;; These helpers create one 32-bit unit from multiple components.
  284. (define-inline (check-urange x mask)
  285. (unless (and (exact-integer? x) (= x (logand x mask)))
  286. (error "out of range" x))
  287. x)
  288. (define-inline (check-srange x mask)
  289. (let ((x* (logand x mask)))
  290. (unless (if (negative? x)
  291. (= (+ x mask 1) x*)
  292. (= x x*))
  293. (error "out of range" x))
  294. x*))
  295. (define-inline (pack-u8-u24 x y)
  296. (let ((x (check-urange x #xff))
  297. (y (check-urange y #xffffff)))
  298. (logior x (ash y 8))))
  299. (define-inline (pack-u8-s24 x y)
  300. (let ((x (check-urange x #xff))
  301. (y (check-srange y #xffffff)))
  302. (logior x (ash y 8))))
  303. (define-inline (pack-u16-u16 x y)
  304. (let ((x (check-urange x #xffff))
  305. (y (check-urange y #xffff)))
  306. (logior x (ash y 16))))
  307. (define-inline (pack-u1-u7-u24 x y z)
  308. (let ((x (check-urange x #x1))
  309. (y (check-urange y #x7f))
  310. (z (check-urange z #xffffff)))
  311. (logior x (ash y 1) (ash z 8))))
  312. (define-inline (pack-u8-u12-u12 x y z)
  313. (let ((x (check-urange x #xff))
  314. (y (check-urange y #xfff))
  315. (z (check-urange z #xfff)))
  316. (logior x (ash y 8) (ash z 20))))
  317. (define-inline (pack-u8-u12-s12 x y z)
  318. (let ((x (check-urange x #xff))
  319. (y (check-urange y #xfff))
  320. (z (check-srange z #xfff)))
  321. (logior x (ash y 8) (ash z 20))))
  322. (define-inline (pack-u8-u8-u16 x y z)
  323. (let ((x (check-urange x #xff))
  324. (y (check-urange y #xff))
  325. (z (check-urange z #xffff)))
  326. (logior x (ash y 8) (ash z 16))))
  327. (define-inline (pack-u8-u8-u8-u8 x y z w)
  328. (let ((x (check-urange x #xff))
  329. (y (check-urange y #xff))
  330. (z (check-urange z #xff))
  331. (w (check-urange w #xff)))
  332. (logior x (ash y 8) (ash z 16) (ash w 24))))
  333. (eval-when (expand)
  334. (define-syntax pack-flags
  335. (syntax-rules ()
  336. ;; Add clauses as needed.
  337. ((pack-flags f1 f2) (logior (if f1 (ash 1 0) 0)
  338. (if f2 (ash 1 1) 0))))))
  339. (define-syntax-rule (define-byte-order-swapper name size ref set)
  340. (define* (name buf #:optional (start 0) (end (bytevector-length buf)))
  341. "Patch up the text buffer @var{buf}, swapping the endianness of each
  342. N-byte unit."
  343. (unless (zero? (modulo (- end start) size))
  344. (error "unexpected length"))
  345. (let lp ((pos start))
  346. (when (< pos end)
  347. (set buf pos (ref buf pos (endianness big)) (endianness little))
  348. (lp (+ pos size))))))
  349. (define-byte-order-swapper byte-swap/2!
  350. 2 bytevector-u16-ref bytevector-u16-set!)
  351. (define-byte-order-swapper byte-swap/4!
  352. 4 bytevector-u32-ref bytevector-u32-set!)
  353. (define-byte-order-swapper byte-swap/8!
  354. 8 bytevector-u64-ref bytevector-u64-set!)
  355. ;;; A <meta> entry collects metadata for one procedure. Procedures are
  356. ;;; written as contiguous ranges of bytecode.
  357. ;;;
  358. (eval-when (expand)
  359. (define-syntax-rule (assert-match arg pattern kind)
  360. (let ((x arg))
  361. (unless (match x (pattern #t) (_ #f))
  362. (error (string-append "expected " kind) x)))))
  363. (define-record-type <jit-data>
  364. (make-jit-data low-pc high-pc)
  365. jit-data?
  366. (low-pc jit-data-low-pc)
  367. (high-pc jit-data-high-pc))
  368. (define-record-type <meta>
  369. (%make-meta label properties low-pc high-pc arities jit-data-label)
  370. meta?
  371. (label meta-label)
  372. (properties meta-properties set-meta-properties!)
  373. (low-pc meta-low-pc)
  374. (high-pc meta-high-pc set-meta-high-pc!)
  375. (arities meta-arities set-meta-arities!)
  376. (jit-data-label meta-jit-data-label))
  377. (define (make-meta label properties low-pc)
  378. (assert-match label (or (? exact-integer?) (? symbol?)) "symbol")
  379. (assert-match properties (((? symbol?) . _) ...) "alist with symbolic keys")
  380. (%make-meta label properties low-pc #f '() (gensym "jit-data")))
  381. (define (meta-name meta)
  382. (assq-ref (meta-properties meta) 'name))
  383. ;; Metadata for one <lambda-case>.
  384. (define-record-type <arity>
  385. (make-arity req opt rest kw-indices allow-other-keys?
  386. low-pc high-pc definitions)
  387. arity?
  388. (req arity-req)
  389. (opt arity-opt)
  390. (rest arity-rest)
  391. (kw-indices arity-kw-indices)
  392. (allow-other-keys? arity-allow-other-keys?)
  393. (low-pc arity-low-pc)
  394. (high-pc arity-high-pc set-arity-high-pc!)
  395. (definitions arity-definitions set-arity-definitions!))
  396. ;;; An assembler collects all of the words emitted during assembly, and
  397. ;;; also maintains ancillary information such as the constant table, a
  398. ;;; relocation list, and so on.
  399. ;;;
  400. ;;; Bytecode consists of 32-bit units. We emit bytecode using native
  401. ;;; endianness. If we're targeting a foreign endianness, we byte-swap
  402. ;;; the bytevector as a whole instead of conditionalizing each access.
  403. ;;;
  404. (define-record-type <asm>
  405. (make-asm buf pos start
  406. labels relocs
  407. word-size endianness
  408. constants inits
  409. shstrtab next-section-number
  410. meta sources
  411. slot-maps)
  412. asm?
  413. ;; We write bytecode into a bytevector, growing the bytevector as
  414. ;; needed. asm-cur is that bytevector, and asm-pos is the byte offset
  415. ;; into the vector at which the next word should be written.
  416. ;;
  417. (buf asm-buf set-asm-buf!)
  418. (pos asm-pos set-asm-pos!)
  419. ;; asm-start is an absolute position, indicating the byte offset of
  420. ;; the beginning of an instruction. It is updated after writing all
  421. ;; the words for one primitive instruction. It models the position of
  422. ;; the instruction pointer during execution, given that the VM updates
  423. ;; the IP only at the end of executing the instruction, and is thus
  424. ;; useful for computing offsets between two points in a program.
  425. ;;
  426. (start asm-start set-asm-start!)
  427. ;; An alist of symbol -> position pairs, indicating the labels defined
  428. ;; in this compilation unit.
  429. ;;
  430. (labels asm-labels set-asm-labels!)
  431. ;; A list of relocations needed by the program text. We use an
  432. ;; internal representation for relocations, and handle textual
  433. ;; relative relocations in the assembler. Other kinds of relocations
  434. ;; are later reified as linker relocations and resolved by the linker.
  435. ;;
  436. (relocs asm-relocs set-asm-relocs!)
  437. ;; Target information.
  438. ;;
  439. (word-size asm-word-size)
  440. (endianness asm-endianness)
  441. ;; The constant table, as a vhash of object -> label. All constants
  442. ;; get de-duplicated and written into separate sections -- either the
  443. ;; .rodata section, for read-only data, or .data, for constants that
  444. ;; need initialization at load-time (like symbols). Constants can
  445. ;; depend on other constants (e.g. a symbol depending on a stringbuf),
  446. ;; so order in this table is important.
  447. ;;
  448. (constants asm-constants set-asm-constants!)
  449. ;; A list of instructions needed to initialize the constants. Will
  450. ;; run in a thunk with 2 local variables.
  451. ;;
  452. (inits asm-inits set-asm-inits!)
  453. ;; The shstrtab, for section names.
  454. ;;
  455. (shstrtab asm-shstrtab set-asm-shstrtab!)
  456. ;; The section number for the next section to be written.
  457. ;;
  458. (next-section-number asm-next-section-number set-asm-next-section-number!)
  459. ;; A list of <meta>, corresponding to procedure metadata.
  460. ;;
  461. (meta asm-meta set-asm-meta!)
  462. ;; A list of (pos . source) pairs, indicating source information. POS
  463. ;; is relative to the beginning of the text section, and SOURCE is in
  464. ;; the same format that source-properties returns.
  465. ;;
  466. (sources asm-sources set-asm-sources!)
  467. ;; A list of (pos . slot-map) pairs, indicating slot maps. POS is
  468. ;; relative to the beginning of the text section. SLOT-MAP is a
  469. ;; bitfield describing the stack at call sites, as an integer.
  470. ;;
  471. (slot-maps asm-slot-maps set-asm-slot-maps!))
  472. (define* (make-assembler #:key (word-size (target-word-size))
  473. (endianness (target-endianness)))
  474. "Create an assembler for a given target @var{word-size} and
  475. @var{endianness}, falling back to appropriate values for the configured
  476. target."
  477. (make-asm (make-u32vector 1000) 0 0
  478. (make-hash-table) '()
  479. word-size endianness
  480. vlist-null '()
  481. (make-string-table) 1
  482. '() '() '()))
  483. (define (intern-section-name! asm string)
  484. "Add a string to the section name table (shstrtab)."
  485. (string-table-intern! (asm-shstrtab asm) string))
  486. (define (grow-buffer! asm)
  487. "Grow the code buffer of the asm."
  488. (let* ((buf (asm-buf asm))
  489. (len (bytevector-length buf))
  490. (new (make-u32vector (ash len -1) 0)))
  491. (bytevector-copy! buf 0 new 0 len)
  492. (set-asm-buf! asm new)
  493. #f))
  494. (define-inline (emit asm u32)
  495. "Emit one 32-bit word into the instruction stream. Assumes that there
  496. is space for the word."
  497. (bytevector-u32-native-set! (asm-buf asm) (asm-pos asm) u32)
  498. (set-asm-pos! asm (+ (asm-pos asm) 4)))
  499. (define-inline (make-reloc type label base word)
  500. "Make an internal relocation of type @var{type} referencing symbol
  501. @var{label}, @var{word} words after position @var{start}. @var{type}
  502. may be x8-s24, indicating a 24-bit relative label reference that can be
  503. fixed up by the assembler, or s32, indicating a 32-bit relative
  504. reference that needs to be fixed up by the linker."
  505. (list type label base word))
  506. (define-inline (reset-asm-start! asm)
  507. "Reset the asm-start after writing the words for one instruction."
  508. (set-asm-start! asm (asm-pos asm)))
  509. (define (record-label-reference asm label)
  510. "Record an x8-s24 local label reference. This value will get patched
  511. up later by the assembler."
  512. (let* ((start (asm-start asm))
  513. (pos (asm-pos asm))
  514. (reloc (make-reloc 'x8-s24 label start (- pos start))))
  515. (set-asm-relocs! asm (cons reloc (asm-relocs asm)))))
  516. (define* (record-far-label-reference asm label #:optional (offset 0))
  517. "Record an s32 far label reference. This value will get patched up
  518. later by the linker."
  519. (let* ((start (- (asm-start asm) offset))
  520. (pos (asm-pos asm))
  521. (reloc (make-reloc 's32 label start (- pos start))))
  522. (set-asm-relocs! asm (cons reloc (asm-relocs asm)))))
  523. ;;;
  524. ;;; Primitive assemblers are defined by expanding `assembler' for each
  525. ;;; opcode in `(instruction-list)'.
  526. ;;;
  527. (eval-when (expand)
  528. (define (id-append ctx a b)
  529. (datum->syntax ctx (symbol-append (syntax->datum a) (syntax->datum b))))
  530. (define-syntax encoder
  531. (lambda (x)
  532. (define-syntax op-case
  533. (lambda (x)
  534. (syntax-case x ()
  535. ((_ asm name ((type arg ...) code ...) clause ...)
  536. #`(if (eq? name 'type)
  537. (with-syntax (((arg ...) (generate-temporaries #'(arg ...))))
  538. #'((arg ...)
  539. code ...))
  540. (op-case asm name clause ...)))
  541. ((_ asm name)
  542. #'(error "unmatched name" name)))))
  543. (define (pack-first-word asm opcode type)
  544. (with-syntax ((opcode opcode))
  545. (op-case
  546. asm type
  547. ((X32)
  548. (emit asm opcode))
  549. ((X8_S24 arg)
  550. (emit asm (pack-u8-u24 opcode arg)))
  551. ((X8_F24 arg)
  552. (emit asm (pack-u8-u24 opcode arg)))
  553. ((X8_C24 arg)
  554. (emit asm (pack-u8-u24 opcode arg)))
  555. ((X8_L24 label)
  556. (record-label-reference asm label)
  557. (emit asm opcode))
  558. ((X8_S8_I16 a imm)
  559. (emit asm (pack-u8-u8-u16 opcode a (immediate-bits asm imm))))
  560. ((X8_S12_S12 a b)
  561. (emit asm (pack-u8-u12-u12 opcode a b)))
  562. ((X8_S12_C12 a b)
  563. (emit asm (pack-u8-u12-u12 opcode a b)))
  564. ((X8_S12_Z12 a b)
  565. (emit asm (pack-u8-u12-s12 opcode a b)))
  566. ((X8_C12_C12 a b)
  567. (emit asm (pack-u8-u12-u12 opcode a b)))
  568. ((X8_F12_F12 a b)
  569. (emit asm (pack-u8-u12-u12 opcode a b)))
  570. ((X8_S8_S8_S8 a b c)
  571. (emit asm (pack-u8-u8-u8-u8 opcode a b c)))
  572. ((X8_S8_S8_C8 a b c)
  573. (emit asm (pack-u8-u8-u8-u8 opcode a b c)))
  574. ((X8_S8_C8_S8 a b c)
  575. (emit asm (pack-u8-u8-u8-u8 opcode a b c)))
  576. ((X8_S8_C8_C8 a b c)
  577. (emit asm (pack-u8-u8-u8-u8 opcode a b c))))))
  578. (define (pack-tail-word asm type)
  579. (op-case
  580. asm type
  581. ((C32 a)
  582. (emit asm a))
  583. ((I32 imm)
  584. (let ((val (immediate-bits asm imm)))
  585. (emit asm val)))
  586. ((A32 imm)
  587. (unless (= (asm-word-size asm) 8)
  588. (error "make-long-immediate unavailable for this target"))
  589. (let ((bits (immediate-bits asm imm)))
  590. (emit asm (ash bits -32))
  591. (emit asm (logand bits (1- (ash 1 32))))))
  592. ((AF32 f64)
  593. (let ((u64 (u64vector-ref (f64vector f64) 0)))
  594. (emit asm (ash u64 -32))
  595. (emit asm (logand u64 (1- (ash 1 32))))))
  596. ((AU32 u64)
  597. (emit asm (ash u64 -32))
  598. (emit asm (logand u64 (1- (ash 1 32)))))
  599. ((AS32 s64)
  600. (let ((u64 (u64vector-ref (s64vector s64) 0)))
  601. (emit asm (ash u64 -32))
  602. (emit asm (logand u64 (1- (ash 1 32))))))
  603. ((B32))
  604. ((BU32))
  605. ((BS32))
  606. ((BF32))
  607. ((N32 label)
  608. (record-far-label-reference asm label)
  609. (emit asm 0))
  610. ((R32 label)
  611. (record-far-label-reference asm label)
  612. (emit asm 0))
  613. ((L32 label)
  614. (record-far-label-reference asm label)
  615. (emit asm 0))
  616. ((LO32 label offset)
  617. (record-far-label-reference asm label
  618. (* offset (asm-word-size asm)))
  619. (emit asm 0))
  620. ((C8_C24 a b)
  621. (emit asm (pack-u8-u24 a b)))
  622. ((C8_S24 a b)
  623. (emit asm (pack-u8-u24 a b)))
  624. ((C16_C16 a b)
  625. (emit asm (pack-u16-u16 a b)))
  626. ((B1_X7_L24 a label)
  627. (record-label-reference asm label)
  628. (emit asm (pack-u1-u7-u24 (if a 1 0) 0 0)))
  629. ((B1_C7_L24 a b label)
  630. (record-label-reference asm label)
  631. (emit asm (pack-u1-u7-u24 (if a 1 0) b 0)))
  632. ((B1_X31 a)
  633. (emit asm (pack-u1-u7-u24 (if a 1 0) 0 0)))
  634. ((B1_X7_S24 a b)
  635. (emit asm (pack-u1-u7-u24 (if a 1 0) 0 b)))
  636. ((B1_X7_F24 a b)
  637. (emit asm (pack-u1-u7-u24 (if a 1 0) 0 b)))
  638. ((B1_X7_C24 a b)
  639. (emit asm (pack-u1-u7-u24 (if a 1 0) 0 b)))
  640. ((X8_S24 a)
  641. (emit asm (pack-u8-u24 0 a)))
  642. ((X8_F24 a)
  643. (emit asm (pack-u8-u24 0 a)))
  644. ((X8_C24 a)
  645. (emit asm (pack-u8-u24 0 a)))
  646. ((X8_L24 label)
  647. (record-label-reference asm label)
  648. (emit asm 0))))
  649. (syntax-case x ()
  650. ((_ word0 word* ...)
  651. (with-syntax ((((formal0 ...)
  652. code0 ...)
  653. (pack-first-word #'asm #'opcode
  654. (syntax->datum #'word0)))
  655. ((((formal* ...)
  656. code* ...) ...)
  657. (map (lambda (word) (pack-tail-word #'asm word))
  658. (syntax->datum #'(word* ...)))))
  659. ;; The opcode is the last argument, so that assemblers don't
  660. ;; have to shuffle their arguments before tail-calling an
  661. ;; encoder.
  662. #'(lambda (asm formal0 ... formal* ... ... opcode)
  663. (let lp ()
  664. (let ((words (length '(word0 word* ...))))
  665. (unless (<= (+ (asm-pos asm) (* 4 words))
  666. (bytevector-length (asm-buf asm)))
  667. (grow-buffer! asm)
  668. (lp))))
  669. code0 ...
  670. code* ... ...
  671. (reset-asm-start! asm)))))))
  672. (define (encoder-name operands)
  673. (let lp ((operands operands) (out #'encode))
  674. (syntax-case operands ()
  675. (() out)
  676. ((operand . operands)
  677. (lp #'operands
  678. (id-append #'operand (id-append out out #'-) #'operand))))))
  679. (define-syntax define-encoder
  680. (lambda (x)
  681. (syntax-case x ()
  682. ((_ operand ...)
  683. (with-syntax ((encode (encoder-name #'(operand ...))))
  684. #'(define encode (encoder operand ...)))))))
  685. (define-syntax visit-instruction-kinds
  686. (lambda (x)
  687. (syntax-case x ()
  688. ((visit-instruction-kinds macro arg ...)
  689. (with-syntax (((operands ...)
  690. (delete-duplicates
  691. (map (match-lambda
  692. ((name opcode kind . operands)
  693. (datum->syntax #'macro operands)))
  694. (instruction-list)))))
  695. #'(begin
  696. (macro arg ... . operands)
  697. ...)))))))
  698. (visit-instruction-kinds define-encoder)
  699. ;; In Guile's VM, locals are usually addressed via the stack pointer
  700. ;; (SP). There can be up to 2^24 slots for local variables in a
  701. ;; frame. Some instructions encode their operands using a restricted
  702. ;; subset of the full 24-bit local address space, in order to make the
  703. ;; bytecode more dense in the usual case that a function needs few
  704. ;; local slots. To allow these instructions to be used when there are
  705. ;; many local slots, we can temporarily push the values on the stack,
  706. ;; operate on them there, and then store back any result as we pop the
  707. ;; SP to its original position.
  708. ;;
  709. ;; We implement this shuffling via wrapper encoders that have the same
  710. ;; arity as the encoder they wrap, e.g. encode-X8_S12_S12/shuffle that
  711. ;; wraps encode-X8_S12_S12. We make the emit-cons public interface
  712. ;; use the shuffling encoder. That way we solve the problem fully and
  713. ;; in just one place.
  714. (define (encode-X8_S12_S12!/shuffle asm a b opcode)
  715. (cond
  716. ((< (logior a b) (ash 1 12))
  717. (encode-X8_S12_S12 asm a b opcode))
  718. (else
  719. (emit-push asm a)
  720. (emit-push asm (1+ b))
  721. (encode-X8_S12_S12 asm 1 0 opcode)
  722. (emit-drop asm 2))))
  723. (define (encode-X8_S12_S12<-/shuffle asm dst a opcode)
  724. (cond
  725. ((< (logior dst a) (ash 1 12))
  726. (encode-X8_S12_S12 asm dst a opcode))
  727. (else
  728. (emit-push asm a)
  729. (encode-X8_S12_S12 asm 0 0 opcode)
  730. (emit-pop asm dst))))
  731. (define (encode-X8_S12_C12!/shuffle asm a const opcode)
  732. (cond
  733. ((< a (ash 1 12))
  734. (encode-X8_S12_C12 asm a const opcode))
  735. (else
  736. (emit-push asm a)
  737. (encode-X8_S12_C12 asm 0 const opcode)
  738. (emit-drop asm 1))))
  739. (define (encode-X8_S12_C12<-/shuffle asm dst const opcode)
  740. (cond
  741. ((< dst (ash 1 12))
  742. (encode-X8_S12_C12 asm dst const opcode))
  743. (else
  744. ;; Push garbage value to make space for dst.
  745. (emit-push asm dst)
  746. (encode-X8_S12_C12 asm 0 const opcode)
  747. (emit-pop asm dst))))
  748. (define (encode-X8_S12_Z12!/shuffle asm a const opcode)
  749. (cond
  750. ((< a (ash 1 12))
  751. (encode-X8_S12_Z12 asm a const opcode))
  752. (else
  753. (emit-push asm a)
  754. (encode-X8_S12_Z12 asm 0 const opcode)
  755. (emit-drop asm 1))))
  756. (define (encode-X8_S8_I16<-/shuffle asm dst imm opcode)
  757. (cond
  758. ((< dst (ash 1 8))
  759. (encode-X8_S8_I16 asm dst imm opcode))
  760. (else
  761. ;; Push garbage value to make space for dst.
  762. (emit-push asm dst)
  763. (encode-X8_S8_I16 asm 0 imm opcode)
  764. (emit-pop asm dst))))
  765. (define (encode-X8_S8_S8_S8!/shuffle asm a b c opcode)
  766. (cond
  767. ((< (logior a b c) (ash 1 8))
  768. (encode-X8_S8_S8_S8 asm a b c opcode))
  769. (else
  770. (emit-push asm a)
  771. (emit-push asm (+ b 1))
  772. (emit-push asm (+ c 2))
  773. (encode-X8_S8_S8_S8 asm 2 1 0 opcode)
  774. (emit-drop asm 3))))
  775. (define (encode-X8_S8_S8_S8<-/shuffle asm dst a b opcode)
  776. (cond
  777. ((< (logior dst a b) (ash 1 8))
  778. (encode-X8_S8_S8_S8 asm dst a b opcode))
  779. (else
  780. (emit-push asm a)
  781. (emit-push asm (1+ b))
  782. (encode-X8_S8_S8_S8 asm 1 1 0 opcode)
  783. (emit-drop asm 1)
  784. (emit-pop asm dst))))
  785. (define (encode-X8_S8_S8_C8<-/shuffle asm dst a const opcode)
  786. (cond
  787. ((< (logior dst a) (ash 1 8))
  788. (encode-X8_S8_S8_C8 asm dst a const opcode))
  789. (else
  790. (emit-push asm a)
  791. (encode-X8_S8_S8_C8 asm 0 0 const opcode)
  792. (emit-pop asm dst))))
  793. (define (encode-X8_S8_C8_S8!/shuffle asm a const b opcode)
  794. (cond
  795. ((< (logior a b) (ash 1 8))
  796. (encode-X8_S8_C8_S8 asm a const b opcode))
  797. (else
  798. (emit-push asm a)
  799. (emit-push asm (1+ b))
  800. (encode-X8_S8_C8_S8 asm 1 const 0 opcode)
  801. (emit-drop asm 2))))
  802. (define (encode-X8_S8_C8_S8<-/shuffle asm dst const a opcode)
  803. (cond
  804. ((< (logior dst a) (ash 1 8))
  805. (encode-X8_S8_C8_S8 asm dst const a opcode))
  806. (else
  807. (emit-push asm a)
  808. (encode-X8_S8_C8_S8 asm 0 const 0 opcode)
  809. (emit-pop asm dst))))
  810. (define (encode-X8_S8_C8_C8!/shuffle asm a const1 const2 opcode)
  811. (cond
  812. ((< a (ash 1 8))
  813. (encode-X8_S8_C8_C8 asm a const1 const2 opcode))
  814. (else
  815. (emit-push asm a)
  816. (encode-X8_S8_C8_C8 asm 0 const1 const2 opcode)
  817. (emit-drop asm 1))))
  818. (define (encode-X8_S8_C8_C8<-/shuffle asm dst const1 const2 opcode)
  819. (cond
  820. ((< dst (ash 1 8))
  821. (encode-X8_S8_C8_C8 asm dst const1 const2 opcode))
  822. (else
  823. ;; Push garbage value to make space for dst.
  824. (emit-push asm dst)
  825. (encode-X8_S8_C8_C8 asm 0 const1 const2 opcode)
  826. (emit-pop asm dst))))
  827. (define (encode-X8_S8_S8_S8-C32<-/shuffle asm dst a b c32 opcode)
  828. (cond
  829. ((< (logior dst a b) (ash 1 8))
  830. (encode-X8_S8_S8_S8-C32 asm dst a b c32 opcode))
  831. (else
  832. (emit-push asm a)
  833. (emit-push asm (1+ b))
  834. (encode-X8_S8_S8_S8-C32 asm 1 1 0 c32 opcode)
  835. (emit-drop asm 1)
  836. (emit-pop asm dst))))
  837. (define (encode-X8_S8_S8_C8-C32<-/shuffle asm dst a const c32 opcode)
  838. (cond
  839. ((< (logior dst a) (ash 1 8))
  840. (encode-X8_S8_S8_C8-C32 asm dst a const c32 opcode))
  841. (else
  842. (emit-push asm a)
  843. (encode-X8_S8_S8_C8-C32 asm 0 0 const c32 opcode)
  844. (emit-pop asm dst))))
  845. (define (encode-X8_S8_S8_S8-C32!/shuffle asm a b c c32 opcode)
  846. (cond
  847. ((< (logior a b c) (ash 1 8))
  848. (encode-X8_S8_S8_S8-C32 asm a b c c32 opcode))
  849. (else
  850. (emit-push asm a)
  851. (emit-push asm (+ b 1))
  852. (emit-push asm (+ c 2))
  853. (encode-X8_S8_S8_S8-C32 asm 2 1 0 c32 opcode)
  854. (emit-drop asm 3))))
  855. (define (encode-X8_S12_S12-C32<-/shuffle asm dst src c32 opcode)
  856. (cond
  857. ((< (logior dst src) (ash 1 12))
  858. (encode-X8_S12_S12-C32 asm dst src c32 opcode))
  859. (else
  860. (emit-push asm src)
  861. (encode-X8_S12_S12-C32 asm 0 0 c32 opcode)
  862. (emit-pop asm dst))))
  863. (define (encode-X8_S12_S12-C32!/shuffle asm a b c32 opcode)
  864. (cond
  865. ((< (logior a b) (ash 1 12))
  866. (encode-X8_S12_S12-C32 asm a b c32 opcode))
  867. (else
  868. (emit-push asm a)
  869. (emit-push asm b)
  870. (encode-X8_S12_S12-C32 asm 1 0 c32 opcode)
  871. (emit-drop asm 2))))
  872. (eval-when (expand)
  873. (define (id-append ctx a b)
  874. (datum->syntax ctx (symbol-append (syntax->datum a) (syntax->datum b))))
  875. (define (shuffling-encoder-name kind operands)
  876. (match (cons (syntax->datum kind) (syntax->datum operands))
  877. (('! 'X8_S12_S12) #'encode-X8_S12_S12!/shuffle)
  878. (('<- 'X8_S12_S12) #'encode-X8_S12_S12<-/shuffle)
  879. (('! 'X8_S12_S12 'X8_C24) #'encode-X8_S12_S12-X8_C24!/shuffle)
  880. (('<- 'X8_S12_S12 'X8_C24) #'encode-X8_S12_S12-X8_C24<-/shuffle)
  881. (('! 'X8_S12_C12) #'encode-X8_S12_C12!/shuffle)
  882. (('<- 'X8_S12_C12) #'encode-X8_S12_C12<-/shuffle)
  883. (('! 'X8_S12_Z12) #'encode-X8_S12_Z12!/shuffle)
  884. (('<- 'X8_S8_I16) #'encode-X8_S8_I16<-/shuffle)
  885. (('! 'X8_S8_S8_S8) #'encode-X8_S8_S8_S8!/shuffle)
  886. (('<- 'X8_S8_S8_S8) #'encode-X8_S8_S8_S8<-/shuffle)
  887. (('<- 'X8_S8_S8_C8) #'encode-X8_S8_S8_C8<-/shuffle)
  888. (('<- 'X8_S8_S8_S8 'C32) #'encode-X8_S8_S8_S8-C32<-/shuffle)
  889. (('<- 'X8_S8_S8_C8 'C32) #'encode-X8_S8_S8_C8-C32<-/shuffle)
  890. (('! 'X8_S8_S8_C8 'C32) #'encode-X8_S8_S8_C8-C32!/shuffle)
  891. (('<- 'X8_S12_S12 'C32) #'encode-X8_S12_S12-C32<-/shuffle)
  892. (('! 'X8_S12_S12 'C32) #'encode-X8_S12_S12-C32!/shuffle)
  893. (('! 'X8_S8_C8_S8) #'encode-X8_S8_C8_S8!/shuffle)
  894. (('<- 'X8_S8_C8_S8) #'encode-X8_S8_C8_S8<-/shuffle)
  895. (('! 'X8_S8_C8_C8) #'encode-X8_S8_C8_C8!/shuffle)
  896. (('<- 'X8_S8_C8_C8) #'encode-X8_S8_C8_C8<-/shuffle)
  897. (else (encoder-name operands))))
  898. (define-syntax assembler
  899. (lambda (x)
  900. (define (word-args word)
  901. (match word
  902. ('C32 #'(a))
  903. ('I32 #'(imm))
  904. ('A32 #'(imm))
  905. ('AF32 #'(f64))
  906. ('AU32 #'(u64))
  907. ('AS32 #'(s64))
  908. ('B32 #'())
  909. ('BU32 #'())
  910. ('BS32 #'())
  911. ('BF32 #'())
  912. ('N32 #'(label))
  913. ('R32 #'(label))
  914. ('L32 #'(label))
  915. ('LO32 #'(label offset))
  916. ('C8_C24 #'(a b))
  917. ('C8_S24 #'(a b))
  918. ('C16_C16 #'(a b))
  919. ('B1_X7_L24 #'(a label))
  920. ('B1_C7_L24 #'(a b label))
  921. ('B1_X31 #'(a))
  922. ('B1_X7_S24 #'(a b))
  923. ('B1_X7_F24 #'(a b))
  924. ('B1_X7_C24 #'(a b))
  925. ('X8_S24 #'(arg))
  926. ('X8_F24 #'(arg))
  927. ('X8_C24 #'(arg))
  928. ('X8_L24 #'(label))
  929. ('X8_S8_I16 #'(a imm))
  930. ('X8_S12_S12 #'(a b))
  931. ('X8_S12_C12 #'(a b))
  932. ('X8_S12_Z12 #'(a b))
  933. ('X8_C12_C12 #'(a b))
  934. ('X8_F12_F12 #'(a b))
  935. ('X8_S8_S8_S8 #'(a b c))
  936. ('X8_S8_S8_C8 #'(a b c))
  937. ('X8_S8_C8_S8 #'(a b c))
  938. ('X8_S8_C8_C8 #'(a b c))
  939. ('X32 #'())))
  940. (syntax-case x ()
  941. ((_ name opcode kind word ...)
  942. (with-syntax (((formal ...)
  943. (generate-temporaries
  944. (append-map word-args (syntax->datum #'(word ...)))))
  945. (encode (shuffling-encoder-name #'kind #'(word ...))))
  946. #'(lambda (asm formal ...)
  947. (encode asm formal ... opcode))))))))
  948. (define assemblers (make-hash-table))
  949. (eval-when (expand)
  950. (define-syntax define-assembler
  951. (lambda (x)
  952. (syntax-case x ()
  953. ((_ name opcode kind arg ...)
  954. (with-syntax ((emit (id-append #'name #'emit- #'name)))
  955. #'(define emit
  956. (let ((emit (assembler name opcode kind arg ...)))
  957. (hashq-set! assemblers 'name emit)
  958. emit)))))))
  959. (define-syntax visit-opcodes
  960. (lambda (x)
  961. (syntax-case x ()
  962. ((visit-opcodes macro arg ...)
  963. (with-syntax (((inst ...)
  964. (map (lambda (x) (datum->syntax #'macro x))
  965. (instruction-list))))
  966. #'(begin
  967. (macro arg ... . inst)
  968. ...)))))))
  969. (visit-opcodes define-assembler)
  970. ;; Shuffling is a general mechanism to get around address space
  971. ;; limitations for SP-relative variable references. FP-relative
  972. ;; variables need special support. Also, some instructions like `mov'
  973. ;; have multiple variations with different addressing limits.
  974. (define (emit-mov* asm dst src)
  975. (if (and (< dst (ash 1 12)) (< src (ash 1 12)))
  976. (emit-mov asm dst src)
  977. (emit-long-mov asm dst src)))
  978. (define (emit-fmov* asm dst src)
  979. (emit-long-fmov asm dst src))
  980. (define (emit-receive* asm dst proc nlocals)
  981. (if (and (< dst (ash 1 12)) (< proc (ash 1 12)))
  982. (emit-receive asm dst proc nlocals)
  983. (begin
  984. (emit-receive-values asm proc #t 1)
  985. (emit-fmov* asm dst (1+ proc))
  986. (emit-reset-frame asm nlocals))))
  987. (define (emit-throw/value* asm val param)
  988. (emit-throw/value asm val (intern-non-immediate asm param)))
  989. (define (emit-throw/value+data* asm val param)
  990. (emit-throw/value+data asm val (intern-non-immediate asm param)))
  991. (define (emit-instrument-entry* asm)
  992. (let ((meta (car (asm-meta asm))))
  993. (emit-instrument-entry asm (meta-jit-data-label meta))))
  994. (define (emit-instrument-loop* asm)
  995. (let ((meta (car (asm-meta asm))))
  996. (emit-instrument-loop asm (meta-jit-data-label meta))))
  997. (define (emit-text asm instructions)
  998. "Assemble @var{instructions} using the assembler @var{asm}.
  999. @var{instructions} is a sequence of instructions, expressed as a list of
  1000. lists. This procedure can be called many times before calling
  1001. @code{link-assembly}."
  1002. (for-each (lambda (inst)
  1003. (apply (or (hashq-ref assemblers (car inst))
  1004. (error 'bad-instruction inst))
  1005. asm
  1006. (cdr inst)))
  1007. instructions))
  1008. ;;;
  1009. ;;; The constant table records a topologically sorted set of literal
  1010. ;;; constants used by a program. For example, a pair uses its car and
  1011. ;;; cdr, a string uses its stringbuf, etc.
  1012. ;;;
  1013. ;;; Some things we want to add to the constant table are not actually
  1014. ;;; Scheme objects: for example, stringbufs, cache cells for toplevel
  1015. ;;; references, or cache cells for non-closure procedures. For these we
  1016. ;;; define special record types and add instances of those record types
  1017. ;;; to the table.
  1018. ;;;
  1019. (define (immediate-bits asm x)
  1020. "Return the bit pattern to write into the buffer if @var{x} is
  1021. immediate, and @code{#f} otherwise."
  1022. (if (exact-integer? x)
  1023. ;; Object is an immediate if it is a fixnum on the target.
  1024. (and (target-fixnum? x)
  1025. (let* ((fixnum-max (target-most-positive-fixnum))
  1026. (fixnum-bits (if (negative? x)
  1027. (+ fixnum-max 1 (logand x fixnum-max))
  1028. x)))
  1029. (logior (ash fixnum-bits (target-fixnum-tag-bits))
  1030. (target-fixnum-tag))))
  1031. ;; Otherwise, the object will be immediate on the target if and
  1032. ;; only if it is immediate on the host. Except for integers,
  1033. ;; which we handle specially above, any immediate value is an
  1034. ;; immediate on both 32-bit and 64-bit targets.
  1035. (let ((bits (object-address x)))
  1036. ;; TAGS-SENSITIVE
  1037. (and (not (= (logand bits %thob-tag-mask)
  1038. %thob-tag))
  1039. (not (= (logand bits (target-pair-tag-mask))
  1040. (target-pair-tag)))
  1041. bits))))
  1042. (define-record-type <stringbuf>
  1043. (make-stringbuf string)
  1044. stringbuf?
  1045. (string stringbuf-string))
  1046. (define-record-type <static-procedure>
  1047. (make-static-procedure code)
  1048. static-procedure?
  1049. (code static-procedure-code))
  1050. (define-record-type <uniform-vector-backing-store>
  1051. (make-uniform-vector-backing-store bytes element-size)
  1052. uniform-vector-backing-store?
  1053. (bytes uniform-vector-backing-store-bytes)
  1054. (element-size uniform-vector-backing-store-element-size))
  1055. (define-record-type <cache-cell>
  1056. (make-cache-cell key)
  1057. cache-cell?
  1058. (key cache-cell-key))
  1059. (define (simple-vector? obj)
  1060. (and (vector? obj)
  1061. (equal? (array-shape obj) (list (list 0 (1- (vector-length obj)))))))
  1062. (define (simple-uniform-vector? obj)
  1063. (and (array? obj)
  1064. (symbol? (array-type obj))
  1065. (match (array-shape obj)
  1066. (((0 n)) #t)
  1067. (else #f))))
  1068. (define (statically-allocatable? x)
  1069. "Return @code{#t} if a non-immediate constant can be allocated
  1070. statically, and @code{#f} if it would need some kind of runtime
  1071. allocation."
  1072. (or (pair? x) (string? x) (stringbuf? x) (static-procedure? x)
  1073. (array? x) (syntax? x)))
  1074. (define (intern-constant asm obj)
  1075. "Add an object to the constant table, and return a label that can be
  1076. used to reference it. If the object is already present in the constant
  1077. table, its existing label is used directly."
  1078. (define (recur obj)
  1079. (intern-constant asm obj))
  1080. (define (field dst n obj)
  1081. (let ((src (recur obj)))
  1082. (if src
  1083. (cond ((pair? obj)
  1084. `((static-patch! (target-pair-tag) ,dst ,n ,src)))
  1085. ((statically-allocatable? obj)
  1086. `((static-patch! 0 ,dst ,n ,src)))
  1087. (else
  1088. `((static-ref 1 ,src)
  1089. (static-set! 1 ,dst ,n))))
  1090. '())))
  1091. (define (intern obj label)
  1092. (cond
  1093. ((pair? obj)
  1094. (append (field label 0 (car obj))
  1095. (field label 1 (cdr obj))))
  1096. ((simple-vector? obj)
  1097. (let lp ((i 0) (inits '()))
  1098. (if (< i (vector-length obj))
  1099. (lp (1+ i)
  1100. (append-reverse (field label (1+ i) (vector-ref obj i))
  1101. inits))
  1102. (reverse inits))))
  1103. ((syntax? obj)
  1104. (append (field label 1 (syntax-expression obj))
  1105. (field label 2 (syntax-wrap obj))
  1106. (field label 3 (syntax-module obj))))
  1107. ((stringbuf? obj) '())
  1108. ((static-procedure? obj)
  1109. `((static-patch! 0 ,label 1 ,(static-procedure-code obj))))
  1110. ((cache-cell? obj) '())
  1111. ((symbol? obj)
  1112. (unless (symbol-interned? obj)
  1113. (error "uninterned symbol cannot be saved to object file" obj))
  1114. `((make-non-immediate 1 ,(recur (symbol->string obj)))
  1115. (string->symbol 1 1)
  1116. (static-set! 1 ,label 0)))
  1117. ((string? obj)
  1118. `((static-patch! 0 ,label 1 ,(recur (make-stringbuf obj)))))
  1119. ((keyword? obj)
  1120. `((static-ref 1 ,(recur (keyword->symbol obj)))
  1121. (symbol->keyword 1 1)
  1122. (static-set! 1 ,label 0)))
  1123. ((number? obj)
  1124. `((make-non-immediate 1 ,(recur (number->string obj)))
  1125. (string->number 1 1)
  1126. (static-set! 1 ,label 0)))
  1127. ((uniform-vector-backing-store? obj) '())
  1128. ((simple-uniform-vector? obj)
  1129. (let ((width (case (array-type obj)
  1130. ((vu8 u8 s8) 1)
  1131. ((u16 s16) 2)
  1132. ;; Bitvectors are addressed in 32-bit units.
  1133. ;; Although a complex number is 8 or 16 bytes wide,
  1134. ;; it should be byteswapped in 4 or 8 byte units.
  1135. ((u32 s32 f32 c32 b) 4)
  1136. ((u64 s64 f64 c64) 8)
  1137. (else
  1138. (error "unhandled array type" obj)))))
  1139. `((static-patch! 0 ,label 2
  1140. ,(recur (make-uniform-vector-backing-store
  1141. (uniform-array->bytevector obj)
  1142. width))))))
  1143. ((array? obj)
  1144. `((static-patch! 0 ,label 1 ,(recur (shared-array-root obj)))))
  1145. (else
  1146. (error "don't know how to intern" obj))))
  1147. (cond
  1148. ((immediate-bits asm obj) #f)
  1149. ((vhash-assoc obj (asm-constants asm)) => cdr)
  1150. (else
  1151. ;; Note that calling intern may mutate asm-constants and asm-inits.
  1152. (let* ((label (gensym "constant"))
  1153. (inits (intern obj label)))
  1154. (set-asm-constants! asm (vhash-cons obj label (asm-constants asm)))
  1155. (set-asm-inits! asm (append-reverse inits (asm-inits asm)))
  1156. label))))
  1157. (define (intern-non-immediate asm obj)
  1158. "Intern a non-immediate into the constant table, and return its
  1159. label."
  1160. (when (immediate-bits asm obj)
  1161. (error "expected a non-immediate" obj))
  1162. (intern-constant asm obj))
  1163. (define (intern-cache-cell asm key)
  1164. "Intern a cache cell into the constant table, and return its label.
  1165. If there is already a cache cell with the given scope and key, it is
  1166. returned instead."
  1167. (intern-constant asm (make-cache-cell key)))
  1168. ;;;
  1169. ;;; Macro assemblers bridge the gap between primitive instructions and
  1170. ;;; some higher-level operations.
  1171. ;;;
  1172. (eval-when (expand)
  1173. (define-syntax define-macro-assembler
  1174. (lambda (x)
  1175. (syntax-case x ()
  1176. ((_ (name arg ...) body body* ...)
  1177. (with-syntax ((emit (id-append #'name #'emit- #'name)))
  1178. #'(begin
  1179. (define emit
  1180. (let ((emit (lambda (arg ...) body body* ...)))
  1181. (hashq-set! assemblers 'name emit)
  1182. emit))
  1183. (export emit))))))))
  1184. (define-macro-assembler (load-constant asm dst obj)
  1185. (cond
  1186. ((immediate-bits asm obj)
  1187. => (lambda (bits)
  1188. (cond
  1189. ((and (< dst 256) (zero? (ash bits -16)))
  1190. (emit-make-short-immediate asm dst obj))
  1191. ((zero? (ash bits -32))
  1192. (emit-make-long-immediate asm dst obj))
  1193. (else
  1194. (emit-make-long-long-immediate asm dst obj)))))
  1195. ((pair? obj)
  1196. (emit-make-tagged-non-immediate asm dst (target-pair-tag)
  1197. (intern-non-immediate asm obj)))
  1198. ((statically-allocatable? obj)
  1199. (emit-make-non-immediate asm dst (intern-non-immediate asm obj)))
  1200. (else
  1201. (emit-static-ref asm dst (intern-non-immediate asm obj)))))
  1202. (define-macro-assembler (load-static-procedure asm dst label)
  1203. (let ((loc (intern-constant asm (make-static-procedure label))))
  1204. (emit-make-non-immediate asm dst loc)))
  1205. (define-syntax-rule (define-immediate-tag=?-macro-assembler name pred mask tag)
  1206. (define-macro-assembler (pred asm slot)
  1207. (emit-immediate-tag=? asm slot mask tag)))
  1208. (visit-immediate-tags define-immediate-tag=?-macro-assembler)
  1209. (define-syntax-rule (define-heap-tag=?-macro-assembler name pred mask tag)
  1210. (define-macro-assembler (pred asm slot)
  1211. (emit-heap-tag=? asm slot mask tag)))
  1212. (visit-heap-tags define-heap-tag=?-macro-assembler)
  1213. (define-syntax-rule (define-scm<-scm-scm-intrinsic name)
  1214. (define-macro-assembler (name asm dst a b)
  1215. (emit-call-scm<-scm-scm asm dst a b (intrinsic-name->index 'name))))
  1216. (define-syntax-rule (define-scm<-scm-uimm-intrinsic name)
  1217. (define-macro-assembler (name asm dst a b)
  1218. (emit-call-scm<-scm-uimm asm dst a b (intrinsic-name->index 'name))))
  1219. (define-syntax-rule (define-scm-sz-u32-intrinsic name)
  1220. (define-macro-assembler (name asm a b c)
  1221. (emit-call-scm-sz-u32 asm a b c (intrinsic-name->index 'name))))
  1222. (define-syntax-rule (define-scm<-scm-intrinsic name)
  1223. (define-macro-assembler (name asm dst src)
  1224. (emit-call-scm<-scm asm dst src (intrinsic-name->index 'name))))
  1225. (define-syntax-rule (define-f64<-scm-intrinsic name)
  1226. (define-macro-assembler (name asm dst src)
  1227. (emit-call-f64<-scm asm dst src (intrinsic-name->index 'name))))
  1228. (define-syntax-rule (define-u64<-scm-intrinsic name)
  1229. (define-macro-assembler (name asm dst src)
  1230. (emit-call-u64<-scm asm dst src (intrinsic-name->index 'name))))
  1231. (define-syntax-rule (define-s64<-scm-intrinsic name)
  1232. (define-macro-assembler (name asm dst src)
  1233. (emit-call-s64<-scm asm dst src (intrinsic-name->index 'name))))
  1234. (define-syntax-rule (define-scm<-u64-intrinsic name)
  1235. (define-macro-assembler (name asm dst src)
  1236. (emit-call-scm<-u64 asm dst src (intrinsic-name->index 'name))))
  1237. (define-syntax-rule (define-scm<-s64-intrinsic name)
  1238. (define-macro-assembler (name asm dst src)
  1239. (emit-call-scm<-s64 asm dst src (intrinsic-name->index 'name))))
  1240. (define-syntax-rule (define-thread-intrinsic name)
  1241. (define-macro-assembler (name asm)
  1242. (emit-call-thread asm (intrinsic-name->index 'name))))
  1243. (define-syntax-rule (define-thread-scm-intrinsic name)
  1244. (define-macro-assembler (name asm a)
  1245. (emit-call-thread-scm asm a (intrinsic-name->index 'name))))
  1246. (define-syntax-rule (define-thread-scm-scm-intrinsic name)
  1247. (define-macro-assembler (name asm a b)
  1248. (emit-call-thread-scm-scm asm a b (intrinsic-name->index 'name))))
  1249. (define-syntax-rule (define-scm<-thread-scm-intrinsic name)
  1250. (define-macro-assembler (name asm dst src)
  1251. (emit-call-scm<-thread-scm asm dst src (intrinsic-name->index 'name))))
  1252. (define-syntax-rule (define-scm<-scm-u64-intrinsic name)
  1253. (define-macro-assembler (name asm dst a b)
  1254. (emit-call-scm<-scm-u64 asm dst a b (intrinsic-name->index 'name))))
  1255. (define-syntax-rule (define-scm<-scm-bool-intrinsic name)
  1256. (define-macro-assembler (name asm dst a b)
  1257. (emit-call-scm<-scm-uimm asm dst a (if b 1 0) (intrinsic-name->index 'name))))
  1258. (define-syntax-rule (define-scm<-thread-intrinsic name)
  1259. (define-macro-assembler (name asm dst)
  1260. (emit-call-scm<-thread asm dst (intrinsic-name->index 'name))))
  1261. (define-scm<-scm-scm-intrinsic add)
  1262. (define-scm<-scm-uimm-intrinsic add/immediate)
  1263. (define-scm<-scm-scm-intrinsic sub)
  1264. (define-scm<-scm-uimm-intrinsic sub/immediate)
  1265. (define-scm<-scm-scm-intrinsic mul)
  1266. (define-scm<-scm-scm-intrinsic div)
  1267. (define-scm<-scm-scm-intrinsic quo)
  1268. (define-scm<-scm-scm-intrinsic rem)
  1269. (define-scm<-scm-scm-intrinsic mod)
  1270. (define-scm<-scm-scm-intrinsic logand)
  1271. (define-scm<-scm-scm-intrinsic logior)
  1272. (define-scm<-scm-scm-intrinsic logxor)
  1273. (define-scm<-scm-scm-intrinsic logsub)
  1274. (define-scm-sz-u32-intrinsic string-set!)
  1275. (define-scm<-scm-intrinsic string->number)
  1276. (define-scm<-scm-intrinsic string->symbol)
  1277. (define-scm<-scm-intrinsic symbol->keyword)
  1278. (define-scm<-scm-intrinsic class-of)
  1279. (define-f64<-scm-intrinsic scm->f64)
  1280. (define-u64<-scm-intrinsic scm->u64)
  1281. (define-u64<-scm-intrinsic scm->u64/truncate)
  1282. (define-s64<-scm-intrinsic scm->s64)
  1283. (define-scm<-u64-intrinsic u64->scm)
  1284. (define-scm<-s64-intrinsic s64->scm)
  1285. (define-thread-scm-scm-intrinsic wind)
  1286. (define-thread-intrinsic unwind)
  1287. (define-thread-scm-scm-intrinsic push-fluid)
  1288. (define-thread-intrinsic pop-fluid)
  1289. (define-scm<-thread-scm-intrinsic fluid-ref)
  1290. (define-thread-scm-scm-intrinsic fluid-set!)
  1291. (define-thread-scm-intrinsic push-dynamic-state)
  1292. (define-thread-intrinsic pop-dynamic-state)
  1293. (define-scm<-scm-u64-intrinsic lsh)
  1294. (define-scm<-scm-u64-intrinsic rsh)
  1295. (define-scm<-scm-uimm-intrinsic lsh/immediate)
  1296. (define-scm<-scm-uimm-intrinsic rsh/immediate)
  1297. (define-scm<-scm-bool-intrinsic resolve-module)
  1298. (define-scm<-scm-scm-intrinsic lookup)
  1299. (define-scm<-scm-scm-intrinsic define!)
  1300. (define-scm<-thread-intrinsic current-module)
  1301. (define-macro-assembler (begin-program asm label properties)
  1302. (emit-label asm label)
  1303. (let ((meta (make-meta label properties (asm-start asm))))
  1304. (set-asm-meta! asm (cons meta (asm-meta asm))))
  1305. (emit-instrument-entry* asm))
  1306. (define-macro-assembler (end-program asm)
  1307. (let ((meta (car (asm-meta asm))))
  1308. (set-meta-high-pc! meta (asm-start asm))
  1309. (set-meta-arities! meta (reverse (meta-arities meta)))
  1310. (set-asm-constants!
  1311. asm
  1312. (vhash-cons (make-jit-data (meta-low-pc meta) (meta-high-pc meta))
  1313. (meta-jit-data-label meta)
  1314. (asm-constants asm)))))
  1315. (define-macro-assembler (begin-standard-arity asm req nlocals alternate)
  1316. (emit-begin-opt-arity asm req '() #f nlocals alternate))
  1317. (define-macro-assembler (begin-opt-arity asm req opt rest nlocals alternate)
  1318. (emit-begin-kw-arity asm req opt rest '() #f nlocals alternate))
  1319. (define-macro-assembler (begin-kw-arity asm req opt rest kw-indices
  1320. allow-other-keys? nlocals alternate)
  1321. (assert-match req ((? symbol?) ...) "list of symbols")
  1322. (assert-match opt ((? symbol?) ...) "list of symbols")
  1323. (assert-match rest (or #f (? symbol?)) "#f or symbol")
  1324. (assert-match kw-indices (((? keyword?) . (? integer?)) ...)
  1325. "alist of keyword -> integer")
  1326. (assert-match allow-other-keys? (? boolean?) "boolean")
  1327. (assert-match nlocals (? integer?) "integer")
  1328. (assert-match alternate (or #f (? exact-integer?) (? symbol?)) "#f or symbol")
  1329. (let* ((meta (car (asm-meta asm)))
  1330. (arity (make-arity req opt rest kw-indices allow-other-keys?
  1331. ;; Include the initial instrument-entry in
  1332. ;; the first arity.
  1333. (if (null? (meta-arities meta))
  1334. (meta-low-pc meta)
  1335. (asm-start asm))
  1336. #f '()))
  1337. ;; The procedure itself is in slot 0, in the standard calling
  1338. ;; convention. For procedure prologues, nreq includes the
  1339. ;; procedure, so here we add 1.
  1340. (nreq (1+ (length req)))
  1341. (nopt (length opt))
  1342. (rest? (->bool rest)))
  1343. (set-meta-arities! meta (cons arity (meta-arities meta)))
  1344. (cond
  1345. ((or allow-other-keys? (pair? kw-indices))
  1346. (emit-kw-prelude asm nreq nopt rest? kw-indices allow-other-keys?
  1347. nlocals alternate))
  1348. ((or rest? (pair? opt))
  1349. (emit-opt-prelude asm nreq nopt rest? nlocals alternate))
  1350. (else
  1351. (emit-standard-prelude asm nreq nlocals alternate)))))
  1352. (define-macro-assembler (end-arity asm)
  1353. (let ((arity (car (meta-arities (car (asm-meta asm))))))
  1354. (set-arity-definitions! arity (reverse (arity-definitions arity)))
  1355. (set-arity-high-pc! arity (asm-start asm))))
  1356. (define-macro-assembler (standard-prelude asm nreq nlocals alternate)
  1357. (cond
  1358. (alternate
  1359. (emit-arguments<=? asm nreq)
  1360. (emit-jne asm alternate)
  1361. (emit-alloc-frame asm nlocals))
  1362. ((and (< nreq (ash 1 12)) (< (- nlocals nreq) (ash 1 12)))
  1363. (emit-assert-nargs-ee/locals asm nreq (- nlocals nreq)))
  1364. (else
  1365. (emit-assert-nargs-ee asm nreq)
  1366. (emit-alloc-frame asm nlocals))))
  1367. (define-macro-assembler (opt-prelude asm nreq nopt rest? nlocals alternate)
  1368. (if alternate
  1369. (begin
  1370. (emit-arguments<=? asm nreq)
  1371. (emit-jl asm alternate))
  1372. (emit-assert-nargs-ge asm nreq))
  1373. (cond
  1374. (rest?
  1375. (emit-bind-rest asm (+ nreq nopt)))
  1376. (alternate
  1377. (emit-arguments<=? asm (+ nreq nopt))
  1378. ;; The arguments<=? instruction sets NONE to indicate greater-than,
  1379. ;; whereas for <, NONE usually indicates greater-than-or-equal,
  1380. ;; hence the name jge. Perhaps we just need to rename jge to
  1381. ;; br-if-none.
  1382. (emit-jge asm alternate))
  1383. (else
  1384. (emit-assert-nargs-le asm (+ nreq nopt))))
  1385. (emit-alloc-frame asm nlocals))
  1386. (define-macro-assembler (kw-prelude asm nreq nopt rest? kw-indices
  1387. allow-other-keys? nlocals alternate)
  1388. (if alternate
  1389. (begin
  1390. (emit-arguments<=? asm nreq)
  1391. (emit-jl asm alternate)
  1392. (unless rest?
  1393. (emit-positional-arguments<=? asm nreq (+ nreq nopt))
  1394. (emit-jge asm alternate)))
  1395. (emit-assert-nargs-ge asm nreq))
  1396. (let ((ntotal (fold (lambda (kw ntotal)
  1397. (match kw
  1398. (((? keyword?) . idx)
  1399. (max (1+ idx) ntotal))))
  1400. (+ nreq nopt) kw-indices)))
  1401. ;; FIXME: port 581f410f
  1402. (emit-bind-kwargs asm nreq
  1403. (pack-flags allow-other-keys? rest?)
  1404. (+ nreq nopt)
  1405. ntotal
  1406. (intern-constant asm kw-indices))
  1407. (emit-alloc-frame asm nlocals)))
  1408. (define-macro-assembler (label asm sym)
  1409. (hashq-set! (asm-labels asm) sym (asm-start asm)))
  1410. (define-macro-assembler (source asm source)
  1411. (set-asm-sources! asm (acons (asm-start asm) source (asm-sources asm))))
  1412. (define-macro-assembler (definition asm name slot representation)
  1413. (let* ((arity (car (meta-arities (car (asm-meta asm)))))
  1414. (def (vector name slot representation
  1415. (- (asm-start asm) (arity-low-pc arity)))))
  1416. (set-arity-definitions! arity (cons def (arity-definitions arity)))))
  1417. (define-macro-assembler (cache-ref asm dst key)
  1418. (emit-static-ref asm dst (intern-cache-cell asm key)))
  1419. (define-macro-assembler (cache-set! asm key val)
  1420. (emit-static-set! asm val (intern-cache-cell asm key) 0))
  1421. (define-macro-assembler (slot-map asm proc-slot slot-map)
  1422. (unless (zero? slot-map)
  1423. (set-asm-slot-maps! asm (cons
  1424. (cons* (asm-start asm) proc-slot slot-map)
  1425. (asm-slot-maps asm)))))
  1426. ;;;
  1427. ;;; Helper for linking objects.
  1428. ;;;
  1429. (define (make-object asm name bv relocs labels . kwargs)
  1430. "Make a linker object. This helper handles interning the name in the
  1431. shstrtab, assigning the size, allocating a fresh index, and defining a
  1432. corresponding linker symbol for the start of the section."
  1433. (let ((name-idx (intern-section-name! asm (symbol->string name)))
  1434. (index (asm-next-section-number asm)))
  1435. (set-asm-next-section-number! asm (1+ index))
  1436. (make-linker-object (symbol->string name)
  1437. (apply make-elf-section
  1438. #:index index
  1439. #:name name-idx
  1440. #:size (bytevector-length bv)
  1441. kwargs)
  1442. bv relocs
  1443. (cons (make-linker-symbol name 0) labels))))
  1444. ;;;
  1445. ;;; Linking the constant table. This code is somewhat intertwingled
  1446. ;;; with the intern-constant code above, as that procedure also
  1447. ;;; residualizes instructions to initialize constants at load time.
  1448. ;;;
  1449. (define (write-immediate asm buf pos bits)
  1450. (let ((endianness (asm-endianness asm)))
  1451. (case (asm-word-size asm)
  1452. ((4) (bytevector-u32-set! buf pos bits endianness))
  1453. ((8) (bytevector-u64-set! buf pos bits endianness))
  1454. (else (error "bad word size" asm)))))
  1455. (define (write-placeholder asm buf pos)
  1456. (write-immediate asm buf pos (immediate-bits asm #f)))
  1457. (define (emit-init-constants asm)
  1458. "If there is writable data that needs initialization at runtime, emit
  1459. a procedure to do that and return its label. Otherwise return
  1460. @code{#f}."
  1461. (let ((inits (asm-inits asm)))
  1462. (and (not (null? inits))
  1463. (let ((label (gensym "init-constants")))
  1464. (emit-text asm
  1465. `((begin-program ,label ())
  1466. (assert-nargs-ee/locals 1 1)
  1467. ,@(reverse inits)
  1468. (reset-frame 1)
  1469. (load-constant 0 ,*unspecified*)
  1470. (return-values)
  1471. (end-program)))
  1472. label))))
  1473. (define (link-data asm data name)
  1474. "Link the static data for a program into the @var{name} section (which
  1475. should be .data or .rodata), and return the resulting linker object.
  1476. @var{data} should be a vhash mapping objects to labels."
  1477. (define (align address alignment)
  1478. (+ address
  1479. (modulo (- alignment (modulo address alignment)) alignment)))
  1480. (define tc7-vector #x0d)
  1481. (define vector-immutable-flag #x80)
  1482. (define tc7-string #x15)
  1483. (define string-read-only-flag #x200)
  1484. (define tc7-stringbuf #x27)
  1485. (define stringbuf-wide-flag #x400)
  1486. (define tc7-syntax #x3d)
  1487. (define tc7-program #x45)
  1488. (define tc7-bytevector #x4d)
  1489. ;; This flag is intended to be left-shifted by 7 bits.
  1490. (define bytevector-immutable-flag #x200)
  1491. (define tc7-array #x5d)
  1492. (define tc7-bitvector #x5f)
  1493. (define bitvector-immutable-flag #x80)
  1494. (let ((word-size (asm-word-size asm))
  1495. (endianness (asm-endianness asm)))
  1496. (define (byte-length x)
  1497. (cond
  1498. ((stringbuf? x)
  1499. (let ((x (stringbuf-string x)))
  1500. (+ (* 2 word-size)
  1501. (case (string-bytes-per-char x)
  1502. ((1) (1+ (string-length x)))
  1503. ((4) (* (1+ (string-length x)) 4))
  1504. (else (error "bad string bytes per char" x))))))
  1505. ((static-procedure? x)
  1506. (* 2 word-size))
  1507. ((string? x)
  1508. (* 4 word-size))
  1509. ((pair? x)
  1510. (* 2 word-size))
  1511. ((simple-vector? x)
  1512. (* (1+ (vector-length x)) word-size))
  1513. ((syntax? x)
  1514. (* 4 word-size))
  1515. ((jit-data? x)
  1516. (case word-size
  1517. ((4) (+ word-size (* 4 3)))
  1518. ((8) (+ word-size (* 4 4))) ;; One additional uint32_t for padding.
  1519. (else (error word-size))))
  1520. ((simple-uniform-vector? x)
  1521. (* 4 word-size))
  1522. ((uniform-vector-backing-store? x)
  1523. (bytevector-length (uniform-vector-backing-store-bytes x)))
  1524. ((array? x)
  1525. (* word-size (+ 3 (* 3 (array-rank x)))))
  1526. (else
  1527. word-size)))
  1528. (define (write-constant-reference buf pos x)
  1529. (let ((bits (immediate-bits asm x)))
  1530. (if bits
  1531. (write-immediate asm buf pos bits)
  1532. ;; The asm-inits will fix up any reference to a
  1533. ;; non-immediate.
  1534. (write-placeholder asm buf pos))))
  1535. (define (write buf pos obj)
  1536. (cond
  1537. ((stringbuf? obj)
  1538. (let* ((x (stringbuf-string obj))
  1539. (len (string-length x))
  1540. (tag (logior tc7-stringbuf
  1541. (if (= (string-bytes-per-char x) 1)
  1542. 0
  1543. stringbuf-wide-flag))))
  1544. (case word-size
  1545. ((4)
  1546. (bytevector-u32-set! buf pos tag endianness)
  1547. (bytevector-u32-set! buf (+ pos 4) len endianness))
  1548. ((8)
  1549. (bytevector-u64-set! buf pos tag endianness)
  1550. (bytevector-u64-set! buf (+ pos 8) len endianness))
  1551. (else
  1552. (error "bad word size" asm)))
  1553. (let ((pos (+ pos (* word-size 2))))
  1554. (case (string-bytes-per-char x)
  1555. ((1)
  1556. (let lp ((i 0))
  1557. (if (< i len)
  1558. (let ((u8 (char->integer (string-ref x i))))
  1559. (bytevector-u8-set! buf (+ pos i) u8)
  1560. (lp (1+ i)))
  1561. (bytevector-u8-set! buf (+ pos i) 0))))
  1562. ((4)
  1563. (let lp ((i 0))
  1564. (if (< i len)
  1565. (let ((u32 (char->integer (string-ref x i))))
  1566. (bytevector-u32-set! buf (+ pos (* i 4)) u32 endianness)
  1567. (lp (1+ i)))
  1568. (bytevector-u32-set! buf (+ pos (* i 4)) 0 endianness))))
  1569. (else (error "bad string bytes per char" x))))))
  1570. ((static-procedure? obj)
  1571. (case word-size
  1572. ((4)
  1573. (bytevector-u32-set! buf pos tc7-program endianness)
  1574. (bytevector-u32-set! buf (+ pos 4) 0 endianness))
  1575. ((8)
  1576. (bytevector-u64-set! buf pos tc7-program endianness)
  1577. (bytevector-u64-set! buf (+ pos 8) 0 endianness))
  1578. (else (error "bad word size"))))
  1579. ((cache-cell? obj)
  1580. (write-placeholder asm buf pos))
  1581. ((jit-data? obj)
  1582. ;; Default initialization of 0.
  1583. (values))
  1584. ((string? obj)
  1585. (let ((tag (logior tc7-string string-read-only-flag)))
  1586. (case word-size
  1587. ((4)
  1588. (bytevector-u32-set! buf pos tag endianness)
  1589. (write-placeholder asm buf (+ pos 4)) ; stringbuf
  1590. (bytevector-u32-set! buf (+ pos 8) 0 endianness)
  1591. (bytevector-u32-set! buf (+ pos 12) (string-length obj) endianness))
  1592. ((8)
  1593. (bytevector-u64-set! buf pos tag endianness)
  1594. (write-placeholder asm buf (+ pos 8)) ; stringbuf
  1595. (bytevector-u64-set! buf (+ pos 16) 0 endianness)
  1596. (bytevector-u64-set! buf (+ pos 24) (string-length obj) endianness))
  1597. (else (error "bad word size")))))
  1598. ((pair? obj)
  1599. (write-constant-reference buf pos (car obj))
  1600. (write-constant-reference buf (+ pos word-size) (cdr obj)))
  1601. ((simple-vector? obj)
  1602. (let* ((len (vector-length obj))
  1603. (tag (logior tc7-vector vector-immutable-flag (ash len 8))))
  1604. (case word-size
  1605. ((4) (bytevector-u32-set! buf pos tag endianness))
  1606. ((8) (bytevector-u64-set! buf pos tag endianness))
  1607. (else (error "bad word size")))
  1608. (let lp ((i 0))
  1609. (when (< i (vector-length obj))
  1610. (let ((pos (+ pos word-size (* i word-size)))
  1611. (elt (vector-ref obj i)))
  1612. (write-constant-reference buf pos elt)
  1613. (lp (1+ i)))))))
  1614. ((symbol? obj)
  1615. (write-placeholder asm buf pos))
  1616. ((keyword? obj)
  1617. (write-placeholder asm buf pos))
  1618. ((syntax? obj)
  1619. (case word-size
  1620. ((4) (bytevector-u32-set! buf pos tc7-syntax endianness))
  1621. ((8) (bytevector-u64-set! buf pos tc7-syntax endianness))
  1622. (else (error "bad word size")))
  1623. (write-constant-reference buf (+ pos (* 1 word-size))
  1624. (syntax-expression obj))
  1625. (write-constant-reference buf (+ pos (* 2 word-size))
  1626. (syntax-wrap obj))
  1627. (write-constant-reference buf (+ pos (* 3 word-size))
  1628. (syntax-module obj)))
  1629. ((number? obj)
  1630. (write-placeholder asm buf pos))
  1631. ((simple-uniform-vector? obj)
  1632. (let ((tag (if (bitvector? obj)
  1633. (logior tc7-bitvector
  1634. bitvector-immutable-flag)
  1635. (logior tc7-bytevector
  1636. ;; Bytevector immutable flag also shifted
  1637. ;; left. TAGS-SENSITIVE
  1638. (ash (logior bytevector-immutable-flag
  1639. (array-type-code obj))
  1640. 7)))))
  1641. (case word-size
  1642. ((4)
  1643. (bytevector-u32-set! buf pos tag endianness)
  1644. (bytevector-u32-set! buf (+ pos 4)
  1645. (if (bitvector? obj)
  1646. (bitvector-length obj)
  1647. (bytevector-length obj))
  1648. endianness) ; length
  1649. (bytevector-u32-set! buf (+ pos 8) 0 endianness) ; pointer
  1650. (write-placeholder asm buf (+ pos 12))) ; owner
  1651. ((8)
  1652. (bytevector-u64-set! buf pos tag endianness)
  1653. (bytevector-u64-set! buf (+ pos 8)
  1654. (if (bitvector? obj)
  1655. (bitvector-length obj)
  1656. (bytevector-length obj))
  1657. endianness) ; length
  1658. (bytevector-u64-set! buf (+ pos 16) 0 endianness) ; pointer
  1659. (write-placeholder asm buf (+ pos 24))) ; owner
  1660. (else (error "bad word size")))))
  1661. ((uniform-vector-backing-store? obj)
  1662. (let ((bv (uniform-vector-backing-store-bytes obj)))
  1663. (bytevector-copy! bv 0 buf pos (bytevector-length bv))
  1664. (unless (eq? endianness (native-endianness))
  1665. (case (uniform-vector-backing-store-element-size obj)
  1666. ((1) #f) ;; Nothing to do.
  1667. ((2) (byte-swap/2! buf pos (+ pos (bytevector-length bv))))
  1668. ((4) (byte-swap/4! buf pos (+ pos (bytevector-length bv))))
  1669. ((8) (byte-swap/8! buf pos (+ pos (bytevector-length bv))))
  1670. (else (error "FIXME: Implement byte order swap"))))))
  1671. ((array? obj)
  1672. (let-values
  1673. ;; array tag + rank + contp flag: see libguile/arrays.h .
  1674. (((tag) (logior tc7-array (ash (array-rank obj) 17) (ash 1 16)))
  1675. ((bv-set! bvs-set!)
  1676. (case word-size
  1677. ((4) (values bytevector-u32-set! bytevector-s32-set!))
  1678. ((8) (values bytevector-u64-set! bytevector-s64-set!))
  1679. (else (error "bad word size")))))
  1680. (bv-set! buf pos tag endianness)
  1681. (write-placeholder asm buf (+ pos word-size)) ; root vector (fixed later)
  1682. (bv-set! buf (+ pos (* word-size 2)) 0 endianness) ; base
  1683. (let lp ((pos (+ pos (* word-size 3)))
  1684. (bounds (array-shape obj))
  1685. (incs (shared-array-increments obj)))
  1686. (when (pair? bounds)
  1687. (bvs-set! buf pos (first (first bounds)) endianness)
  1688. (bvs-set! buf (+ pos word-size) (second (first bounds)) endianness)
  1689. (bvs-set! buf (+ pos (* word-size 2)) (first incs) endianness)
  1690. (lp (+ pos (* 3 word-size)) (cdr bounds) (cdr incs))))))
  1691. (else
  1692. (error "unrecognized object" obj))))
  1693. (define (add-relocs obj pos relocs)
  1694. (match obj
  1695. (($ <jit-data> low-pc high-pc)
  1696. ;; Patch "start" and "end" fields of "struct jit_data".
  1697. (cons* (make-linker-reloc 'rel32/1 (+ pos word-size 4)
  1698. (+ low-pc word-size 4)
  1699. '.rtl-text)
  1700. (make-linker-reloc 'rel32/1 (+ pos word-size 8)
  1701. (+ high-pc word-size 8)
  1702. '.rtl-text)
  1703. relocs))
  1704. (_ relocs)))
  1705. (cond
  1706. ((vlist-null? data) #f)
  1707. (else
  1708. (let* ((byte-len (vhash-fold (lambda (k v len)
  1709. (+ (byte-length k) (align len 16))) ; temporary alignment hack XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
  1710. 0 data))
  1711. (buf (make-bytevector byte-len 0)))
  1712. (let lp ((i 0) (pos 0) (relocs '()) (symbols '()))
  1713. (if (< i (vlist-length data))
  1714. (match (vlist-ref data i)
  1715. ((obj . obj-label)
  1716. (write buf pos obj)
  1717. (lp (1+ i)
  1718. (align (+ (byte-length obj) pos) 16) ; temporary alignment hack XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
  1719. (add-relocs obj pos relocs)
  1720. (cons (make-linker-symbol obj-label pos) symbols))))
  1721. (make-object asm name buf relocs symbols
  1722. #:flags (match name
  1723. ('.data (logior SHF_ALLOC SHF_WRITE))
  1724. ('.rodata SHF_ALLOC))))))))))
  1725. (define (link-constants asm)
  1726. "Link sections to hold constants needed by the program text emitted
  1727. using @var{asm}.
  1728. Returns three values: an object for the .rodata section, an object for
  1729. the .data section, and a label for an initialization procedure. Any of
  1730. these may be @code{#f}."
  1731. (define (shareable? x)
  1732. (cond
  1733. ((stringbuf? x) #t)
  1734. ((pair? x)
  1735. (and (immediate-bits asm (car x)) (immediate-bits asm (cdr x))))
  1736. ((simple-vector? x)
  1737. (let lp ((i 0))
  1738. (or (= i (vector-length x))
  1739. (and (immediate-bits asm (vector-ref x i))
  1740. (lp (1+ i))))))
  1741. ((uniform-vector-backing-store? x) #t)
  1742. (else #f)))
  1743. (let* ((init-constants (emit-init-constants asm))
  1744. (constants (asm-constants asm))
  1745. (len (vlist-length constants)))
  1746. (let lp ((i 0)
  1747. (ro vlist-null)
  1748. (rw vlist-null))
  1749. (if (= i len)
  1750. (values (link-data asm ro '.rodata)
  1751. (link-data asm rw '.data)
  1752. init-constants)
  1753. (match (vlist-ref constants i)
  1754. ((obj . label)
  1755. (if (shareable? obj)
  1756. (lp (1+ i) (vhash-consq obj label ro) rw)
  1757. (lp (1+ i) ro (vhash-consq obj label rw)))))))))
  1758. ;;;
  1759. ;;; Linking program text.
  1760. ;;;
  1761. (define (process-relocs buf relocs labels)
  1762. "Patch up internal x8-s24 relocations, and any s32 relocations that
  1763. reference symbols in the text section. Return a list of linker
  1764. relocations for references to symbols defined outside the text section."
  1765. (fold
  1766. (lambda (reloc tail)
  1767. (match reloc
  1768. ((type label base offset)
  1769. (let ((abs (hashq-ref labels label))
  1770. (dst (+ base offset)))
  1771. (case type
  1772. ((s32)
  1773. (if abs
  1774. (let ((rel (- abs base)))
  1775. (unless (zero? (logand rel #x3))
  1776. (error "reloc not in 32-bit units!"))
  1777. (bytevector-s32-native-set! buf dst (ash rel -2))
  1778. tail)
  1779. (cons (make-linker-reloc 'rel32/4 dst offset label)
  1780. tail)))
  1781. ((x8-s24)
  1782. (unless abs
  1783. (error "unbound near relocation" reloc))
  1784. (let ((rel (- abs base))
  1785. (u32 (bytevector-u32-native-ref buf dst)))
  1786. (unless (zero? (logand rel #x3))
  1787. (error "reloc not in 32-bit units!"))
  1788. (bytevector-u32-native-set! buf dst
  1789. (pack-u8-s24 (logand u32 #xff)
  1790. (ash rel -2)))
  1791. tail))
  1792. (else (error "bad relocation kind" reloc)))))))
  1793. '()
  1794. relocs))
  1795. (define (process-labels labels)
  1796. "Define linker symbols for the label-offset map in @var{labels}.
  1797. The offsets are expected to be expressed in words."
  1798. (hash-map->list (lambda (label loc)
  1799. (make-linker-symbol label loc))
  1800. labels))
  1801. (define (link-text-object asm)
  1802. "Link the .rtl-text section, swapping the endianness of the bytes if
  1803. needed."
  1804. (let ((buf (make-bytevector (asm-pos asm))))
  1805. (bytevector-copy! (asm-buf asm) 0 buf 0 (bytevector-length buf))
  1806. (unless (eq? (asm-endianness asm) (native-endianness))
  1807. (byte-swap/4! buf))
  1808. (make-object asm '.rtl-text
  1809. buf
  1810. (process-relocs buf (asm-relocs asm)
  1811. (asm-labels asm))
  1812. (process-labels (asm-labels asm)))))
  1813. ;;;
  1814. ;;; Create the frame maps. These maps are used by GC to identify dead
  1815. ;;; slots in pending call frames, to avoid marking them. We only do
  1816. ;;; this when frame makes a non-tail call, as that is the common case.
  1817. ;;; Only the topmost frame will see a GC at any other point, but we mark
  1818. ;;; top frames conservatively as serializing live slot maps at every
  1819. ;;; instruction would take up too much space in the object file.
  1820. ;;;
  1821. ;; The .guile.frame-maps section starts with two packed u32 values: one
  1822. ;; indicating the offset of the first byte of the .rtl-text section, and
  1823. ;; another indicating the relative offset in bytes of the slots data.
  1824. (define frame-maps-prefix-len 8)
  1825. ;; Each header is 8 bytes: 4 for the offset from .rtl_text, and 4 for
  1826. ;; the offset of the slot map from the beginning of the
  1827. ;; .guile.frame-maps section. The length of a frame map depends on the
  1828. ;; frame size at the call site, and is not encoded into this section as
  1829. ;; it is available at run-time.
  1830. (define frame-map-header-len 8)
  1831. (define (link-frame-maps asm)
  1832. (define (map-byte-length proc-slot)
  1833. (ceiling-quotient (* 2 (- proc-slot 2)) 8))
  1834. (define (make-frame-maps maps count map-len)
  1835. (let* ((endianness (asm-endianness asm))
  1836. (header-pos frame-maps-prefix-len)
  1837. (map-pos (+ header-pos (* count frame-map-header-len)))
  1838. (bv (make-bytevector (+ map-pos map-len) 0)))
  1839. (bytevector-u32-set! bv 4 map-pos endianness)
  1840. (let lp ((maps maps) (header-pos header-pos) (map-pos map-pos))
  1841. (match maps
  1842. (()
  1843. (make-object asm '.guile.frame-maps bv
  1844. (list (make-linker-reloc 'abs32/1 0 0 '.rtl-text))
  1845. '() #:type SHT_PROGBITS #:flags SHF_ALLOC))
  1846. (((pos proc-slot . map) . maps)
  1847. (bytevector-u32-set! bv header-pos pos endianness)
  1848. (bytevector-u32-set! bv (+ header-pos 4) map-pos endianness)
  1849. (let write-bytes ((map-pos map-pos)
  1850. (map map)
  1851. (byte-length (map-byte-length proc-slot)))
  1852. (if (zero? byte-length)
  1853. (lp maps (+ header-pos frame-map-header-len) map-pos)
  1854. (begin
  1855. (bytevector-u8-set! bv map-pos (logand map #xff))
  1856. (write-bytes (1+ map-pos) (ash map -8)
  1857. (1- byte-length))))))))))
  1858. (match (asm-slot-maps asm)
  1859. (() #f)
  1860. (in
  1861. (let lp ((in in) (out '()) (count 0) (map-len 0))
  1862. (match in
  1863. (() (make-frame-maps out count map-len))
  1864. (((and head (pos proc-slot . map)) . in)
  1865. (lp in (cons head out)
  1866. (1+ count)
  1867. (+ (map-byte-length proc-slot) map-len))))))))
  1868. ;;;
  1869. ;;; Linking other sections of the ELF file, like the dynamic segment,
  1870. ;;; the symbol table, etc.
  1871. ;;;
  1872. ;; FIXME: Define these somewhere central, shared with C.
  1873. (define *bytecode-major-version* #x0300)
  1874. (define *bytecode-minor-version* 1)
  1875. (define (link-dynamic-section asm text rw rw-init frame-maps)
  1876. "Link the dynamic section for an ELF image with bytecode @var{text},
  1877. given the writable data section @var{rw} needing fixup from the
  1878. procedure with label @var{rw-init}. @var{rw-init} may be false. If
  1879. @var{rw} is true, it will be added to the GC roots at runtime."
  1880. (define-syntax-rule (emit-dynamic-section word-size %set-uword! reloc-type)
  1881. (let* ((endianness (asm-endianness asm))
  1882. (words 6)
  1883. (words (if rw (+ words 4) words))
  1884. (words (if rw-init (+ words 2) words))
  1885. (words (if frame-maps (+ words 2) words))
  1886. (bv (make-bytevector (* word-size words) 0))
  1887. (set-uword!
  1888. (lambda (i uword)
  1889. (%set-uword! bv (* i word-size) uword endianness)))
  1890. (relocs '())
  1891. (set-label!
  1892. (lambda (i label)
  1893. (set! relocs (cons (make-linker-reloc 'reloc-type
  1894. (* i word-size) 0 label)
  1895. relocs))
  1896. (%set-uword! bv (* i word-size) 0 endianness))))
  1897. (set-uword! 0 DT_GUILE_VM_VERSION)
  1898. (set-uword! 1 (logior (ash *bytecode-major-version* 16)
  1899. *bytecode-minor-version*))
  1900. (set-uword! 2 DT_GUILE_ENTRY)
  1901. (set-label! 3 '.rtl-text)
  1902. (when rw
  1903. ;; Add roots to GC.
  1904. (set-uword! 4 DT_GUILE_GC_ROOT)
  1905. (set-label! 5 '.data)
  1906. (set-uword! 6 DT_GUILE_GC_ROOT_SZ)
  1907. (set-uword! 7 (bytevector-length (linker-object-bv rw)))
  1908. (when rw-init
  1909. (set-uword! 8 DT_INIT) ; constants
  1910. (set-label! 9 rw-init)))
  1911. (when frame-maps
  1912. (set-uword! (- words 4) DT_GUILE_FRAME_MAPS)
  1913. (set-label! (- words 3) '.guile.frame-maps))
  1914. (set-uword! (- words 2) DT_NULL)
  1915. (set-uword! (- words 1) 0)
  1916. (make-object asm '.dynamic bv relocs '()
  1917. #:type SHT_DYNAMIC #:flags SHF_ALLOC)))
  1918. (case (asm-word-size asm)
  1919. ((4) (emit-dynamic-section 4 bytevector-u32-set! abs32/1))
  1920. ((8) (emit-dynamic-section 8 bytevector-u64-set! abs64/1))
  1921. (else (error "bad word size" asm))))
  1922. (define (link-shstrtab asm)
  1923. "Link the string table for the section headers."
  1924. (intern-section-name! asm ".shstrtab")
  1925. (make-object asm '.shstrtab
  1926. (link-string-table! (asm-shstrtab asm))
  1927. '() '()
  1928. #:type SHT_STRTAB #:flags 0))
  1929. (define (link-symtab text-section asm)
  1930. (let* ((endianness (asm-endianness asm))
  1931. (word-size (asm-word-size asm))
  1932. (size (elf-symbol-len word-size))
  1933. (meta (reverse (asm-meta asm)))
  1934. (n (length meta))
  1935. (strtab (make-string-table))
  1936. (bv (make-bytevector (* n size) 0)))
  1937. (define (intern-string! name)
  1938. (string-table-intern! strtab (if name (symbol->string name) "")))
  1939. (for-each
  1940. (lambda (meta n)
  1941. (let ((name (intern-string! (meta-name meta))))
  1942. (write-elf-symbol bv (* n size) endianness word-size
  1943. (make-elf-symbol
  1944. #:name name
  1945. ;; Symbol value and size are measured in
  1946. ;; bytes, not u32s.
  1947. #:value (meta-low-pc meta)
  1948. #:size (- (meta-high-pc meta)
  1949. (meta-low-pc meta))
  1950. #:type STT_FUNC
  1951. #:visibility STV_HIDDEN
  1952. #:shndx (elf-section-index text-section)))))
  1953. meta (iota n))
  1954. (let ((strtab (make-object asm '.strtab
  1955. (link-string-table! strtab)
  1956. '() '()
  1957. #:type SHT_STRTAB #:flags 0)))
  1958. (values (make-object asm '.symtab
  1959. bv
  1960. '() '()
  1961. #:type SHT_SYMTAB #:flags 0 #:entsize size
  1962. #:link (elf-section-index
  1963. (linker-object-section strtab)))
  1964. strtab))))
  1965. ;;; The .guile.arities section describes the arities that a function can
  1966. ;;; have. It is in two parts: a sorted array of headers describing
  1967. ;;; basic arities, and an array of links out to a string table (and in
  1968. ;;; the case of keyword arguments, to the data section) for argument
  1969. ;;; names. The whole thing is prefixed by a uint32 indicating the
  1970. ;;; offset of the end of the headers array.
  1971. ;;;
  1972. ;;; The arity headers array is a packed array of structures of the form:
  1973. ;;;
  1974. ;;; struct arity_header {
  1975. ;;; uint32_t low_pc;
  1976. ;;; uint32_t high_pc;
  1977. ;;; uint32_t offset;
  1978. ;;; uint32_t flags;
  1979. ;;; uint32_t nreq;
  1980. ;;; uint32_t nopt;
  1981. ;;; uint32_t nlocals;
  1982. ;;; }
  1983. ;;;
  1984. ;;; All of the offsets and addresses are 32 bits. We can expand in the
  1985. ;;; future to use 64-bit offsets if appropriate, but there are other
  1986. ;;; aspects of bytecode that constrain us to a total image that fits in
  1987. ;;; 32 bits, so for the moment we'll simplify the problem space.
  1988. ;;;
  1989. ;;; The following flags values are defined:
  1990. ;;;
  1991. ;;; #x1: has-rest?
  1992. ;;; #x2: allow-other-keys?
  1993. ;;; #x4: has-keyword-args?
  1994. ;;; #x8: is-case-lambda?
  1995. ;;; #x10: is-in-case-lambda?
  1996. ;;;
  1997. ;;; Functions with a single arity specify their number of required and
  1998. ;;; optional arguments in nreq and nopt, and do not have the
  1999. ;;; is-case-lambda? flag set. Their "offset" member links to an array
  2000. ;;; of pointers into the associated .guile.arities.strtab string table,
  2001. ;;; identifying the argument names. This offset is relative to the
  2002. ;;; start of the .guile.arities section.
  2003. ;;;
  2004. ;;; If the arity has keyword arguments -- if has-keyword-args? is set in
  2005. ;;; the flags -- the first uint32 pointed to by offset encodes a link to
  2006. ;;; the "keyword indices" literal, in the data section. Then follow the
  2007. ;;; names for all locals, in order, as uleb128 values. The required
  2008. ;;; arguments will be the first locals, followed by the optionals,
  2009. ;;; followed by the rest argument if if has-rest? is set. The names
  2010. ;;; point into the associated string table section.
  2011. ;;;
  2012. ;;; Functions with no arities have no arities information present in the
  2013. ;;; .guile.arities section.
  2014. ;;;
  2015. ;;; Functions with multiple arities are preceded by a header with
  2016. ;;; is-case-lambda? set. All other fields are 0, except low-pc and
  2017. ;;; high-pc which should be the bounds of the whole function. Headers
  2018. ;;; for the individual arities follow, with the is-in-case-lambda? flag
  2019. ;;; set. In this way the whole headers array is sorted in increasing
  2020. ;;; low-pc order, and case-lambda clauses are contained within the
  2021. ;;; [low-pc, high-pc] of the case-lambda header.
  2022. ;; Length of the prefix to the arities section, in bytes.
  2023. (define arities-prefix-len 4)
  2024. ;; Length of an arity header, in bytes.
  2025. (define arity-header-len (* 7 4))
  2026. ;; Some helpers.
  2027. (define (put-uleb128 port val)
  2028. (let lp ((val val))
  2029. (let ((next (ash val -7)))
  2030. (if (zero? next)
  2031. (put-u8 port val)
  2032. (begin
  2033. (put-u8 port (logior #x80 (logand val #x7f)))
  2034. (lp next))))))
  2035. (define (put-sleb128 port val)
  2036. (let lp ((val val))
  2037. (if (<= 0 (+ val 64) 127)
  2038. (put-u8 port (logand val #x7f))
  2039. (begin
  2040. (put-u8 port (logior #x80 (logand val #x7f)))
  2041. (lp (ash val -7))))))
  2042. (define (port-position port)
  2043. (seek port 0 SEEK_CUR))
  2044. (define-inline (pack-arity-flags has-rest? allow-other-keys?
  2045. has-keyword-args? is-case-lambda?
  2046. is-in-case-lambda?)
  2047. (logior (if has-rest? (ash 1 0) 0)
  2048. (if allow-other-keys? (ash 1 1) 0)
  2049. (if has-keyword-args? (ash 1 2) 0)
  2050. (if is-case-lambda? (ash 1 3) 0)
  2051. (if is-in-case-lambda? (ash 1 4) 0)))
  2052. (define (write-arities asm metas headers names-port strtab)
  2053. (define (write-header pos low-pc high-pc offset flags nreq nopt nlocals)
  2054. (unless (<= (+ nreq nopt) nlocals)
  2055. (error "forgot to emit definition instructions?"))
  2056. (bytevector-u32-set! headers pos low-pc (asm-endianness asm))
  2057. (bytevector-u32-set! headers (+ pos 4) high-pc (asm-endianness asm))
  2058. (bytevector-u32-set! headers (+ pos 8) offset (asm-endianness asm))
  2059. (bytevector-u32-set! headers (+ pos 12) flags (asm-endianness asm))
  2060. (bytevector-u32-set! headers (+ pos 16) nreq (asm-endianness asm))
  2061. (bytevector-u32-set! headers (+ pos 20) nopt (asm-endianness asm))
  2062. (bytevector-u32-set! headers (+ pos 24) nlocals (asm-endianness asm)))
  2063. (define (write-kw-indices kw-indices relocs)
  2064. ;; FIXME: Assert that kw-indices is already interned.
  2065. (if (pair? kw-indices)
  2066. (let ((pos (+ (bytevector-length headers)
  2067. (port-position names-port)))
  2068. (label (intern-constant asm kw-indices)))
  2069. (put-bytevector names-port #vu8(0 0 0 0))
  2070. (cons (make-linker-reloc 'abs32/1 pos 0 label) relocs))
  2071. relocs))
  2072. (define (write-arity pos arity in-case-lambda? relocs)
  2073. (write-header pos (arity-low-pc arity)
  2074. (arity-high-pc arity)
  2075. ;; FIXME: Seems silly to add on bytevector-length of
  2076. ;; headers, given the arities-prefix.
  2077. (+ (bytevector-length headers) (port-position names-port))
  2078. (pack-arity-flags (arity-rest arity)
  2079. (arity-allow-other-keys? arity)
  2080. (pair? (arity-kw-indices arity))
  2081. #f
  2082. in-case-lambda?)
  2083. (length (arity-req arity))
  2084. (length (arity-opt arity))
  2085. (length (arity-definitions arity)))
  2086. (let ((relocs (write-kw-indices (arity-kw-indices arity) relocs)))
  2087. ;; Write local names.
  2088. (let lp ((definitions (arity-definitions arity)))
  2089. (match definitions
  2090. (() relocs)
  2091. ((#(name slot representation def) . definitions)
  2092. (let ((sym (if (symbol? name)
  2093. (string-table-intern! strtab (symbol->string name))
  2094. 0)))
  2095. (put-uleb128 names-port sym)
  2096. (lp definitions)))))
  2097. ;; Now write their definitions.
  2098. (let lp ((definitions (arity-definitions arity)))
  2099. (match definitions
  2100. (() relocs)
  2101. ((#(name slot representation def) . definitions)
  2102. (put-uleb128 names-port def)
  2103. (let ((tag (case representation
  2104. ((scm) 0)
  2105. ((f64) 1)
  2106. ((u64) 2)
  2107. ((s64) 3)
  2108. ((ptr) 4)
  2109. (else (error "what!" representation)))))
  2110. (put-uleb128 names-port (logior (ash slot 3) tag)))
  2111. (lp definitions))))))
  2112. (let lp ((metas metas) (pos arities-prefix-len) (relocs '()))
  2113. (match metas
  2114. (()
  2115. (unless (= pos (bytevector-length headers))
  2116. (error "expected to fully fill the bytevector"
  2117. pos (bytevector-length headers)))
  2118. relocs)
  2119. ((meta . metas)
  2120. (match (meta-arities meta)
  2121. (() (lp metas pos relocs))
  2122. ((arity)
  2123. (lp metas
  2124. (+ pos arity-header-len)
  2125. (write-arity pos arity #f relocs)))
  2126. (arities
  2127. ;; Write a case-lambda header, then individual arities.
  2128. ;; The case-lambda header's offset link is 0.
  2129. (write-header pos (meta-low-pc meta) (meta-high-pc meta) 0
  2130. (pack-arity-flags #f #f #f #t #f) 0 0 0)
  2131. (let lp* ((arities arities) (pos (+ pos arity-header-len))
  2132. (relocs relocs))
  2133. (match arities
  2134. (() (lp metas pos relocs))
  2135. ((arity . arities)
  2136. (lp* arities
  2137. (+ pos arity-header-len)
  2138. (write-arity pos arity #t relocs)))))))))))
  2139. (define (link-arities asm)
  2140. (define (meta-arities-header-size meta)
  2141. (define (lambda-size arity)
  2142. arity-header-len)
  2143. (define (case-lambda-size arities)
  2144. (fold +
  2145. arity-header-len ;; case-lambda header
  2146. (map lambda-size arities))) ;; the cases
  2147. (match (meta-arities meta)
  2148. (() 0)
  2149. ((arity) (lambda-size arity))
  2150. (arities (case-lambda-size arities))))
  2151. (define (bytevector-append a b)
  2152. (let ((out (make-bytevector (+ (bytevector-length a)
  2153. (bytevector-length b)))))
  2154. (bytevector-copy! a 0 out 0 (bytevector-length a))
  2155. (bytevector-copy! b 0 out (bytevector-length a) (bytevector-length b))
  2156. out))
  2157. (let* ((endianness (asm-endianness asm))
  2158. (metas (reverse (asm-meta asm)))
  2159. (header-size (fold (lambda (meta size)
  2160. (+ size (meta-arities-header-size meta)))
  2161. arities-prefix-len
  2162. metas))
  2163. (strtab (make-string-table))
  2164. (headers (make-bytevector header-size 0)))
  2165. (bytevector-u32-set! headers 0 (bytevector-length headers) endianness)
  2166. (let-values (((names-port get-name-bv) (open-bytevector-output-port)))
  2167. (let* ((relocs (write-arities asm metas headers names-port strtab))
  2168. (strtab (make-object asm '.guile.arities.strtab
  2169. (link-string-table! strtab)
  2170. '() '()
  2171. #:type SHT_STRTAB #:flags 0)))
  2172. (values (make-object asm '.guile.arities
  2173. (bytevector-append headers (get-name-bv))
  2174. relocs '()
  2175. #:type SHT_PROGBITS #:flags 0
  2176. #:link (elf-section-index
  2177. (linker-object-section strtab)))
  2178. strtab)))))
  2179. ;;;
  2180. ;;; The .guile.docstrs section is a packed, sorted array of (pc, str)
  2181. ;;; values. Pc and str are both 32 bits wide. (Either could change to
  2182. ;;; 64 bits if appropriate in the future.) Pc is the address of the
  2183. ;;; entry to a program, relative to the start of the text section, in
  2184. ;;; bytes, and str is an index into the associated .guile.docstrs.strtab
  2185. ;;; string table section.
  2186. ;;;
  2187. ;; The size of a docstrs entry, in bytes.
  2188. (define docstr-size 8)
  2189. (define (link-docstrs asm)
  2190. (define (find-docstrings)
  2191. (filter-map (lambda (meta)
  2192. (define (is-documentation? pair)
  2193. (eq? (car pair) 'documentation))
  2194. (let* ((props (meta-properties meta))
  2195. (tail (find-tail is-documentation? props)))
  2196. (and tail
  2197. (not (find-tail is-documentation? (cdr tail)))
  2198. (string? (cdar tail))
  2199. (cons (meta-low-pc meta) (cdar tail)))))
  2200. (reverse (asm-meta asm))))
  2201. (let* ((endianness (asm-endianness asm))
  2202. (docstrings (find-docstrings))
  2203. (strtab (make-string-table))
  2204. (bv (make-bytevector (* (length docstrings) docstr-size) 0)))
  2205. (fold (lambda (pair pos)
  2206. (match pair
  2207. ((pc . string)
  2208. (bytevector-u32-set! bv pos pc endianness)
  2209. (bytevector-u32-set! bv (+ pos 4)
  2210. (string-table-intern! strtab string)
  2211. endianness)
  2212. (+ pos docstr-size))))
  2213. 0
  2214. docstrings)
  2215. (let ((strtab (make-object asm '.guile.docstrs.strtab
  2216. (link-string-table! strtab)
  2217. '() '()
  2218. #:type SHT_STRTAB #:flags 0)))
  2219. (values (make-object asm '.guile.docstrs
  2220. bv
  2221. '() '()
  2222. #:type SHT_PROGBITS #:flags 0
  2223. #:link (elf-section-index
  2224. (linker-object-section strtab)))
  2225. strtab))))
  2226. ;;;
  2227. ;;; The .guile.procprops section is a packed, sorted array of (pc, addr)
  2228. ;;; values. Pc and addr are both 32 bits wide. (Either could change to
  2229. ;;; 64 bits if appropriate in the future.) Pc is the address of the
  2230. ;;; entry to a program, relative to the start of the text section, and
  2231. ;;; addr is the address of the associated properties alist, relative to
  2232. ;;; the start of the ELF image.
  2233. ;;;
  2234. ;;; Since procedure properties are stored in the data sections, we need
  2235. ;;; to link the procedures property section first. (Note that this
  2236. ;;; constraint does not apply to the arities section, which may
  2237. ;;; reference the data sections via the kw-indices literal, because
  2238. ;;; assembling the text section already makes sure that the kw-indices
  2239. ;;; are interned.)
  2240. ;;;
  2241. ;; The size of a procprops entry, in bytes.
  2242. (define procprops-size 8)
  2243. (define (link-procprops asm)
  2244. (define (assoc-remove-one alist key value-pred)
  2245. (match alist
  2246. (() '())
  2247. ((((? (lambda (x) (eq? x key))) . value) . alist)
  2248. (if (value-pred value)
  2249. alist
  2250. (acons key value alist)))
  2251. (((k . v) . alist)
  2252. (acons k v (assoc-remove-one alist key value-pred)))))
  2253. (define (props-without-name-or-docstring meta)
  2254. (assoc-remove-one
  2255. (assoc-remove-one (meta-properties meta) 'name (lambda (x) #t))
  2256. 'documentation
  2257. string?))
  2258. (define (find-procprops)
  2259. (filter-map (lambda (meta)
  2260. (let ((props (props-without-name-or-docstring meta)))
  2261. (and (pair? props)
  2262. (cons (meta-low-pc meta) props))))
  2263. (reverse (asm-meta asm))))
  2264. (let* ((endianness (asm-endianness asm))
  2265. (procprops (find-procprops))
  2266. (bv (make-bytevector (* (length procprops) procprops-size) 0)))
  2267. (let lp ((procprops procprops) (pos 0) (relocs '()))
  2268. (match procprops
  2269. (()
  2270. (make-object asm '.guile.procprops
  2271. bv
  2272. relocs '()
  2273. #:type SHT_PROGBITS #:flags 0))
  2274. (((pc . props) . procprops)
  2275. (bytevector-u32-set! bv pos pc endianness)
  2276. (lp procprops
  2277. (+ pos procprops-size)
  2278. (cons (make-linker-reloc 'abs32/1 (+ pos 4) 0
  2279. (intern-constant asm props))
  2280. relocs)))))))
  2281. ;;;
  2282. ;;; The DWARF .debug_info, .debug_abbrev, .debug_str, and .debug_loc
  2283. ;;; sections provide line number and local variable liveness
  2284. ;;; information. Their format is defined by the DWARF
  2285. ;;; specifications.
  2286. ;;;
  2287. (define (asm-language asm)
  2288. ;; FIXME: Plumb language through to the assembler.
  2289. 'scheme)
  2290. ;; -> 5 values: .debug_info, .debug_abbrev, .debug_str, .debug_loc, .debug_lines
  2291. (define (link-debug asm)
  2292. (define (put-s8 port val)
  2293. (let ((bv (make-bytevector 1)))
  2294. (bytevector-s8-set! bv 0 val)
  2295. (put-bytevector port bv)))
  2296. (define (put-u16 port val)
  2297. (let ((bv (make-bytevector 2)))
  2298. (bytevector-u16-set! bv 0 val (asm-endianness asm))
  2299. (put-bytevector port bv)))
  2300. (define (put-u32 port val)
  2301. (let ((bv (make-bytevector 4)))
  2302. (bytevector-u32-set! bv 0 val (asm-endianness asm))
  2303. (put-bytevector port bv)))
  2304. (define (put-u64 port val)
  2305. (let ((bv (make-bytevector 8)))
  2306. (bytevector-u64-set! bv 0 val (asm-endianness asm))
  2307. (put-bytevector port bv)))
  2308. (define (meta->subprogram-die meta)
  2309. `(subprogram
  2310. (@ ,@(cond
  2311. ((meta-name meta)
  2312. => (lambda (name) `((name ,(symbol->string name)))))
  2313. (else
  2314. '()))
  2315. (low-pc ,(meta-label meta))
  2316. (high-pc ,(- (meta-high-pc meta) (meta-low-pc meta))))))
  2317. (define (make-compile-unit-die asm)
  2318. `(compile-unit
  2319. (@ (producer ,(string-append "Guile " (version)))
  2320. (language ,(asm-language asm))
  2321. (low-pc .rtl-text)
  2322. (high-pc ,(asm-pos asm))
  2323. (stmt-list 0))
  2324. ,@(map meta->subprogram-die (reverse (asm-meta asm)))))
  2325. (let-values (((die-port get-die-bv) (open-bytevector-output-port))
  2326. ((die-relocs) '())
  2327. ((abbrev-port get-abbrev-bv) (open-bytevector-output-port))
  2328. ;; (tag has-kids? attrs forms) -> code
  2329. ((abbrevs) vlist-null)
  2330. ((strtab) (make-string-table))
  2331. ((line-port get-line-bv) (open-bytevector-output-port))
  2332. ((line-relocs) '())
  2333. ;; file -> code
  2334. ((files) vlist-null))
  2335. (define (write-abbrev code tag has-children? attrs forms)
  2336. (put-uleb128 abbrev-port code)
  2337. (put-uleb128 abbrev-port (tag-name->code tag))
  2338. (put-u8 abbrev-port (children-name->code (if has-children? 'yes 'no)))
  2339. (for-each (lambda (attr form)
  2340. (put-uleb128 abbrev-port (attribute-name->code attr))
  2341. (put-uleb128 abbrev-port (form-name->code form)))
  2342. attrs forms)
  2343. (put-uleb128 abbrev-port 0)
  2344. (put-uleb128 abbrev-port 0))
  2345. (define (intern-abbrev tag has-children? attrs forms)
  2346. (let ((key (list tag has-children? attrs forms)))
  2347. (match (vhash-assoc key abbrevs)
  2348. ((_ . code) code)
  2349. (#f (let ((code (1+ (vlist-length abbrevs))))
  2350. (set! abbrevs (vhash-cons key code abbrevs))
  2351. (write-abbrev code tag has-children? attrs forms)
  2352. code)))))
  2353. (define (intern-file file)
  2354. (match (vhash-assoc file files)
  2355. ((_ . code) code)
  2356. (#f (let ((code (1+ (vlist-length files))))
  2357. (set! files (vhash-cons file code files))
  2358. code))))
  2359. (define (write-sources)
  2360. ;; Choose line base and line range values that will allow for an
  2361. ;; address advance range of 16 words. The special opcode range is
  2362. ;; from 10 to 255, so 246 values.
  2363. (define base -4)
  2364. (define range 15)
  2365. (define min-inc 4) ; Minimum PC increment.
  2366. (let lp ((sources (asm-sources asm)) (out '()))
  2367. (match sources
  2368. (((pc . s) . sources)
  2369. (let ((file (assq-ref s 'filename))
  2370. (line (assq-ref s 'line))
  2371. (col (assq-ref s 'column)))
  2372. (lp sources
  2373. ;; Guile line and column numbers are 0-indexed, but
  2374. ;; they are 1-indexed for DWARF.
  2375. (if (and line col)
  2376. (cons (list pc
  2377. (if (string? file) (intern-file file) 0)
  2378. (1+ line)
  2379. (1+ col))
  2380. out)
  2381. out))))
  2382. (()
  2383. ;; Compilation unit header for .debug_line. We write in
  2384. ;; DWARF 2 format because more tools understand it than DWARF
  2385. ;; 4, which incompatibly adds another field to this header.
  2386. (put-u32 line-port 0) ; Length; will patch later.
  2387. (put-u16 line-port 2) ; DWARF 2 format.
  2388. (put-u32 line-port 0) ; Prologue length; will patch later.
  2389. (put-u8 line-port min-inc) ; Minimum instruction length: 4 bytes.
  2390. (put-u8 line-port 1) ; Default is-stmt: true.
  2391. (put-s8 line-port base) ; Line base. See the DWARF standard.
  2392. (put-u8 line-port range) ; Line range. See the DWARF standard.
  2393. (put-u8 line-port 10) ; Opcode base: the first "special" opcode.
  2394. ;; A table of the number of uleb128 arguments taken by each
  2395. ;; of the standard opcodes.
  2396. (put-u8 line-port 0) ; 1: copy
  2397. (put-u8 line-port 1) ; 2: advance-pc
  2398. (put-u8 line-port 1) ; 3: advance-line
  2399. (put-u8 line-port 1) ; 4: set-file
  2400. (put-u8 line-port 1) ; 5: set-column
  2401. (put-u8 line-port 0) ; 6: negate-stmt
  2402. (put-u8 line-port 0) ; 7: set-basic-block
  2403. (put-u8 line-port 0) ; 8: const-add-pc
  2404. (put-u8 line-port 1) ; 9: fixed-advance-pc
  2405. ;; Include directories, as a zero-terminated sequence of
  2406. ;; nul-terminated strings. Nothing, for the moment.
  2407. (put-u8 line-port 0)
  2408. ;; File table. For each file that contributes to this
  2409. ;; compilation unit, a nul-terminated file name string, and a
  2410. ;; uleb128 for each of directory the file was found in, the
  2411. ;; modification time, and the file's size in bytes. We pass
  2412. ;; zero for the latter three fields.
  2413. (vlist-fold-right
  2414. (lambda (pair seed)
  2415. (match pair
  2416. ((file . code)
  2417. (put-bytevector line-port (string->utf8 file))
  2418. (put-u8 line-port 0)
  2419. (put-uleb128 line-port 0) ; directory
  2420. (put-uleb128 line-port 0) ; mtime
  2421. (put-uleb128 line-port 0))) ; size
  2422. seed)
  2423. #f
  2424. files)
  2425. (put-u8 line-port 0) ; 0 byte terminating file list.
  2426. ;; Patch prologue length.
  2427. (let ((offset (port-position line-port)))
  2428. (seek line-port 6 SEEK_SET)
  2429. (put-u32 line-port (- offset 10))
  2430. (seek line-port offset SEEK_SET))
  2431. ;; Now write the statement program.
  2432. (let ()
  2433. (define (extended-op opcode payload-len)
  2434. (put-u8 line-port 0) ; extended op
  2435. (put-uleb128 line-port (1+ payload-len)) ; payload-len + opcode
  2436. (put-uleb128 line-port opcode))
  2437. (define (set-address sym)
  2438. (define (add-reloc! kind)
  2439. (set! line-relocs
  2440. (cons (make-linker-reloc kind
  2441. (port-position line-port)
  2442. 0
  2443. sym)
  2444. line-relocs)))
  2445. (match (asm-word-size asm)
  2446. (4
  2447. (extended-op 2 4)
  2448. (add-reloc! 'abs32/1)
  2449. (put-u32 line-port 0))
  2450. (8
  2451. (extended-op 2 8)
  2452. (add-reloc! 'abs64/1)
  2453. (put-u64 line-port 0))))
  2454. (define (end-sequence pc)
  2455. (let ((pc-inc (/ (- (asm-pos asm) pc) min-inc)))
  2456. (put-u8 line-port 2) ; advance-pc
  2457. (put-uleb128 line-port pc-inc))
  2458. (extended-op 1 0))
  2459. (define (advance-pc pc-inc line-inc)
  2460. (let ((spec (+ (- line-inc base)
  2461. (* (/ pc-inc min-inc) range)
  2462. 10)))
  2463. (cond
  2464. ((or (< line-inc base) (>= line-inc (+ base range)))
  2465. (advance-line line-inc)
  2466. (advance-pc pc-inc 0))
  2467. ((<= spec 255)
  2468. (put-u8 line-port spec))
  2469. ((< spec 500)
  2470. (put-u8 line-port 8) ; const-advance-pc
  2471. (advance-pc (- pc-inc (* (floor/ (- 255 10) range) min-inc))
  2472. line-inc))
  2473. (else
  2474. (put-u8 line-port 2) ; advance-pc
  2475. (put-uleb128 line-port (/ pc-inc min-inc))
  2476. (advance-pc 0 line-inc)))))
  2477. (define (advance-line inc)
  2478. (put-u8 line-port 3)
  2479. (put-sleb128 line-port inc))
  2480. (define (set-file file)
  2481. (put-u8 line-port 4)
  2482. (put-uleb128 line-port file))
  2483. (define (set-column col)
  2484. (put-u8 line-port 5)
  2485. (put-uleb128 line-port col))
  2486. (set-address '.rtl-text)
  2487. (let lp ((in out) (pc 0) (file 1) (line 1) (col 0))
  2488. (match in
  2489. (()
  2490. (when (null? out)
  2491. ;; There was no source info in the first place. Set
  2492. ;; file register to 0 before adding final row.
  2493. (set-file 0))
  2494. (end-sequence pc))
  2495. (((pc* file* line* col*) . in*)
  2496. (cond
  2497. ((and (eqv? file file*) (eqv? line line*) (eqv? col col*))
  2498. (lp in* pc file line col))
  2499. (else
  2500. (unless (eqv? col col*)
  2501. (set-column col*))
  2502. (unless (eqv? file file*)
  2503. (set-file file*))
  2504. (advance-pc (- pc* pc) (- line* line))
  2505. (lp in* pc* file* line* col*)))))))))))
  2506. (define (compute-code attr val)
  2507. (match attr
  2508. ('name (string-table-intern! strtab val))
  2509. ('low-pc val)
  2510. ('high-pc val)
  2511. ('producer (string-table-intern! strtab val))
  2512. ('language (language-name->code val))
  2513. ('stmt-list val)))
  2514. (define (choose-form attr val code)
  2515. (cond
  2516. ((string? val) 'strp)
  2517. ((eq? attr 'stmt-list) 'sec-offset)
  2518. ((eq? attr 'low-pc) 'addr)
  2519. ((exact-integer? code)
  2520. (cond
  2521. ((< code 0) 'sleb128)
  2522. ((<= code #xff) 'data1)
  2523. ((<= code #xffff) 'data2)
  2524. ((<= code #xffffffff) 'data4)
  2525. ((<= code #xffffffffffffffff) 'data8)
  2526. (else 'uleb128)))
  2527. (else (error "unhandled case" attr val code))))
  2528. (define (add-die-relocation! kind sym)
  2529. (set! die-relocs
  2530. (cons (make-linker-reloc kind (port-position die-port) 0 sym)
  2531. die-relocs)))
  2532. (define (write-value code form)
  2533. (match form
  2534. ('data1 (put-u8 die-port code))
  2535. ('data2 (put-u16 die-port code))
  2536. ('data4 (put-u32 die-port code))
  2537. ('data8 (put-u64 die-port code))
  2538. ('uleb128 (put-uleb128 die-port code))
  2539. ('sleb128 (put-sleb128 die-port code))
  2540. ('addr
  2541. (match (asm-word-size asm)
  2542. (4
  2543. (add-die-relocation! 'abs32/1 code)
  2544. (put-u32 die-port 0))
  2545. (8
  2546. (add-die-relocation! 'abs64/1 code)
  2547. (put-u64 die-port 0))))
  2548. ('sec-offset (put-u32 die-port code))
  2549. ('strp (put-u32 die-port code))))
  2550. (define (write-die die)
  2551. (match die
  2552. ((tag ('@ (attrs vals) ...) children ...)
  2553. (let* ((codes (map compute-code attrs vals))
  2554. (forms (map choose-form attrs vals codes))
  2555. (has-children? (not (null? children)))
  2556. (abbrev-code (intern-abbrev tag has-children? attrs forms)))
  2557. (put-uleb128 die-port abbrev-code)
  2558. (for-each write-value codes forms)
  2559. (when has-children?
  2560. (for-each write-die children)
  2561. (put-uleb128 die-port 0))))))
  2562. ;; Compilation unit header.
  2563. (put-u32 die-port 0) ; Length; will patch later.
  2564. (put-u16 die-port 4) ; DWARF 4.
  2565. (put-u32 die-port 0) ; Abbrevs offset.
  2566. (put-u8 die-port (asm-word-size asm)) ; Address size.
  2567. (write-die (make-compile-unit-die asm))
  2568. ;; Terminate the abbrevs list.
  2569. (put-uleb128 abbrev-port 0)
  2570. (write-sources)
  2571. (values (let ((bv (get-die-bv)))
  2572. ;; Patch DWARF32 length.
  2573. (bytevector-u32-set! bv 0 (- (bytevector-length bv) 4)
  2574. (asm-endianness asm))
  2575. (make-object asm '.debug_info bv die-relocs '()
  2576. #:type SHT_PROGBITS #:flags 0))
  2577. (make-object asm '.debug_abbrev (get-abbrev-bv) '() '()
  2578. #:type SHT_PROGBITS #:flags 0)
  2579. (make-object asm '.debug_str (link-string-table! strtab) '() '()
  2580. #:type SHT_PROGBITS #:flags 0)
  2581. (make-object asm '.debug_loc #vu8() '() '()
  2582. #:type SHT_PROGBITS #:flags 0)
  2583. (let ((bv (get-line-bv)))
  2584. ;; Patch DWARF32 length.
  2585. (bytevector-u32-set! bv 0 (- (bytevector-length bv) 4)
  2586. (asm-endianness asm))
  2587. (make-object asm '.debug_line bv line-relocs '()
  2588. #:type SHT_PROGBITS #:flags 0)))))
  2589. (define (link-objects asm)
  2590. (let*-values (;; Link procprops before constants, because it probably
  2591. ;; interns more constants.
  2592. ((procprops) (link-procprops asm))
  2593. ((ro rw rw-init) (link-constants asm))
  2594. ;; Link text object after constants, so that the
  2595. ;; constants initializer gets included.
  2596. ((text) (link-text-object asm))
  2597. ((frame-maps) (link-frame-maps asm))
  2598. ((dt) (link-dynamic-section asm text rw rw-init frame-maps))
  2599. ((symtab strtab) (link-symtab (linker-object-section text) asm))
  2600. ((arities arities-strtab) (link-arities asm))
  2601. ((docstrs docstrs-strtab) (link-docstrs asm))
  2602. ((dinfo dabbrev dstrtab dloc dline) (link-debug asm))
  2603. ;; This needs to be linked last, because linking other
  2604. ;; sections adds entries to the string table.
  2605. ((shstrtab) (link-shstrtab asm)))
  2606. (filter identity
  2607. (list text ro frame-maps rw dt symtab strtab
  2608. arities arities-strtab
  2609. docstrs docstrs-strtab procprops
  2610. dinfo dabbrev dstrtab dloc dline
  2611. shstrtab))))
  2612. ;;;
  2613. ;;; High-level public interfaces.
  2614. ;;;
  2615. (define* (link-assembly asm #:key (page-aligned? #t))
  2616. "Produce an ELF image from the code and data emitted into @var{asm}.
  2617. The result is a bytevector, by default linked so that read-only and
  2618. writable data are on separate pages. Pass @code{#:page-aligned? #f} to
  2619. disable this behavior."
  2620. (link-elf (link-objects asm) #:page-aligned? page-aligned?))