cg.doc 55 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832
  1. .RP
  2. .TL
  3. The table driven code generator from
  4. .br
  5. the Amsterdam Compiler Kit
  6. .AU
  7. Hans van Staveren
  8. .AI
  9. Dept. of Mathematics and Computer Science
  10. Vrije Universiteit
  11. Amsterdam, The Netherlands
  12. .AB
  13. It is possible to automate the process of compiler building
  14. to a great extent using collections of tools.
  15. The Amsterdam Compiler Kit is such a collection of tools.
  16. This document provides a description of the internal workings
  17. of the table driven code generator in the Amsterdam Compiler Kit,
  18. and a description of syntax and semantics of the driving table.
  19. .AE
  20. .NH 1
  21. Introduction
  22. .PP
  23. Part of the Amsterdam Compiler Kit is a code generator system consisting
  24. of a code generator generator (\fIcgg\fP for short) and some machine
  25. independent C code.
  26. .I Cgg
  27. reads a machine description table and creates two files,
  28. tables.h and tables.c.
  29. These are then used together with other C code to produce
  30. a code generator for the machine at hand.
  31. .PP
  32. This in turn reads compact EM code and produces
  33. assembly code.
  34. The remainder of this document will first broadly describe
  35. the working of the code generator,
  36. then a description of the machine table follows after which
  37. the internal workings of the code generator will be explained.
  38. .PP
  39. The reader is assumed to have at least a vague notion about the
  40. semantics of the intermediary EM code.
  41. Someone wishing to write a table for a new machine
  42. should be thoroughly acquainted with EM code
  43. and the assembly code of the machine at hand.
  44. .NH 1
  45. Global overview of the workings of the code generator.
  46. .PP
  47. The code generator or
  48. .I cg
  49. tries to generate good code by simulating the runtime stack
  50. of the program compiled and delaying emission of code as long
  51. as possible.
  52. It also keeps track of register contents, which enables it to
  53. eliminate redundant moves, and tries to eliminate redundant tests
  54. by keeping information about condition code status,
  55. if applicable for the machine.
  56. .PP
  57. .I Cg
  58. maintains a `fakestack' containing `tokens' that are built
  59. by executing the pseudo code contained in the code rules given
  60. by the table writer.
  61. One can think of the fakestack as a logical extension of the real
  62. stack the program compiled will have when run.
  63. During code generation tokens will be kept on the fakestack as long
  64. as possible but when they are moved to the real stack,
  65. by generating code for the push,
  66. all tokens above\u*\d
  67. .FS
  68. * in the rest of this document the stack is assumed to grow downwards,
  69. although the top of the stack will mean the first element that will
  70. be popped.
  71. .FE
  72. the tokens pushed will be pushed also,
  73. so that the fakestack will not contain holes.
  74. .PP
  75. The main loop of
  76. .I cg
  77. is this:
  78. .IP 1)
  79. find a pattern of EM instructions starting at the current one to
  80. generate code for.
  81. This pattern will usually be of length one but longer patterns can be used.
  82. .IP 2)
  83. Select one of the possibly many stack patterns that go with this
  84. EM pattern on the basis of heuristics and/or lookahead.
  85. .IP 3)
  86. Force the current fakestack contents to match the pattern.
  87. This may involve
  88. copying tokens to registers, making dummy transformations, e.g. to
  89. transform a "local" into an "register offsetted" or might even
  90. cause to have the complete fakestack contents put to the real stack
  91. and then back into registers if no suitable transformations
  92. were provided by the table writer.
  93. .IP 4)
  94. Execute the pseudocode associated with the code rule just selected,
  95. this may cause registers to be allocated,
  96. code to be emitted etc..
  97. .IP 5)
  98. Put tokens onto the fakestack to reflect the result of the operation.
  99. .IP 6)
  100. Insert some EM instructions into the stream,
  101. this is possible but not common.
  102. .IP 7)
  103. Account for the cost.
  104. The cost is kept in a (space, time) vector and lookahead decisions
  105. are based on a linear combination of these.
  106. .PP
  107. The table that drives
  108. .I cg
  109. is not read in every time,
  110. but instead is used at compiletime
  111. of
  112. .I cg
  113. to set parameters and to load pseudocode tables.
  114. A program called
  115. .I cgg
  116. reads the table and produces large lists of numbers that are
  117. compiled together with machine independent code to produce
  118. a code generator for the machine at hand.
  119. .NH 1
  120. Description of the machine table
  121. .PP
  122. The machine description table consists of the following sections:
  123. .IP 1)
  124. Constant definitions
  125. .IP 2)
  126. Register definitions
  127. .IP 3)
  128. Token definitions
  129. .IP 4)
  130. Token expression definitions
  131. .IP 5)
  132. Code rules
  133. .IP 6)
  134. Move definitions
  135. .IP 7)
  136. Test definitions
  137. .IP 8)
  138. Stacking definitions
  139. .PP
  140. Input is in free format, white space and newlines may be used
  141. at will to improve legibility.
  142. Identifiers used in the table have the same syntax as C identifiers,
  143. upper and lower case considered different, all characters significant.
  144. There is however one exception:
  145. identifiers must be more than one character long for parsing reasons.
  146. C style comments are accepted
  147. .DS
  148. /* this is a comment */
  149. .DE
  150. and #define macros may be used if the need arises.
  151. .NH 2
  152. Some constants
  153. .PP
  154. Before anything else three constants must be defined,
  155. all with the syntax NAME=value, value being an integer.
  156. These constants are:
  157. .IP EM_WSIZE 10
  158. Number of bytes in a machine word.
  159. This is the number of bytes
  160. a simple \fBloc\fP instruction will put on the stack.
  161. .IP EM_PSIZE
  162. Number of bytes in a pointer.
  163. This is the number of bytes
  164. a \fBlal\fP instruction will put on the stack.
  165. .IP EM_BSIZE
  166. Number of bytes in the hole between AB and LB.
  167. If the calling sequence just saves PC and LB this
  168. size will be twice the pointersize.
  169. .PP
  170. EM_WSIZE and EM_PSIZE are checked when a program is compiled
  171. with the resulting code generator.
  172. EM_BSIZE is used by
  173. .I cg
  174. to add to the offset of instructions dealing with locals
  175. having positive offsets,
  176. i.e. parameters.
  177. .PP
  178. Optionally one can give here the factors with which the size and time
  179. parts of the cost function have to be multiplied to ensure they have the
  180. same order of magnitude.
  181. This can be done as
  182. .DS
  183. TIMEFACTOR = C\d1\u/C\d2\u
  184. SIZEFACTOR = C\d3\u/C\d4\u
  185. .DE
  186. Above numbers must be read as rational numbers.
  187. Defaults are 1/1 for both of them.
  188. These constants set the default size/time tradeoff in the code generator,
  189. so if TIMEFACTOR and SIZEFACTOR are both 1 the code generator will choose
  190. at random between two codesequences where one has
  191. cost (10,4) and the other has cost (8,6).
  192. See also the description of the cost field below.
  193. .PP
  194. Also optional is the definition of a printformat for integers in the codefile.
  195. This is given as
  196. .DS
  197. FORMAT = string
  198. .DE
  199. The default for string is "%d" or "%ld" depending on the wordsize of
  200. the machine. For example on the PDP 11 one can use
  201. .DS
  202. FORMAT= "0%o"
  203. .DE
  204. to satisfy the old UNIX assembler that reads octal unless followed by
  205. a period, and the ACK assembler that follows C conventions.
  206. .NH 2
  207. Register definition
  208. .PP
  209. The next part of the tables describes the various registers of the
  210. machine and defines identifiers
  211. to be used in later parts of the tables.
  212. Example for the PDP-11:
  213. .DS L
  214. REGISTERS:
  215. R0 = ( "r0",2), REG.
  216. R1 = ( "r1",2), REG, ODDREG.
  217. R2 = ( "r2",2), REG.
  218. R3 = ( "r3",2), REG, ODDREG.
  219. R4 = ( "r4",2), REG.
  220. LB = ( "r5",2), LOCALBASE.
  221. R01= ( "r0",4,R0,R1), REGPAIR.
  222. R23= ( "r2",4,R2,R3), REGPAIR.
  223. FR0= ( "r0",4), FREG.
  224. FR1= ( "r1",4), FREG.
  225. FR2= ( "r2",4), FREG.
  226. FR3= ( "r3",4), FREG.
  227. DR0= ( "r0",8,FR0), DREG.
  228. DR1= ( "r1",8,FR1), DREG.
  229. DR2= ( "r2",8,FR2), DREG.
  230. DR3= ( "r3",8,FR3), DREG.
  231. .DE
  232. .PP
  233. The identifier before the '=' sign is the name of the register
  234. as used further on in the table.
  235. The string is the name of the register as far as the assembler is concerned.
  236. The number is the size of the register in bytes.
  237. Identifiers following the number but within the parentheses are previously
  238. defined registernames that are contained in the register being defined.
  239. The identifiers following the closing parenthesis are properties
  240. of the register.
  241. So for example R23 is a register with assembler name r2, 4 bytes long,
  242. contains the registers R2 and R3 and has the property REGPAIR.
  243. .PP
  244. It might seem wise to list each and every property of a register,
  245. so one might give R0 the extra property MFPTREG named after the not
  246. too well known MFPT instruction on newer PDP-11 types,
  247. but this is not a good idea.
  248. Every extra property means the registerset is more unorthogonal
  249. and
  250. .I cg
  251. execution time is influenced by that,
  252. because it has to take into account a larger set of registers
  253. that are not equivalent.
  254. .PP
  255. There is a predefined property SCRATCH that is dynamic,
  256. i.e. a register can have the property SCRATCH one time,
  257. and loose it the next.
  258. A register has the property SCRATCH when it has a reference count of one.
  259. One needs to be able to discriminate between SCRATCH registers
  260. and others,
  261. because it is only allowed to do arithmetic on
  262. SCRATCH registers.
  263. .NH 2
  264. Stack token definition
  265. .PP
  266. The next part describes all possible tokens that can reside on
  267. the fakestack during code generation.
  268. Attributes of a token are described in the form of a C struct declaration,
  269. this is followed by the size in bytes of the token,
  270. optionally followed by the cost of the token when used as an addressing mode
  271. and the format
  272. to be used on output.
  273. .PP
  274. Tokens should usually be declared for every addressing mode
  275. of the machine at hand and for every size directly usable in
  276. a machine instruction.
  277. Example for the PDP-11 (incomplete):
  278. .DS L
  279. TOKENS:
  280. IREG2 = { REGISTER reg; } 2 "*%[reg]" /* indirect register */
  281. REGCONST = { REGISTER reg; STRING off; } 2 /* not really addressable */
  282. REGOFF2 = { REGISTER reg; STRING off; } 2 "%[off](%[reg])"
  283. IREGOFF2 = { REGISTER reg; STRING off; } 2 "*%[off](%[reg])"
  284. CONST = { INT off; } 2 cost=(2,850) "$%[off]."
  285. EXTERN2 = { STRING off; } 2 "%[off]"
  286. IEXTERN2 = { STRING off; } 2 "*%[off]"
  287. PAIRSIGNED = { REGISTER regeven,regodd; } 2 "%[regeven]"
  288. .DE
  289. .PP
  290. Types allowed in the struct are REGISTER, INT and STRING.
  291. Tokens without a printformat should never be output.
  292. .PP
  293. Notice that tokens need not correspond to addressing modes,
  294. the REGCONST token listed above,
  295. meaning the sum of the contents of the register and the constant,
  296. has no corresponding addressing mode on the PDP-11,
  297. but is included so that a sequence of add constant, load indirect,
  298. can be handled efficiently.
  299. This REGCONST token is needed as part of the path
  300. .DS
  301. REGISTER -> REGCONST -> REGOFF
  302. .DE
  303. of which the first and the last "exist" and the middle is needed
  304. only as an intermediate step.
  305. .NH 2
  306. Token expressions
  307. .PP
  308. Usually machines have certain collections of addressing modes that
  309. can be used with certain instructions.
  310. The stack patterns in the table are lists of these collections
  311. and since it is cumbersome to write out these long lists
  312. every time, there is a section here to give names to these
  313. collections.
  314. Please note that it is not forbidden to write out a token expression
  315. in the remainder of the table,
  316. but for clarity it is usually better not to.
  317. Example for the PDP-11 (incomplete):
  318. .DS L
  319. TOKENEXPRESSIONS:
  320. SOURCE2 = REG + IREG2 + REGOFF2 + IREGOFF2 + CONST + EXTERN2 +
  321. IEXTERN2
  322. SREG = REG * SCRATCH
  323. .DE
  324. Permissible in the expressions are all PASCAL set operators, i.e.
  325. .IP +
  326. set union
  327. .IP -
  328. set difference
  329. .IP *
  330. set intersection
  331. .PP
  332. Every tokenidentifier is also a token expression identifier
  333. denoting the singleton collection of tokens containing
  334. just itself.
  335. Every register property as defined above is also a token expression
  336. matching all registers with that property when on the fakestack.
  337. The standard token expression identifier ALL denotes the collection of
  338. all tokens.
  339. .NH 2
  340. Expressions
  341. .PP
  342. Throughout the rest of the table expressions can be used in some
  343. places.
  344. This section will give the syntax and semantics of expressions.
  345. There are four types of expressions: integer, string, register and undefined.
  346. Type checking is performed by
  347. .I cgg .
  348. An operator with at least one undefined operand returns undefined except
  349. for the defined() function mentioned below.
  350. An undefined expression is interpreted as FALSE when it is needed
  351. as a truth value.
  352. Basic terms in an expression are
  353. .IP number 16
  354. A number is a constant of type integer.
  355. .IP "string"
  356. A string within double quotes is a constant of type string.
  357. All the normal C style escapes may be used within the string.
  358. .IP REGIDENT
  359. The name of a register is a constant of type register.
  360. .IP $\fIi\fP
  361. A dollarsign followed by a number is the representation of the argument
  362. of EM instruction \fI\fP.
  363. The type of the operand is dependent on the instruction,
  364. sometimes it is integer,
  365. sometimes it is string.
  366. It is undefined when the instruction has no operand.
  367. .br
  368. Although an exhaustive list could be given describing all the types
  369. the following rule of thumb will suffice.
  370. If you cannot imagine the operand of the instruction ever to be
  371. something different from a plain integer, the type is integer,
  372. otherwise it is string.
  373. .br
  374. .I Cg
  375. makes all necessary conversions for you,
  376. like adding EM_BSIZE to positive arguments of instructions
  377. dealing with locals,
  378. prepending underlines to global names,
  379. converting codelabels into a unique representation etc.
  380. Details about this can be found in the section about
  381. machine dependent C code.
  382. .IP %[1]
  383. This in general means the token mentioned first in the
  384. stack pattern.
  385. When used inside an expression the token must be a simple register.
  386. Type of this is register.
  387. .IP %[1.off]
  388. This means field "off" of the first stack pattern token.
  389. Type is the same as that of field "off".
  390. To use this expression implies a check that all tokens
  391. in the token expression used have the same attributes.
  392. .IP %[1.1]
  393. This is the first subregister of the first token.
  394. Previous comments apply.
  395. .IP %[b]
  396. The second allocated register.
  397. .IP %[a.2]
  398. The second subregister of the first allocated register.
  399. .PP
  400. All normal C operators apply to integers,
  401. the + operator serves for string concatenation
  402. and register expressions can only be compared to each other.
  403. Furthermore there are some special "functions":
  404. .IP tostring(e) 16
  405. Converts an integer expression e to a string.
  406. .IP defined(e)
  407. Returns 1 if expression e is defined, 0 otherwise.
  408. .IP samesign(e1,e2)
  409. Returns 1 if integer expression e1 and e2 have the same sign.
  410. .IP sfit(e1,e2)
  411. Returns 1 if integer expression e1 fits as a signed integer
  412. into a field of e2 bits, 0 otherwise.
  413. .IP ufit(e1,e2)
  414. Same as above but now for unsigned e1.
  415. .IP rom(a,n)
  416. Integer expression giving the n'th argument from the \fBrom\fP descriptor
  417. pointed at by the a'th EM instruction.
  418. Undefined if that descriptor does not exist.
  419. .IP loww(a)
  420. Returns the lower half of the argument of the a'th EM instruction.
  421. This is used to split the arguments of a \fBldc\fP instruction.
  422. .IP highw(a)
  423. Same for upper half.
  424. .NH 2
  425. Code rules
  426. .PP
  427. The largest section of the tables consists of the code generation rules.
  428. They specify EM patterns, stack patterns, code to be generated etc.
  429. Syntax is
  430. .DS L
  431. code rule : EM pattern '|' stack pattern '|' code '|'
  432. stack replacement '|' EM replacement '|' cost ;
  433. .DE
  434. All parts are optional, however there must be at least one pattern present.
  435. If the empattern is missing the rule becomes a rewriting rule or
  436. .I coercion
  437. to be used when code generation cannot continue
  438. because of an invalid stack pattern.
  439. The code rules are preceded by the word
  440. .DS
  441. CODE:
  442. .DE
  443. The next paragraphs describe the various parts in detail.
  444. .NH 3
  445. The EM pattern
  446. .PP
  447. The EM pattern consists of a list of EM mnemonics followed
  448. by a boolean expression.
  449. Examples:
  450. .DS
  451. \fBloe\fP
  452. .DE
  453. will match a single \fBloe\fP instruction,
  454. .DS
  455. \fBloc\fP \fBloc\fP \fBcif\fP $1==2 && $2==8
  456. .DE
  457. is a pattern that will match
  458. .DS
  459. \fBloc\fP 2
  460. \fBloc\fP 8
  461. \fBcif\fP
  462. .DE
  463. and
  464. .DS
  465. \fBlol\fP \fBinc\fP \fBstl\fP $1==$3
  466. .DE
  467. will match for example
  468. .DS
  469. \fBlol\fP 6
  470. \fBinc\fP
  471. \fBstl\fP 6
  472. .DE
  473. A missing boolean expression evaluates to TRUE.
  474. .PP
  475. When the EM pattern is the same as in the previous code rule the pattern
  476. should be given as `...'.
  477. The code generator will match the longest EM pattern on every occasion,
  478. if two patterns of the same length match the first in the table will be chosen,
  479. while all patterns of length greater than or equal to three are considered
  480. to be of the same length.
  481. .NH 3
  482. The stack pattern
  483. .PP
  484. The stack pattern is a list of token expressions,
  485. usually token expression identifiers for clarity.
  486. No boolean expression is allowed here.
  487. The first expression is the one that matches the top of the stack.
  488. .PP
  489. The pattern can be followed by the word STACK
  490. in which case the pattern only matches if there is nothing
  491. else on the fakestack.
  492. The code generator will stack everything not matched at the start
  493. of the rule.
  494. .PP
  495. The pattern can be preceded with the word
  496. .DS
  497. nocoercions:
  498. .DE
  499. which tells the code generator not to try to coerce to the pattern
  500. but only to use it when it is already there.
  501. There are two reasons for this construction,
  502. correctness and speed.
  503. It is needed for correctness when the pattern contains a register
  504. that is not transparent when data is moved through it.
  505. .PP
  506. Example: on the PDP-11 the shortest code for
  507. .DS
  508. \fBlae\fP a
  509. \fBloi\fP 8
  510. \fBlae\fP b
  511. \fBsti\fP 8
  512. .DE
  513. is
  514. .DS
  515. movf _a,fr0
  516. movf fr0,_b
  517. .DE
  518. assuming that the floating point processor is in double
  519. precision mode and fr0 is free.
  520. Unfortunately this is not correct since a trap can occur on certain
  521. kinds of data.
  522. This could happen if there was a pattern for \fBsti\fP\ 8 that allowed
  523. one to move a floating point register not preceded by nocoercions: .
  524. The code generator would then find that moving the 8-byte global _a
  525. to a floating point register and then storing it to _b was the cheapest,
  526. assuming that the space/time knob was turned far enough to space.
  527. It is unfortunate that the type information is no longer present,
  528. since if _a really is a floating point number the move could be
  529. made without error.
  530. .PP
  531. The second reason for the nocoercions: construct is speed.
  532. When the code generator has a long list of possible stack patterns
  533. for one EM pattern it can waste a lot of time trying to find coercions
  534. to all of them, while the mere presence of such a long list
  535. indicates that the table writer has given a lot of special cases.
  536. In this case prepending all the special cases by nocoercions:
  537. will stop the code generator from trying to find things there aren't.
  538. .NH 3
  539. The code part
  540. .PP
  541. The code part consists of three parts, stack cleanup, register allocation
  542. and code to generate.
  543. All of these may be omitted.
  544. .NH 4
  545. Stack cleanup
  546. .PP
  547. The stack cleanup part describes certain stacktokens that should neither remain on
  548. the fakestack, nor remembered as contents of registers.
  549. This is usually only required with store operations.
  550. The entire fakestack, except for the part matched in the stack pattern,
  551. is searched for tokens matching the expression and they are copied
  552. to the real stack.
  553. Every register that contains the stacktoken is marked as empty.
  554. .PP
  555. Syntax is
  556. .DS
  557. remove(token expression) \fIor\fP
  558. remove(token expression, boolean expression)
  559. .DE
  560. Example:
  561. .DS
  562. remove(REGOFF2,%[reg] != LB || %[off] == $1)
  563. .DE
  564. is part of a remove() call for use in the \fBstl\fP code rule.
  565. It removes all register offsetted tokens where the register is not the
  566. localbase plus the local wherein the store is done.
  567. The necessity for this can be seen from the following example:
  568. .DS
  569. \fBlol\fP 4
  570. \fBinl\fP 4
  571. \fBstl\fP 6
  572. .DE
  573. Without a proper remove() call in the rule for \fBinl\fP code would
  574. be generated as here
  575. .DS
  576. inc 4(r5)
  577. mov 4(r5),6(r5)
  578. .DE
  579. so local 6 would be given the new value of local 4 instead of the old
  580. as the EM code prescribed.
  581. .PP
  582. When generating something like a branch instruction it
  583. might be needed to empty the fakestack completely.
  584. This can of course be done with
  585. .DS
  586. remove(ALL)
  587. .DE
  588. .NH 4
  589. Register allocation
  590. .PP
  591. The register allocation part describes the kind of registers needed.
  592. Syntax for allocate() is
  593. .DS
  594. allocate(itemlist)
  595. .DE
  596. where itemlist is a list of three kinds of things:
  597. .IP 1)
  598. a tokendescription, for example %[1].
  599. .br
  600. This will instruct the code generator to temporarily decrement the reference count
  601. of all registers contained in the token,
  602. so that they are available for allocation in this allocate() call
  603. if they were only used in that token.
  604. See example below.
  605. .IP 2)
  606. a register property.
  607. .br
  608. This will allocate a register with that property.
  609. The register will be marked as empty at this point.
  610. Lookahead will be performed if necessary.
  611. .IP 3)
  612. a register property with initialization.
  613. .br
  614. This will allocate the register as in 2) but will also
  615. initialize it.
  616. This eases the task of the code generator because it can
  617. find a register already filled with the right value
  618. if it exists.
  619. .PP
  620. Examples:
  621. .DS
  622. allocate(OREG)
  623. .DE
  624. will allocate an odd register, while
  625. .DS
  626. allocate(REG={REGOFF2,LB,$1})
  627. .DE
  628. will allocate a register while simultaneously filling it with
  629. the asked value.
  630. .br
  631. Inside the coercion from SOURCE2 to REGISTER in the PDP-11 table
  632. the following allocate() can be found.
  633. .DS
  634. allocate(%[1],REG=%[1])
  635. .DE
  636. This tells the code generator that registers contained in %[1] can be used
  637. again and asks to fill the register allocated with %[1].
  638. So if %[1]={REGOFF2,R3,"4"} and R3 has a reference count of 1
  639. the following code might be generated.
  640. .DS
  641. mov 4(r3),r3
  642. .DE
  643. In the rest of the line the registers allocated can be named by
  644. %[a] and %[b.1],%[b.2], i.e. with lower case letters
  645. in order of allocation.
  646. .PP
  647. Warning:
  648. .DS
  649. allocate(R3)
  650. .DE
  651. is \fRnot\fP the way to allocate R3.
  652. R3 is not a register property, so it will be seen as a token description
  653. and the effect is that R3 will have its reference count decremented.
  654. .NH 4
  655. Code
  656. .PP
  657. Code to be generated is specified as a list of items of the following kind:
  658. .IP 1)
  659. a string in double quotes ("This is a string").
  660. .br
  661. This is copied to the codefile and a newline ( \en ) is appended.
  662. Inside the string all normal C string conventions are allowed,
  663. and substitutions can be made of the following sorts.
  664. .RS
  665. .IP a)
  666. $1, $2 etc.
  667. These are the operands of the corresponding EM instructions
  668. and are printed according to their type.
  669. To put a real '$' inside the string it must be doubled ('$$').
  670. .IP b)
  671. %[1], %[2.reg], %[b.1] etc.
  672. These have their obvious meaning.
  673. If they describe a complete token ( %[1] )
  674. the printformat for the token is used.
  675. If they stand for a basic term in an expression
  676. they will be printed according to their type.
  677. To put a real '%' inside the string it must be doubled ('%%').
  678. .IP c)
  679. %( arbitrary expression %).
  680. This allows inclusion of arbitrary expressions inside strings.
  681. Usually not needed very often,
  682. so that the awkward notation is not too bad.
  683. Note that %(%[1]%) is equivalent to %[1].
  684. .RE
  685. .IP 2)
  686. a move() call.
  687. This has the following syntax:
  688. .DS
  689. move(token description, token description)
  690. .DE
  691. Moves are handled specially since that enables the code generator
  692. to keep track of register contents.
  693. Example:
  694. .DS
  695. move(R3,{REGOFF2,LB,$1})
  696. .DE
  697. will generate code to move R3 to $1(r5) except when
  698. R3 already was a copy of $1(r5).
  699. Then the code will be omitted.
  700. The rules describing how to move things to each other
  701. can be found in the MOVES section described below.
  702. .IP 3)
  703. an erase() call.
  704. This has the following syntax:
  705. .DS
  706. erase(register expression)
  707. .DE
  708. This tells the code generator that the register mentioned no longer has any
  709. useful value.
  710. This is
  711. .I necessary
  712. after code in the table has changed the contents of registers.
  713. For example, after an add to a register the register must be erased,
  714. because the contents do no longer match any token.
  715. .IP 4)
  716. For machines that have condition codes,
  717. alas most of them do,
  718. there are provisions to remember condition code setting
  719. and prevent needless testing.
  720. To set the condition code to a token put in the code the following call:
  721. .DS
  722. test(token)
  723. .DE
  724. where token can be all of the standard forms that can also be used in move().
  725. This will generate a test if the condition codes
  726. were not already set to that token.
  727. It is also possible to tell
  728. .I cg
  729. that a certain operation, like a preceding add
  730. has set the condition codes to some token with the call
  731. .DS
  732. setcc(token)
  733. .DE
  734. So a sequence of a setcc and a test on the same token will generate
  735. no code.
  736. Another allowed call within the code is
  737. .DS
  738. samecc
  739. .DE
  740. which tells the code generator that condition codes were unaffected
  741. in this rule.
  742. If no setcc or samecc has been given the default is
  743. .DS
  744. nocc
  745. .DE
  746. when a piece of code contained strings,
  747. which tells the code generator that the condition codes
  748. have no useful value any more.
  749. .NH 3
  750. Stack replacement
  751. .PP
  752. The stack replacement is a possibly empty list of items to be pushed onto
  753. the fakestack. Three kinds of items are possible:
  754. .IP 1)
  755. An item of the form %[1]. This will push the stacktoken mentioned back
  756. onto the stack unchanged.
  757. .IP 2)
  758. A register expression. This will push the register mentioned
  759. onto the fakestack.
  760. .IP 3)
  761. An item of the form { REGOFF2,%[1.reg],$1 }.
  762. This generates a token with tokenidentifier REGOFF2 and attributes
  763. in order of declaration.
  764. .PP
  765. All tokens matched by the stack pattern at the beginning of the code rule
  766. are first removed and their registers deallocated.
  767. Items are pushed in the order of appearance.
  768. This means that the last item will be on the top of the
  769. stack after the push.
  770. So if the stack pattern contained two token expressions
  771. and you want to push them back unchanged,
  772. you have to specify as stack replacement
  773. .DS
  774. %[2] %[1]
  775. .DE
  776. and not the other way around.
  777. .NH 3
  778. EM replacement
  779. .PP
  780. In exceptional cases it might be useful to leave part of an empattern
  781. undone.
  782. For example, a \fBsdl\fP instruction might be split into two \fBstl\fP instructions
  783. when there is no 4-byte quantity on the stack. The emreplacement part allows
  784. one to express this.
  785. Example:
  786. .DS
  787. \fBstl\fP $1 \fBstl\fP $1+2
  788. .DE
  789. The instructions are inserted in the stream so that they can match
  790. the first part of a pattern in the next step.
  791. Note that since the code generator traverses the EM instructions in a strict
  792. linear fashion,
  793. it is impossible to let the EM replacement match later parts of a pattern.
  794. So if there is a pattern
  795. .DS
  796. \fBloc\fP \fBstl\fP $1==0
  797. .DE
  798. and the input is
  799. .DS
  800. \fBloc\fP 0 \fBsdl\fP 4
  801. .DE
  802. the \fBloc\fP\ 0 will be processed first,
  803. then the \fBsdl\fP might be split into two \fBstl\fP's but the pattern
  804. cannot match now.
  805. .NH 3
  806. Cost
  807. .PP
  808. The cost field can be specified when there is more than one
  809. code rule with the same empattern.
  810. If the code generator has a choice between two possibilities
  811. to generate code it will choose the cheapest according to
  812. the cost field.
  813. The cost for a code generation is the sum of the costs
  814. of all the coercions needed, plus the cost for freeing
  815. registers plus the cost of the code rule itself.
  816. .PP
  817. The format of the costfield is
  818. .DS
  819. ( nbytes, time ) or
  820. ( nbytes, time ) + %[\fIi\fP]
  821. .DE
  822. with time in the metric desired, like nanoseconds or states.
  823. See constants section above.
  824. The %[\fIi\fP] in the second example is used for adding the cost of a certain
  825. address mode used in the code generated.
  826. This can of course be repeated if desired.
  827. The cost of the address mode must then be specified in the token definition
  828. section.
  829. .NH 3
  830. Examples
  831. .PP
  832. A list of examples for the PDP-11 is given here.
  833. Far from being complete it gives examples of most kinds
  834. of instructions.
  835. .DS L
  836. \fBadi\fP $1==2 | SREG,SOURCE2 |
  837. "add %[2],%[1]" erase(%[1]) setcc(%[1])
  838. | %[1] | | (2,450) + %[2]
  839. \&... | SOURCE2,SREG |
  840. "add %[1],%[2]" erase(%[2]) setcc(%[2])
  841. | %[2] | | (2,450) + %[1]
  842. .DE
  843. is an example of the use of the `...' construct
  844. and shows how to place erase() and setcc() calls.
  845. .DS L
  846. \fBdvi\fP $1==2 | SOURCE2,SPAIRSIGNED |
  847. "div %[1],%[2]" erase(%[2])
  848. | %[2.regeven] | |
  849. \fBcmi\fP \fBtgt\fP $1==2 | SOURCE2,SOURCE2 | allocate(REG={CONST,0})
  850. "cmp %[2],%[1];ble 1f;inc %[a];1:" erase(%[a])
  851. | %[a] | |
  852. \fBcal\fP | STACK |
  853. "jsr pc,$1"
  854. | | |
  855. \fBlol\fP | | | { REGOFF2, LB, $1 } | |
  856. \fBstl\fP | SOURCE2 |
  857. remove(REGOFF2,%[off]==$1)
  858. move(%[1],{REGOFF2,LB,$1})
  859. | | |
  860. | SOURCE2 |
  861. allocate(%[1],REGPAIR)
  862. move(%[1],%[a.2])
  863. test(%[a.2])
  864. "sxt %[a.even]" | { PAIRSIGNED, %[a.1], %[a.2] }| |
  865. .DE
  866. This coercion shows how to use the move and test calls.
  867. At first you might think that the testcall is unnecessary,
  868. since the move will have set the condition codes,
  869. but the move may never have been executed
  870. if the register already contained the value,
  871. in which case it is necessary to do the test.
  872. If the move was executed the test will be omitted.
  873. .DS L
  874. | SOURCE2 | allocate(%[1],REG=%[1]) | %[a] | |
  875. \fBsdl\fP | SOURCE2 | | %[1] | \fBstl\fP $1 \fBstl\fP $1+2 |
  876. \fBexg\fP $1==2 | SOURCE2 SOURCE2 | | %[1] %[2] | |
  877. .DE
  878. This last example again shows the difference in the order
  879. of the stack pattern and the stack replacement.
  880. .NH 2
  881. Move code rules
  882. .PP
  883. When issuing a move() call as described above or a register allocation
  884. with initialization, the code generator has to know which
  885. instruction to use for the move.
  886. The code will of course only be generated if it cannot be omitted.
  887. This is listed in the move section of the tables by giving a list
  888. of tuples:
  889. .DS
  890. ( source, destination, codepart [ , costfield ] )
  891. .DE
  892. where the square brackets mean the costfield is optional.
  893. Example for the PDP-11
  894. .DS
  895. MOVES:
  896. ( CONST %[off]==0 , SOURCE2, "clr %[2]" )
  897. ( SOURCE2, SOURCE2, "mov %[1],%[2]" )
  898. .DE
  899. The moves are scanned from top to bottom,
  900. so the first one that matches will be chosen.
  901. .NH 2
  902. Test code rules
  903. .PP
  904. When issuing a test() call as described above,
  905. the code generator has to know which instruction
  906. to use for the test.
  907. The code will only be generated if the condition codes
  908. were not already set to the token.
  909. This is listed in the test section of the tables by giving
  910. a list of tuples:
  911. .DS
  912. ( source, codepart [ , costfield ] )
  913. .DE
  914. Example for the PDP-11
  915. .DS
  916. TESTS:
  917. ( SOURCE2, "tst %[1]")
  918. ( DREG, "tstf %[1]\encfcc")
  919. .DE
  920. The tests are scanned from top to bottom,
  921. so the first one that matches will be chosen.
  922. .NH 2
  923. Stacking code rules.
  924. .PP
  925. When the code generator has to stack a token it must know
  926. which code to use.
  927. Since it must at all times be possible to empty the fakestack
  928. even when no registers are free,
  929. it is mandatory that all
  930. tokens used must have a rule attached for stacking them
  931. without using a scratch register.
  932. Since however this might be clumsy and
  933. a register might in practice be available
  934. it is also possible to give rules
  935. which use a register.
  936. On the Intel 8086 for example,
  937. there is no instruction to push a constant without using a register,
  938. and the code needed to do it without, must use global data
  939. and as such is very complicated and wasteful of memory and time.
  940. It can therefore be left to be used in extreme cases,
  941. while in general the constant is pushed through a register.
  942. The stacking rules are listed in the stack section of the table as a list
  943. of tuples:
  944. .DS
  945. (source, [ register property ] , codepart [ , costfield ] )
  946. .DE
  947. Example for the Intel 8086:
  948. .DS
  949. STACKS:
  950. (CONST, REG, move(%[1],%[a]) "push %[a]")
  951. (REG ,, "push %[1]")
  952. .DE
  953. .NH 1
  954. The files mach.h and mach.c
  955. .PP
  956. The table writer must also supply two files containing
  957. machine dependent declarations and C code.
  958. These files are mach.h and mach.c.
  959. .NH 2
  960. Types in the code generator
  961. .PP
  962. Three different types of integer coexist in the code generator
  963. and their range depends on the machine at hand.
  964. The type 'int' is used for things like labelcounters that won't require
  965. more than 16 bits precision.
  966. The type 'word' is used among others to assemble datawords and
  967. is of type 'long' if EM_WSIZE>2.
  968. The type 'full' is used for addresses and is of type 'long' if
  969. EM_WSIZE>2 or EM_PSIZE>2.
  970. .PP
  971. In macro and function definitions in later paragraphs implicit typing
  972. will be used for parameters, that is parameters starting with an 's'
  973. will be of type string, and the letters 'i','w','f' will stand for
  974. int, word and full respectively.
  975. .NH 2
  976. Global variables to work with
  977. .PP
  978. Some global variables are present in the code generator
  979. that can be manipulated by the routines in mach.h and mach.c.
  980. .LP
  981. The declarations are:
  982. .DS L
  983. .ta 20
  984. FILE *codefile; /* code is emitted on this stream */
  985. word part_word; /* words to be output are put together here */
  986. int part_size; /* number of bytes already put in part_word */
  987. char str[]; /* Last string read in */
  988. long argval; /* Last int read and kept */
  989. .DE
  990. .NH 2
  991. Macros in mach.h
  992. .PP
  993. In the file mach.h a collection of macros is defined that have
  994. to do with formatting of assembly code for the machine at hand.
  995. Some of these macros can of course be left undefined in which case the
  996. macro calls are left in the source and will be treated as
  997. function calls.
  998. These functions can then be defined in \fImach.c\fR.
  999. .PP
  1000. The macros to be defined are:
  1001. .IP ex_ap(s) 16
  1002. Must print the magic incantations that will mark the symbol \fI\fR
  1003. to be exported to other modules.
  1004. This is the translation of the EM \fBexa\fP and \fBexp\fP instructions.
  1005. .IP in_ap(s)
  1006. Same to import the symbol.
  1007. Translation of \fBina\fP and \fBinp\fP.
  1008. .IP newilb(s)
  1009. Must print the definition of instruction label \fIs\fR.
  1010. .IP newdlb(s)
  1011. Must print the definition of data label \fIs\fR.
  1012. .IP dlbdlb(s1,s2)
  1013. Must define data label
  1014. .I s1
  1015. to be equal to
  1016. .I s2 .
  1017. .IP newlbss(s,f)
  1018. Must declare a piece of memory initialized to BSS_INIT(see below)
  1019. of length
  1020. .I f
  1021. and with label
  1022. .I s .
  1023. .IP cst_fmt
  1024. Format to be used when converting constant arguments of
  1025. EM instructions to string.
  1026. Argument to be formatted will be 'full'.
  1027. .IP off_fmt
  1028. Format to be used for integer part of label+constant,
  1029. argument will be 'full'.
  1030. .IP ilb_fmt
  1031. Format to be used for creation of unique instruction labels.
  1032. Arguments will be a unique procedure number (int) and the label
  1033. number (int).
  1034. .IP dlb_fmt
  1035. Format to be used for printing numeric data labels.
  1036. Argument will be 'int'.
  1037. .IP hol_fmt
  1038. Format to be used for generation of labels for
  1039. space generated by a
  1040. .B hol
  1041. pseudo.
  1042. Argument will be 'int'.
  1043. .IP hol_off
  1044. Format to be used for printing of the address of an element in
  1045. .B hol
  1046. space.
  1047. Arguments will be the offset in the
  1048. .B hol
  1049. block (word) and the number of the
  1050. .B hol
  1051. (int).
  1052. .IP con_cst(w)
  1053. Must generate output that will assemble into one machineword.
  1054. .IP con_ilb(s)
  1055. Must generate output that will put the address of the instruction label
  1056. into the datastream.
  1057. .IP con_dlb(s)
  1058. Must generate output that will put the address of the data label
  1059. into the datastream.
  1060. .IP id_first
  1061. Must be a character.
  1062. This is prepended to all nonnumeric global labels if their length
  1063. is shorter than the maximum allowed(currently 8) or if they already
  1064. start with that character.
  1065. This is to avoid conflicts of user labels with system labels.
  1066. .IP BSS_INIT
  1067. Must be a constant.
  1068. This is the value filled in all the words not initialized explicitly.
  1069. This is loader and system dependent.
  1070. If omitted no initialization is assumed.
  1071. .NH 3
  1072. Example mach.h for the PDP-11
  1073. .DS L
  1074. .ta 8 16 24 32 40 48 56
  1075. #define ex_ap(y) fprintf(codefile,"\et.globl %s\en",y)
  1076. #define in_ap(y) /* nothing */
  1077. #define newilb(x) fprintf(codefile,"%s:\en",x)
  1078. #define newdlb(x) fprintf(codefile,"%s:\en",x)
  1079. #define dlbdlb(x,y) fprintf(codefile,"%s=%s\en",x,y)
  1080. #define newlbss(l,x) fprintf(codefile,"%s:.=.+%d.\en",l,x);
  1081. #define cst_fmt "$%d."
  1082. #define off_fmt "%d."
  1083. #define ilb_fmt "I%02x%x"
  1084. #define dlb_fmt "_%d"
  1085. #define hol_fmt "hol%d"
  1086. #define hol_off "%d.+hol%d"
  1087. #define con_cst(x) fprintf(codefile,"%d.\en",x)
  1088. #define con_ilb(x) fprintf(codefile,"%s\en",x)
  1089. #define con_dlb(x) fprintf(codefile,"%s\en",x)
  1090. #define id_first '_'
  1091. #define BSS_INIT 0
  1092. .DE
  1093. .NH 2
  1094. Functions in mach.c
  1095. .PP
  1096. In mach.c some functions must be supplied,
  1097. mostly manipulating data resulting from pseudoinstructions.
  1098. The specifications are given here,
  1099. implicit typing of parameters as above.
  1100. .IP con_part(isz,word) 20
  1101. This function must manipulate the globals
  1102. part_word and part_size to append the isz bytes
  1103. contained in word to the output stream.
  1104. If part_word is full, i.e. part_size==EM_WSIZE
  1105. the function part_flush() may be called to empty the buffer.
  1106. This is the function that must go through the trouble of
  1107. doing byte order in words correct.
  1108. .IP con_mult(w_size)
  1109. This function must take the string str[] and create an integer
  1110. from the string of size w_size and generate code to assemble global
  1111. data for that integer.
  1112. Only the sizes for which arithmetic is implemented need be
  1113. handled,
  1114. so if you didn't implement 200-byte integer division
  1115. you don't have to implement 200-byte integer global data.
  1116. Here one must take care of word order in long integers.
  1117. .IP con_float()
  1118. This function must generate code to assemble a floating
  1119. point number of which the size is contained in argval
  1120. and the ASCII representation in str[].
  1121. .IP prolog(f_nlocals)
  1122. This function is called at the start of every procedure.
  1123. Function prolog code must be generated,
  1124. and room made for local variables for a total of f_nlocals bytes.
  1125. .IP mes(w_mesno)
  1126. This function is called when a
  1127. .B mes
  1128. pseudo is seen that is not handled by the machine independent part.
  1129. Example below shows all you probably have to know about that.
  1130. .IP segname[]
  1131. This is not a function,
  1132. but an array of four strings.
  1133. These strings are put out whenever the code generator
  1134. switches segments.
  1135. Segments are SEGTXT, SEGCON, SEGROM and SEGBSS in that order.
  1136. .NH 3
  1137. Example mach.c for the PDP-11
  1138. .PP
  1139. As an example of the sort of code expected,
  1140. the mach.c for the PDP-11 is presented here.
  1141. .DS L
  1142. .ta 8 16 24 32 40 48 56 64
  1143. /*
  1144. * machine dependent back end routines for the PDP-11
  1145. */
  1146. con_part(sz,w) register sz; word w; {
  1147. while (part_size % sz)
  1148. part_size++;
  1149. if (part_size == EM_WSIZE)
  1150. part_flush();
  1151. if (sz == 1) {
  1152. w &= 0xFF;
  1153. if (part_size)
  1154. w <<= 8;
  1155. part_word |= w;
  1156. } else {
  1157. assert(sz == 2);
  1158. part_word = w;
  1159. }
  1160. part_size += sz;
  1161. }
  1162. con_mult(sz) word sz; {
  1163. long l;
  1164. if (sz != 4)
  1165. fatal("bad icon/ucon size");
  1166. l = atol(str);
  1167. fprintf(codefile,"\et%o;%o\en",(int)(l>>16),(int)l);
  1168. }
  1169. con_float() {
  1170. double f;
  1171. register short *p,i;
  1172. /*
  1173. * This code is correct only when the code generator is
  1174. * run on a PDP-11 or VAX-11 since it assumes native
  1175. * floating point format is PDP-11 format.
  1176. */
  1177. if (argval != 4 && argval != 8)
  1178. fatal("bad fcon size");
  1179. f = atof(str);
  1180. p = (short *) &f;
  1181. i = *p++;
  1182. if (argval == 8) {
  1183. fprintf(codefile,"\et%o;%o;",i,*p++);
  1184. i = *p++;
  1185. }
  1186. fprintf(codefile,"\et%o;%o\en",i,*p++);
  1187. }
  1188. prolog(nlocals) full nlocals; {
  1189. fprintf(codefile,"mov r5,-(sp)\enmov sp,r5\en");
  1190. if (nlocals == 0)
  1191. return;
  1192. if (nlocals == 2)
  1193. fprintf(codefile,"tst -(sp)\en");
  1194. else
  1195. fprintf(codefile,"sub $%d.,sp\en",nlocals);
  1196. }
  1197. mes(type) word type; {
  1198. int argt ;
  1199. switch ( (int)type ) {
  1200. case ms_ext :
  1201. for (;;) {
  1202. switch ( argt=getarg(
  1203. ptyp(sp_cend)|ptyp(sp_pnam)|sym_ptyp) ) {
  1204. case sp_cend :
  1205. return ;
  1206. default:
  1207. strarg(argt) ;
  1208. fprintf(codefile,".globl %s\en",argstr) ;
  1209. break ;
  1210. }
  1211. }
  1212. default :
  1213. while ( getarg(any_ptyp) != sp_cend ) ;
  1214. break ;
  1215. }
  1216. }
  1217. char *segname[] = {
  1218. ".text", /* SEGTXT */
  1219. ".data", /* SEGCON */
  1220. ".data", /* SEGROM */
  1221. ".bss" /* SEGBSS */
  1222. };
  1223. .DE
  1224. .NH 1
  1225. Coercions
  1226. .PP
  1227. A central part in code generation is taken by the
  1228. .I coercions .
  1229. It is the responsibility of the table writer to provide
  1230. all necessary coercions so that code generation can continue.
  1231. The very minimal set of coercions are
  1232. the coercions to unstack every token expression,
  1233. in combination with the rules to stack every token.
  1234. .PP
  1235. If these are present the code generator can always make the necessary
  1236. transformations by stacking and unstacking.
  1237. Of course for codequality it is usually best to provide extra coercions
  1238. to prevent this stacking to take place.
  1239. .I Cg
  1240. discriminates three types of coercions:
  1241. .IP 1)
  1242. Unstacking coercions.
  1243. This category can use the allocate() call in its code.
  1244. .IP 2)
  1245. Splitting coercions, these are the coercions that split
  1246. larger tokens into smaller ones.
  1247. .IP 3)
  1248. Transforming coercions, these are the coercions that transform
  1249. a token into another one of the same size.
  1250. This category can use the allocate() call in its code.
  1251. .PP
  1252. When a stack configuration does not match the stack pattern
  1253. .I coercions
  1254. are searched for in the following order:
  1255. .IP 1)
  1256. First tokens are split if necessary to get their sizes right.
  1257. .IP 2)
  1258. Then transforming coercions are found that will make the pattern match.
  1259. .IP 3)
  1260. Finally if the stack pattern is longer than the fakestack contents
  1261. unstacking coercions will be used to fill up the pattern.
  1262. .PP
  1263. At any point, when coercions are missing so code generation could not
  1264. continue, the offending tokens are stacked.
  1265. .NH 1
  1266. Internal workings of the code generator.
  1267. .NH 2
  1268. Description of tables.c and tables.h contents
  1269. .PP
  1270. In this section the intermediate files will be described
  1271. that are produced by
  1272. .I cgg
  1273. and compiled with machine independent code to produce a code generator.
  1274. .NH 3
  1275. Tables.c
  1276. .PP
  1277. Tables.c contains a large number of initialized array's of all sorts.
  1278. Description of each follows:
  1279. .br
  1280. .in 1i
  1281. .ti -0.5i
  1282. byte code rules[]
  1283. .br
  1284. Pseudo code interpreted by the code generator.
  1285. Always starts with some opcode followed by operands depending
  1286. on the opcode.
  1287. Integers in this table are between 0 and 32767 and have a one byte
  1288. encoding if between 0 and 127.
  1289. .ti -0.5i
  1290. char stregclass[]
  1291. .br
  1292. Number of computed static register class per register.
  1293. Two registers are in the same class if they have the same properties
  1294. and don't share a common subregister.
  1295. .ti -0.5i
  1296. struct reginfo machregs[]
  1297. .br
  1298. Info per register.
  1299. Initialized with representation string, size,
  1300. members of the register and set of registers affected when this
  1301. one is changed.
  1302. Also contains room for runtime information,
  1303. like contents and reference count.
  1304. .ti -0.5i
  1305. tkdef_t tokens[]
  1306. .br
  1307. Information per tokentype.
  1308. Initialized with size, cost, type of operands and formatstring.
  1309. .ti -0.5i
  1310. node_t enodes[]
  1311. .br
  1312. List of triples representing expressions for the code generator.
  1313. .ti -0.5i
  1314. string code strings[]
  1315. .br
  1316. List of strings.
  1317. All strings are put in a list and checked for duplication,
  1318. so only one copy per string will reside here.
  1319. .ti -0.5i
  1320. set_t machsets[]
  1321. .br
  1322. List of token expression sets.
  1323. Bit 0 of the set is used for the SCRATCH property of registers,
  1324. bit 1 upto NREG are for the corresponding registers
  1325. and bit NREG+1 upto the end are for corresponding tokens.
  1326. .ti -0.5i
  1327. inst_t tokeninstances[]
  1328. .br
  1329. List of descriptions for building tokens.
  1330. Contains type of rule for building one,
  1331. plus operands depending on the type.
  1332. .ti -0.5i
  1333. move_t moves[]
  1334. .br
  1335. List of move rules.
  1336. Contains token expressions for source and destination
  1337. plus cost and index for code rule.
  1338. .ti -0.5i
  1339. byte pattern[]
  1340. .br
  1341. EM patterns.
  1342. This is structured internally as chains of patterns,
  1343. each chain pointed at by pathash[].
  1344. After each pattern the list of possible code rules is given.
  1345. .ti -0.5i
  1346. int pathash[256]
  1347. .br
  1348. Indices into pattern[] for all patterns with a certain low order
  1349. byte of the hashing function.
  1350. .ti -0.5i
  1351. c1_t c1coercs[]
  1352. .br
  1353. List of rules to stack tokens.
  1354. Contains token expressions,
  1355. register needed,
  1356. cost
  1357. and code rule.
  1358. .ti -0.5i
  1359. c2_t c2coercs[]
  1360. .br
  1361. List of splitting coercions.
  1362. Token expressions,
  1363. split factor,
  1364. replacements
  1365. and code rule.
  1366. .ti -0.5i
  1367. c3_t c3coercs[]
  1368. .br
  1369. List of one to one coercions.
  1370. Token expressions,
  1371. register needed,
  1372. replacement
  1373. and code rule.
  1374. .ti -0.5i
  1375. struct reginfo **reglist[]
  1376. .br
  1377. List of lists of pointers to register information.
  1378. For every property the list is here
  1379. to find the registers corresponding to it.
  1380. .in 0
  1381. .NH 3
  1382. tables.h
  1383. .PP
  1384. In tables.h various derived constants for the tables are
  1385. given.
  1386. They are then used to determine array sizes in the actual code generator,
  1387. plus loop termination in some cases.
  1388. .NH 2
  1389. Other important data structures
  1390. .PP
  1391. During code generation some other data structures are used
  1392. and here is a short description of some of the important ones.
  1393. .PP
  1394. Tokens are kept in the code generator as a struct consisting of
  1395. one integer
  1396. .I t_token
  1397. which is -1 if the token is a register,
  1398. and the number of the token otherwise,
  1399. plus an array of
  1400. .I TOKENSIZE
  1401. unions
  1402. .I t_att
  1403. of which the first is the register number in case of a register.
  1404. .PP
  1405. The fakestack is an array of these tokens,
  1406. there is a global variable
  1407. .I stackheight .
  1408. .PP
  1409. The results of expressions are kept in a struct
  1410. .I result
  1411. with elements
  1412. .I e_typ ,
  1413. giving the type of the expression:
  1414. .I EV_INT ,
  1415. .I EV_REG
  1416. or
  1417. .I EV_STR ,
  1418. and a union
  1419. .I e_v
  1420. which contains the real result.
  1421. .NH 2
  1422. A tour through the sources
  1423. .NH 3
  1424. codegen.c
  1425. .PP
  1426. The file codegen.c contains one large function consisting
  1427. of one giant switch statement.
  1428. It is the interpreter for the code generator pseudo code
  1429. as contained in code rules[].
  1430. This function can call itself recursively when doing lookahead.
  1431. Arguments are:
  1432. .IP codep 10
  1433. Pointer into code rules, pseudo program counter.
  1434. .IP ply
  1435. Number of EM pattern lookahead allowed.
  1436. .IP toplevel
  1437. Boolean telling whether this is the toplevel codegen() or
  1438. a deeper incarnation.
  1439. .IP costlimit
  1440. A cutoff value to limit searches.
  1441. If the cost crosses costlimit the incarnation can terminate.
  1442. .IP forced
  1443. A register number if nonzero.
  1444. This is used inside coercions to force the allocate() call to allocate
  1445. a register determined by earlier lookahead.
  1446. .PP
  1447. The instructions inplemented in the switch:
  1448. .NH 4
  1449. DO_NEXTEM
  1450. .PP
  1451. Matches the next EM pattern and does lookahead if necessary to find the best
  1452. code rule associated with this pattern.
  1453. Heuristics are used to determine best code rule when possible.
  1454. This is done by calling the distance() function.
  1455. .NH 4
  1456. DO_COERC
  1457. .PP
  1458. This sets the code generator in the state to do a from stack coercion.
  1459. .NH 4
  1460. DO_XMATCH
  1461. .PP
  1462. This is done when a match no longer has to be checked.
  1463. Used when the nocoercions: trick is used in the table.
  1464. .NH 4
  1465. DO_MATCH
  1466. .PP
  1467. This is the big one inside this function.
  1468. It has the task to transform the contents of the current
  1469. fakestack to match the pattern given after it.
  1470. .PP
  1471. Since the code generator does not know combining coercions,
  1472. i.e. there is no way to make a big token out of two smaller ones,
  1473. the first thing done is to stack every token that is too small.
  1474. After that all tokens too big are split if possible to the right size.
  1475. .PP
  1476. Next the coercions are sought that would transform tokens in place to
  1477. the right one, plus the coercions that would pop tokens of the stack.
  1478. Each of those might need a register, so a list of registers is generated
  1479. and at the end of looking for coercions the function
  1480. .I tuples()
  1481. is called to generate the list of all possible \fIn\fP-tuples,
  1482. where
  1483. .I n
  1484. equals the number of registers needed.
  1485. .PP
  1486. Lookahead is now performed if the number of tuples is greater than one.
  1487. If no possibility is found within the costlimit,
  1488. the fakestack is made smaller by pushing the bottom token,
  1489. and this process is repeated until either a way is found or
  1490. the fakestack is completely empty and there is still no way
  1491. to make the match.
  1492. .PP
  1493. If there is a way the corresponding coercions are executed
  1494. and the code is finished.
  1495. .NH 4
  1496. DO_REMOVE
  1497. .PP
  1498. Here the remove() call is executed, all tokens matched by the
  1499. token expression plus boolean expression are pushed.
  1500. In the current implementation there is no attempt to move those
  1501. tokens to registers, but that is a possible future extension.
  1502. .NH 4
  1503. DO_DEALLOCATE
  1504. .PP
  1505. This one temporarily decrements by one the reference count of all registers
  1506. contained in the token given as argument.
  1507. .NH 4
  1508. DO_REALLOCATE
  1509. .PP
  1510. Here all temporary deallocates are made undone.
  1511. .NH 4
  1512. DO_ALLOCATE
  1513. .PP
  1514. This is the part that allocates a register and decides which one to use.
  1515. If the
  1516. .I forced
  1517. argument was given its task is simple,
  1518. otherwise some work must be done.
  1519. First the list of possible registers is scanned,
  1520. all free registers noted and it is noted whether any of those
  1521. registers is already
  1522. containing the initialization.
  1523. If no registers are available some fakestack token is stacked and the
  1524. process is repeated.
  1525. .PP
  1526. After that if an exact match was found,
  1527. the list of registers is reduced to one register matching exactly
  1528. out of every register class.
  1529. Now lookahead is performed if necessary and the register chosen.
  1530. If an initialization was given the corresponding move is performed,
  1531. otherwise the register is marked empty.
  1532. .NH 4
  1533. DO_LOUTPUT
  1534. .PP
  1535. This prints a string and an expression.
  1536. Only done on toplevel.
  1537. .NH 4
  1538. DO_ROUTPUT
  1539. .PP
  1540. Prints a string and a new line.
  1541. Only on toplevel.
  1542. .NH 4
  1543. DO_MOVE
  1544. .PP
  1545. Calls the move() function in the code generator to implement the move()
  1546. function in the table.
  1547. .NH 4
  1548. DO_ERASE
  1549. .PP
  1550. Marks the register that is its argument as empty.
  1551. .NH 4
  1552. DO_TOKREPLACE
  1553. .PP
  1554. This is the token replacement part.
  1555. It is also called if there is no token replacement because it has
  1556. some other functions as well.
  1557. .PP
  1558. First the tokens that will be pushed on the fakestack are computed
  1559. and stored in a temporary array.
  1560. Then the tokens that were matched in this rule are popped
  1561. and their embedded registers have their reference count
  1562. decremented.
  1563. After that the replacement tokens are pushed.
  1564. .PP
  1565. Finally all registers allocated in this rule have their reference count
  1566. decremented.
  1567. If they were not pushed on the fakestack they will be available again
  1568. in the next code rule.
  1569. .NH 4
  1570. DO_EMREPLACE
  1571. .PP
  1572. Places replacement EM instructions back into the instruction stream.
  1573. .NH 4
  1574. DO_COST
  1575. .PP
  1576. Accounts for cost as given in the code rule.
  1577. .NH 4
  1578. DO_RETURN
  1579. .PP
  1580. Returns from this level of codegen().
  1581. Is used at the end of coercions,
  1582. move rules etc..
  1583. .NH 3
  1584. compute.c
  1585. .PP
  1586. This module computes the various expressions as given
  1587. in the enodes[] array.
  1588. Nothing very special happens here,
  1589. it is just a recursive function computing leaves
  1590. of expressions and applying the operator.
  1591. .NH 3
  1592. equiv.c
  1593. .PP
  1594. In this module the tuples() function is implemented.
  1595. It is given the number of registers needed and
  1596. a list of register lists and it constructs a list of tuples
  1597. where the \fIn\fP'th register comes from the \fIn\fP'th list.
  1598. Before the list is constructed however
  1599. the dynamic register classes are computed.
  1600. Two registers are in the same dynamic class if they are in the
  1601. same static class and their contents is the same.
  1602. .PP
  1603. After that the permute() recursive function is called to
  1604. generate the list of tuples.
  1605. After construction a generated tuple is added to the list
  1606. if it is not already pairwise in the same class
  1607. or if the register relations are not the same,
  1608. i.e. if the first and second register share a common
  1609. subregister in one tuple and not in the other they are considered different.
  1610. .NH 3
  1611. fillem.c
  1612. .PP
  1613. This is the routine that does the reading of EM instructions
  1614. and the handling of pseudos.
  1615. The mach.c module provided by the table writer is included
  1616. at the end of this module.
  1617. The routine fillemlines() is called by nextem() at toplevel
  1618. to make sure there are enough instruction to match.
  1619. It fills the EM instruction buffer up to 5 places from the end to
  1620. keep room for EM replacement instructions,
  1621. or up to a pseudo.
  1622. .PP
  1623. The dopseudo() function performs the function of the pseudo last
  1624. encountered.
  1625. If the pseudo is a
  1626. .B rom
  1627. the corresponding label is saved with the contents of the
  1628. .B rom
  1629. to be available to the code generator later.
  1630. The rest of the routines are small service routines for either
  1631. input or data output.
  1632. .NH 3
  1633. gencode.c
  1634. .PP
  1635. This module contains routines called by codegen() to generate the real
  1636. code to the codefile.
  1637. The function gencode() gets a string as argument and copies it to codefile
  1638. while processing certain embedded control characters implementing
  1639. the $2 and [1.reg] escapes.
  1640. The function genexpr() prints the expression given as argument.
  1641. It is used to implement the %(\ expr\ %) escape.
  1642. The prtoken() function interprets the tokenformat as given in
  1643. the tokens[] array.
  1644. .NH 3
  1645. glosym.c
  1646. .PP
  1647. This module maintains a list of global symbols that have a
  1648. .B rom
  1649. pseudo associated.
  1650. There are functions to enter a symbol and to find a symbol.
  1651. .NH 3
  1652. main.c
  1653. .PP
  1654. Main routine of the code generator.
  1655. Processes arguments and flags.
  1656. Flags available are:
  1657. .IP -d
  1658. Sets debug mode if the code generator was not compiled with
  1659. the NDEBUG macro defined.
  1660. Debug mode gives very long output on stderr indicating
  1661. all steps of the code generation process including nesting
  1662. of the codegen() function.
  1663. .IP -p\fIn\fP
  1664. Sets the lookahead depth to
  1665. .I n ,
  1666. the
  1667. .I p
  1668. stands for ply,
  1669. a well known word in chess playing programs.
  1670. .IP -w\fIn\fP
  1671. Sets the weight percentage for size in the cost function to
  1672. .I n
  1673. percent.
  1674. Uses Euclides algorithm to simplify rationals.
  1675. .NH 3
  1676. move.c
  1677. .PP
  1678. Function to implement the move() pseudo function in the tables,
  1679. register initialization and the setcc and test pseudo functions.
  1680. First tests are made to try to prevent the move from really happening.
  1681. The condition code register is treated special here.
  1682. After that, if there is an after that,
  1683. the move rule is found and the code executed.
  1684. .NH 3
  1685. nextem.c
  1686. .PP
  1687. The entry point of this module is nextem().
  1688. It hashes the next three EM instructions,
  1689. and uses the low order byte of the hash
  1690. as an index into the array pathash[],
  1691. to find a chain of patterns in the array
  1692. pattern[],
  1693. that are all tried for a match.
  1694. .PP
  1695. The function trypat() does most of the work
  1696. checking patterns.
  1697. When a pattern is found to match all instructions
  1698. the operands of the instruction are placed into the dollar[] array.
  1699. Then the boolean expression is tried.
  1700. If it matches the function can return,
  1701. leaving the operands still in the dollar[] array,
  1702. so later in the code rule they can still be used.
  1703. .NH 3
  1704. reg.c
  1705. .PP
  1706. Collection of routines to handle registers.
  1707. Reference count routines are here,
  1708. chrefcount() and getrefcount(),
  1709. plus routines to erase a single register or all of them,
  1710. erasereg() and cleanregs().
  1711. .PP
  1712. If NDEBUG hasn't been defined, here is also the routine that checks
  1713. if the reference count kept with the register information is in
  1714. agreement with the number of times it occurs on the fakestack.
  1715. .NH 3
  1716. salloc.c
  1717. .PP
  1718. Module for string allocation and garbage collection.
  1719. Contains entry points myalloc(),
  1720. a routine calling malloc() and checking whether room is left,
  1721. myfree(), just free(),
  1722. popstr() a function called from state.c to free all strings
  1723. made since the last saved status.
  1724. Furthermore there is salloc() which has the size of the string as parameter
  1725. and returns a pointer to the allocated space,
  1726. while keeping a copy of the pointer for garbage allocation purposes.
  1727. .PP
  1728. The function garbage_collect is called from codegen() at toplevel
  1729. every now and then,
  1730. and checks all places where strings may reside to mark strings
  1731. as being in use.
  1732. Strings not in use are returned to the pool of free space.
  1733. .NH 3
  1734. state.c
  1735. .PP
  1736. Set of routines called to save current status,
  1737. restore a previous saved state and to free the room
  1738. occupied by a saved state.
  1739. A list of structs is kept here to save the state.
  1740. If this is not done,
  1741. small allocates will take space
  1742. from the holes big enough for state saves,
  1743. and as a result every new state save will need a new struct.
  1744. The code generator runs out of room very rapidly under these conditions.
  1745. .NH 3
  1746. subr.c
  1747. .PP
  1748. Random set of leftover routines.
  1749. .NH 4
  1750. match
  1751. .PP
  1752. Computes whether a certain token matches a certain token expression.
  1753. Just computes a bitnumber according to the algorithm explained with
  1754. machsets[],
  1755. and tests the bit and the boolean expression if it is there.
  1756. .NH 4
  1757. instance,cinstance
  1758. .PP
  1759. These two functions compute a token from a description.
  1760. They differ very slight, cinstance() is used to compute
  1761. the result of a coercion in a certain context
  1762. and therefore has more arguments, which it uses instead of
  1763. the global information instance() works on.
  1764. .NH 4
  1765. eqtoken
  1766. .PP
  1767. eqtoken computes whether two tokens can be considered identical.
  1768. Used to check register contents during moves mainly.
  1769. .NH 4
  1770. distance
  1771. .PP
  1772. This is the heuristic function that computes a distance from
  1773. the current fakestack contents to the token pattern in the table.
  1774. It likes exact matches most, then matches where at least the sizes are correct
  1775. and if the sizes are not correct it likes too large sizes more than too
  1776. small, since splitting a token is easier than combining one.
  1777. .NH 4
  1778. split
  1779. .PP
  1780. This function tries to find a splitting coercion
  1781. and executes it immediately when found.
  1782. The fakestack is shuffled thoroughly when this happens,
  1783. so pieces below the token that must be split are saved first.
  1784. .NH 4
  1785. docoerc
  1786. .PP
  1787. This function executes a coercion that was found.
  1788. The same shuffling is done, so the top of the stack is again saved.
  1789. .NH 4
  1790. stackupto
  1791. .PP
  1792. This function gets a pointer into the fakestack and must stack
  1793. every token including the one pointed at up to the bottom of the fakestack.
  1794. The first stacking rule possible is used,
  1795. so rules using registers must come first.
  1796. .NH 4
  1797. findcoerc
  1798. .PP
  1799. Looks for a one to one coercion, if found it returns a pointer
  1800. to it and leaves a list of possible registers to use in the global
  1801. variable curreglist.
  1802. This is used by codegen().
  1803. .NH 3
  1804. var.c
  1805. .PP
  1806. Global variables used by more than one module.
  1807. External definitions are in extern.h.