agjasmin.pas 41 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228
  1. {
  2. Copyright (c) 1998-2010 by the Free Pascal team
  3. This unit implements the Jasmin assembler writer
  4. This program is free software; you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation; either version 2 of the License, or
  7. (at your option) any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with this program; if not, write to the Free Software
  14. Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  15. ****************************************************************************
  16. }
  17. { Unit for writing Jasmin assembler (JVM bytecode) output.
  18. }
  19. unit agjasmin;
  20. {$i fpcdefs.inc}
  21. interface
  22. uses
  23. cclasses,
  24. globtype,globals,
  25. symconst,symbase,symdef,symsym,
  26. aasmbase,aasmtai,aasmdata,aasmcpu,
  27. assemble;
  28. type
  29. TJasminInstrWriter = class;
  30. {# This is a derived class which is used to write
  31. Jasmin-styled assembler.
  32. }
  33. { TJasminAssembler }
  34. TJasminAssembler=class(texternalassembler)
  35. protected
  36. jasminjar: tcmdstr;
  37. asmfiles: TCmdStrList;
  38. procedure WriteExtraHeader(obj: tabstractrecorddef);
  39. procedure WriteInstruction(hp: tai);
  40. procedure NewAsmFileForStructDef(obj: tabstractrecorddef);
  41. function VisibilityToStr(vis: tvisibility): ansistring;
  42. function MethodDefinition(pd: tprocdef): ansistring;
  43. function ConstValue(csym: tconstsym): ansistring;
  44. function ConstAssignmentValue(csym: tconstsym): ansistring;
  45. function ConstDefinition(sym: tconstsym): ansistring;
  46. function FieldDefinition(sym: tabstractvarsym): ansistring;
  47. function InnerStructDef(obj: tabstractrecorddef): ansistring;
  48. procedure WriteProcDef(pd: tprocdef);
  49. procedure WriteFieldSym(sym: tabstractvarsym);
  50. procedure WriteConstSym(sym: tconstsym);
  51. procedure WriteSymtableVarSyms(st: TSymtable);
  52. procedure WriteSymtableProcdefs(st: TSymtable);
  53. procedure WriteSymtableStructDefs(st: TSymtable);
  54. public
  55. constructor Create(smart: boolean); override;
  56. function MakeCmdLine: TCmdStr;override;
  57. procedure WriteTree(p:TAsmList);override;
  58. procedure WriteAsmList;override;
  59. procedure RemoveAsm; override;
  60. destructor destroy; override;
  61. protected
  62. InstrWriter: TJasminInstrWriter;
  63. end;
  64. {# This is the base class for writing instructions.
  65. The WriteInstruction() method must be overridden
  66. to write a single instruction to the assembler
  67. file.
  68. }
  69. { TJasminInstrWriter }
  70. TJasminInstrWriter = class
  71. constructor create(_owner: TJasminAssembler);
  72. procedure WriteInstruction(hp : tai); virtual;
  73. protected
  74. owner: TJasminAssembler;
  75. end;
  76. implementation
  77. uses
  78. SysUtils,
  79. cutils,cfileutl,systems,script,
  80. fmodule,finput,verbose,
  81. symtype,symcpu,symtable,jvmdef,
  82. itcpujas,cpubase,cpuinfo,cgutils,
  83. widestr
  84. ;
  85. const
  86. line_length = 70;
  87. type
  88. t64bitarray = array[0..7] of byte;
  89. t32bitarray = array[0..3] of byte;
  90. {****************************************************************************}
  91. { Support routines }
  92. {****************************************************************************}
  93. function fixline(s:string):string;
  94. {
  95. return s with all leading and ending spaces and tabs removed
  96. }
  97. var
  98. i,j,k : integer;
  99. begin
  100. i:=length(s);
  101. while (i>0) and (s[i] in [#9,' ']) do
  102. dec(i);
  103. j:=1;
  104. while (j<i) and (s[j] in [#9,' ']) do
  105. inc(j);
  106. for k:=j to i do
  107. if s[k] in [#0..#31,#127..#255] then
  108. s[k]:='.';
  109. fixline:=Copy(s,j,i-j+1);
  110. end;
  111. function constastr(p: pchar; len: longint): ansistring;
  112. var
  113. i,runstart,runlen: longint;
  114. procedure flush;
  115. begin
  116. if runlen>0 then
  117. begin
  118. setlength(result,length(result)+runlen);
  119. move(p[runstart],result[length(result)-runlen+1],runlen);
  120. runlen:=0;
  121. end;
  122. end;
  123. begin
  124. result:='"';
  125. runlen:=0;
  126. runstart:=0;
  127. for i:=0 to len-1 do
  128. begin
  129. { escape control codes }
  130. case p[i] of
  131. { LF and CR must be escaped specially, because \uXXXX parsing
  132. happens in the pre-processor, so it's the same as actually
  133. inserting a newline in the middle of a string constant }
  134. #10:
  135. begin
  136. flush;
  137. result:=result+'\n';
  138. end;
  139. #13:
  140. begin
  141. flush;
  142. result:=result+'\r';
  143. end;
  144. '"','\':
  145. begin
  146. flush;
  147. result:=result+'\'+p[i];
  148. end
  149. else if p[i]<#32 then
  150. begin
  151. flush;
  152. result:=result+'\u'+hexstr(ord(p[i]),4);
  153. end
  154. else if p[i]<#127 then
  155. begin
  156. if runlen=0 then
  157. runstart:=i;
  158. inc(runlen);
  159. end
  160. else
  161. begin
  162. { see comments in njvmcon }
  163. flush;
  164. result:=result+'\u'+hexstr(ord(p[i]),4)
  165. end;
  166. end;
  167. end;
  168. flush;
  169. result:=result+'"';
  170. end;
  171. function constwstr(w: pcompilerwidechar; len: longint): ansistring;
  172. var
  173. i: longint;
  174. begin
  175. result:='"';
  176. for i:=0 to len-1 do
  177. begin
  178. { escape control codes }
  179. case w[i] of
  180. 10:
  181. result:=result+'\n';
  182. 13:
  183. result:=result+'\r';
  184. ord('"'),ord('\'):
  185. result:=result+'\'+chr(w[i]);
  186. else if (w[i]<32) or
  187. (w[i]>=127) then
  188. result:=result+'\u'+hexstr(w[i],4)
  189. else
  190. result:=result+char(w[i]);
  191. end;
  192. end;
  193. result:=result+'"';
  194. end;
  195. function constsingle(s: single): ansistring;
  196. begin
  197. result:='0fx'+hexstr(longint(t32bitarray(s)),8);
  198. end;
  199. function constdouble(d: double): ansistring;
  200. begin
  201. // force interpretation as double (since we write it out as an
  202. // integer, we never have to swap the endianess). We have to
  203. // include the sign separately because of the way Java parses
  204. // hex numbers (0x8000000000000000 is not a valid long)
  205. result:=hexstr(abs(int64(t64bitarray(d))),16);
  206. if int64(t64bitarray(d))<0 then
  207. result:='-'+result;
  208. result:='0dx'+result;
  209. end;
  210. {****************************************************************************}
  211. { Jasmin Assembler writer }
  212. {****************************************************************************}
  213. destructor TJasminAssembler.Destroy;
  214. begin
  215. InstrWriter.free;
  216. asmfiles.free;
  217. inherited destroy;
  218. end;
  219. procedure TJasminAssembler.WriteTree(p:TAsmList);
  220. var
  221. ch : char;
  222. hp : tai;
  223. hp1 : tailineinfo;
  224. s : ansistring;
  225. i,pos : longint;
  226. InlineLevel : longint;
  227. do_line : boolean;
  228. begin
  229. if not assigned(p) then
  230. exit;
  231. InlineLevel:=0;
  232. { lineinfo is only needed for al_procedures (PFV) }
  233. do_line:=(cs_asm_source in current_settings.globalswitches);
  234. hp:=tai(p.first);
  235. while assigned(hp) do
  236. begin
  237. prefetch(pointer(hp.next)^);
  238. if not(hp.typ in SkipLineInfo) then
  239. begin
  240. hp1 := hp as tailineinfo;
  241. current_filepos:=hp1.fileinfo;
  242. { no line info for inlined code }
  243. if do_line and (inlinelevel=0) then
  244. begin
  245. { load infile }
  246. if lastfileinfo.fileindex<>hp1.fileinfo.fileindex then
  247. begin
  248. infile:=current_module.sourcefiles.get_file(hp1.fileinfo.fileindex);
  249. if assigned(infile) then
  250. begin
  251. { open only if needed !! }
  252. if (cs_asm_source in current_settings.globalswitches) then
  253. infile.open;
  254. end;
  255. { avoid unnecessary reopens of the same file !! }
  256. lastfileinfo.fileindex:=hp1.fileinfo.fileindex;
  257. { be sure to change line !! }
  258. lastfileinfo.line:=-1;
  259. end;
  260. { write source }
  261. if (cs_asm_source in current_settings.globalswitches) and
  262. assigned(infile) then
  263. begin
  264. if (infile<>lastinfile) then
  265. begin
  266. AsmWriteLn(target_asm.comment+'['+infile.name+']');
  267. if assigned(lastinfile) then
  268. lastinfile.close;
  269. end;
  270. if (hp1.fileinfo.line<>lastfileinfo.line) and
  271. ((hp1.fileinfo.line<infile.maxlinebuf) or (InlineLevel>0)) then
  272. begin
  273. if (hp1.fileinfo.line<>0) and
  274. ((infile.linebuf^[hp1.fileinfo.line]>=0) or (InlineLevel>0)) then
  275. AsmWriteLn(target_asm.comment+'['+tostr(hp1.fileinfo.line)+'] '+
  276. fixline(infile.GetLineStr(hp1.fileinfo.line)));
  277. { set it to a negative value !
  278. to make that is has been read already !! PM }
  279. if (infile.linebuf^[hp1.fileinfo.line]>=0) then
  280. infile.linebuf^[hp1.fileinfo.line]:=-infile.linebuf^[hp1.fileinfo.line]-1;
  281. end;
  282. end;
  283. lastfileinfo:=hp1.fileinfo;
  284. lastinfile:=infile;
  285. end;
  286. end;
  287. case hp.typ of
  288. ait_comment :
  289. Begin
  290. AsmWrite(target_asm.comment);
  291. AsmWritePChar(tai_comment(hp).str);
  292. AsmLn;
  293. End;
  294. ait_regalloc :
  295. begin
  296. if (cs_asm_regalloc in current_settings.globalswitches) then
  297. begin
  298. AsmWrite(#9+target_asm.comment+'Register ');
  299. repeat
  300. AsmWrite(std_regname(Tai_regalloc(hp).reg));
  301. if (hp.next=nil) or
  302. (tai(hp.next).typ<>ait_regalloc) or
  303. (tai_regalloc(hp.next).ratype<>tai_regalloc(hp).ratype) then
  304. break;
  305. hp:=tai(hp.next);
  306. AsmWrite(',');
  307. until false;
  308. AsmWrite(' ');
  309. AsmWriteLn(regallocstr[tai_regalloc(hp).ratype]);
  310. end;
  311. end;
  312. ait_tempalloc :
  313. begin
  314. if (cs_asm_tempalloc in current_settings.globalswitches) then
  315. begin
  316. {$ifdef EXTDEBUG}
  317. if assigned(tai_tempalloc(hp).problem) then
  318. AsmWriteLn(target_asm.comment+'Temp '+tostr(tai_tempalloc(hp).temppos)+','+
  319. tostr(tai_tempalloc(hp).tempsize)+' '+tai_tempalloc(hp).problem^)
  320. else
  321. {$endif EXTDEBUG}
  322. AsmWriteLn(target_asm.comment+'Temp '+tostr(tai_tempalloc(hp).temppos)+','+
  323. tostr(tai_tempalloc(hp).tempsize)+' '+tempallocstr[tai_tempalloc(hp).allocation]);
  324. end;
  325. end;
  326. ait_align :
  327. begin
  328. end;
  329. ait_section :
  330. begin
  331. end;
  332. ait_datablock :
  333. begin
  334. internalerror(2010122701);
  335. end;
  336. ait_const:
  337. begin
  338. AsmWriteln('constant');
  339. // internalerror(2010122702);
  340. end;
  341. ait_realconst :
  342. begin
  343. internalerror(2010122703);
  344. end;
  345. ait_string :
  346. begin
  347. pos:=0;
  348. for i:=1 to tai_string(hp).len do
  349. begin
  350. if pos=0 then
  351. begin
  352. AsmWrite(#9'strconst: '#9'"');
  353. pos:=20;
  354. end;
  355. ch:=tai_string(hp).str[i-1];
  356. case ch of
  357. #0, {This can't be done by range, because a bug in FPC}
  358. #1..#31,
  359. #128..#255 : s:='\'+tostr(ord(ch) shr 6)+tostr((ord(ch) and 63) shr 3)+tostr(ord(ch) and 7);
  360. '"' : s:='\"';
  361. '\' : s:='\\';
  362. else
  363. s:=ch;
  364. end;
  365. AsmWrite(s);
  366. inc(pos,length(s));
  367. if (pos>line_length) or (i=tai_string(hp).len) then
  368. begin
  369. AsmWriteLn('"');
  370. pos:=0;
  371. end;
  372. end;
  373. end;
  374. ait_label :
  375. begin
  376. if (tai_label(hp).labsym.is_used) then
  377. begin
  378. AsmWrite(tai_label(hp).labsym.name);
  379. AsmWriteLn(':');
  380. end;
  381. end;
  382. ait_symbol :
  383. begin
  384. if (tai_symbol(hp).sym.typ = AT_FUNCTION) then
  385. begin
  386. end
  387. else
  388. begin
  389. AsmWrite('data symbol: ');
  390. AsmWriteln(tai_symbol(hp).sym.name);
  391. // internalerror(2010122706);
  392. end;
  393. end;
  394. ait_symbol_end :
  395. begin
  396. end;
  397. ait_instruction :
  398. begin
  399. WriteInstruction(hp);
  400. end;
  401. ait_force_line,
  402. ait_function_name : ;
  403. ait_cutobject :
  404. begin
  405. end;
  406. ait_marker :
  407. if tai_marker(hp).kind=mark_NoLineInfoStart then
  408. inc(InlineLevel)
  409. else if tai_marker(hp).kind=mark_NoLineInfoEnd then
  410. dec(InlineLevel);
  411. ait_directive :
  412. begin
  413. AsmWrite('.'+directivestr[tai_directive(hp).directive]+' ');
  414. if tai_directive(hp).name<>'' then
  415. AsmWrite(tai_directive(hp).name);
  416. AsmLn;
  417. end;
  418. ait_jvar:
  419. begin
  420. AsmWrite('.var ');
  421. AsmWrite(tostr(tai_jvar(hp).stackslot));
  422. AsmWrite(' is ');
  423. AsmWrite(tai_jvar(hp).desc^);
  424. AsmWrite(' from ');
  425. AsmWrite(tai_jvar(hp).startlab.name);
  426. AsmWrite(' to ');
  427. AsmWriteLn(tai_jvar(hp).stoplab.name);
  428. end;
  429. ait_jcatch:
  430. begin
  431. AsmWrite('.catch ');
  432. AsmWrite(tai_jcatch(hp).name^);
  433. AsmWrite(' from ');
  434. AsmWrite(tai_jcatch(hp).startlab.name);
  435. AsmWrite(' to ');
  436. AsmWrite(tai_jcatch(hp).stoplab.name);
  437. AsmWrite(' using ');
  438. AsmWriteLn(tai_jcatch(hp).handlerlab.name);
  439. end;
  440. else
  441. internalerror(2010122707);
  442. end;
  443. hp:=tai(hp.next);
  444. end;
  445. end;
  446. procedure TJasminAssembler.WriteExtraHeader(obj: tabstractrecorddef);
  447. var
  448. superclass,
  449. intf: tobjectdef;
  450. n: ansistring;
  451. i: longint;
  452. toplevelowner: tsymtable;
  453. begin
  454. { JVM 1.5+ }
  455. AsmWriteLn('.bytecode 49.0');
  456. // include files are not support by Java, and the directory of the main
  457. // source file must not be specified
  458. if current_module.mainsource<>'' then
  459. n:=ExtractFileName(current_module.mainsource)
  460. else
  461. n:=InputFileName;
  462. AsmWriteLn('.source '+ExtractFileName(n));
  463. { class/interface name }
  464. if not assigned(obj) then
  465. begin
  466. { fake class type for unit -> name=unitname and
  467. superclass=java.lang.object, make final so you cannot descend
  468. from it }
  469. AsmWrite('.class final public ');
  470. if assigned(current_module.namespace) then
  471. AsmWrite(current_module.namespace^+'.');
  472. AsmWriteln(current_module.realmodulename^);
  473. AsmWriteLn('.super java/lang/Object');
  474. end
  475. else
  476. begin
  477. toplevelowner:=obj.owner;
  478. while not(toplevelowner.symtabletype in [staticsymtable,globalsymtable]) do
  479. toplevelowner:=toplevelowner.defowner.owner;
  480. case obj.typ of
  481. recorddef:
  482. begin
  483. { can't inherit from records }
  484. AsmWrite('.class final ');
  485. if toplevelowner.symtabletype=globalsymtable then
  486. AsmWrite('public ');
  487. AsmWriteln(obj.jvm_full_typename(true));
  488. superclass:=java_fpcbaserecordtype;
  489. end;
  490. objectdef:
  491. begin
  492. case tobjectdef(obj).objecttype of
  493. odt_javaclass:
  494. begin
  495. AsmWrite('.class ');
  496. if oo_is_sealed in tobjectdef(obj).objectoptions then
  497. AsmWrite('final ');
  498. if (oo_is_abstract in tobjectdef(obj).objectoptions) or
  499. (tobjectdef(obj).abstractcnt<>0) then
  500. AsmWrite('abstract ');
  501. if toplevelowner.symtabletype=globalsymtable then
  502. AsmWrite('public ');
  503. if (oo_is_enum_class in tobjectdef(obj).objectoptions) then
  504. AsmWrite('enum ');
  505. AsmWriteln(obj.jvm_full_typename(true));
  506. superclass:=tobjectdef(obj).childof;
  507. end;
  508. odt_interfacejava:
  509. begin
  510. AsmWrite('.interface abstract ');
  511. if toplevelowner.symtabletype=globalsymtable then
  512. AsmWrite('public ');
  513. AsmWriteLn(obj.jvm_full_typename(true));
  514. { interfaces must always specify Java.lang.object as
  515. superclass }
  516. superclass:=java_jlobject;
  517. end
  518. else
  519. internalerror(2011010906);
  520. end;
  521. end;
  522. end;
  523. { superclass }
  524. if assigned(superclass) then
  525. begin
  526. AsmWrite('.super ');
  527. if assigned(superclass.import_lib) then
  528. AsmWrite(superclass.import_lib^+'/');
  529. AsmWriteln(superclass.objextname^);
  530. end;
  531. { implemented interfaces }
  532. if (obj.typ=objectdef) and
  533. assigned(tobjectdef(obj).ImplementedInterfaces) then
  534. begin
  535. for i:=0 to tobjectdef(obj).ImplementedInterfaces.count-1 do
  536. begin
  537. intf:=TImplementedInterface(tobjectdef(obj).ImplementedInterfaces[i]).IntfDef;
  538. AsmWrite('.implements ');
  539. AsmWriteLn(intf.jvm_full_typename(true));
  540. end;
  541. end;
  542. { signature for enum classes (must come after superclass and
  543. implemented interfaces) }
  544. if (obj.typ=objectdef) and
  545. (oo_is_enum_class in tobjectdef(obj).objectoptions) then
  546. AsmWriteln('.signature "Ljava/lang/Enum<L'+obj.jvm_full_typename(true)+';>;"');
  547. { in case of nested class: relation to parent class }
  548. if obj.owner.symtabletype in [objectsymtable,recordsymtable] then
  549. AsmWriteln(InnerStructDef(obj));
  550. { add all nested classes }
  551. for i:=0 to obj.symtable.deflist.count-1 do
  552. if (is_java_class_or_interface(tdef(obj.symtable.deflist[i])) or
  553. (tdef(obj.symtable.deflist[i]).typ=recorddef)) and
  554. not(df_generic in tdef(obj.symtable.deflist[i]).defoptions) then
  555. AsmWriteln(InnerStructDef(tabstractrecorddef(obj.symtable.deflist[i])));
  556. end;
  557. AsmLn;
  558. end;
  559. procedure TJasminAssembler.WriteInstruction(hp: tai);
  560. begin
  561. InstrWriter.WriteInstruction(hp);
  562. end;
  563. function TJasminAssembler.MakeCmdLine: TCmdStr;
  564. const
  565. jasminjarname = 'jasmin.jar';
  566. var
  567. filenames: tcmdstr;
  568. asmfile: tcmdstrlistitem;
  569. jasminjarfound: boolean;
  570. begin
  571. if jasminjar='' then
  572. begin
  573. jasminjarfound:=false;
  574. if utilsdirectory<>'' then
  575. jasminjarfound:=FindFile(jasminjarname,utilsdirectory,false,jasminjar);
  576. if not jasminjarfound then
  577. jasminjarfound:=FindFileInExeLocations(jasminjarname,false,jasminjar);
  578. if (not jasminjarfound) and not(cs_asm_extern in current_settings.globalswitches) then
  579. begin
  580. Message1(exec_e_assembler_not_found,jasminjarname);
  581. current_settings.globalswitches:=current_settings.globalswitches+[cs_asm_extern];
  582. end;
  583. if jasminjarfound then
  584. Message1(exec_t_using_assembler,jasminjar);
  585. end;
  586. result:=target_asm.asmcmd;
  587. filenames:=ScriptFixFileName(AsmFileName);
  588. if cs_asm_extern in current_settings.globalswitches then
  589. filenames:=maybequoted(filenames);
  590. asmfile:=tcmdstrlistitem(asmfiles.First);
  591. while assigned(asmfile) do
  592. begin
  593. if cs_asm_extern in current_settings.globalswitches then
  594. filenames:=filenames+' '+maybequoted(ScriptFixFileName(asmfile.str))
  595. else
  596. filenames:=filenames+' '+ScriptFixFileName(asmfile.str);
  597. asmfile:=tcmdstrlistitem(asmfile.next);
  598. end;
  599. Replace(result,'$ASM',filenames);
  600. if (path<>'') then
  601. if cs_asm_extern in current_settings.globalswitches then
  602. Replace(result,'$OBJDIR',maybequoted(ScriptFixFileName(path)))
  603. else
  604. Replace(result,'$OBJDIR',ScriptFixFileName(path))
  605. else
  606. Replace(result,'$OBJDIR','.');
  607. if cs_asm_extern in current_settings.globalswitches then
  608. Replace(result,'$JASMINJAR',maybequoted(ScriptFixFileName(jasminjar)))
  609. else
  610. Replace(result,'$JASMINJAR',ScriptFixFileName(jasminjar));
  611. Replace(result,'$EXTRAOPT',asmextraopt);
  612. end;
  613. procedure TJasminAssembler.NewAsmFileForStructDef(obj: tabstractrecorddef);
  614. begin
  615. if AsmSize<>AsmStartSize then
  616. begin
  617. AsmClose;
  618. asmfiles.Concat(AsmFileName);
  619. end
  620. else
  621. AsmClear;
  622. AsmFileName:=obj.jvm_full_typename(false);
  623. AsmFileName:=Path+FixFileName(AsmFileName)+target_info.asmext;
  624. AsmCreate(cut_normal);
  625. end;
  626. function TJasminAssembler.VisibilityToStr(vis: tvisibility): ansistring;
  627. begin
  628. case vis of
  629. vis_hidden,
  630. vis_strictprivate:
  631. result:='private ';
  632. { protected in Java means "accessible by subclasses *and* by classes
  633. in the same package" -> similar to regular "protected" in Pascal;
  634. "strict protected" is actually more strict in Pascal than in Java,
  635. but there's not much we can do about that }
  636. vis_protected,
  637. vis_strictprotected:
  638. result:='protected ';
  639. vis_private:
  640. { pick default visibility = "package" visibility; required because
  641. other classes in the same unit can also access these symbols }
  642. result:='';
  643. vis_public:
  644. result:='public '
  645. else
  646. internalerror(2010122609);
  647. end;
  648. end;
  649. function TJasminAssembler.MethodDefinition(pd: tprocdef): ansistring;
  650. begin
  651. result:=VisibilityToStr(pd.visibility);
  652. if (pd.procsym.owner.symtabletype in [globalsymtable,staticsymtable,localsymtable]) or
  653. (po_classmethod in pd.procoptions) then
  654. result:=result+'static ';
  655. if (po_abstractmethod in pd.procoptions) or
  656. is_javainterface(tdef(pd.owner.defowner)) then
  657. result:=result+'abstract ';
  658. if (pd.procsym.owner.symtabletype in [globalsymtable,staticsymtable,localsymtable]) or
  659. (po_finalmethod in pd.procoptions) or
  660. (not(po_virtualmethod in pd.procoptions) and
  661. not(po_classmethod in pd.procoptions) and
  662. not(pd.proctypeoption in [potype_constructor,potype_class_constructor])) then
  663. result:=result+'final ';
  664. result:=result+tcpuprocdef(pd).jvmmangledbasename(false);
  665. end;
  666. function TJasminAssembler.ConstValue(csym: tconstsym): ansistring;
  667. begin
  668. case csym.consttyp of
  669. constord:
  670. { always interpret as signed value, because the JVM does not
  671. support unsigned values }
  672. case csym.constdef.size of
  673. 1:result:=tostr(shortint(csym.value.valueord.svalue));
  674. 2:result:=tostr(smallint(csym.value.valueord.svalue));
  675. 4:result:=tostr(longint(csym.value.valueord.svalue));
  676. 8:result:=tostr(csym.value.valueord.svalue);
  677. end;
  678. conststring:
  679. result:=constastr(pchar(csym.value.valueptr),csym.value.len);
  680. constreal:
  681. case tfloatdef(csym.constdef).floattype of
  682. s32real:
  683. result:=constsingle(pbestreal(csym.value.valueptr)^);
  684. s64real:
  685. result:=constdouble(pbestreal(csym.value.valueptr)^);
  686. else
  687. internalerror(2011021204);
  688. end;
  689. constset:
  690. result:='TODO: add support for constant sets';
  691. constpointer:
  692. { can only be null, but that's the default value and should not
  693. be written; there's no primitive type that can hold nill }
  694. internalerror(2011021201);
  695. constnil:
  696. internalerror(2011021202);
  697. constresourcestring:
  698. result:='TODO: add support for constant resource strings';
  699. constwstring:
  700. result:=constwstr(pcompilerwidestring(csym.value.valueptr)^.data,pcompilerwidestring(csym.value.valueptr)^.len);
  701. constguid:
  702. result:='TODO: add support for constant guids';
  703. else
  704. internalerror(2011021205);
  705. end;
  706. end;
  707. function TJasminAssembler.ConstAssignmentValue(csym: tconstsym): ansistring;
  708. begin
  709. result:='';
  710. { nil is the default value -> don't write explicitly }
  711. case csym.consttyp of
  712. constpointer:
  713. begin
  714. if csym.value.valueordptr<>0 then
  715. internalerror(2011021206);
  716. end;
  717. constnil:
  718. ;
  719. else
  720. begin
  721. { enums and sets are initialized as typed constants }
  722. if not assigned(csym.constdef) or
  723. not(csym.constdef.typ in [enumdef,setdef]) then
  724. result:=' = '+ConstValue(csym);
  725. end;
  726. end;
  727. end;
  728. function TJasminAssembler.ConstDefinition(sym: tconstsym): ansistring;
  729. begin
  730. result:=VisibilityToStr(sym.visibility);
  731. { formal constants are always class-level, not instance-level }
  732. result:=result+'static final ';
  733. if sp_internal in sym.symoptions then
  734. result:=result+'synthetic ';
  735. result:=result+jvmmangledbasename(sym,true);
  736. result:=result+ConstAssignmentValue(tconstsym(sym));
  737. end;
  738. function TJasminAssembler.FieldDefinition(sym: tabstractvarsym): ansistring;
  739. begin
  740. case sym.typ of
  741. staticvarsym:
  742. begin
  743. if sym.owner.symtabletype=globalsymtable then
  744. result:='public '
  745. else
  746. { package visbility }
  747. result:='';
  748. end;
  749. fieldvarsym,
  750. absolutevarsym:
  751. result:=VisibilityToStr(tstoredsym(sym).visibility);
  752. else
  753. internalerror(2011011204);
  754. end;
  755. if (sym.typ=staticvarsym) or
  756. (sp_static in sym.symoptions) then
  757. result:=result+'static ';
  758. if sym.varspez in [vs_const,vs_final] then
  759. result:=result+'final ';
  760. if sp_internal in sym.symoptions then
  761. result:=result+'synthetic ';
  762. { mark the class fields of enum classes that contain the initialised
  763. enum instances as "enum" (recognise them by the fact that their type
  764. is the same as their parent class, and that this parent class is
  765. marked as oo_is_enum_class) }
  766. if assigned(sym.owner.defowner) and
  767. (tdef(sym.owner.defowner).typ=objectdef) and
  768. (oo_is_enum_class in tobjectdef(sym.owner.defowner).objectoptions) and
  769. (sym.typ=staticvarsym) and
  770. (tstaticvarsym(sym).vardef=tdef(sym.owner.defowner)) then
  771. result:=result+'enum ';
  772. result:=result+jvmmangledbasename(sym,true);
  773. end;
  774. function TJasminAssembler.InnerStructDef(obj: tabstractrecorddef): ansistring;
  775. var
  776. extname: pshortstring;
  777. kindname: ansistring;
  778. begin
  779. if not(obj.owner.defowner.typ in [objectdef,recorddef]) then
  780. internalerror(2011021701);
  781. { Nested classes in the Pascal sense are equivalent to "static"
  782. inner classes in Java -- will be changed when support for
  783. Java-style non-static classes is added }
  784. case obj.typ of
  785. recorddef:
  786. begin
  787. kindname:='class static ';
  788. extname:=obj.symtable.realname;
  789. end;
  790. objectdef:
  791. begin
  792. extname:=tobjectdef(obj).objextname;
  793. case tobjectdef(obj).objecttype of
  794. odt_javaclass:
  795. kindname:='class static ';
  796. odt_interfacejava:
  797. kindname:='interface static abstract ';
  798. else
  799. internalerror(2011021702);
  800. end;
  801. end;
  802. else
  803. internalerror(2011032809);
  804. end;
  805. result:=
  806. '.inner '+
  807. kindname+
  808. VisibilityToStr(obj.typesym.visibility)+
  809. extname^+
  810. ' inner '+
  811. obj.jvm_full_typename(true)+
  812. ' outer '+
  813. tabstractrecorddef(obj.owner.defowner).jvm_full_typename(true);
  814. end;
  815. procedure TJasminAssembler.WriteProcDef(pd: tprocdef);
  816. begin
  817. if not assigned(tcpuprocdef(pd).exprasmlist) and
  818. not(po_abstractmethod in pd.procoptions) and
  819. (not is_javainterface(pd.struct) or
  820. (pd.proctypeoption in [potype_unitinit,potype_unitfinalize])) then
  821. exit;
  822. AsmWrite('.method ');
  823. AsmWriteln(MethodDefinition(pd));
  824. if jvmtypeneedssignature(pd) then
  825. begin
  826. AsmWrite('.signature "');
  827. AsmWrite(tcpuprocdef(pd).jvmmangledbasename(true));
  828. AsmWriteln('"');
  829. end;
  830. WriteTree(tcpuprocdef(pd).exprasmlist);
  831. AsmWriteln('.end method');
  832. AsmLn;
  833. end;
  834. procedure TJasminAssembler.WriteFieldSym(sym: tabstractvarsym);
  835. begin
  836. { internal static field definition alias -> skip }
  837. if (sym.owner.symtabletype in [recordsymtable,ObjectSymtable]) and
  838. (sym.typ=staticvarsym) then
  839. exit;
  840. { external or threadvar definition -> no definition here }
  841. if ([vo_is_external,vo_is_thread_var]*sym.varoptions)<>[] then
  842. exit;
  843. AsmWrite('.field ');
  844. AsmWriteln(FieldDefinition(sym));
  845. end;
  846. procedure TJasminAssembler.WriteConstSym(sym: tconstsym);
  847. begin
  848. AsmWrite('.field ');
  849. AsmWriteln(ConstDefinition(sym));
  850. end;
  851. procedure TJasminAssembler.WriteSymtableVarSyms(st: TSymtable);
  852. var
  853. sym : tsym;
  854. i,j : longint;
  855. begin
  856. if not assigned(st) then
  857. exit;
  858. for i:=0 to st.SymList.Count-1 do
  859. begin
  860. sym:=tsym(st.SymList[i]);
  861. case sym.typ of
  862. staticvarsym,
  863. fieldvarsym:
  864. begin
  865. WriteFieldSym(tabstractvarsym(sym));
  866. if (sym.typ=staticvarsym) and
  867. assigned(tstaticvarsym(sym).defaultconstsym) then
  868. WriteFieldSym(tabstractvarsym(tstaticvarsym(sym).defaultconstsym));
  869. end;
  870. constsym:
  871. begin
  872. { multiple procedures can have constants with the same name }
  873. if not assigned(sym.owner.defowner) or
  874. (tdef(sym.owner.defowner).typ<>procdef) then
  875. WriteConstSym(tconstsym(sym));
  876. end;
  877. procsym:
  878. begin
  879. for j:=0 to tprocsym(sym).procdeflist.count-1 do
  880. if not(df_generic in tprocdef(tprocsym(sym).procdeflist[j]).defoptions) then
  881. WriteSymtableVarSyms(tprocdef(tprocsym(sym).procdeflist[j]).localst);
  882. end;
  883. end;
  884. end;
  885. end;
  886. procedure TJasminAssembler.WriteSymtableProcdefs(st: TSymtable);
  887. var
  888. i : longint;
  889. def : tdef;
  890. begin
  891. if not assigned(st) then
  892. exit;
  893. for i:=0 to st.DefList.Count-1 do
  894. begin
  895. def:=tdef(st.DefList[i]);
  896. case def.typ of
  897. procdef :
  898. begin
  899. { methods are also in the static/globalsymtable of the unit
  900. -> make sure they are only written for the objectdefs that
  901. own them }
  902. if (not(st.symtabletype in [staticsymtable,globalsymtable]) or
  903. (def.owner=st)) and
  904. not(df_generic in def.defoptions) then
  905. begin
  906. WriteProcDef(tprocdef(def));
  907. if assigned(tprocdef(def).localst) then
  908. WriteSymtableProcdefs(tprocdef(def).localst);
  909. end;
  910. end;
  911. end;
  912. end;
  913. end;
  914. procedure TJasminAssembler.WriteSymtableStructDefs(st: TSymtable);
  915. var
  916. i : longint;
  917. def : tdef;
  918. obj : tabstractrecorddef;
  919. nestedstructs: tfpobjectlist;
  920. begin
  921. if not assigned(st) then
  922. exit;
  923. nestedstructs:=tfpobjectlist.create(false);
  924. for i:=0 to st.DefList.Count-1 do
  925. begin
  926. def:=tdef(st.DefList[i]);
  927. if df_generic in def.defoptions then
  928. continue;
  929. case def.typ of
  930. objectdef:
  931. if not(oo_is_external in tobjectdef(def).objectoptions) then
  932. nestedstructs.add(def);
  933. recorddef:
  934. nestedstructs.add(def);
  935. end;
  936. end;
  937. for i:=0 to nestedstructs.count-1 do
  938. begin
  939. obj:=tabstractrecorddef(nestedstructs[i]);
  940. NewAsmFileForStructDef(obj);
  941. WriteExtraHeader(obj);
  942. WriteSymtableVarSyms(obj.symtable);
  943. AsmLn;
  944. WriteSymtableProcDefs(obj.symtable);
  945. WriteSymtableStructDefs(obj.symtable);
  946. end;
  947. nestedstructs.free;
  948. end;
  949. constructor TJasminAssembler.Create(smart: boolean);
  950. begin
  951. inherited create(smart);
  952. InstrWriter:=TJasminInstrWriter.Create(self);
  953. asmfiles:=TCmdStrList.Create;
  954. end;
  955. procedure TJasminAssembler.WriteAsmList;
  956. begin
  957. {$ifdef EXTDEBUG}
  958. if assigned(current_module.mainsource) then
  959. Comment(V_Debug,'Start writing Jasmin-styled assembler output for '+current_module.mainsource);
  960. {$endif}
  961. AsmStartSize:=AsmSize;
  962. WriteExtraHeader(nil);
  963. (*
  964. for hal:=low(TasmlistType) to high(TasmlistType) do
  965. begin
  966. AsmWriteLn(target_asm.comment+'Begin asmlist '+AsmlistTypeStr[hal]);
  967. writetree(current_asmdata.asmlists[hal]);
  968. AsmWriteLn(target_asm.comment+'End asmlist '+AsmlistTypeStr[hal]);
  969. end;
  970. *)
  971. { print all global variables }
  972. WriteSymtableVarSyms(current_module.globalsymtable);
  973. WriteSymtableVarSyms(current_module.localsymtable);
  974. AsmLn;
  975. { print all global procedures/functions }
  976. WriteSymtableProcdefs(current_module.globalsymtable);
  977. WriteSymtableProcdefs(current_module.localsymtable);
  978. WriteSymtableStructDefs(current_module.globalsymtable);
  979. WriteSymtableStructDefs(current_module.localsymtable);
  980. AsmLn;
  981. {$ifdef EXTDEBUG}
  982. if assigned(current_module.mainsource) then
  983. Comment(V_Debug,'Done writing gas-styled assembler output for '+current_module.mainsource);
  984. {$endif EXTDEBUG}
  985. end;
  986. procedure TJasminAssembler.RemoveAsm;
  987. var
  988. g : file;
  989. begin
  990. inherited;
  991. if cs_asm_leave in current_settings.globalswitches then
  992. exit;
  993. while not asmfiles.empty do
  994. begin
  995. if cs_asm_extern in current_settings.globalswitches then
  996. AsmRes.AddDeleteCommand(asmfiles.GetFirst)
  997. else
  998. begin
  999. assign(g,asmfiles.GetFirst);
  1000. {$I-}
  1001. erase(g);
  1002. {$I+}
  1003. if ioresult<>0 then;
  1004. end;
  1005. end;
  1006. end;
  1007. {****************************************************************************}
  1008. { Jasmin Instruction Writer }
  1009. {****************************************************************************}
  1010. constructor TJasminInstrWriter.create(_owner: TJasminAssembler);
  1011. begin
  1012. inherited create;
  1013. owner := _owner;
  1014. end;
  1015. function getreferencestring(var ref : treference) : ansistring;
  1016. begin
  1017. if (ref.arrayreftype<>art_none) or
  1018. (ref.index<>NR_NO) then
  1019. internalerror(2010122809);
  1020. if assigned(ref.symbol) then
  1021. begin
  1022. // global symbol or field -> full type and name
  1023. // ref.base can be <> NR_NO in case an instance field is loaded.
  1024. // This register is not part of this instruction, it will have
  1025. // been placed on the stack by the previous one.
  1026. if (ref.offset<>0) then
  1027. internalerror(2010122811);
  1028. result:=ref.symbol.name;
  1029. end
  1030. else
  1031. begin
  1032. // local symbol -> stack slot, stored in offset
  1033. if ref.base<>NR_STACK_POINTER_REG then
  1034. internalerror(2010122810);
  1035. result:=tostr(ref.offset);
  1036. end;
  1037. end;
  1038. function getopstr(const o:toper) : ansistring;
  1039. var
  1040. d: double;
  1041. s: single;
  1042. begin
  1043. case o.typ of
  1044. top_reg:
  1045. // should have been translated into a memory location by the
  1046. // register allocator)
  1047. if (cs_no_regalloc in current_settings.globalswitches) then
  1048. getopstr:=std_regname(o.reg)
  1049. else
  1050. internalerror(2010122803);
  1051. top_const:
  1052. str(o.val,result);
  1053. top_ref:
  1054. getopstr:=getreferencestring(o.ref^);
  1055. top_single:
  1056. begin
  1057. result:=constsingle(o.sval);
  1058. end;
  1059. top_double:
  1060. begin
  1061. result:=constdouble(o.dval);
  1062. end;
  1063. top_string:
  1064. begin
  1065. result:=constastr(o.pcval,o.pcvallen);
  1066. end;
  1067. top_wstring:
  1068. begin
  1069. result:=constwstr(o.pwstrval^.data,getlengthwidestring(o.pwstrval));
  1070. end
  1071. else
  1072. internalerror(2010122802);
  1073. end;
  1074. end;
  1075. procedure TJasminInstrWriter.WriteInstruction(hp: tai);
  1076. var
  1077. s: ansistring;
  1078. i: byte;
  1079. sep: ansistring;
  1080. begin
  1081. s:=#9+jas_op2str[taicpu(hp).opcode];
  1082. if taicpu(hp).ops<>0 then
  1083. begin
  1084. sep:=#9;
  1085. for i:=0 to taicpu(hp).ops-1 do
  1086. begin
  1087. s:=s+sep+getopstr(taicpu(hp).oper[i]^);
  1088. sep:=' ';
  1089. end;
  1090. end;
  1091. owner.AsmWriteLn(s);
  1092. end;
  1093. {****************************************************************************}
  1094. { Jasmin Instruction Writer }
  1095. {****************************************************************************}
  1096. const
  1097. as_jvm_jasmin_info : tasminfo =
  1098. (
  1099. id : as_jvm_jasmin;
  1100. idtxt : 'Jasmin';
  1101. asmbin : 'java';
  1102. asmcmd : '-jar $JASMINJAR $ASM $EXTRAOPT -d $OBJDIR';
  1103. supported_targets : [system_jvm_java32,system_jvm_android32];
  1104. flags : [];
  1105. labelprefix : 'L';
  1106. comment : ' ; ';
  1107. dollarsign : '$';
  1108. );
  1109. begin
  1110. RegisterAssembler(as_jvm_jasmin_info,TJasminAssembler);
  1111. end.