agjasmin.pas 35 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090
  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. begin
  459. { JVM 1.5+ }
  460. AsmWriteLn('.bytecode 49.0');
  461. // include files are not support by Java, and the directory of the main
  462. // source file must not be specified
  463. if assigned(current_module.mainsource) then
  464. n:=ExtractFileName(current_module.mainsource^)
  465. else
  466. n:=InputFileName;
  467. AsmWriteLn('.source '+ExtractFileName(n));
  468. { class/interface name }
  469. if not assigned(obj) then
  470. begin
  471. { fake class type for unit -> name=unitname and
  472. superclass=java.lang.object }
  473. AsmWriteLn('.class '+current_module.realmodulename^);
  474. AsmWriteLn('.super java/lang/Object');
  475. end
  476. else
  477. begin
  478. case obj.objecttype of
  479. odt_javaclass:
  480. begin
  481. AsmWriteLn('.class '+obj.jvm_full_typename(false));
  482. superclass:=obj.childof;
  483. end;
  484. odt_interfacejava:
  485. begin
  486. AsmWriteLn('.interface abstract '+obj.objextname^);
  487. { interfaces must always specify Java.lang.object as
  488. superclass }
  489. superclass:=java_jlobject;
  490. end
  491. else
  492. internalerror(2011010906);
  493. end;
  494. { superclass }
  495. if assigned(superclass) then
  496. begin
  497. AsmWrite('.super ');
  498. if assigned(superclass.import_lib) then
  499. AsmWrite(superclass.import_lib^+'/');
  500. AsmWriteln(superclass.objextname^);
  501. end;
  502. { implemented interfaces }
  503. if assigned(obj.ImplementedInterfaces) then
  504. begin
  505. for i:=0 to obj.ImplementedInterfaces.count-1 do
  506. begin
  507. intf:=TImplementedInterface(obj.ImplementedInterfaces[i]).IntfDef;
  508. AsmWrite('.implements ');
  509. if assigned(intf.import_lib) then
  510. AsmWrite(intf.import_lib^+'/');
  511. AsmWriteln(intf.objextname^);
  512. end;
  513. end;
  514. { in case of nested class: relation to parent class }
  515. if obj.owner.symtabletype=objectsymtable then
  516. AsmWriteln(InnerObjDef(obj));
  517. { all all nested classes }
  518. for i:=0 to obj.symtable.deflist.count-1 do
  519. if is_java_class_or_interface(tdef(obj.symtable.deflist[i])) then
  520. AsmWriteln(InnerObjDef(tobjectdef(obj.symtable.deflist[i])));
  521. end;
  522. AsmLn;
  523. end;
  524. procedure TJasminAssembler.WriteInstruction(hp: tai);
  525. begin
  526. InstrWriter.WriteInstruction(hp);
  527. end;
  528. function TJasminAssembler.MakeCmdLine: TCmdStr;
  529. const
  530. jasminjarname = 'jasmin.jar';
  531. var
  532. filenames: tcmdstr;
  533. jasminjarfound: boolean;
  534. begin
  535. if jasminjar='' then
  536. begin
  537. jasminjarfound:=false;
  538. if utilsdirectory<>'' then
  539. jasminjarfound:=FindFile(jasminjarname,utilsdirectory,false,jasminjar);
  540. if not jasminjarfound then
  541. jasminjarfound:=FindFileInExeLocations(jasminjarname,false,jasminjar);
  542. if (not jasminjarfound) and not(cs_asm_extern in current_settings.globalswitches) then
  543. begin
  544. Message1(exec_e_assembler_not_found,jasminjarname);
  545. current_settings.globalswitches:=current_settings.globalswitches+[cs_asm_extern];
  546. end;
  547. if jasminjarfound then
  548. Message1(exec_t_using_assembler,jasminjar);
  549. end;
  550. result:=target_asm.asmcmd;
  551. filenames:=maybequoted(ScriptFixFileName(AsmFileName));
  552. while not asmfiles.empty do
  553. filenames:=filenames+' '+asmfiles.GetFirst;
  554. Replace(result,'$ASM',filenames);
  555. if (path<>'') then
  556. Replace(result,'$OBJDIR',maybequoted(ScriptFixFileName(path)))
  557. else
  558. Replace(result,'$OBJDIR','.');
  559. Replace(result,'$JASMINJAR',maybequoted(ScriptFixFileName(jasminjar)));
  560. end;
  561. procedure TJasminAssembler.NewAsmFileForObjectDef(obj: tobjectdef);
  562. begin
  563. if AsmSize<>AsmStartSize then
  564. begin
  565. AsmClose;
  566. asmfiles.Concat(maybequoted(ScriptFixFileName(AsmFileName)));
  567. end
  568. else
  569. AsmClear;
  570. AsmFileName:=obj.jvm_full_typename(false);
  571. AsmFileName:=Path+FixFileName(AsmFileName)+target_info.asmext;
  572. AsmCreate(cut_normal);
  573. end;
  574. function TJasminAssembler.VisibilityToStr(vis: tvisibility): string;
  575. begin
  576. case vis of
  577. vis_hidden,
  578. vis_strictprivate:
  579. result:='private ';
  580. vis_strictprotected:
  581. result:='protected ';
  582. vis_protected,
  583. vis_private:
  584. { pick default visibility = "package" visibility; required because
  585. other classes in the same unit can also access these symbols }
  586. result:='';
  587. vis_public:
  588. result:='public '
  589. else
  590. internalerror(2010122609);
  591. end;
  592. end;
  593. function TJasminAssembler.MethodDefinition(pd: tprocdef): string;
  594. begin
  595. result:=VisibilityToStr(pd.visibility);
  596. if (pd.procsym.owner.symtabletype in [globalsymtable,staticsymtable,localsymtable]) or
  597. (po_staticmethod in pd.procoptions) then
  598. result:=result+'static ';
  599. if is_javainterface(tdef(pd.owner.defowner)) then
  600. result:=result+'abstract ';
  601. result:=result+pd.jvmmangledbasename;
  602. end;
  603. function TJasminAssembler.ConstValue(csym: tconstsym): ansistring;
  604. begin
  605. case csym.consttyp of
  606. constord:
  607. { always interpret as signed value, because the JVM does not
  608. support unsigned 64 bit values }
  609. result:=tostr(csym.value.valueord.svalue);
  610. conststring:
  611. result:=constastr(pchar(csym.value.valueptr),csym.value.len);
  612. constreal:
  613. case tfloatdef(csym.constdef).floattype of
  614. s32real:
  615. result:=constsingle(pbestreal(csym.value.valueptr)^);
  616. s64real:
  617. result:=constdouble(pbestreal(csym.value.valueptr)^);
  618. else
  619. internalerror(2011021204);
  620. end;
  621. constset:
  622. result:='TODO: add support for constant sets';
  623. constpointer:
  624. { can only be null, but that's the default value and should not
  625. be written; there's no primitive type that can hold nill }
  626. internalerror(2011021201);
  627. constnil:
  628. internalerror(2011021202);
  629. constresourcestring:
  630. result:='TODO: add support for constant resource strings';
  631. constwstring:
  632. result:=constwstr(pcompilerwidestring(csym.value.valueptr)^.data,pcompilerwidestring(csym.value.valueptr)^.len);
  633. constguid:
  634. result:='TODO: add support for constant guids';
  635. else
  636. internalerror(2011021205);
  637. end;
  638. end;
  639. function TJasminAssembler.ConstAssignmentValue(csym: tconstsym): ansistring;
  640. begin
  641. { nil is the default value -> don't write explicitly }
  642. case csym.consttyp of
  643. constpointer:
  644. begin
  645. if csym.value.valueordptr<>0 then
  646. internalerror(2011021206);
  647. result:='';
  648. end;
  649. constnil:
  650. result:='';
  651. else
  652. result:=' = '+ConstValue(csym)
  653. end;
  654. end;
  655. function TJasminAssembler.ConstDefinition(sym: tconstsym): string;
  656. begin
  657. result:=VisibilityToStr(sym.visibility);
  658. { formal constants are always class-level, not instance-level }
  659. result:=result+'static final ';
  660. result:=result+jvmmangledbasename(sym);
  661. result:=result+ConstAssignmentValue(tconstsym(sym));
  662. end;
  663. function TJasminAssembler.FieldDefinition(sym: tabstractvarsym): string;
  664. var
  665. vissym: tabstractvarsym;
  666. begin
  667. vissym:=sym;
  668. { static field definition -> get original field definition for
  669. visibility }
  670. if (vissym.typ=staticvarsym) and
  671. (vissym.owner.symtabletype=objectsymtable) then
  672. begin
  673. vissym:=tabstractvarsym(search_struct_member(
  674. tobjectdef(vissym.owner.defowner),
  675. jvminternalstaticfieldname(vissym.name)));
  676. if not assigned(vissym) or
  677. (vissym.typ<>fieldvarsym) then
  678. internalerror(2011011501);
  679. end;
  680. case vissym.typ of
  681. staticvarsym:
  682. begin
  683. if vissym.owner.symtabletype=globalsymtable then
  684. result:='public '
  685. else
  686. { package visbility }
  687. result:='';
  688. end;
  689. fieldvarsym:
  690. result:=VisibilityToStr(tstoredsym(vissym).visibility);
  691. else
  692. internalerror(2011011204);
  693. end;
  694. if (vissym.owner.symtabletype in [staticsymtable,globalsymtable]) or
  695. (sp_static in vissym.symoptions) then
  696. result:=result+'static ';
  697. result:=result+jvmmangledbasename(sym);
  698. end;
  699. function TJasminAssembler.InnerObjDef(obj: tobjectdef): string;
  700. var
  701. kindname: string;
  702. begin
  703. if obj.owner.defowner.typ<>objectdef then
  704. internalerror(2011021701);
  705. case obj.objecttype of
  706. odt_javaclass:
  707. kindname:='class ';
  708. odt_interfacejava:
  709. kindname:='interface ';
  710. else
  711. internalerror(2011021702);
  712. end;
  713. result:=
  714. '.inner '+
  715. kindname+
  716. VisibilityToStr(obj.typesym.visibility)+
  717. { Nested classes in the Pascal sense are equivalent to "static"
  718. inner classes in Java -- will be changed when support for
  719. Java-style non-static classes is added }
  720. ' static '+
  721. obj.objextname^+
  722. ' inner '+
  723. obj.jvm_full_typename(true)+
  724. ' outer '+
  725. tobjectdef(obj.owner.defowner).jvm_full_typename(true);
  726. end;
  727. procedure TJasminAssembler.WriteProcDef(pd: tprocdef);
  728. begin
  729. if not assigned(pd.exprasmlist) and
  730. (not is_javainterface(pd.struct) or
  731. (pd.proctypeoption in [potype_unitinit,potype_unitfinalize])) then
  732. exit;
  733. AsmWrite('.method ');
  734. AsmWriteln(MethodDefinition(pd));
  735. WriteTree(pd.exprasmlist);
  736. AsmWriteln('.end method');
  737. AsmLn;
  738. end;
  739. procedure TJasminAssembler.WriteFieldSym(sym: tabstractvarsym);
  740. begin
  741. { internal static field definition alias -> skip }
  742. if sp_static in sym.symoptions then
  743. exit;
  744. AsmWrite('.field ');
  745. AsmWriteln(FieldDefinition(sym));
  746. end;
  747. procedure TJasminAssembler.WriteConstSym(sym: tconstsym);
  748. begin
  749. AsmWrite('.field ');
  750. AsmWriteln(ConstDefinition(sym));
  751. end;
  752. procedure TJasminAssembler.WriteSymtableVarSyms(st: TSymtable);
  753. var
  754. sym : tsym;
  755. i : longint;
  756. begin
  757. if not assigned(st) then
  758. exit;
  759. for i:=0 to st.SymList.Count-1 do
  760. begin
  761. sym:=tsym(st.SymList[i]);
  762. case sym.typ of
  763. staticvarsym,
  764. fieldvarsym:
  765. begin
  766. WriteFieldSym(tabstractvarsym(sym));
  767. end;
  768. constsym:
  769. begin
  770. WriteConstSym(tconstsym(sym));
  771. end;
  772. end;
  773. end;
  774. end;
  775. procedure TJasminAssembler.WriteSymtableProcdefs(st: TSymtable);
  776. var
  777. i : longint;
  778. def : tdef;
  779. begin
  780. if not assigned(st) then
  781. exit;
  782. for i:=0 to st.DefList.Count-1 do
  783. begin
  784. def:=tdef(st.DefList[i]);
  785. case def.typ of
  786. procdef :
  787. begin
  788. { methods are also in the static/globalsymtable of the unit
  789. -> make sure they are only written for the objectdefs that
  790. own them }
  791. if not(st.symtabletype in [staticsymtable,globalsymtable]) or
  792. (def.owner=st) then
  793. begin
  794. WriteProcDef(tprocdef(def));
  795. if assigned(tprocdef(def).localst) then
  796. WriteSymtableProcdefs(tprocdef(def).localst);
  797. end;
  798. end;
  799. end;
  800. end;
  801. end;
  802. procedure TJasminAssembler.WriteSymtableObjectDefs(st: TSymtable);
  803. var
  804. i : longint;
  805. def : tdef;
  806. obj : tobjectdef;
  807. nestedclasses: tfpobjectlist;
  808. begin
  809. if not assigned(st) then
  810. exit;
  811. nestedclasses:=tfpobjectlist.create(false);
  812. for i:=0 to st.DefList.Count-1 do
  813. begin
  814. def:=tdef(st.DefList[i]);
  815. case def.typ of
  816. objectdef:
  817. if not(oo_is_external in tobjectdef(def).objectoptions) then
  818. nestedclasses.add(def);
  819. end;
  820. end;
  821. for i:=0 to nestedclasses.count-1 do
  822. begin
  823. obj:=tobjectdef(nestedclasses[i]);
  824. NewAsmFileForObjectDef(obj);
  825. WriteExtraHeader(obj);
  826. WriteSymtableVarSyms(obj.symtable);
  827. AsmLn;
  828. WriteSymtableProcDefs(obj.symtable);
  829. WriteSymtableObjectDefs(obj.symtable);
  830. end;
  831. nestedclasses.free;
  832. end;
  833. constructor TJasminAssembler.Create(smart: boolean);
  834. begin
  835. inherited create(smart);
  836. InstrWriter:=TJasminInstrWriter.Create(self);
  837. asmfiles:=TCmdStrList.Create;
  838. end;
  839. procedure TJasminAssembler.WriteAsmList;
  840. begin
  841. {$ifdef EXTDEBUG}
  842. if assigned(current_module.mainsource) then
  843. Comment(V_Debug,'Start writing Jasmin-styled assembler output for '+current_module.mainsource^);
  844. {$endif}
  845. AsmStartSize:=AsmSize;
  846. WriteExtraHeader(nil);
  847. (*
  848. for hal:=low(TasmlistType) to high(TasmlistType) do
  849. begin
  850. AsmWriteLn(target_asm.comment+'Begin asmlist '+AsmlistTypeStr[hal]);
  851. writetree(current_asmdata.asmlists[hal]);
  852. AsmWriteLn(target_asm.comment+'End asmlist '+AsmlistTypeStr[hal]);
  853. end;
  854. *)
  855. { print all global variables }
  856. WriteSymtableVarSyms(current_module.globalsymtable);
  857. WriteSymtableVarSyms(current_module.localsymtable);
  858. AsmLn;
  859. { print all global procedures/functions }
  860. WriteSymtableProcdefs(current_module.globalsymtable);
  861. WriteSymtableProcdefs(current_module.localsymtable);
  862. WriteSymtableObjectDefs(current_module.globalsymtable);
  863. WriteSymtableObjectDefs(current_module.localsymtable);
  864. AsmLn;
  865. {$ifdef EXTDEBUG}
  866. if assigned(current_module.mainsource) then
  867. Comment(V_Debug,'Done writing gas-styled assembler output for '+current_module.mainsource^);
  868. {$endif EXTDEBUG}
  869. end;
  870. {****************************************************************************}
  871. { Jasmin Instruction Writer }
  872. {****************************************************************************}
  873. constructor TJasminInstrWriter.create(_owner: TJasminAssembler);
  874. begin
  875. inherited create;
  876. owner := _owner;
  877. end;
  878. function getreferencestring(var ref : treference) : string;
  879. begin
  880. if (ref.arrayreftype<>art_none) or
  881. (ref.index<>NR_NO) then
  882. internalerror(2010122809);
  883. if assigned(ref.symbol) then
  884. begin
  885. // global symbol or field -> full type and name
  886. // ref.base can be <> NR_NO in case an instance field is loaded.
  887. // This register is not part of this instruction, it will have
  888. // been placed on the stack by the previous one.
  889. if (ref.offset<>0) then
  890. internalerror(2010122811);
  891. result:=ref.symbol.name;
  892. end
  893. else
  894. begin
  895. // local symbol -> stack slot, stored in offset
  896. if ref.base<>NR_STACK_POINTER_REG then
  897. internalerror(2010122810);
  898. result:=tostr(ref.offset);
  899. end;
  900. end;
  901. function getopstr(const o:toper) : ansistring;
  902. var
  903. d: double;
  904. s: single;
  905. begin
  906. case o.typ of
  907. top_reg:
  908. // should have been translated into a memory location by the
  909. // register allocator)
  910. if (cs_no_regalloc in current_settings.globalswitches) then
  911. getopstr:=std_regname(o.reg)
  912. else
  913. internalerror(2010122803);
  914. top_const:
  915. str(o.val,result);
  916. top_ref:
  917. getopstr:=getreferencestring(o.ref^);
  918. top_single:
  919. begin
  920. result:=constsingle(o.sval);
  921. end;
  922. top_double:
  923. begin
  924. result:=constdouble(o.dval);
  925. end;
  926. top_string:
  927. begin
  928. result:=constastr(o.pcval,o.pcvallen);
  929. end;
  930. top_wstring:
  931. begin
  932. result:=constwstr(o.pwstrval^.data,getlengthwidestring(o.pwstrval));
  933. end
  934. else
  935. internalerror(2010122802);
  936. end;
  937. end;
  938. procedure TJasminInstrWriter.WriteInstruction(hp: tai);
  939. var
  940. s: ansistring;
  941. i: byte;
  942. sep: string[3];
  943. begin
  944. s:=#9+jas_op2str[taicpu(hp).opcode];
  945. if taicpu(hp).ops<>0 then
  946. begin
  947. sep:=#9;
  948. for i:=0 to taicpu(hp).ops-1 do
  949. begin
  950. s:=s+sep+getopstr(taicpu(hp).oper[i]^);
  951. sep:=' ';
  952. end;
  953. end;
  954. owner.AsmWriteLn(s);
  955. end;
  956. {****************************************************************************}
  957. { Jasmin Instruction Writer }
  958. {****************************************************************************}
  959. const
  960. as_jvm_jasmin_info : tasminfo =
  961. (
  962. id : as_jvm_jasmin;
  963. idtxt : 'Jasmin';
  964. asmbin : 'java';
  965. asmcmd : '-jar $JASMINJAR $ASM -d $OBJDIR';
  966. supported_targets : [system_jvm_java32];
  967. flags : [];
  968. labelprefix : 'L';
  969. comment : ' ; ';
  970. );
  971. begin
  972. RegisterAssembler(as_jvm_jasmin_info,TJasminAssembler);
  973. end.