agjasmin.pas 36 KB

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