agjasmin.pas 40 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202
  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. 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. begin
  161. { see comments in njvmcon }
  162. flush;
  163. result:=result+'\u'+hexstr(ord(p[i]),4)
  164. end;
  165. end;
  166. end;
  167. flush;
  168. result:=result+'"';
  169. end;
  170. function constwstr(w: pcompilerwidechar; len: longint): ansistring;
  171. var
  172. i: longint;
  173. begin
  174. result:='"';
  175. for i:=0 to len-1 do
  176. begin
  177. { escape control codes }
  178. case w[i] of
  179. 10:
  180. result:=result+'\n';
  181. 13:
  182. result:=result+'\r';
  183. ord('"'),ord('\'):
  184. result:=result+'\'+chr(w[i]);
  185. else if (w[i]<32) or
  186. (w[i]>=127) then
  187. result:=result+'\u'+hexstr(w[i],4)
  188. else
  189. result:=result+char(w[i]);
  190. end;
  191. end;
  192. result:=result+'"';
  193. end;
  194. function constsingle(s: single): ansistring;
  195. begin
  196. result:='0fx'+hexstr(longint(t32bitarray(s)),8);
  197. end;
  198. function constdouble(d: double): ansistring;
  199. begin
  200. // force interpretation as double (since we write it out as an
  201. // integer, we never have to swap the endianess). We have to
  202. // include the sign separately because of the way Java parses
  203. // hex numbers (0x8000000000000000 is not a valid long)
  204. result:=hexstr(abs(int64(t64bitarray(d))),16);
  205. if int64(t64bitarray(d))<0 then
  206. result:='-'+result;
  207. result:='0dx'+result;
  208. end;
  209. {****************************************************************************}
  210. { Jasmin Assembler writer }
  211. {****************************************************************************}
  212. destructor TJasminAssembler.Destroy;
  213. begin
  214. InstrWriter.free;
  215. asmfiles.free;
  216. inherited destroy;
  217. end;
  218. procedure TJasminAssembler.WriteTree(p:TAsmList);
  219. var
  220. ch : char;
  221. hp : tai;
  222. hp1 : tailineinfo;
  223. s : ansistring;
  224. i,pos : longint;
  225. InlineLevel : longint;
  226. do_line : boolean;
  227. begin
  228. if not assigned(p) then
  229. exit;
  230. InlineLevel:=0;
  231. { lineinfo is only needed for al_procedures (PFV) }
  232. do_line:=(cs_asm_source in current_settings.globalswitches);
  233. hp:=tai(p.first);
  234. while assigned(hp) do
  235. begin
  236. prefetch(pointer(hp.next)^);
  237. if not(hp.typ in SkipLineInfo) then
  238. begin
  239. hp1 := hp as tailineinfo;
  240. current_filepos:=hp1.fileinfo;
  241. { no line info for inlined code }
  242. if do_line and (inlinelevel=0) then
  243. begin
  244. { load infile }
  245. if lastfileinfo.fileindex<>hp1.fileinfo.fileindex then
  246. begin
  247. infile:=current_module.sourcefiles.get_file(hp1.fileinfo.fileindex);
  248. if assigned(infile) then
  249. begin
  250. { open only if needed !! }
  251. if (cs_asm_source in current_settings.globalswitches) then
  252. infile.open;
  253. end;
  254. { avoid unnecessary reopens of the same file !! }
  255. lastfileinfo.fileindex:=hp1.fileinfo.fileindex;
  256. { be sure to change line !! }
  257. lastfileinfo.line:=-1;
  258. end;
  259. { write source }
  260. if (cs_asm_source in current_settings.globalswitches) and
  261. assigned(infile) then
  262. begin
  263. if (infile<>lastinfile) then
  264. begin
  265. AsmWriteLn(target_asm.comment+'['+infile.name^+']');
  266. if assigned(lastinfile) then
  267. lastinfile.close;
  268. end;
  269. if (hp1.fileinfo.line<>lastfileinfo.line) and
  270. ((hp1.fileinfo.line<infile.maxlinebuf) or (InlineLevel>0)) then
  271. begin
  272. if (hp1.fileinfo.line<>0) and
  273. ((infile.linebuf^[hp1.fileinfo.line]>=0) or (InlineLevel>0)) then
  274. AsmWriteLn(target_asm.comment+'['+tostr(hp1.fileinfo.line)+'] '+
  275. fixline(infile.GetLineStr(hp1.fileinfo.line)));
  276. { set it to a negative value !
  277. to make that is has been read already !! PM }
  278. if (infile.linebuf^[hp1.fileinfo.line]>=0) then
  279. infile.linebuf^[hp1.fileinfo.line]:=-infile.linebuf^[hp1.fileinfo.line]-1;
  280. end;
  281. end;
  282. lastfileinfo:=hp1.fileinfo;
  283. lastinfile:=infile;
  284. end;
  285. end;
  286. case hp.typ of
  287. ait_comment :
  288. Begin
  289. AsmWrite(target_asm.comment);
  290. AsmWritePChar(tai_comment(hp).str);
  291. AsmLn;
  292. End;
  293. ait_regalloc :
  294. begin
  295. if (cs_asm_regalloc in current_settings.globalswitches) then
  296. begin
  297. AsmWrite(#9+target_asm.comment+'Register ');
  298. repeat
  299. AsmWrite(std_regname(Tai_regalloc(hp).reg));
  300. if (hp.next=nil) or
  301. (tai(hp.next).typ<>ait_regalloc) or
  302. (tai_regalloc(hp.next).ratype<>tai_regalloc(hp).ratype) then
  303. break;
  304. hp:=tai(hp.next);
  305. AsmWrite(',');
  306. until false;
  307. AsmWrite(' ');
  308. AsmWriteLn(regallocstr[tai_regalloc(hp).ratype]);
  309. end;
  310. end;
  311. ait_tempalloc :
  312. begin
  313. if (cs_asm_tempalloc in current_settings.globalswitches) then
  314. begin
  315. {$ifdef EXTDEBUG}
  316. if assigned(tai_tempalloc(hp).problem) then
  317. AsmWriteLn(target_asm.comment+'Temp '+tostr(tai_tempalloc(hp).temppos)+','+
  318. tostr(tai_tempalloc(hp).tempsize)+' '+tai_tempalloc(hp).problem^)
  319. else
  320. {$endif EXTDEBUG}
  321. AsmWriteLn(target_asm.comment+'Temp '+tostr(tai_tempalloc(hp).temppos)+','+
  322. tostr(tai_tempalloc(hp).tempsize)+' '+tempallocstr[tai_tempalloc(hp).allocation]);
  323. end;
  324. end;
  325. ait_align :
  326. begin
  327. end;
  328. ait_section :
  329. begin
  330. end;
  331. ait_datablock :
  332. begin
  333. internalerror(2010122701);
  334. end;
  335. ait_const:
  336. begin
  337. AsmWriteln('constant');
  338. // internalerror(2010122702);
  339. end;
  340. ait_real_64bit :
  341. begin
  342. internalerror(2010122703);
  343. end;
  344. ait_real_32bit :
  345. begin
  346. internalerror(2010122703);
  347. end;
  348. ait_comp_64bit :
  349. begin
  350. internalerror(2010122704);
  351. end;
  352. ait_string :
  353. begin
  354. pos:=0;
  355. for i:=1 to tai_string(hp).len do
  356. begin
  357. if pos=0 then
  358. begin
  359. AsmWrite(#9'strconst: '#9'"');
  360. pos:=20;
  361. end;
  362. ch:=tai_string(hp).str[i-1];
  363. case ch of
  364. #0, {This can't be done by range, because a bug in FPC}
  365. #1..#31,
  366. #128..#255 : s:='\'+tostr(ord(ch) shr 6)+tostr((ord(ch) and 63) shr 3)+tostr(ord(ch) and 7);
  367. '"' : s:='\"';
  368. '\' : s:='\\';
  369. else
  370. s:=ch;
  371. end;
  372. AsmWrite(s);
  373. inc(pos,length(s));
  374. if (pos>line_length) or (i=tai_string(hp).len) then
  375. begin
  376. AsmWriteLn('"');
  377. pos:=0;
  378. end;
  379. end;
  380. end;
  381. ait_label :
  382. begin
  383. if (tai_label(hp).labsym.is_used) then
  384. begin
  385. AsmWrite(tai_label(hp).labsym.name);
  386. AsmWriteLn(':');
  387. end;
  388. end;
  389. ait_symbol :
  390. begin
  391. if (tai_symbol(hp).sym.typ = AT_FUNCTION) then
  392. begin
  393. end
  394. else
  395. begin
  396. AsmWrite('data symbol: ');
  397. AsmWriteln(tai_symbol(hp).sym.name);
  398. // internalerror(2010122706);
  399. end;
  400. end;
  401. ait_symbol_end :
  402. begin
  403. end;
  404. ait_instruction :
  405. begin
  406. WriteInstruction(hp);
  407. end;
  408. ait_force_line,
  409. ait_function_name : ;
  410. ait_cutobject :
  411. begin
  412. end;
  413. ait_marker :
  414. if tai_marker(hp).kind=mark_NoLineInfoStart then
  415. inc(InlineLevel)
  416. else if tai_marker(hp).kind=mark_NoLineInfoEnd then
  417. dec(InlineLevel);
  418. ait_directive :
  419. begin
  420. AsmWrite('.'+directivestr[tai_directive(hp).directive]+' ');
  421. if assigned(tai_directive(hp).name) then
  422. AsmWrite(tai_directive(hp).name^);
  423. AsmLn;
  424. end;
  425. ait_jvar:
  426. begin
  427. AsmWrite('.var ');
  428. AsmWrite(tostr(tai_jvar(hp).stackslot));
  429. AsmWrite(' is ');
  430. AsmWrite(tai_jvar(hp).desc^);
  431. AsmWrite(' from ');
  432. AsmWrite(tai_jvar(hp).startlab.name);
  433. AsmWrite(' to ');
  434. AsmWriteLn(tai_jvar(hp).stoplab.name);
  435. end;
  436. ait_jcatch:
  437. begin
  438. AsmWrite('.catch ');
  439. AsmWrite(tai_jcatch(hp).name^);
  440. AsmWrite(' from ');
  441. AsmWrite(tai_jcatch(hp).startlab.name);
  442. AsmWrite(' to ');
  443. AsmWrite(tai_jcatch(hp).stoplab.name);
  444. AsmWrite(' using ');
  445. AsmWriteLn(tai_jcatch(hp).handlerlab.name);
  446. end;
  447. else
  448. internalerror(2010122707);
  449. end;
  450. hp:=tai(hp.next);
  451. end;
  452. end;
  453. procedure TJasminAssembler.WriteExtraHeader(obj: tabstractrecorddef);
  454. var
  455. superclass,
  456. intf: tobjectdef;
  457. n: ansistring;
  458. i: longint;
  459. toplevelowner: tsymtable;
  460. begin
  461. { JVM 1.5+ }
  462. AsmWriteLn('.bytecode 49.0');
  463. // include files are not support by Java, and the directory of the main
  464. // source file must not be specified
  465. if assigned(current_module.mainsource) then
  466. n:=ExtractFileName(current_module.mainsource^)
  467. else
  468. n:=InputFileName;
  469. AsmWriteLn('.source '+ExtractFileName(n));
  470. { class/interface name }
  471. if not assigned(obj) then
  472. begin
  473. { fake class type for unit -> name=unitname and
  474. superclass=java.lang.object, make final so you cannot descend
  475. from it }
  476. AsmWrite('.class final public ');
  477. if assigned(current_module.namespace) then
  478. AsmWrite(current_module.namespace^+'.');
  479. AsmWriteln(current_module.realmodulename^);
  480. AsmWriteLn('.super java/lang/Object');
  481. end
  482. else
  483. begin
  484. toplevelowner:=obj.owner;
  485. while not(toplevelowner.symtabletype in [staticsymtable,globalsymtable]) do
  486. toplevelowner:=toplevelowner.defowner.owner;
  487. case obj.typ of
  488. recorddef:
  489. begin
  490. { can't inherit from records }
  491. AsmWrite('.class final ');
  492. if toplevelowner.symtabletype=globalsymtable then
  493. AsmWrite('public ');
  494. AsmWriteln(obj.jvm_full_typename(true));
  495. superclass:=java_fpcbaserecordtype;
  496. end;
  497. objectdef:
  498. begin
  499. case tobjectdef(obj).objecttype of
  500. odt_javaclass:
  501. begin
  502. AsmWrite('.class ');
  503. if oo_is_sealed in tobjectdef(obj).objectoptions then
  504. AsmWrite('final ');
  505. if (oo_is_abstract in tobjectdef(obj).objectoptions) or
  506. (tobjectdef(obj).abstractcnt<>0) then
  507. AsmWrite('abstract ');
  508. if toplevelowner.symtabletype=globalsymtable then
  509. AsmWrite('public ');
  510. if (oo_is_enum_class in tobjectdef(obj).objectoptions) then
  511. AsmWrite('enum ');
  512. AsmWriteln(obj.jvm_full_typename(true));
  513. superclass:=tobjectdef(obj).childof;
  514. end;
  515. odt_interfacejava:
  516. begin
  517. AsmWrite('.interface abstract ');
  518. if toplevelowner.symtabletype=globalsymtable then
  519. AsmWrite('public ');
  520. AsmWriteLn(obj.jvm_full_typename(true));
  521. { interfaces must always specify Java.lang.object as
  522. superclass }
  523. superclass:=java_jlobject;
  524. end
  525. else
  526. internalerror(2011010906);
  527. end;
  528. end;
  529. end;
  530. { superclass }
  531. if assigned(superclass) then
  532. begin
  533. AsmWrite('.super ');
  534. if assigned(superclass.import_lib) then
  535. AsmWrite(superclass.import_lib^+'/');
  536. AsmWriteln(superclass.objextname^);
  537. end;
  538. { implemented interfaces }
  539. if (obj.typ=objectdef) and
  540. assigned(tobjectdef(obj).ImplementedInterfaces) then
  541. begin
  542. for i:=0 to tobjectdef(obj).ImplementedInterfaces.count-1 do
  543. begin
  544. intf:=TImplementedInterface(tobjectdef(obj).ImplementedInterfaces[i]).IntfDef;
  545. AsmWrite('.implements ');
  546. if assigned(intf.import_lib) then
  547. AsmWrite(intf.import_lib^+'/');
  548. AsmWriteln(intf.objextname^);
  549. end;
  550. end;
  551. { signature for enum classes (must come after superclass and
  552. implemented interfaces) }
  553. if (obj.typ=objectdef) and
  554. (oo_is_enum_class in tobjectdef(obj).objectoptions) then
  555. AsmWriteln('.signature "Ljava/lang/Enum<L'+obj.jvm_full_typename(true)+';>;"');
  556. { in case of nested class: relation to parent class }
  557. if obj.owner.symtabletype in [objectsymtable,recordsymtable] then
  558. AsmWriteln(InnerStructDef(obj));
  559. { all all nested classes }
  560. for i:=0 to obj.symtable.deflist.count-1 do
  561. if is_java_class_or_interface(tdef(obj.symtable.deflist[i])) or
  562. (tdef(obj.symtable.deflist[i]).typ=recorddef) then
  563. AsmWriteln(InnerStructDef(tabstractrecorddef(obj.symtable.deflist[i])));
  564. end;
  565. AsmLn;
  566. end;
  567. procedure TJasminAssembler.WriteInstruction(hp: tai);
  568. begin
  569. InstrWriter.WriteInstruction(hp);
  570. end;
  571. function TJasminAssembler.MakeCmdLine: TCmdStr;
  572. const
  573. jasminjarname = 'jasmin.jar';
  574. var
  575. filenames: tcmdstr;
  576. jasminjarfound: boolean;
  577. begin
  578. if jasminjar='' then
  579. begin
  580. jasminjarfound:=false;
  581. if utilsdirectory<>'' then
  582. jasminjarfound:=FindFile(jasminjarname,utilsdirectory,false,jasminjar);
  583. if not jasminjarfound then
  584. jasminjarfound:=FindFileInExeLocations(jasminjarname,false,jasminjar);
  585. if (not jasminjarfound) and not(cs_asm_extern in current_settings.globalswitches) then
  586. begin
  587. Message1(exec_e_assembler_not_found,jasminjarname);
  588. current_settings.globalswitches:=current_settings.globalswitches+[cs_asm_extern];
  589. end;
  590. if jasminjarfound then
  591. Message1(exec_t_using_assembler,jasminjar);
  592. end;
  593. result:=target_asm.asmcmd;
  594. filenames:=maybequoted(ScriptFixFileName(AsmFileName));
  595. while not asmfiles.empty do
  596. filenames:=filenames+' '+asmfiles.GetFirst;
  597. Replace(result,'$ASM',filenames);
  598. if (path<>'') then
  599. Replace(result,'$OBJDIR',maybequoted(ScriptFixFileName(path)))
  600. else
  601. Replace(result,'$OBJDIR','.');
  602. Replace(result,'$JASMINJAR',maybequoted(ScriptFixFileName(jasminjar)));
  603. end;
  604. procedure TJasminAssembler.NewAsmFileForStructDef(obj: tabstractrecorddef);
  605. begin
  606. if AsmSize<>AsmStartSize then
  607. begin
  608. AsmClose;
  609. asmfiles.Concat(maybequoted(ScriptFixFileName(AsmFileName)));
  610. end
  611. else
  612. AsmClear;
  613. AsmFileName:=obj.jvm_full_typename(false);
  614. AsmFileName:=Path+FixFileName(AsmFileName)+target_info.asmext;
  615. AsmCreate(cut_normal);
  616. end;
  617. function TJasminAssembler.VisibilityToStr(vis: tvisibility): ansistring;
  618. begin
  619. case vis of
  620. vis_hidden,
  621. vis_strictprivate:
  622. result:='private ';
  623. vis_strictprotected:
  624. result:='protected ';
  625. vis_protected,
  626. vis_private:
  627. { pick default visibility = "package" visibility; required because
  628. other classes in the same unit can also access these symbols }
  629. result:='';
  630. vis_public:
  631. result:='public '
  632. else
  633. internalerror(2010122609);
  634. end;
  635. end;
  636. function TJasminAssembler.MethodDefinition(pd: tprocdef): ansistring;
  637. begin
  638. result:=VisibilityToStr(pd.visibility);
  639. if (pd.procsym.owner.symtabletype in [globalsymtable,staticsymtable,localsymtable]) or
  640. (po_classmethod in pd.procoptions) then
  641. result:=result+'static ';
  642. if (po_abstractmethod in pd.procoptions) or
  643. is_javainterface(tdef(pd.owner.defowner)) then
  644. result:=result+'abstract ';
  645. if (pd.procsym.owner.symtabletype in [globalsymtable,staticsymtable,localsymtable]) or
  646. (po_finalmethod in pd.procoptions) or
  647. (not(po_virtualmethod in pd.procoptions) and
  648. not(pd.proctypeoption in [potype_constructor,potype_class_constructor])) then
  649. result:=result+'final ';
  650. result:=result+pd.jvmmangledbasename(false);
  651. end;
  652. function TJasminAssembler.ConstValue(csym: tconstsym): ansistring;
  653. begin
  654. case csym.consttyp of
  655. constord:
  656. { always interpret as signed value, because the JVM does not
  657. support unsigned 64 bit values }
  658. result:=tostr(csym.value.valueord.svalue);
  659. conststring:
  660. result:=constastr(pchar(csym.value.valueptr),csym.value.len);
  661. constreal:
  662. case tfloatdef(csym.constdef).floattype of
  663. s32real:
  664. result:=constsingle(pbestreal(csym.value.valueptr)^);
  665. s64real:
  666. result:=constdouble(pbestreal(csym.value.valueptr)^);
  667. else
  668. internalerror(2011021204);
  669. end;
  670. constset:
  671. result:='TODO: add support for constant sets';
  672. constpointer:
  673. { can only be null, but that's the default value and should not
  674. be written; there's no primitive type that can hold nill }
  675. internalerror(2011021201);
  676. constnil:
  677. internalerror(2011021202);
  678. constresourcestring:
  679. result:='TODO: add support for constant resource strings';
  680. constwstring:
  681. result:=constwstr(pcompilerwidestring(csym.value.valueptr)^.data,pcompilerwidestring(csym.value.valueptr)^.len);
  682. constguid:
  683. result:='TODO: add support for constant guids';
  684. else
  685. internalerror(2011021205);
  686. end;
  687. end;
  688. function TJasminAssembler.ConstAssignmentValue(csym: tconstsym): ansistring;
  689. begin
  690. { nil is the default value -> don't write explicitly }
  691. case csym.consttyp of
  692. constpointer:
  693. begin
  694. if csym.value.valueordptr<>0 then
  695. internalerror(2011021206);
  696. result:='';
  697. end;
  698. constnil:
  699. result:='';
  700. else
  701. begin
  702. { enums and sets are initialized as typed constants }
  703. if not assigned(csym.constdef) or
  704. not(csym.constdef.typ in [enumdef,setdef]) then
  705. result:=' = '+ConstValue(csym)
  706. end;
  707. end;
  708. end;
  709. function TJasminAssembler.ConstDefinition(sym: tconstsym): ansistring;
  710. begin
  711. result:=VisibilityToStr(sym.visibility);
  712. { formal constants are always class-level, not instance-level }
  713. result:=result+'static final ';
  714. if sp_internal in sym.symoptions then
  715. result:=result+'synthetic ';
  716. result:=result+jvmmangledbasename(sym,true);
  717. result:=result+ConstAssignmentValue(tconstsym(sym));
  718. end;
  719. function TJasminAssembler.FieldDefinition(sym: tabstractvarsym): ansistring;
  720. var
  721. vissym: tabstractvarsym;
  722. begin
  723. vissym:=sym;
  724. { static field definition -> get original field definition for
  725. visibility }
  726. if (sym.typ=staticvarsym) and
  727. (sym.owner.symtabletype in [objectsymtable,recordsymtable]) then
  728. begin
  729. vissym:=tabstractvarsym(
  730. tabstractrecorddef(sym.owner.defowner).symtable.find(
  731. internal_static_field_name(sym.name)));
  732. if not assigned(vissym) then
  733. vissym:=tabstractvarsym(
  734. tabstractrecorddef(sym.owner.defowner).symtable.find(
  735. generate_nested_name(sym.owner,'_')+'_'+sym.name));
  736. if not assigned(vissym) or
  737. not(vissym.typ in [fieldvarsym,absolutevarsym]) then
  738. internalerror(2011011501);
  739. end;
  740. case vissym.typ of
  741. staticvarsym:
  742. begin
  743. if vissym.owner.symtabletype=globalsymtable then
  744. result:='public '
  745. else
  746. { package visbility }
  747. result:='';
  748. end;
  749. fieldvarsym,
  750. absolutevarsym:
  751. result:=VisibilityToStr(tstoredsym(vissym).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. case obj.typ of
  782. recorddef:
  783. begin
  784. kindname:='class ';
  785. extname:=obj.symtable.realname;
  786. end;
  787. objectdef:
  788. begin
  789. extname:=tobjectdef(obj).objextname;
  790. case tobjectdef(obj).objecttype of
  791. odt_javaclass:
  792. kindname:='class ';
  793. odt_interfacejava:
  794. kindname:='interface ';
  795. else
  796. internalerror(2011021702);
  797. end;
  798. end;
  799. else
  800. internalerror(2011032809);
  801. end;
  802. result:=
  803. '.inner '+
  804. kindname+
  805. VisibilityToStr(obj.typesym.visibility)+
  806. { Nested classes in the Pascal sense are equivalent to "static"
  807. inner classes in Java -- will be changed when support for
  808. Java-style non-static classes is added }
  809. ' static '+
  810. extname^+
  811. ' inner '+
  812. obj.jvm_full_typename(true)+
  813. ' outer '+
  814. tabstractrecorddef(obj.owner.defowner).jvm_full_typename(true);
  815. end;
  816. procedure TJasminAssembler.WriteProcDef(pd: tprocdef);
  817. begin
  818. if not assigned(pd.exprasmlist) and
  819. not(po_abstractmethod in pd.procoptions) and
  820. (not is_javainterface(pd.struct) or
  821. (pd.proctypeoption in [potype_unitinit,potype_unitfinalize])) then
  822. exit;
  823. AsmWrite('.method ');
  824. AsmWriteln(MethodDefinition(pd));
  825. if jvmtypeneedssignature(pd) then
  826. begin
  827. AsmWrite('.signature "');
  828. AsmWrite(pd.jvmmangledbasename(true));
  829. AsmWriteln('"');
  830. end;
  831. WriteTree(pd.exprasmlist);
  832. AsmWriteln('.end method');
  833. AsmLn;
  834. end;
  835. procedure TJasminAssembler.WriteFieldSym(sym: tabstractvarsym);
  836. begin
  837. { internal static field definition alias -> skip }
  838. if sp_static in sym.symoptions then
  839. exit;
  840. { external definition -> no definition here }
  841. if vo_is_external in 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. WriteSymtableVarSyms(tprocdef(tprocsym(sym).procdeflist[j]).localst);
  881. end;
  882. end;
  883. end;
  884. end;
  885. procedure TJasminAssembler.WriteSymtableProcdefs(st: TSymtable);
  886. var
  887. i : longint;
  888. def : tdef;
  889. begin
  890. if not assigned(st) then
  891. exit;
  892. for i:=0 to st.DefList.Count-1 do
  893. begin
  894. def:=tdef(st.DefList[i]);
  895. case def.typ of
  896. procdef :
  897. begin
  898. { methods are also in the static/globalsymtable of the unit
  899. -> make sure they are only written for the objectdefs that
  900. own them }
  901. if not(st.symtabletype in [staticsymtable,globalsymtable]) or
  902. (def.owner=st) then
  903. begin
  904. WriteProcDef(tprocdef(def));
  905. if assigned(tprocdef(def).localst) then
  906. WriteSymtableProcdefs(tprocdef(def).localst);
  907. end;
  908. end;
  909. end;
  910. end;
  911. end;
  912. procedure TJasminAssembler.WriteSymtableStructDefs(st: TSymtable);
  913. var
  914. i : longint;
  915. def : tdef;
  916. obj : tabstractrecorddef;
  917. nestedstructs: tfpobjectlist;
  918. begin
  919. if not assigned(st) then
  920. exit;
  921. nestedstructs:=tfpobjectlist.create(false);
  922. for i:=0 to st.DefList.Count-1 do
  923. begin
  924. def:=tdef(st.DefList[i]);
  925. case def.typ of
  926. objectdef:
  927. if not(oo_is_external in tobjectdef(def).objectoptions) then
  928. nestedstructs.add(def);
  929. recorddef:
  930. nestedstructs.add(def);
  931. end;
  932. end;
  933. for i:=0 to nestedstructs.count-1 do
  934. begin
  935. obj:=tabstractrecorddef(nestedstructs[i]);
  936. NewAsmFileForStructDef(obj);
  937. WriteExtraHeader(obj);
  938. WriteSymtableVarSyms(obj.symtable);
  939. AsmLn;
  940. WriteSymtableProcDefs(obj.symtable);
  941. WriteSymtableStructDefs(obj.symtable);
  942. end;
  943. nestedstructs.free;
  944. end;
  945. constructor TJasminAssembler.Create(smart: boolean);
  946. begin
  947. inherited create(smart);
  948. InstrWriter:=TJasminInstrWriter.Create(self);
  949. asmfiles:=TCmdStrList.Create;
  950. end;
  951. procedure TJasminAssembler.WriteAsmList;
  952. begin
  953. {$ifdef EXTDEBUG}
  954. if assigned(current_module.mainsource) then
  955. Comment(V_Debug,'Start writing Jasmin-styled assembler output for '+current_module.mainsource^);
  956. {$endif}
  957. AsmStartSize:=AsmSize;
  958. WriteExtraHeader(nil);
  959. (*
  960. for hal:=low(TasmlistType) to high(TasmlistType) do
  961. begin
  962. AsmWriteLn(target_asm.comment+'Begin asmlist '+AsmlistTypeStr[hal]);
  963. writetree(current_asmdata.asmlists[hal]);
  964. AsmWriteLn(target_asm.comment+'End asmlist '+AsmlistTypeStr[hal]);
  965. end;
  966. *)
  967. { print all global variables }
  968. WriteSymtableVarSyms(current_module.globalsymtable);
  969. WriteSymtableVarSyms(current_module.localsymtable);
  970. AsmLn;
  971. { print all global procedures/functions }
  972. WriteSymtableProcdefs(current_module.globalsymtable);
  973. WriteSymtableProcdefs(current_module.localsymtable);
  974. WriteSymtableStructDefs(current_module.globalsymtable);
  975. WriteSymtableStructDefs(current_module.localsymtable);
  976. AsmLn;
  977. {$ifdef EXTDEBUG}
  978. if assigned(current_module.mainsource) then
  979. Comment(V_Debug,'Done writing gas-styled assembler output for '+current_module.mainsource^);
  980. {$endif EXTDEBUG}
  981. end;
  982. {****************************************************************************}
  983. { Jasmin Instruction Writer }
  984. {****************************************************************************}
  985. constructor TJasminInstrWriter.create(_owner: TJasminAssembler);
  986. begin
  987. inherited create;
  988. owner := _owner;
  989. end;
  990. function getreferencestring(var ref : treference) : ansistring;
  991. begin
  992. if (ref.arrayreftype<>art_none) or
  993. (ref.index<>NR_NO) then
  994. internalerror(2010122809);
  995. if assigned(ref.symbol) then
  996. begin
  997. // global symbol or field -> full type and name
  998. // ref.base can be <> NR_NO in case an instance field is loaded.
  999. // This register is not part of this instruction, it will have
  1000. // been placed on the stack by the previous one.
  1001. if (ref.offset<>0) then
  1002. internalerror(2010122811);
  1003. result:=ref.symbol.name;
  1004. end
  1005. else
  1006. begin
  1007. // local symbol -> stack slot, stored in offset
  1008. if ref.base<>NR_STACK_POINTER_REG then
  1009. internalerror(2010122810);
  1010. result:=tostr(ref.offset);
  1011. end;
  1012. end;
  1013. function getopstr(const o:toper) : ansistring;
  1014. var
  1015. d: double;
  1016. s: single;
  1017. begin
  1018. case o.typ of
  1019. top_reg:
  1020. // should have been translated into a memory location by the
  1021. // register allocator)
  1022. if (cs_no_regalloc in current_settings.globalswitches) then
  1023. getopstr:=std_regname(o.reg)
  1024. else
  1025. internalerror(2010122803);
  1026. top_const:
  1027. str(o.val,result);
  1028. top_ref:
  1029. getopstr:=getreferencestring(o.ref^);
  1030. top_single:
  1031. begin
  1032. result:=constsingle(o.sval);
  1033. end;
  1034. top_double:
  1035. begin
  1036. result:=constdouble(o.dval);
  1037. end;
  1038. top_string:
  1039. begin
  1040. result:=constastr(o.pcval,o.pcvallen);
  1041. end;
  1042. top_wstring:
  1043. begin
  1044. result:=constwstr(o.pwstrval^.data,getlengthwidestring(o.pwstrval));
  1045. end
  1046. else
  1047. internalerror(2010122802);
  1048. end;
  1049. end;
  1050. procedure TJasminInstrWriter.WriteInstruction(hp: tai);
  1051. var
  1052. s: ansistring;
  1053. i: byte;
  1054. sep: ansistring;
  1055. begin
  1056. s:=#9+jas_op2str[taicpu(hp).opcode];
  1057. if taicpu(hp).ops<>0 then
  1058. begin
  1059. sep:=#9;
  1060. for i:=0 to taicpu(hp).ops-1 do
  1061. begin
  1062. s:=s+sep+getopstr(taicpu(hp).oper[i]^);
  1063. sep:=' ';
  1064. end;
  1065. end;
  1066. owner.AsmWriteLn(s);
  1067. end;
  1068. {****************************************************************************}
  1069. { Jasmin Instruction Writer }
  1070. {****************************************************************************}
  1071. const
  1072. as_jvm_jasmin_info : tasminfo =
  1073. (
  1074. id : as_jvm_jasmin;
  1075. idtxt : 'Jasmin';
  1076. asmbin : 'java';
  1077. asmcmd : '-jar $JASMINJAR $ASM -d $OBJDIR';
  1078. supported_targets : [system_jvm_java32];
  1079. flags : [];
  1080. labelprefix : 'L';
  1081. comment : ' ; ';
  1082. );
  1083. begin
  1084. RegisterAssembler(as_jvm_jasmin_info,TJasminAssembler);
  1085. end.