2
0

agllvm.pas 60 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760
  1. {
  2. Copyright (c) 1998-2013 by the Free Pascal team
  3. This unit implements the generic part of the LLVM IR 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 agllvm;
  18. {$i fpcdefs.inc}
  19. interface
  20. uses
  21. cclasses,
  22. globtype,globals,systems,
  23. aasmbase,aasmtai,aasmdata,
  24. assemble,
  25. aasmllvm, aasmllvmmetadata;
  26. type
  27. TLLVMInstrWriter = class;
  28. TLLVMModuleInlineAssemblyDecorator = class(IExternalAssemblerOutputFileDecorator)
  29. function LineFilter(const s: AnsiString): AnsiString;
  30. function LinePrefix: AnsiString;
  31. function LinePostfix: AnsiString;
  32. function LineEnding(const deflineending: ShortString): ShortString;
  33. end;
  34. TLLVMFunctionInlineAssemblyDecorator = class(IExternalAssemblerOutputFileDecorator)
  35. function LineFilter(const s: AnsiString): AnsiString;
  36. function LinePrefix: AnsiString;
  37. function LinePostfix: AnsiString;
  38. function LineEnding(const deflineending: ShortString): ShortString;
  39. end;
  40. TLLVMAssember=class(texternalassembler)
  41. protected
  42. ffuncinlasmdecorator: TLLVMFunctionInlineAssemblyDecorator;
  43. fdecllevel: longint;
  44. procedure WriteExtraHeader;virtual;
  45. procedure WriteExtraFooter;virtual;
  46. procedure WriteInstruction(hp: tai);
  47. procedure WriteLlvmInstruction(hp: tai);
  48. procedure WriteDirectiveName(dir: TAsmDirective); virtual;
  49. procedure WriteRealConst(hp: tai_realconst; do_line: boolean);
  50. procedure WriteOrdConst(hp: tai_const);
  51. procedure WriteTai(const replaceforbidden: boolean; const do_line, inmetadata: boolean; var InlineLevel: cardinal; var asmblock: boolean; var hp: tai);
  52. public
  53. constructor CreateWithWriter(info: pasminfo; wr: TExternalAssemblerOutputFile; freewriter, smart: boolean); override;
  54. procedure WriteTree(p:TAsmList);override;
  55. procedure WriteAsmList;override;
  56. procedure WriteFunctionInlineAsmList(list: tasmlist);
  57. destructor destroy; override;
  58. protected
  59. InstrWriter: TLLVMInstrWriter;
  60. end;
  61. TLLVMLLCAssember=class(TLLVMAssember)
  62. public
  63. function MakeCmdLine: TCmdStr; override;
  64. end;
  65. TLLVMClangAssember=class(TLLVMAssember)
  66. public
  67. function MakeCmdLine: TCmdStr; override;
  68. function DoAssemble: boolean; override;
  69. function RerunAssembler: boolean; override;
  70. protected
  71. function DoPipe: boolean; override;
  72. private
  73. fnextpass: byte;
  74. end;
  75. {# This is the base class for writing instructions.
  76. The WriteInstruction() method must be overridden
  77. to write a single instruction to the assembler
  78. file.
  79. }
  80. TLLVMInstrWriter = class
  81. constructor create(_owner: TLLVMAssember);
  82. procedure WriteInstruction(hp : tai);
  83. protected
  84. owner: TLLVMAssember;
  85. fstr: TSymStr;
  86. function getopcodestr(hp: taillvm): TSymStr;
  87. function getopstr(const o:toper; refwithalign: boolean) : TSymStr;
  88. procedure writeparas(const paras: tfplist);
  89. procedure WriteAsmRegisterAllocationClobbers(list: tasmlist);
  90. end;
  91. implementation
  92. uses
  93. SysUtils,
  94. cutils,cfileutl,
  95. fmodule,verbose,
  96. objcasm,
  97. aasmcnst,symconst,symdef,symtable,
  98. llvmbase,itllvm,llvmdef,
  99. cgbase,cgutils,cpubase,cpuinfo,llvminfo;
  100. const
  101. line_length = 70;
  102. type
  103. {$ifdef cpuextended}
  104. t80bitarray = array[0..9] of byte;
  105. {$endif cpuextended}
  106. t64bitarray = array[0..7] of byte;
  107. t32bitarray = array[0..3] of byte;
  108. {****************************************************************************}
  109. { Support routines }
  110. {****************************************************************************}
  111. function single2str(d : single) : string;
  112. var
  113. hs : string;
  114. begin
  115. str(d,hs);
  116. { replace space with + }
  117. if hs[1]=' ' then
  118. hs[1]:='+';
  119. single2str:=hs
  120. end;
  121. function double2str(d : double) : string;
  122. var
  123. hs : string;
  124. begin
  125. str(d,hs);
  126. { replace space with + }
  127. if hs[1]=' ' then
  128. hs[1]:='+';
  129. double2str:=hs
  130. end;
  131. function extended2str(e : extended) : string;
  132. var
  133. hs : string;
  134. begin
  135. str(e,hs);
  136. { replace space with + }
  137. if hs[1]=' ' then
  138. hs[1]:='+';
  139. extended2str:=hs
  140. end;
  141. {****************************************************************************}
  142. { Decorator for module-level inline assembly }
  143. {****************************************************************************}
  144. function TLLVMModuleInlineAssemblyDecorator.LineFilter(const s: AnsiString): AnsiString;
  145. var
  146. i: longint;
  147. begin
  148. result:='';
  149. for i:=1 to length(s) do
  150. begin
  151. case s[i] of
  152. #0..#31,
  153. #127..#255,
  154. '"','\':
  155. result:=result+
  156. '\'+
  157. chr((ord(s[i]) shr 4)+ord('0'))+
  158. chr((ord(s[i]) and $f)+ord('0'));
  159. else
  160. result:=result+s[i];
  161. end;
  162. end;
  163. end;
  164. function TLLVMModuleInlineAssemblyDecorator.LinePrefix: AnsiString;
  165. begin
  166. result:='module asm "';
  167. end;
  168. function TLLVMModuleInlineAssemblyDecorator.LinePostfix: AnsiString;
  169. begin
  170. result:='"';
  171. end;
  172. function TLLVMModuleInlineAssemblyDecorator.LineEnding(const deflineending: ShortString): ShortString;
  173. begin
  174. result:=deflineending
  175. end;
  176. {****************************************************************************}
  177. { Decorator for function-level inline assembly }
  178. {****************************************************************************}
  179. function TLLVMFunctionInlineAssemblyDecorator.LineFilter(const s: AnsiString): AnsiString;
  180. var
  181. i: longint;
  182. begin
  183. result:='';
  184. for i:=1 to length(s) do
  185. begin
  186. case s[i] of
  187. { escape dollars }
  188. '$':
  189. result:=result+'$$';
  190. { ` is used as placeholder for a single dollar (reference to
  191. argument to the inline assembly) }
  192. '`':
  193. result:=result+'$';
  194. #0..#31,
  195. #127..#255,
  196. '"','\':
  197. result:=result+
  198. '\'+
  199. chr((ord(s[i]) shr 4)+ord('0'))+
  200. chr((ord(s[i]) and $f)+ord('0'));
  201. else
  202. result:=result+s[i];
  203. end;
  204. end;
  205. end;
  206. function TLLVMFunctionInlineAssemblyDecorator.LinePrefix: AnsiString;
  207. begin
  208. result:='';
  209. end;
  210. function TLLVMFunctionInlineAssemblyDecorator.LinePostfix: AnsiString;
  211. begin
  212. result:='';
  213. end;
  214. function TLLVMFunctionInlineAssemblyDecorator.LineEnding(const deflineending: ShortString): ShortString;
  215. begin
  216. result:='\0A';
  217. end;
  218. {****************************************************************************}
  219. { LLVM Instruction writer }
  220. {****************************************************************************}
  221. function getregisterstring(reg: tregister): ansistring;
  222. begin
  223. if getregtype(reg)=R_METADATAREGISTER then
  224. result:='!"'+tllvmmetadata.getregstring(reg)+'"'
  225. else
  226. begin
  227. if getregtype(reg)=R_TEMPREGISTER then
  228. result:='%tmp.'
  229. else
  230. result:='%reg.'+tostr(byte(getregtype(reg)))+'_';
  231. result:=result+tostr(getsupreg(reg));
  232. end;
  233. end;
  234. function getreferencealignstring(var ref: treference) : ansistring;
  235. begin
  236. result:=', align '+tostr(ref.alignment);
  237. end;
  238. function getreferencestring(var ref : treference; withalign: boolean) : ansistring;
  239. begin
  240. result:='';
  241. if assigned(ref.relsymbol) or
  242. (assigned(ref.symbol) and
  243. (ref.base<>NR_NO)) or
  244. (ref.index<>NR_NO) or
  245. (ref.offset<>0) then
  246. begin
  247. result:=' **(error ref: ';
  248. if assigned(ref.symbol) then
  249. result:=result+'sym='+ref.symbol.name+', ';
  250. if assigned(ref.relsymbol) then
  251. result:=result+'sym='+ref.relsymbol.name+', ';
  252. if ref.base=NR_NO then
  253. result:=result+'base=NR_NO, ';
  254. if ref.index<>NR_NO then
  255. result:=result+'index<>NR_NO, ';
  256. if ref.offset<>0 then
  257. result:=result+'offset='+tostr(ref.offset);
  258. result:=result+')**';
  259. internalerror(2013060225);
  260. end;
  261. if ref.base<>NR_NO then
  262. result:=result+getregisterstring(ref.base)
  263. else if assigned(ref.symbol) then
  264. result:=result+LlvmAsmSymName(ref.symbol)
  265. else
  266. result:=result+'null';
  267. if withalign then
  268. result:=result+getreferencealignstring(ref);
  269. end;
  270. procedure TLLVMInstrWriter.writeparas(const paras: tfplist);
  271. var
  272. i: longint;
  273. tmpinline: cardinal;
  274. para: pllvmcallpara;
  275. tmpasmblock: boolean;
  276. hp: tai;
  277. begin
  278. tmpinline:=1;
  279. tmpasmblock:=false;
  280. owner.writer.AsmWrite(fstr);
  281. fstr:='';
  282. owner.writer.AsmWrite('(');
  283. for i:=0 to paras.count-1 do
  284. begin
  285. if i<>0 then
  286. owner.writer.AsmWrite(', ');
  287. para:=pllvmcallpara(paras[i]);
  288. owner.writer.AsmWrite(llvmencodetypename(para^.def));
  289. if para^.valueext<>lve_none then
  290. owner.writer.AsmWrite(llvmvalueextension2str[para^.valueext]);
  291. if para^.byval then
  292. owner.writer.AsmWrite(' byval');
  293. if para^.sret then
  294. owner.writer.AsmWrite(' sret');
  295. { For byval, this means "alignment on the stack" and of the passed source data.
  296. For other pointer parameters, this means "alignment of the passed source data" }
  297. if (para^.alignment<>std_param_align) or
  298. (para^.alignment<0) then
  299. begin
  300. owner.writer.AsmWrite(' align ');
  301. owner.writer.AsmWrite(tostr(abs(para^.alignment)));
  302. end;
  303. case para^.typ of
  304. top_reg:
  305. begin
  306. owner.writer.AsmWrite(' ');
  307. owner.writer.AsmWrite(getregisterstring(para^.register));
  308. end;
  309. top_ref:
  310. begin
  311. owner.writer.AsmWrite(' ');
  312. owner.writer.AsmWrite(llvmasmsymname(para^.sym));
  313. end;
  314. top_const:
  315. begin
  316. owner.writer.AsmWrite(' ');
  317. owner.writer.AsmWrite(tostr(para^.value));
  318. end;
  319. top_tai:
  320. begin
  321. tmpinline:=1;
  322. tmpasmblock:=false;
  323. hp:=para^.ai;
  324. owner.writer.AsmWrite(fstr);
  325. fstr:='';
  326. owner.WriteTai(false,false,para^.def=llvm_metadatatype,tmpinline,tmpasmblock,hp);
  327. end;
  328. { empty records }
  329. top_undef:
  330. owner.writer.AsmWrite(' undef');
  331. else
  332. internalerror(2014010801);
  333. end;
  334. end;
  335. owner.writer.AsmWrite(')');
  336. end;
  337. function llvmdoubletostr(const d: double): TSymStr;
  338. type
  339. tdoubleval = record
  340. case byte of
  341. 1: (d: double);
  342. 2: (i: int64);
  343. end;
  344. begin
  345. { "When using the hexadecimal form, constants of types half,
  346. float, and double are represented using the 16-digit form shown
  347. above (which matches the IEEE754 representation for double)"
  348. And always in big endian form (sign bit leftmost)
  349. }
  350. result:='0x'+hexstr(tdoubleval(d).i,16);
  351. end;
  352. {$if defined(cpuextended) and defined(FPC_HAS_TYPE_EXTENDED)}
  353. function llvmextendedtostr(const e: extended): TSymStr;
  354. var
  355. extendedval: record
  356. case byte of
  357. 1: (e: extended);
  358. 2: (r: packed record
  359. {$ifdef FPC_LITTLE_ENDIAN}
  360. l: int64;
  361. h: word;
  362. {$else FPC_LITTLE_ENDIAN}
  363. h: int64;
  364. l: word;
  365. {$endif FPC_LITTLE_ENDIAN}
  366. end;
  367. );
  368. end;
  369. begin
  370. extendedval.e:=e;
  371. { hex format is always big endian in llvm }
  372. result:='0xK'+hexstr(extendedval.r.h,sizeof(extendedval.r.h)*2)+
  373. hexstr(extendedval.r.l,sizeof(extendedval.r.l)*2);
  374. end;
  375. {$endif cpuextended}
  376. function TLLVMInstrWriter.getopstr(const o:toper; refwithalign: boolean) : TSymStr;
  377. var
  378. hp: tai;
  379. tmpinline: cardinal;
  380. tmpasmblock: boolean;
  381. begin
  382. case o.typ of
  383. top_reg:
  384. getopstr:=getregisterstring(o.reg);
  385. top_const:
  386. getopstr:=tostr(int64(o.val));
  387. top_ref:
  388. if o.ref^.refaddr=addr_full then
  389. begin
  390. getopstr:='';
  391. if assigned(o.ref^.symbol) then
  392. getopstr:=LlvmAsmSymName(o.ref^.symbol)
  393. else
  394. getopstr:='null';
  395. if o.ref^.offset<>0 then
  396. internalerror(2013060223);
  397. end
  398. else
  399. getopstr:=getreferencestring(o.ref^,refwithalign);
  400. top_def:
  401. begin
  402. getopstr:=llvmencodetypename(o.def);
  403. end;
  404. top_cond:
  405. begin
  406. getopstr:=llvm_cond2str[o.cond];
  407. end;
  408. top_fpcond:
  409. begin
  410. getopstr:=llvm_fpcond2str[o.fpcond];
  411. end;
  412. top_single,
  413. top_double:
  414. begin
  415. { "When using the hexadecimal form, constants of types half,
  416. float, and double are represented using the 16-digit form shown
  417. above (which matches the IEEE754 representation for double)"
  418. And always in big endian form (sign bit leftmost)
  419. }
  420. if o.typ=top_double then
  421. result:=llvmdoubletostr(o.dval)
  422. else
  423. result:=llvmdoubletostr(o.sval)
  424. end;
  425. top_para:
  426. begin
  427. writeparas(o.paras);
  428. result:='';
  429. end;
  430. top_tai:
  431. begin
  432. if assigned(o.ai) then
  433. begin
  434. tmpinline:=1;
  435. tmpasmblock:=false;
  436. hp:=o.ai;
  437. owner.writer.AsmWrite(fstr);
  438. fstr:='';
  439. owner.WriteTai(false,false,false,tmpinline,tmpasmblock,hp);
  440. end;
  441. result:='';
  442. end;
  443. {$if defined(cpuextended) and defined(FPC_HAS_TYPE_EXTENDED)}
  444. top_extended80:
  445. begin
  446. result:=llvmextendedtostr(o.eval);
  447. end;
  448. {$endif cpuextended}
  449. top_undef:
  450. result:='undef';
  451. top_callingconvention:
  452. result:=llvm_callingconvention_name(o.callingconvention);
  453. else
  454. internalerror(2013060227);
  455. end;
  456. end;
  457. procedure TLLVMInstrWriter.WriteAsmRegisterAllocationClobbers(list: tasmlist);
  458. var
  459. hp: tai;
  460. begin
  461. hp:=tai(list.first);
  462. while assigned(hp) do
  463. begin
  464. if (hp.typ=ait_regalloc) and
  465. (tai_regalloc(hp).ratype=ra_alloc) then
  466. begin
  467. owner.writer.AsmWrite(',~{');
  468. owner.writer.AsmWrite(std_regname(tai_regalloc(hp).reg));
  469. owner.writer.AsmWrite('}');
  470. end;
  471. hp:=tai(hp.next);
  472. end;
  473. end;
  474. procedure TLLVMInstrWriter.WriteInstruction(hp: tai);
  475. var
  476. op: tllvmop;
  477. tmpstr,
  478. sep: TSymStr;
  479. i, opstart: longint;
  480. nested: boolean;
  481. opdone,
  482. done: boolean;
  483. begin
  484. op:=taillvm(hp).llvmopcode;
  485. { we write everything immediately rather than adding it into a string,
  486. because operands may contain other tai that will also write things out
  487. (and their output must come after everything that was processed in this
  488. instruction, such as its opcode or previous operands) }
  489. if owner.fdecllevel=0 then
  490. owner.writer.AsmWrite(#9);
  491. sep:=' ';
  492. opdone:=false;
  493. done:=false;
  494. opstart:=0;
  495. nested:=false;
  496. case op of
  497. la_type:
  498. begin
  499. owner.writer.AsmWrite(llvmtypeidentifier(taillvm(hp).oper[0]^.def));
  500. owner.writer.AsmWrite(' = type ');
  501. owner.writer.AsmWrite(llvmencodetypedecl(taillvm(hp).oper[0]^.def));
  502. done:=true;
  503. end;
  504. la_asmblock:
  505. begin
  506. owner.writer.AsmWrite('call void asm sideeffect "');
  507. owner.WriteFunctionInlineAsmList(taillvm(hp).oper[0]^.asmlist);
  508. owner.writer.AsmWrite('","');
  509. { we pass all accessed local variables as in/out address parameters,
  510. since we don't analyze the assembly code to determine what exactly
  511. happens to them; this is also compatible with the regular code
  512. generators, which always place local place local variables
  513. accessed from assembly code in memory }
  514. for i:=0 to taillvm(hp).oper[1]^.paras.Count-1 do
  515. begin
  516. owner.writer.AsmWrite('=*m,');
  517. end;
  518. owner.writer.AsmWrite('~{memory},~{fpsr},~{flags}');
  519. WriteAsmRegisterAllocationClobbers(taillvm(hp).oper[0]^.asmlist);
  520. owner.writer.AsmWrite('"');
  521. writeparas(taillvm(hp).oper[1]^.paras);
  522. done:=true;
  523. end;
  524. la_load,
  525. la_getelementptr:
  526. begin
  527. if (taillvm(hp).oper[0]^.typ<>top_reg) or
  528. (taillvm(hp).oper[0]^.reg<>NR_NO) then
  529. owner.writer.AsmWrite(getopstr(taillvm(hp).oper[0]^,false)+' = ')
  530. else
  531. nested:=true;
  532. opstart:=1;
  533. owner.writer.AsmWrite(getopcodestr(taillvm(hp)));
  534. opdone:=true;
  535. if nested then
  536. owner.writer.AsmWrite(' (')
  537. else
  538. owner.writer.AsmWrite(' ');
  539. { can't just dereference the type, because it may be an
  540. implicit pointer type such as a class -> resort to string
  541. manipulation... Not very clean :( }
  542. tmpstr:=llvmencodetypename(taillvm(hp).spilling_get_reg_type(0));
  543. if op=la_getelementptr then
  544. begin
  545. if tmpstr[length(tmpstr)]<>'*' then
  546. begin
  547. writeln(tmpstr);
  548. internalerror(2016071101);
  549. end
  550. else
  551. setlength(tmpstr,length(tmpstr)-1);
  552. end;
  553. owner.writer.AsmWrite(tmpstr);
  554. owner.writer.AsmWrite(',');
  555. end;
  556. la_ret, la_br, la_switch, la_indirectbr,
  557. la_resume,
  558. la_unreachable,
  559. la_store,
  560. la_fence,
  561. la_cmpxchg,
  562. la_atomicrmw,
  563. la_catch,
  564. la_filter,
  565. la_cleanup:
  566. begin
  567. { instructions that never have a result }
  568. end;
  569. la_call,
  570. la_invoke:
  571. begin
  572. if taillvm(hp).oper[1]^.reg<>NR_NO then
  573. owner.writer.AsmWrite(getregisterstring(taillvm(hp).oper[1]^.reg)+' = ');
  574. opstart:=2;
  575. owner.writer.AsmWrite(getopcodestr(taillvm(hp)));
  576. tmpstr:=llvm_callingconvention_name(taillvm(hp).oper[2]^.callingconvention);
  577. if tmpstr<>'' then
  578. begin
  579. owner.writer.AsmWrite(' ');
  580. owner.writer.AsmWrite(tmpstr);
  581. end;
  582. opdone:=true;
  583. tmpstr:=llvmencodetypename(taillvm(hp).oper[3]^.def);
  584. if tmpstr[length(tmpstr)]<>'*' then
  585. begin
  586. writeln(tmpstr);
  587. internalerror(2016071102);
  588. end
  589. else
  590. setlength(tmpstr,length(tmpstr)-1);
  591. owner.writer.AsmWrite(tmpstr);
  592. opstart:=4;
  593. end;
  594. la_blockaddress:
  595. begin
  596. { nested -> no type }
  597. if owner.fdecllevel = 0 then
  598. begin
  599. owner.writer.AsmWrite(getopstr(taillvm(hp).oper[0]^,false));
  600. owner.writer.AsmWrite(' ');
  601. end;
  602. owner.writer.AsmWrite('blockaddress(');
  603. owner.writer.AsmWrite(getopstr(taillvm(hp).oper[1]^,false));
  604. { getopstr would add a "label" qualifier, which blockaddress does
  605. not want }
  606. owner.writer.AsmWrite(',%');
  607. with taillvm(hp).oper[2]^ do
  608. begin
  609. if (typ<>top_ref) or
  610. (ref^.refaddr<>addr_full) then
  611. internalerror(2016112001);
  612. owner.writer.AsmWrite(ref^.symbol.name);
  613. end;
  614. nested:=true;
  615. done:=true;
  616. end;
  617. la_alloca:
  618. begin
  619. owner.writer.AsmWrite(getreferencestring(taillvm(hp).oper[0]^.ref^,false)+' = ');
  620. sep:=' ';
  621. opstart:=1;
  622. end;
  623. la_trunc, la_zext, la_sext, la_fptrunc, la_fpext,
  624. la_fptoui, la_fptosi, la_uitofp, la_sitofp,
  625. la_ptrtoint, la_inttoptr,
  626. la_bitcast:
  627. begin
  628. { destination can be empty in case of nested constructs, or
  629. data initialisers }
  630. if (taillvm(hp).oper[0]^.typ<>top_reg) or
  631. (taillvm(hp).oper[0]^.reg<>NR_NO) then
  632. owner.writer.AsmWrite(getopstr(taillvm(hp).oper[0]^,false)+' = ')
  633. else
  634. nested:=true;
  635. owner.writer.AsmWrite(getopcodestr(taillvm(hp)));
  636. if not nested then
  637. owner.writer.AsmWrite(' ')
  638. else
  639. owner.writer.AsmWrite(' (');
  640. owner.writer.AsmWrite(getopstr(taillvm(hp).oper[1]^,false));
  641. { if there's a tai operand, its def is used instead of an
  642. explicit def operand }
  643. if taillvm(hp).ops=4 then
  644. begin
  645. owner.writer.AsmWrite(' ');
  646. owner.writer.AsmWrite(getopstr(taillvm(hp).oper[2]^,false));
  647. opstart:=3;
  648. end
  649. else
  650. opstart:=2;
  651. owner.writer.AsmWrite(' to ');
  652. owner.writer.AsmWrite(getopstr(taillvm(hp).oper[opstart]^,false));
  653. done:=true;
  654. end
  655. else
  656. begin
  657. if (taillvm(hp).oper[0]^.typ<>top_reg) or
  658. (taillvm(hp).oper[0]^.reg<>NR_NO) then
  659. begin
  660. owner.writer.AsmWrite(getopstr(taillvm(hp).oper[0]^,true)+' = ');
  661. end
  662. else
  663. nested:=true;
  664. sep:=' ';
  665. opstart:=1
  666. end;
  667. end;
  668. { process operands }
  669. if not done then
  670. begin
  671. if not opdone then
  672. begin
  673. owner.writer.AsmWrite(getopcodestr(taillvm(hp)));
  674. if nested then
  675. owner.writer.AsmWrite(' (');
  676. end;
  677. if taillvm(hp).ops<>0 then
  678. begin
  679. for i:=opstart to taillvm(hp).ops-1 do
  680. begin
  681. owner.writer.AsmWrite(sep);
  682. { special invoke interjections: "to label X unwind label Y" }
  683. if (op=la_invoke) then
  684. case i of
  685. 6: owner.writer.AsmWrite('to ');
  686. 7: owner.writer.AsmWrite('unwind ');
  687. end;
  688. owner.writer.AsmWrite(getopstr(taillvm(hp).oper[i]^,op in [la_load,la_store]));
  689. if (taillvm(hp).oper[i]^.typ in [top_def,top_cond,top_fpcond]) or
  690. (op in [la_call,la_invoke,la_landingpad,la_catch,la_filter,la_cleanup]) then
  691. sep :=' '
  692. else
  693. sep:=', ';
  694. end;
  695. end;
  696. end;
  697. if op=la_alloca then
  698. owner.writer.AsmWrite(getreferencealignstring(taillvm(hp).oper[0]^.ref^));
  699. if nested then
  700. owner.writer.AsmWrite(')')
  701. else if owner.fdecllevel=0 then
  702. owner.writer.AsmLn;
  703. end;
  704. function TLLVMInstrWriter.getopcodestr(hp: taillvm): TSymStr;
  705. begin
  706. result:=llvm_op2str[hp.llvmopcode];
  707. case hp.llvmopcode of
  708. la_load:
  709. begin
  710. if vol_read in hp.oper[2]^.ref^.volatility then
  711. result:=result+' volatile';
  712. end;
  713. la_store:
  714. begin
  715. if vol_write in hp.oper[3]^.ref^.volatility then
  716. result:=result+' volatile';
  717. end;
  718. else
  719. ;
  720. end;
  721. end;
  722. {****************************************************************************}
  723. { LLVM Assembler writer }
  724. {****************************************************************************}
  725. destructor TLLVMAssember.Destroy;
  726. begin
  727. InstrWriter.free;
  728. ffuncinlasmdecorator.free;
  729. inherited destroy;
  730. end;
  731. procedure TLLVMAssember.WriteTree(p:TAsmList);
  732. var
  733. hp : tai;
  734. InlineLevel : cardinal;
  735. asmblock: boolean;
  736. do_line : boolean;
  737. replaceforbidden: boolean;
  738. begin
  739. if not assigned(p) then
  740. exit;
  741. replaceforbidden:=asminfo^.dollarsign<>'$';
  742. InlineLevel:=0;
  743. asmblock:=false;
  744. { lineinfo is only needed for al_procedures (PFV) }
  745. do_line:=(cs_asm_source in current_settings.globalswitches) or
  746. ((cs_lineinfo in current_settings.moduleswitches)
  747. and (p=current_asmdata.asmlists[al_procedures]));
  748. hp:=tai(p.first);
  749. while assigned(hp) do
  750. begin
  751. prefetch(pointer(hp.next)^);
  752. if not(hp.typ in SkipLineInfo) then
  753. begin
  754. current_filepos:=tailineinfo(hp).fileinfo;
  755. { no line info for inlined code }
  756. if do_line and (inlinelevel=0) then
  757. WriteSourceLine(hp as tailineinfo);
  758. end;
  759. WriteTai(replaceforbidden, do_line, false, InlineLevel, asmblock, hp);
  760. hp:=tai(hp.next);
  761. end;
  762. end;
  763. procedure TLLVMAssember.WriteExtraHeader;
  764. begin
  765. writer.AsmWrite('target datalayout = "');
  766. writer.AsmWrite(target_info.llvmdatalayout);
  767. writer.AsmWriteln('"');
  768. writer.AsmWrite('target triple = "');
  769. writer.AsmWrite(llvm_target_name);
  770. writer.AsmWriteln('"');
  771. end;
  772. procedure TLLVMAssember.WriteExtraFooter;
  773. begin
  774. end;
  775. procedure TLLVMAssember.WriteInstruction(hp: tai);
  776. begin
  777. end;
  778. procedure TLLVMAssember.WriteLlvmInstruction(hp: tai);
  779. begin
  780. InstrWriter.WriteInstruction(hp);
  781. end;
  782. procedure TLLVMAssember.WriteRealConst(hp: tai_realconst; do_line: boolean);
  783. begin
  784. if fdecllevel=0 then
  785. begin
  786. case tai_realconst(hp).realtyp of
  787. aitrealconst_s32bit:
  788. writer.AsmWriteLn(asminfo^.comment+'value: '+single2str(tai_realconst(hp).value.s32val));
  789. aitrealconst_s64bit:
  790. writer.AsmWriteLn(asminfo^.comment+'value: '+double2str(tai_realconst(hp).value.s64val));
  791. {$if defined(cpuextended) and defined(FPC_HAS_TYPE_EXTENDED)}
  792. { can't write full 80 bit floating point constants yet on non-x86 }
  793. aitrealconst_s80bit:
  794. writer.AsmWriteLn(asminfo^.comment+'value: '+extended2str(tai_realconst(hp).value.s80val));
  795. {$endif cpuextended}
  796. aitrealconst_s64comp:
  797. writer.AsmWriteLn(asminfo^.comment+'value: '+extended2str(tai_realconst(hp).value.s64compval));
  798. else
  799. internalerror(2014050604);
  800. end;
  801. internalerror(2016120202);
  802. end;
  803. case hp.realtyp of
  804. aitrealconst_s32bit:
  805. writer.AsmWrite(llvmdoubletostr(hp.value.s32val));
  806. aitrealconst_s64bit:
  807. writer.AsmWriteln(llvmdoubletostr(hp.value.s64val));
  808. {$if defined(cpuextended) and defined(FPC_HAS_TYPE_EXTENDED)}
  809. aitrealconst_s80bit:
  810. writer.AsmWrite(llvmextendedtostr(hp.value.s80val));
  811. {$endif defined(cpuextended)}
  812. aitrealconst_s64comp:
  813. { handled as int64 most of the time in llvm }
  814. writer.AsmWrite(tostr(round(hp.value.s64compval)));
  815. else
  816. internalerror(2014062401);
  817. end;
  818. end;
  819. procedure TLLVMAssember.WriteOrdConst(hp: tai_const);
  820. var
  821. consttyp: taiconst_type;
  822. begin
  823. if fdecllevel=0 then
  824. internalerror(2016120203);
  825. consttyp:=hp.consttype;
  826. case consttyp of
  827. aitconst_got,
  828. aitconst_gotoff_symbol,
  829. aitconst_uleb128bit,
  830. aitconst_sleb128bit,
  831. aitconst_rva_symbol,
  832. aitconst_secrel32_symbol,
  833. aitconst_darwin_dwarf_delta32,
  834. aitconst_darwin_dwarf_delta64,
  835. aitconst_half16bit,
  836. aitconst_gs:
  837. internalerror(2014052901);
  838. aitconst_128bit,
  839. aitconst_64bit,
  840. aitconst_32bit,
  841. aitconst_16bit,
  842. aitconst_8bit,
  843. aitconst_16bit_unaligned,
  844. aitconst_32bit_unaligned,
  845. aitconst_64bit_unaligned:
  846. begin
  847. if fdecllevel=0 then
  848. writer.AsmWrite(asminfo^.comment);
  849. { can't have compile-time differences between symbols; these are
  850. normally for PIC, but llvm takes care of that for us }
  851. if assigned(hp.endsym) then
  852. internalerror(2014052902);
  853. if assigned(hp.sym) then
  854. begin
  855. writer.AsmWrite(LlvmAsmSymName(hp.sym));
  856. { can't have offsets }
  857. if hp.value<>0 then
  858. if fdecllevel<>0 then
  859. internalerror(2014052903)
  860. else
  861. writer.AsmWrite(' -- symbol offset: ' + tostr(hp.value));
  862. end
  863. else if hp.value=0 then
  864. writer.AsmWrite('zeroinitializer')
  865. else
  866. writer.AsmWrite(tostr(hp.value));
  867. {
  868. // activate in case of debugging IE 2016120203
  869. if fdecllevel=0 then
  870. writer.AsmLn;
  871. }
  872. end;
  873. else
  874. internalerror(200704251);
  875. end;
  876. end;
  877. procedure TLLVMAssember.WriteTai(const replaceforbidden: boolean; const do_line, inmetadata: boolean; var InlineLevel: cardinal; var asmblock: boolean; var hp: tai);
  878. procedure WriteLinkageVibilityFlags(bind: TAsmSymBind; is_definition: boolean);
  879. begin
  880. { re-declaration of a symbol defined in the current module (in an
  881. assembler block) }
  882. if not is_definition then
  883. begin
  884. writer.AsmWrite(' external');
  885. exit;
  886. end;
  887. case bind of
  888. AB_EXTERNAL,
  889. AB_EXTERNAL_INDIRECT:
  890. writer.AsmWrite(' external');
  891. AB_COMMON:
  892. writer.AsmWrite(' common');
  893. AB_LOCAL:
  894. writer.AsmWrite(' internal');
  895. AB_GLOBAL,
  896. AB_INDIRECT:
  897. ;
  898. AB_WEAK_EXTERNAL:
  899. writer.AsmWrite(' extern_weak');
  900. AB_PRIVATE_EXTERN:
  901. writer.AsmWrite(' hidden')
  902. else
  903. internalerror(2014020104);
  904. end;
  905. end;
  906. procedure WriteFunctionFlags(pd: tprocdef);
  907. begin
  908. { function attributes }
  909. if (pos('FPC_SETJMP',upper(pd.mangledname))<>0) or
  910. (pd.mangledname=(target_info.cprefix+'setjmp')) then
  911. writer.AsmWrite(' returns_twice');
  912. if po_inline in pd.procoptions then
  913. writer.AsmWrite(' inlinehint');
  914. if po_noinline in pd.procoptions then
  915. writer.AsmWrite(' noinline');
  916. { ensure that functions that happen to have the same name as a
  917. standard C library function, but which are implemented in Pascal,
  918. are not considered to have the same semantics as the C function with
  919. the same name }
  920. if not(po_external in pd.procoptions) then
  921. writer.AsmWrite(' nobuiltin');
  922. if po_noreturn in pd.procoptions then
  923. writer.AsmWrite(' noreturn');
  924. if pio_thunk in pd.implprocoptions then
  925. writer.AsmWrite(' "thunk"');
  926. if llvmflag_null_pointer_valid in llvmversion_properties[current_settings.llvmversion] then
  927. writer.AsmWrite(' "null-pointer-is-valid"="true"');
  928. if not(pio_fastmath in pd.implprocoptions) then
  929. writer.AsmWrite(' strictfp');
  930. end;
  931. procedure WriteTypedConstData(hp: tai_abstracttypedconst; metadata: boolean);
  932. var
  933. p: tai_abstracttypedconst;
  934. pval: tai;
  935. defstr: TSymStr;
  936. first, gotstring: boolean;
  937. begin
  938. if hp.def<>llvm_metadatatype then
  939. begin
  940. defstr:=llvmencodetypename(hp.def)
  941. end
  942. else
  943. begin
  944. defstr:=''
  945. end;
  946. { write the struct, array or simple type }
  947. case hp.adetyp of
  948. tck_record:
  949. begin
  950. if not(metadata) then
  951. begin
  952. writer.AsmWrite(defstr);
  953. if not(df_llvm_no_struct_packing in hp.def.defoptions) then
  954. writer.AsmWrite(' <{')
  955. else
  956. writer.AsmWrite(' {')
  957. end
  958. else
  959. begin
  960. writer.AsmWrite(' !{');
  961. end;
  962. first:=true;
  963. for p in tai_aggregatetypedconst(hp) do
  964. begin
  965. if not first then
  966. writer.AsmWrite(', ')
  967. else
  968. first:=false;
  969. WriteTypedConstData(p,metadata);
  970. end;
  971. if not(metadata) then
  972. begin
  973. if not(df_llvm_no_struct_packing in hp.def.defoptions) then
  974. writer.AsmWrite(' }>')
  975. else
  976. writer.AsmWrite(' }')
  977. end
  978. else
  979. begin
  980. writer.AsmWrite(' }');
  981. end;
  982. end;
  983. tck_array:
  984. begin
  985. if not(metadata) then
  986. begin
  987. writer.AsmWrite(defstr);
  988. end;
  989. first:=true;
  990. gotstring:=false;
  991. for p in tai_aggregatetypedconst(hp) do
  992. begin
  993. if not first then
  994. writer.AsmWrite(', ')
  995. else
  996. begin
  997. writer.AsmWrite(' ');
  998. if (tai_abstracttypedconst(p).adetyp=tck_simple) and
  999. (tai_simpletypedconst(p).val.typ=ait_string) then
  1000. begin
  1001. gotstring:=true;
  1002. end
  1003. else
  1004. begin
  1005. if not metadata then
  1006. begin
  1007. writer.AsmWrite('[');
  1008. end
  1009. else
  1010. begin
  1011. writer.AsmWrite('!{');
  1012. end;
  1013. end;
  1014. first:=false;
  1015. end;
  1016. { cannot concat strings and other things }
  1017. if gotstring and
  1018. not metadata and
  1019. ((tai_abstracttypedconst(p).adetyp<>tck_simple) or
  1020. (tai_simpletypedconst(p).val.typ<>ait_string)) then
  1021. internalerror(2014062701);
  1022. WriteTypedConstData(p,metadata);
  1023. end;
  1024. if not gotstring then
  1025. begin
  1026. if not metadata then
  1027. begin
  1028. writer.AsmWrite(']');
  1029. end
  1030. else
  1031. begin
  1032. writer.AsmWrite('}');
  1033. end;
  1034. end;
  1035. end;
  1036. tck_simple:
  1037. begin
  1038. pval:=tai_simpletypedconst(hp).val;
  1039. if (pval.typ<>ait_string) and
  1040. (defstr<>'') then
  1041. begin
  1042. writer.AsmWrite(defstr);
  1043. writer.AsmWrite(' ');
  1044. end;
  1045. WriteTai(replaceforbidden,do_line,metadata,InlineLevel,asmblock,pval);
  1046. end;
  1047. end;
  1048. end;
  1049. procedure WriteLlvmMetadataNode(hp: tai_llvmbasemetadatanode);
  1050. begin
  1051. { must only appear at the top level }
  1052. if fdecllevel<>0 then
  1053. internalerror(2019050111);
  1054. writer.AsmWrite('!');
  1055. writer.AsmWrite(tai_llvmbasemetadatanode(hp).name);
  1056. writer.AsmWrite(' =');
  1057. inc(fdecllevel);
  1058. WriteTypedConstData(hp,true);
  1059. writer.AsmLn;
  1060. dec(fdecllevel);
  1061. end;
  1062. var
  1063. hp2: tai;
  1064. s: string;
  1065. sstr: TSymStr;
  1066. i: longint;
  1067. ch: ansichar;
  1068. begin
  1069. case hp.typ of
  1070. ait_comment :
  1071. begin
  1072. writer.AsmWrite(asminfo^.comment);
  1073. writer.AsmWritePChar(tai_comment(hp).str);
  1074. if fdecllevel<>0 then
  1075. internalerror(2015090601);
  1076. writer.AsmLn;
  1077. end;
  1078. ait_regalloc :
  1079. begin
  1080. if (cs_asm_regalloc in current_settings.globalswitches) then
  1081. begin
  1082. writer.AsmWrite(#9+asminfo^.comment+'Register ');
  1083. repeat
  1084. writer.AsmWrite(std_regname(Tai_regalloc(hp).reg));
  1085. if (hp.next=nil) or
  1086. (tai(hp.next).typ<>ait_regalloc) or
  1087. (tai_regalloc(hp.next).ratype<>tai_regalloc(hp).ratype) then
  1088. break;
  1089. hp:=tai(hp.next);
  1090. writer.AsmWrite(',');
  1091. until false;
  1092. writer.AsmWrite(' ');
  1093. writer.AsmWriteLn(regallocstr[tai_regalloc(hp).ratype]);
  1094. end;
  1095. end;
  1096. ait_tempalloc :
  1097. begin
  1098. if (cs_asm_tempalloc in current_settings.globalswitches) then
  1099. WriteTempalloc(tai_tempalloc(hp));
  1100. end;
  1101. ait_align,
  1102. ait_section :
  1103. begin
  1104. { ignore, specified as part of declarations -- don't write
  1105. comment, because could appear in the middle of an aggregate
  1106. constant definition }
  1107. end;
  1108. ait_datablock :
  1109. begin
  1110. writer.AsmWrite(asminfo^.comment);
  1111. writer.AsmWriteln('datablock');
  1112. end;
  1113. ait_const:
  1114. begin
  1115. WriteOrdConst(tai_const(hp));
  1116. end;
  1117. ait_realconst :
  1118. begin
  1119. WriteRealConst(tai_realconst(hp), do_line);
  1120. end;
  1121. ait_string :
  1122. begin
  1123. if fdecllevel=0 then
  1124. internalerror(2016120201);
  1125. if not inmetadata then
  1126. writer.AsmWrite('c"')
  1127. else
  1128. writer.AsmWrite('!"');
  1129. for i:=1 to tai_string(hp).len do
  1130. begin
  1131. ch:=tai_string(hp).str[i-1];
  1132. case ch of
  1133. #0, {This can't be done by range, because a bug in FPC}
  1134. #1..#31,
  1135. #128..#255,
  1136. '"',
  1137. '\' : s:='\'+hexStr(ord(ch),2);
  1138. else
  1139. s:=ch;
  1140. end;
  1141. writer.AsmWrite(s);
  1142. end;
  1143. writer.AsmWrite('"');
  1144. end;
  1145. ait_label :
  1146. begin
  1147. if not asmblock and
  1148. (tai_label(hp).labsym.is_used) then
  1149. begin
  1150. if (tai_label(hp).labsym.bind=AB_PRIVATE_EXTERN) then
  1151. begin
  1152. { should be emitted as part of the variable/function def }
  1153. internalerror(2013010703);
  1154. end;
  1155. if tai_label(hp).labsym.bind in [AB_GLOBAL, AB_PRIVATE_EXTERN] then
  1156. begin
  1157. { should be emitted as part of the variable/function def }
  1158. //internalerror(2013010704);
  1159. writer.AsmWriteln(asminfo^.comment+'global/privateextern label: '+tai_label(hp).labsym.name);
  1160. end;
  1161. if replaceforbidden then
  1162. writer.AsmWrite(ReplaceForbiddenAsmSymbolChars(tai_label(hp).labsym.name))
  1163. else
  1164. writer.AsmWrite(tai_label(hp).labsym.name);
  1165. writer.AsmWriteLn(':');
  1166. end;
  1167. end;
  1168. ait_symbol :
  1169. begin
  1170. if fdecllevel=0 then
  1171. writer.AsmWrite(asminfo^.comment);
  1172. writer.AsmWriteln(LlvmAsmSymName(tai_symbol(hp).sym));
  1173. { todo }
  1174. if tai_symbol(hp).has_value then
  1175. internalerror(2014062402);
  1176. end;
  1177. ait_llvmdecl:
  1178. begin
  1179. if taillvmdecl(hp).def.typ=procdef then
  1180. begin
  1181. if not(ldf_definition in taillvmdecl(hp).flags) then
  1182. begin
  1183. writer.AsmWrite('declare');
  1184. writer.AsmWrite(llvmencodeproctype(tprocdef(taillvmdecl(hp).def), taillvmdecl(hp).namesym.name, lpd_decl));
  1185. WriteFunctionFlags(tprocdef(taillvmdecl(hp).def));
  1186. writer.AsmLn;
  1187. end
  1188. else
  1189. begin
  1190. writer.AsmWrite('define');
  1191. if ldf_weak in taillvmdecl(hp).flags then
  1192. writer.AsmWrite(' weak');
  1193. WriteLinkageVibilityFlags(taillvmdecl(hp).namesym.bind, true);
  1194. writer.AsmWrite(llvmencodeproctype(tprocdef(taillvmdecl(hp).def), '', lpd_def));
  1195. WriteFunctionFlags(tprocdef(taillvmdecl(hp).def));
  1196. if assigned(tprocdef(taillvmdecl(hp).def).personality) then
  1197. begin
  1198. writer.AsmWrite(' personality i8* bitcast (');
  1199. writer.AsmWrite(llvmencodeproctype(tprocdef(taillvmdecl(hp).def).personality, '', lpd_procvar));
  1200. writer.AsmWrite('* ');
  1201. writer.AsmWrite(llvmmangledname(tprocdef(taillvmdecl(hp).def).personality.mangledname));
  1202. writer.AsmWrite(' to i8*)');
  1203. end;
  1204. writer.AsmWriteln(' {');
  1205. end;
  1206. end
  1207. else
  1208. begin
  1209. writer.AsmWrite(LlvmAsmSymName(taillvmdecl(hp).namesym));
  1210. writer.AsmWrite(' =');
  1211. if ldf_weak in taillvmdecl(hp).flags then
  1212. writer.AsmWrite(' weak');
  1213. if ldf_appending in taillvmdecl(hp).flags then
  1214. writer.AsmWrite(' appending');
  1215. WriteLinkageVibilityFlags(taillvmdecl(hp).namesym.bind, ldf_definition in taillvmdecl(hp).flags);
  1216. writer.AsmWrite(' ');
  1217. if (ldf_tls in taillvmdecl(hp).flags) then
  1218. writer.AsmWrite('thread_local ');
  1219. if ldf_unnamed_addr in taillvmdecl(hp).flags then
  1220. writer.AsmWrite('unnamed_addr ');
  1221. if taillvmdecl(hp).sec in [sec_rodata,sec_rodata_norel] then
  1222. writer.AsmWrite('constant ')
  1223. else
  1224. writer.AsmWrite('global ');
  1225. if not assigned(taillvmdecl(hp).initdata) then
  1226. begin
  1227. writer.AsmWrite(llvmencodetypename(taillvmdecl(hp).def));
  1228. if ldf_definition in taillvmdecl(hp).flags then
  1229. writer.AsmWrite(' zeroinitializer');
  1230. end
  1231. else
  1232. begin
  1233. inc(fdecllevel);
  1234. { can't have an external symbol with initialisation data }
  1235. if taillvmdecl(hp).namesym.bind in [AB_EXTERNAL, AB_WEAK_EXTERNAL] then
  1236. internalerror(2014052905);
  1237. { bitcast initialisation data to the type of the constant }
  1238. { write initialisation data }
  1239. hp2:=tai(taillvmdecl(hp).initdata.first);
  1240. while assigned(hp2) do
  1241. begin
  1242. WriteTai(replaceforbidden,do_line,inmetadata,InlineLevel,asmblock,hp2);
  1243. hp2:=tai(hp2.next);
  1244. end;
  1245. dec(fdecllevel);
  1246. end;
  1247. { custom section name? }
  1248. case taillvmdecl(hp).sec of
  1249. sec_user:
  1250. begin
  1251. writer.AsmWrite(', section "');
  1252. writer.AsmWrite(taillvmdecl(hp).secname);
  1253. writer.AsmWrite('"');
  1254. end;
  1255. low(TObjCAsmSectionType)..high(TObjCAsmSectionType):
  1256. begin
  1257. writer.AsmWrite(', section "');
  1258. writer.AsmWrite(objc_section_name(taillvmdecl(hp).sec));
  1259. writer.AsmWrite('"');
  1260. end;
  1261. else
  1262. ;
  1263. end;
  1264. { sections whose name starts with 'llvm.' are for LLVM
  1265. internal use and don't have an alignment }
  1266. if pos('llvm.',taillvmdecl(hp).secname)<>1 then
  1267. begin
  1268. { alignment }
  1269. writer.AsmWrite(', align ');
  1270. writer.AsmWriteln(tostr(taillvmdecl(hp).alignment));
  1271. end
  1272. else
  1273. writer.AsmLn;
  1274. end;
  1275. end;
  1276. ait_llvmalias:
  1277. begin
  1278. writer.AsmWrite(LlvmAsmSymName(taillvmalias(hp).newsym));
  1279. writer.AsmWrite(' = alias ');
  1280. WriteLinkageVibilityFlags(taillvmalias(hp).bind, true);
  1281. if taillvmalias(hp).def.typ=procdef then
  1282. sstr:=llvmencodeproctype(tabstractprocdef(taillvmalias(hp).def), '', lpd_alias)
  1283. else
  1284. sstr:=llvmencodetypename(taillvmalias(hp).def);
  1285. writer.AsmWrite(sstr);
  1286. writer.AsmWrite(', ');
  1287. writer.AsmWrite(sstr);
  1288. writer.AsmWrite('* ');
  1289. writer.AsmWriteln(LlvmAsmSymName(taillvmalias(hp).oldsym));
  1290. end;
  1291. ait_llvmmetadatanode:
  1292. begin
  1293. WriteLlvmMetadataNode(tai_llvmbasemetadatanode(hp));
  1294. end;
  1295. ait_llvmmetadatareftypedconst:
  1296. begin
  1297. { must only appear as an element in a typed const }
  1298. if fdecllevel=0 then
  1299. internalerror(2019050110);
  1300. writer.AsmWrite('!');
  1301. writer.AsmWrite(tai_llvmbasemetadatanode(tai_llvmmetadatareftypedconst(hp).val).name);
  1302. end;
  1303. ait_llvmmetadatarefoperand:
  1304. begin
  1305. { must only appear as an operand }
  1306. if fdecllevel=0 then
  1307. internalerror(2019050110);
  1308. writer.AsmWrite('!');
  1309. writer.AsmWrite(tai_llvmmetadatareferenceoperand(hp).id);
  1310. writer.AsmWrite(' !');
  1311. writer.AsmWrite(tai_llvmmetadatareferenceoperand(hp).value.name);
  1312. end;
  1313. ait_symbolpair:
  1314. begin
  1315. { should be emitted as part of the symbol def }
  1316. internalerror(2013010708);
  1317. end;
  1318. ait_symbol_end :
  1319. begin
  1320. if tai_symbol_end(hp).sym.typ=AT_FUNCTION then
  1321. writer.AsmWriteln('}')
  1322. else
  1323. writer.AsmWriteln('; ait_symbol_end error, should not be generated');
  1324. // internalerror(2013010711);
  1325. end;
  1326. ait_instruction :
  1327. begin
  1328. WriteInstruction(hp);
  1329. end;
  1330. ait_llvmins:
  1331. begin
  1332. WriteLlvmInstruction(hp);
  1333. end;
  1334. ait_stab :
  1335. begin
  1336. internalerror(2013010712);
  1337. end;
  1338. ait_force_line,
  1339. ait_function_name :
  1340. ;
  1341. ait_cutobject :
  1342. begin
  1343. end;
  1344. ait_marker :
  1345. case
  1346. tai_marker(hp).kind of
  1347. mark_NoLineInfoStart:
  1348. inc(InlineLevel);
  1349. mark_NoLineInfoEnd:
  1350. dec(InlineLevel);
  1351. { these cannot be nested }
  1352. mark_AsmBlockStart:
  1353. asmblock:=true;
  1354. mark_AsmBlockEnd:
  1355. asmblock:=false;
  1356. else
  1357. ;
  1358. end;
  1359. ait_directive :
  1360. begin
  1361. { CPU directive is commented out for the LLVM }
  1362. if tai_directive(hp).directive=asd_cpu then
  1363. writer.AsmWrite(asminfo^.comment);
  1364. WriteDirectiveName(tai_directive(hp).directive);
  1365. if tai_directive(hp).name <>'' then
  1366. writer.AsmWrite(tai_directive(hp).name);
  1367. if fdecllevel<>0 then
  1368. internalerror(2015090602);
  1369. writer.AsmLn;
  1370. end;
  1371. ait_seh_directive :
  1372. begin
  1373. internalerror(2013010713);
  1374. end;
  1375. ait_varloc:
  1376. begin
  1377. if tai_varloc(hp).newlocationhi<>NR_NO then
  1378. writer.AsmWrite(strpnew('Var '+tai_varloc(hp).varsym.realname+' located in register '+
  1379. std_regname(tai_varloc(hp).newlocationhi)+':'+std_regname(tai_varloc(hp).newlocation)))
  1380. else
  1381. writer.AsmWrite(strpnew('Var '+tai_varloc(hp).varsym.realname+' located in register '+
  1382. std_regname(tai_varloc(hp).newlocation)));
  1383. if fdecllevel<>0 then
  1384. internalerror(2015090603);
  1385. writer.AsmLn;
  1386. end;
  1387. ait_typedconst:
  1388. begin
  1389. WriteTypedConstData(tai_abstracttypedconst(hp),false);
  1390. end
  1391. else
  1392. internalerror(2019012010);
  1393. end;
  1394. end;
  1395. constructor TLLVMAssember.CreateWithWriter(info: pasminfo; wr: TExternalAssemblerOutputFile; freewriter, smart: boolean);
  1396. begin
  1397. inherited;
  1398. InstrWriter:=TLLVMInstrWriter.create(self);
  1399. end;
  1400. procedure TLLVMAssember.WriteDirectiveName(dir: TAsmDirective);
  1401. begin
  1402. writer.AsmWrite('.'+directivestr[dir]+' ');
  1403. end;
  1404. procedure TLLVMAssember.WriteAsmList;
  1405. var
  1406. hal : tasmlisttype;
  1407. a: TExternalAssembler;
  1408. decorator: TLLVMModuleInlineAssemblyDecorator;
  1409. begin
  1410. WriteExtraHeader;
  1411. for hal:=low(TasmlistType) to high(TasmlistType) do
  1412. begin
  1413. if not assigned(current_asmdata.asmlists[hal]) or
  1414. current_asmdata.asmlists[hal].Empty then
  1415. continue;
  1416. writer.AsmWriteLn(asminfo^.comment+'Begin asmlist '+AsmlistTypeStr[hal]);
  1417. if not(hal in [al_pure_assembler,al_dwarf_frame]) then
  1418. writetree(current_asmdata.asmlists[hal])
  1419. else
  1420. begin
  1421. { write routines using the target-specific external assembler
  1422. writer, filtered using the LLVM module-level assembly
  1423. decorator }
  1424. decorator:=TLLVMModuleInlineAssemblyDecorator.Create;
  1425. writer.decorator:=decorator;
  1426. a:=GetExternalGnuAssemblerWithAsmInfoWriter(asminfo,writer);
  1427. a.WriteTree(current_asmdata.asmlists[hal]);
  1428. writer.decorator:=nil;
  1429. decorator.free;
  1430. a.free;
  1431. end;
  1432. writer.AsmWriteLn(asminfo^.comment+'End asmlist '+AsmlistTypeStr[hal]);
  1433. end;
  1434. writer.AsmLn;
  1435. end;
  1436. procedure TLLVMAssember.WriteFunctionInlineAsmList(list: tasmlist);
  1437. var
  1438. a: TExternalAssembler;
  1439. begin
  1440. if not assigned(ffuncinlasmdecorator) then
  1441. ffuncinlasmdecorator:=TLLVMFunctionInlineAssemblyDecorator.create;
  1442. if assigned(writer.decorator) then
  1443. internalerror(2016110201);
  1444. writer.decorator:=ffuncinlasmdecorator;
  1445. a:=GetExternalGnuAssemblerWithAsmInfoWriter(asminfo,writer);
  1446. a.WriteTree(list);
  1447. a.free;
  1448. writer.decorator:=nil;
  1449. end;
  1450. {****************************************************************************}
  1451. { LLVM Instruction Writer }
  1452. {****************************************************************************}
  1453. constructor TLLVMInstrWriter.create(_owner: TLLVMAssember);
  1454. begin
  1455. inherited create;
  1456. owner := _owner;
  1457. end;
  1458. {****************************************************************************}
  1459. { llc Assember }
  1460. {****************************************************************************}
  1461. function TLLVMLLCAssember.MakeCmdLine: TCmdStr;
  1462. var
  1463. optstr: TCmdStr;
  1464. begin
  1465. result:=inherited;
  1466. { standard optimization flags for llc -- todo: this needs to be split
  1467. into a call to opt and one to llc }
  1468. if cs_opt_level3 in current_settings.optimizerswitches then
  1469. optstr:='-O3'
  1470. else if cs_opt_level2 in current_settings.optimizerswitches then
  1471. optstr:='-O2'
  1472. else if cs_opt_level1 in current_settings.optimizerswitches then
  1473. optstr:='-O1'
  1474. else
  1475. optstr:='-O0';
  1476. { stack frame elimination }
  1477. if not(cs_opt_stackframe in current_settings.optimizerswitches) then
  1478. optstr:=optstr+' -disable-fp-elim';
  1479. { fast math }
  1480. if cs_opt_fastmath in current_settings.optimizerswitches then
  1481. optstr:=optstr+' -enable-unsafe-fp-math -fp-contract=fast'; { -enable-fp-mad support depends on version }
  1482. { smart linking }
  1483. if cs_create_smart in current_settings.moduleswitches then
  1484. optstr:=optstr+' -data-sections -function-sections';
  1485. { pic }
  1486. if cs_create_pic in current_settings.moduleswitches then
  1487. optstr:=optstr+' -relocation-model=pic'
  1488. else if not(target_info.system in systems_darwin) then
  1489. optstr:=optstr+' -relocation-model=static'
  1490. else
  1491. optstr:=optstr+' -relocation-model=dynamic-no-pic';
  1492. { force object output instead of textual assembler code }
  1493. optstr:=optstr+' -filetype=obj';
  1494. if fputypestrllvm[current_settings.fputype]<>'' then
  1495. optstr:=optstr+' -mattr=+'+fputypestrllvm[current_settings.fputype];
  1496. replace(result,'$OPT',optstr);
  1497. end;
  1498. {****************************************************************************}
  1499. { clang Assember }
  1500. {****************************************************************************}
  1501. function TLLVMClangAssember.MakeCmdLine: TCmdStr;
  1502. var
  1503. wpostr,
  1504. optstr: TCmdStr;
  1505. begin
  1506. wpostr:='';
  1507. if cs_lto in current_settings.moduleswitches then
  1508. begin
  1509. case fnextpass of
  1510. 0:
  1511. begin
  1512. ObjFileName:=ChangeFileExt(ObjFileName,'.bc');
  1513. wpostr:=' -flto';
  1514. end;
  1515. 1:
  1516. begin
  1517. ObjFileName:=ChangeFileExt(ObjFileName,'.o');
  1518. end;
  1519. end;
  1520. end;
  1521. result:=inherited;
  1522. { standard optimization flags for llc -- todo: this needs to be split
  1523. into a call to opt and one to llc }
  1524. if cs_opt_level3 in current_settings.optimizerswitches then
  1525. optstr:='-O3'
  1526. else if cs_opt_level2 in current_settings.optimizerswitches then
  1527. optstr:='-O2'
  1528. else if cs_opt_level1 in current_settings.optimizerswitches then
  1529. optstr:='-O1'
  1530. else
  1531. optstr:='-O0';
  1532. optstr:=optstr+wpostr;
  1533. { stack frame elimination }
  1534. if not(cs_opt_stackframe in current_settings.optimizerswitches) then
  1535. optstr:=optstr+' -fno-omit-frame-pointer'
  1536. else
  1537. optstr:=optstr+' -fomit-frame-pointer';
  1538. { fast math }
  1539. if cs_opt_fastmath in current_settings.optimizerswitches then
  1540. optstr:=optstr+' -ffast-math';
  1541. { smart linking }
  1542. if cs_create_smart in current_settings.moduleswitches then
  1543. optstr:=optstr+' -fdata-sections -ffunction-sections';
  1544. { pic }
  1545. if cs_create_pic in current_settings.moduleswitches then
  1546. optstr:=optstr+' -fpic'
  1547. else if not(target_info.system in systems_darwin) then
  1548. optstr:=optstr+' -static'
  1549. else
  1550. optstr:=optstr+' -mdynamic-no-pic';
  1551. if not(target_info.system in systems_darwin) then
  1552. begin
  1553. optstr:=optstr+' --target='+llvm_target_name;
  1554. end;
  1555. if fputypestrllvm[current_settings.fputype]<>'' then
  1556. optstr:=optstr+' -m'+fputypestrllvm[current_settings.fputype];
  1557. replace(result,'$OPT',optstr);
  1558. inc(fnextpass);
  1559. end;
  1560. function TLLVMClangAssember.DoAssemble: boolean;
  1561. begin
  1562. fnextpass:=0;
  1563. result:=inherited;
  1564. end;
  1565. function TLLVMClangAssember.RerunAssembler: boolean;
  1566. begin
  1567. result:=
  1568. (cs_lto in current_settings.moduleswitches) and
  1569. (fnextpass<=1);
  1570. end;
  1571. function TLLVMClangAssember.DoPipe: boolean;
  1572. begin
  1573. result:=
  1574. not(cs_lto in current_settings.moduleswitches) and
  1575. inherited;
  1576. end;
  1577. const
  1578. as_llvm_llc_info : tasminfo =
  1579. (
  1580. id : as_llvm_llc;
  1581. idtxt : 'LLVM-LLC';
  1582. asmbin : 'llc';
  1583. asmcmd: '$OPT -o $OBJ $ASM';
  1584. supported_targets : [system_x86_64_linux,system_x86_64_darwin,system_aarch64_linux,system_arm_linux];
  1585. flags : [af_smartlink_sections];
  1586. labelprefix : 'L';
  1587. comment : '; ';
  1588. dollarsign: '$';
  1589. );
  1590. as_llvm_clang_info : tasminfo =
  1591. (
  1592. id : as_llvm_clang;
  1593. idtxt : 'LLVM-CLANG';
  1594. asmbin : 'clang';
  1595. asmcmd: '$OPT $DARWINVERSION -c -o $OBJ $ASM';
  1596. supported_targets : [system_x86_64_linux,system_x86_64_darwin,system_aarch64_linux,system_arm_linux];
  1597. flags : [af_smartlink_sections];
  1598. labelprefix : 'L';
  1599. comment : '; ';
  1600. dollarsign: '$';
  1601. );
  1602. begin
  1603. RegisterAssembler(as_llvm_llc_info,TLLVMLLCAssember);
  1604. RegisterAssembler(as_llvm_clang_info,TLLVMClangAssember);
  1605. end.