FoxARMBackend.Mod 147 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584
  1. MODULE FoxARMBackend; (** AUTHOR ""; PURPOSE "backend for ARM (advanced RISC machines)"; *)
  2. IMPORT
  3. Basic := FoxBasic, SyntaxTree := FoxSyntaxTree, Global := FoxGlobal, Backend := FoxBackend, Sections := FoxSections,
  4. IntermediateCode := FoxIntermediateCode, IntermediateBackend := FoxIntermediateBackend, CodeGenerators := FoxCodeGenerators, BinaryCode := FoxBinaryCode,
  5. SemanticChecker := FoxSemanticChecker, Formats := FoxFormats, Assembler := FoxARMAssembler, InstructionSet := FoxARMInstructionSet,
  6. SYSTEM, Diagnostics, Streams, Options, Strings, ObjectFile, Scanner := FoxScanner, ObjectFileFormat := FoxGenericObjectFile,
  7. D := Debugging;
  8. CONST
  9. Trace = FALSE; (* general trace *)
  10. DefaultRuntimeModuleName = "ARMRuntime";
  11. None = -1;
  12. (* parts of an ARM operand *)
  13. Low = 0; High = 1;
  14. (* mnemonics of the ARM instruction set *)
  15. opADC = InstructionSet.opADC; opADD = InstructionSet.opADD;
  16. opAND = InstructionSet.opAND; opB = InstructionSet.opB;
  17. opBIC = InstructionSet.opBIC; opBKPT = InstructionSet.opBKPT;
  18. opBL = InstructionSet.opBL; opBLX = InstructionSet.opBLX;
  19. opBX = InstructionSet.opBX; opCDP = InstructionSet.opCDP;
  20. opCDP2 = InstructionSet.opCDP2; opCLZ = InstructionSet.opCLZ;
  21. opCMN = InstructionSet.opCMN; opCMP = InstructionSet.opCMP;
  22. opEOR = InstructionSet.opEOR; opFABSD = InstructionSet.opFABSD;
  23. opFABSS = InstructionSet.opFABSS; opFADDD = InstructionSet.opFADDD;
  24. opFADDS = InstructionSet.opFADDS; opFCMPD = InstructionSet.opFCMPD;
  25. opFCMPED = InstructionSet.opFCMPED; opFCMPES = InstructionSet.opFCMPES;
  26. opFCMPEZD = InstructionSet.opFCMPEZD; opFCMPEZS = InstructionSet.opFCMPEZS;
  27. opFCMPS = InstructionSet.opFCMPS; opFCMPZD = InstructionSet.opFCMPZD;
  28. opFCMPZS = InstructionSet.opFCMPZS; opFCPYD = InstructionSet.opFCPYD;
  29. opFCPYS = InstructionSet.opFCPYS; opFCVTDS = InstructionSet.opFCVTDS;
  30. opFCVTSD = InstructionSet.opFCVTSD; opFDIVD = InstructionSet.opFDIVD;
  31. opFDIVS = InstructionSet.opFDIVS; opFLDD = InstructionSet.opFLDD;
  32. opFLDMIAD = InstructionSet.opFLDMIAD; opFLDMIAS = InstructionSet.opFLDMIAS;
  33. opFLDMIAX = InstructionSet.opFLDMIAX; opFLDMDBD = InstructionSet.opFLDMDBD;
  34. opFLDMDBS = InstructionSet.opFLDMDBS; opFLDMDBX = InstructionSet.opFLDMDBX;
  35. opFLDS = InstructionSet.opFLDS; opFMACD = InstructionSet.opFMACD;
  36. opFMACS = InstructionSet.opFMACS; opFMDHR = InstructionSet.opFMDHR;
  37. opFMDLR = InstructionSet.opFMDLR; opFMRDH = InstructionSet.opFMRDH;
  38. opFMRDL = InstructionSet.opFMRDL; opFMRS = InstructionSet.opFMRS;
  39. opFMRX = InstructionSet.opFMRX; opFMSCD = InstructionSet.opFMSCD;
  40. opFMSCS = InstructionSet.opFMSCS; opFMSR = InstructionSet.opFMSR;
  41. opFMSTAT = InstructionSet.opFMSTAT; opFMULD = InstructionSet.opFMULD;
  42. opFMULS = InstructionSet.opFMULS; opFMXR = InstructionSet.opFMXR;
  43. opFNEGD = InstructionSet.opFNEGD; opFNEGS = InstructionSet.opFNEGS;
  44. opFNMACD = InstructionSet.opFNMACD; opFNMACS = InstructionSet.opFNMACS;
  45. opFNMSCD = InstructionSet.opFNMSCD; opFNMSCS = InstructionSet.opFNMSCS;
  46. opFNMULD = InstructionSet.opFNMULD ; opFNMULS = InstructionSet.opFNMULS;
  47. opFSITOD = InstructionSet.opFSITOD; opFSITOS = InstructionSet.opFSITOS;
  48. opFSQRTD = InstructionSet.opFSQRTD; opFSQRTS = InstructionSet.opFSQRTS;
  49. opFSTD = InstructionSet.opFSTD; opFSTMIAD = InstructionSet.opFSTMIAD;
  50. opFSTMIAS = InstructionSet.opFSTMIAS; opFSTMIAX = InstructionSet.opFSTMIAX;
  51. opFSTMDBD = InstructionSet.opFSTMDBD; opFSTMDBS = InstructionSet.opFSTMDBS;
  52. opFSTMDBX = InstructionSet.opFSTMDBX; opFSTS = InstructionSet.opFSTS;
  53. opFSUBD = InstructionSet.opFSUBD; opFSUBS = InstructionSet.opFSUBS;
  54. opFTOSID = InstructionSet.opFTOSID; opFTOSIZD = InstructionSet.opFTOSIZD;
  55. opFTOSIS = InstructionSet.opFTOSIS; opFTOSIZS = InstructionSet.opFTOSIZS;
  56. opFTOUID = InstructionSet.opFTOUID; opFTOUIZD = InstructionSet.opFTOUIZD;
  57. opFTOUIS = InstructionSet.opFTOUIS; opFTOUIZS = InstructionSet.opFTOUIZS;
  58. opFUITOD = InstructionSet.opFUITOD; opFUITOS = InstructionSet.opFUITOS;
  59. opLDC = InstructionSet.opLDC; opLDC2 = InstructionSet.opLDC2;
  60. opLDM = InstructionSet.opLDM; opLDR = InstructionSet.opLDR;
  61. opLDREX = InstructionSet.opLDREX; opSTREX = InstructionSet.opSTREX;
  62. opMCR = InstructionSet.opMCR; opMCR2 = InstructionSet.opMCR2;
  63. opMCRR = InstructionSet.opMCRR; opMLA = InstructionSet.opMLA;
  64. opMOV = InstructionSet.opMOV; opMRC = InstructionSet.opMRC;
  65. opMRC2 = InstructionSet.opMRC2; opMRRC = InstructionSet.opMRRC;
  66. opMRS = InstructionSet.opMRS; opMSR = InstructionSet.opMSR;
  67. opMUL = InstructionSet.opMUL; opMVN = InstructionSet.opMVN;
  68. opORR = InstructionSet.opORR; opPLD = InstructionSet.opPLD;
  69. opQADD = InstructionSet.opQADD; opQDADD = InstructionSet.opQDADD;
  70. opQDSUB = InstructionSet.opQDSUB; opQSUB = InstructionSet.opQSUB;
  71. opRSB = InstructionSet.opRSB; opRSC = InstructionSet.opRSC;
  72. opSBC = InstructionSet.opSBC; opSMLABB = InstructionSet.opSMLABB;
  73. opSMLABT = InstructionSet.opSMLABT; opSMLAL = InstructionSet.opSMLAL;
  74. opSMLATB = InstructionSet.opSMLATB; opSMLATT = InstructionSet.opSMLATT;
  75. opSMLALBB = InstructionSet.opSMLALBB; opSMLALBT = InstructionSet.opSMLALBT;
  76. opSMLALTB = InstructionSet.opSMLALTB; opSMLALTT = InstructionSet.opSMLALTT;
  77. opSMLAWB = InstructionSet.opSMLAWB; opSMLAWT = InstructionSet.opSMLAWT;
  78. opSMULBB = InstructionSet.opSMULBB; opSMULBT = InstructionSet.opSMULBT;
  79. opSMULTB = InstructionSet.opSMULTB; opSMULTT = InstructionSet.opSMULTT;
  80. opSMULWB = InstructionSet.opSMULWB; opSMULWT = InstructionSet.opSMULWT;
  81. opSMULL = InstructionSet.opSMULL; opSTC = InstructionSet.opSTC;
  82. opSTC2 = InstructionSet.opSTC2; opSTM = InstructionSet.opSTM;
  83. opSTR = InstructionSet.opSTR; opSUB = InstructionSet.opSUB;
  84. opSWI = InstructionSet.opSWI; opSWP = InstructionSet.opSWP;
  85. opTEQ = InstructionSet.opTEQ; opTST = InstructionSet.opTST;
  86. opUMLAL = InstructionSet.opUMLAL; opUMULL = InstructionSet.opUMULL;
  87. MaximumFixupDistance = (*4103*) 1024; (* = 2^12-1+8 (maximum distance [in bytes] between a symbol fixup location and an instruction that uses the symbol) *)
  88. (* builtin backend specific system instructions *)
  89. GetSP = 0; SetSP = 1;
  90. GetFP = 2; SetFP = 3;
  91. GetLNK = 4; SetLNK = 5;
  92. GetPC = 6; SetPC = 7;
  93. LDPSR = 8; STPSR = 9;
  94. LDCPR = 10; STCPR = 11;
  95. FLUSH = 12;
  96. NULL = 13; XOR = 14; MULD = 15; ADDC = 16;
  97. PACK = 17; UNPK = 18;
  98. UseFPUFlag = "useFPU";
  99. TYPE
  100. Operand = InstructionSet.Operand;
  101. Ticket = CodeGenerators.Ticket;
  102. (* a citation of a symbol, i.e., an ARM instruction that requires a symbol's address *)
  103. Citation = OBJECT
  104. VAR
  105. pc: LONGINT; (* program counter of the ARM instruction *)
  106. next: Citation;
  107. END Citation;
  108. (* a reference to a symbol and offset in IR units that is used by at least one instruction *)
  109. Reference = OBJECT
  110. VAR
  111. firstCitation, lastCitation: Citation; (* linked list of citations *)
  112. next: Reference;
  113. PROCEDURE & Init;
  114. BEGIN
  115. firstCitation := NIL; lastCitation := NIL; next := NIL;
  116. END Init;
  117. PROCEDURE AddCitation(pc: LONGINT);
  118. VAR
  119. citation: Citation;
  120. BEGIN
  121. NEW(citation); citation.pc := pc; citation.next := NIL;
  122. IF firstCitation = NIL THEN firstCitation := citation ELSE lastCitation.next := citation END;
  123. lastCitation := citation
  124. END AddCitation;
  125. END Reference;
  126. ImmediateReference = OBJECT (Reference)
  127. VAR value: LONGINT;
  128. PROCEDURE & InitImm(v: LONGINT);
  129. BEGIN
  130. Init;
  131. SELF.value := v;
  132. END InitImm;
  133. END ImmediateReference;
  134. (* a reference to a symbol and offset in IR units that is used by at least one instruction *)
  135. SymbolReference = OBJECT (Reference)
  136. VAR
  137. symbol: Sections.SectionName;
  138. fingerprint: LONGINT;
  139. symbolOffset: LONGINT; (* offset to the symbol in IR units *)
  140. PROCEDURE & InitSym(s: Sections.SectionName; fp: LONGINT; offs: LONGINT);
  141. BEGIN
  142. Init;
  143. SELF.symbol := s; SELF.symbolOffset := offs; fingerprint := fp;
  144. END InitSym;
  145. END SymbolReference;
  146. ListOfReferences = OBJECT
  147. VAR
  148. firstReference, lastReference: Reference; (* linked list of all symbol references *)
  149. referenceCount: LONGINT; (* the number of reference = length of the required fixup block *)
  150. pcOfFirstCitation: LONGINT; (* the PC of the first instruction that cites a symbol or immediate *)
  151. PROCEDURE & Init;
  152. BEGIN
  153. firstReference := NIL; lastReference := NIL;
  154. referenceCount := 0;
  155. pcOfFirstCitation := None;
  156. END Init;
  157. PROCEDURE AddSymbol(symbol: Sections.SectionName; fingerprint: LONGINT; symbolOffset: LONGINT; pc: LONGINT);
  158. VAR
  159. reference, foundReference: Reference; symbolReference: SymbolReference;
  160. BEGIN
  161. (* go through the list of symbol/offset-combinations and check if there already is an entry for the symbol and offset in question *)
  162. reference := firstReference;
  163. WHILE reference # NIL DO
  164. IF reference IS SymbolReference THEN
  165. WITH reference: SymbolReference DO
  166. IF (reference.symbol = symbol) & (reference.symbolOffset = symbolOffset) THEN
  167. foundReference := reference (* an entry already exists *)
  168. END;
  169. END;
  170. END;
  171. reference := reference.next
  172. END;
  173. IF foundReference # NIL THEN
  174. reference := foundReference
  175. ELSE
  176. (* no entry was found for the symbol/offset combination: create a new one *)
  177. NEW(symbolReference, symbol, fingerprint, symbolOffset);
  178. reference := symbolReference;
  179. IF firstReference = NIL THEN firstReference := reference ELSE lastReference.next := reference END;
  180. lastReference := reference;
  181. INC(referenceCount)
  182. END;
  183. (* add a citation to the reference *)
  184. reference.AddCitation(pc);
  185. IF pcOfFirstCitation = None THEN pcOfFirstCitation := pc END
  186. END AddSymbol;
  187. PROCEDURE AddImmediate(value: LONGINT; pc: LONGINT);
  188. VAR
  189. reference, foundReference: Reference; immediateReference: ImmediateReference;
  190. BEGIN
  191. (* go through the list of symbol/offset-combinations and check if there already is an entry for the symbol and offset in question *)
  192. reference := firstReference;
  193. WHILE reference # NIL DO
  194. IF reference IS ImmediateReference THEN
  195. WITH reference: ImmediateReference DO
  196. IF (reference.value = value) THEN
  197. foundReference := reference (* an entry already exists *)
  198. END;
  199. END;
  200. END;
  201. reference := reference.next
  202. END;
  203. IF foundReference # NIL THEN
  204. reference := foundReference
  205. ELSE
  206. (* no entry was found for the symbol/offset combination: create a new one *)
  207. NEW(immediateReference, value);
  208. reference := immediateReference;
  209. IF firstReference = NIL THEN firstReference := reference ELSE lastReference.next := reference END;
  210. lastReference := reference;
  211. INC(referenceCount)
  212. END;
  213. (* add a citation to the reference *)
  214. reference.AddCitation(pc);
  215. IF pcOfFirstCitation = None THEN pcOfFirstCitation := pc END
  216. END AddImmediate;
  217. END ListOfReferences;
  218. PhysicalRegisters* = OBJECT(CodeGenerators.PhysicalRegisters)
  219. VAR
  220. toVirtual: ARRAY InstructionSet.NumberRegisters OF Ticket; (* registers real register -> none / reserved / split / blocked / virtual register (>0) *)
  221. reserved: ARRAY InstructionSet.NumberRegisters OF BOOLEAN;
  222. unusable: Ticket;
  223. hint: LONGINT;
  224. useFPU: BOOLEAN;
  225. PROCEDURE & InitPhysicalRegisters(supportFramePointer, useFPU, cooperative: BOOLEAN);
  226. VAR
  227. i: LONGINT;
  228. unusable: Ticket;
  229. BEGIN
  230. SELF.useFPU := useFPU;
  231. FOR i := 0 TO LEN(toVirtual) - 1 DO
  232. toVirtual[i] := NIL;
  233. reserved[i] := FALSE
  234. END;
  235. NEW(unusable);
  236. (* reserve special purpose registers *)
  237. toVirtual[InstructionSet.RES] := unusable; (* low part result register *)
  238. toVirtual[InstructionSet.RESHI] := unusable; (* high part result register *)
  239. toVirtual[InstructionSet.RESFS] := unusable; (* single precision floatin point result register *)
  240. toVirtual[InstructionSet.SP] := unusable; (* stack pointer *)
  241. toVirtual[InstructionSet.FP] := unusable; (* frame pointer *)
  242. toVirtual[InstructionSet.PC] := unusable; (* program counter *)
  243. toVirtual[InstructionSet.LR] := unusable; (* link register *)
  244. toVirtual[InstructionSet.CPSR] := unusable; (* current program state register *)
  245. toVirtual[InstructionSet.SPSR] := unusable; (* saved program state register *)
  246. IF cooperative THEN
  247. toVirtual[InstructionSet.R11] := unusable; (* current activity register *)
  248. END;
  249. (* disable coprocessor registers *)
  250. FOR i := InstructionSet.CR0 TO InstructionSet.CR15 DO toVirtual[i] := unusable END;
  251. IF ~useFPU THEN
  252. (* disable single precision VFP registers *)
  253. FOR i := InstructionSet.SR0 TO InstructionSet.SR15 DO toVirtual[i] := unusable END
  254. END;
  255. (* disable double precision VFP registers *)
  256. FOR i := InstructionSet.DR0 TO InstructionSet.DR15 DO toVirtual[i] := unusable END;
  257. END InitPhysicalRegisters;
  258. (** the number of physical registers **)
  259. PROCEDURE NumberRegisters(): LONGINT;
  260. BEGIN RETURN InstructionSet.NumberRegisters
  261. END NumberRegisters;
  262. (** allocate, i.e., map, a physical register to a ticket **)
  263. PROCEDURE Allocate(physicalRegisterNumber: LONGINT; ticket: Ticket);
  264. BEGIN
  265. ASSERT(~ticket.spilled);
  266. Assert(toVirtual[physicalRegisterNumber] = NIL,"register already allocated");
  267. toVirtual[physicalRegisterNumber] := ticket
  268. END Allocate;
  269. (** set whether a certain physical register is reserved or not **)
  270. PROCEDURE SetReserved(physicalRegisterNumber: LONGINT; isReserved: BOOLEAN);
  271. BEGIN reserved[physicalRegisterNumber] := isReserved
  272. END SetReserved;
  273. (** whether a certain physical register is reserved **)
  274. PROCEDURE Reserved(physicalRegisterNumber: LONGINT): BOOLEAN;
  275. BEGIN RETURN (physicalRegisterNumber > 0) & reserved[physicalRegisterNumber]
  276. END Reserved;
  277. (** free a certain physical register **)
  278. PROCEDURE Free(physicalRegisterNumber: LONGINT);
  279. BEGIN
  280. Assert((toVirtual[physicalRegisterNumber] # NIL), "register not reserved");
  281. toVirtual[physicalRegisterNumber] := NIL
  282. END Free;
  283. (** get the number of the next free physical register for a certain data type
  284. - if a register hint has been set, it is respected if possible
  285. **)
  286. PROCEDURE NextFree(CONST type: IntermediateCode.Type): LONGINT;
  287. VAR
  288. result, i: LONGINT;
  289. BEGIN
  290. result := None;
  291. IF (type.form IN IntermediateCode.Integer) OR ~useFPU THEN
  292. ASSERT(type.sizeInBits <= 32); (* integers of larger size have already been split *)
  293. (* allocate a regular general purpose ARM register *)
  294. FOR i := InstructionSet.R0 TO InstructionSet.R15 DO
  295. IF (toVirtual[i] = NIL) & ((result = None) OR (i = hint)) THEN result := i END
  296. END
  297. ELSIF type.form = IntermediateCode.Float THEN
  298. IF type.sizeInBits = 32 THEN
  299. (* allocate a single precision VFP register *)
  300. FOR i := InstructionSet.SR0 TO InstructionSet.SR31 DO
  301. IF (toVirtual[i] = NIL) & ((result = None) OR (i = hint)) THEN result := i END
  302. END
  303. ELSIF type.sizeInBits = 64 THEN
  304. (* allocate a double precision VFP register *)
  305. HALT(200); (* not supported yet *)
  306. ELSE
  307. HALT(100)
  308. END
  309. ELSE
  310. HALT(100)
  311. END;
  312. IF result # None THEN ASSERT(toVirtual[result] = NIL) END;
  313. RETURN result
  314. END NextFree;
  315. (** give the register allocator a hint on what physical register to use next **)
  316. PROCEDURE AllocationHint(physicalRegisterNumber: LONGINT);
  317. BEGIN hint := physicalRegisterNumber
  318. END AllocationHint;
  319. (** get the ticket that is currently mapped to a certain physical register **)
  320. PROCEDURE Mapped(physicalRegisterNumber: LONGINT): Ticket;
  321. BEGIN RETURN toVirtual[physicalRegisterNumber]
  322. END Mapped;
  323. (** dump the current register mapping to a stream **)
  324. PROCEDURE Dump(w: Streams.Writer);
  325. VAR i: LONGINT; virtual: Ticket;
  326. BEGIN
  327. w.String("---- registers ----"); w.Ln;
  328. FOR i := 0 TO LEN(toVirtual)-1 DO
  329. virtual := toVirtual[i];
  330. IF virtual # unusable THEN
  331. w.String("reg "); w.Int(i,1); w.String(": ");
  332. IF virtual = NIL THEN w.String("free")
  333. ELSE w.String(" r"); w.Int(virtual.register,1);
  334. END;
  335. IF reserved[i] THEN w.String("reserved") END;
  336. w.Ln
  337. END
  338. END
  339. END Dump;
  340. END PhysicalRegisters;
  341. CodeGeneratorARM = OBJECT(CodeGenerators.GeneratorWithTickets)
  342. VAR
  343. runtimeModuleName: SyntaxTree.IdentifierString;
  344. backend: BackendARM;
  345. opSP, opFP, opPC, opLR, opRES, opRESHI, opRESFS: InstructionSet.Operand;
  346. listOfReferences: ListOfReferences;
  347. spillStackStart, pushChainLength: LONGINT;
  348. stackSize: LONGINT; (* the size of the current stack frame *)
  349. stackSizeKnown: BOOLEAN; (* whether the size of the current stack frame is known at compile time *)
  350. inStackAllocation: BOOLEAN;
  351. fixupPattern: ObjectFile.FixupPatterns; (* pattern for an absolute 32-bit fixup *)
  352. PROCEDURE & InitGeneratorARM(CONST runtimeModuleName: SyntaxTree.IdentifierString; diagnostics: Diagnostics.Diagnostics; backend: BackendARM);
  353. VAR
  354. physicalRegisters: PhysicalRegisters;
  355. BEGIN
  356. SELF.runtimeModuleName := runtimeModuleName;
  357. SELF.backend := backend;
  358. IF Trace THEN IF backend.useFPU THEN D.String("use FPU"); D.Ln ELSE D.String("don't use FPU"); D.Ln END END;
  359. NEW(physicalRegisters, TRUE, backend.useFPU, backend.cooperative);
  360. InitTicketGenerator(diagnostics, backend.optimize, 2, physicalRegisters);
  361. error := FALSE;
  362. inStackAllocation := FALSE;
  363. pushChainLength := 0;
  364. opSP := InstructionSet.NewRegister(InstructionSet.SP, None, None, 0);
  365. opFP := InstructionSet.NewRegister(InstructionSet.FP, None, None, 0);
  366. opPC := InstructionSet.NewRegister(InstructionSet.PC, None, None, 0);
  367. opLR := InstructionSet.NewRegister(InstructionSet.LR, None, None, 0);
  368. opRES := InstructionSet.NewRegister(InstructionSet.RES, None, None, 0);
  369. opRESHI := InstructionSet.NewRegister(InstructionSet.RESHI, None, None, 0);
  370. opRESFS := InstructionSet.NewRegister(InstructionSet.RESFS, None, None, 0);
  371. dump := NIL;
  372. NEW(fixupPattern, 1);
  373. fixupPattern[0].offset := 0;
  374. fixupPattern[0].bits := 32;
  375. NEW(listOfReferences);
  376. END InitGeneratorARM;
  377. (*------------------- overwritten methods ----------------------*)
  378. (* TODO: revise this *)
  379. PROCEDURE Section(in: IntermediateCode.Section; out: BinaryCode.Section);
  380. VAR
  381. oldSpillStackSize: LONGINT;
  382. PROCEDURE CheckEmptySpillStack(): BOOLEAN;
  383. BEGIN
  384. IF spillStack.Size() # 0 THEN
  385. Error(inPC,"implementation error, spill stack not cleared");
  386. IF dump # NIL THEN
  387. spillStack.Dump(dump);
  388. tickets.Dump(dump)
  389. END;
  390. RETURN FALSE
  391. ELSE
  392. RETURN TRUE
  393. END
  394. END CheckEmptySpillStack;
  395. BEGIN
  396. stackSizeKnown := TRUE;
  397. stackSize := 0; (* TODO: ok? *)
  398. tickets.Init; spillStack.Init; listOfReferences.Init;
  399. Section^(in, out); (* pass 1 *)
  400. EmitFinalFixupBlock; (* force the emission of fixups for all references *)
  401. IF stackSizeKnown = FALSE THEN
  402. tickets.Init; spillStack.Init; listOfReferences.Init;
  403. out.Reset;
  404. Section^(in, out); (* pass 2 *)
  405. EmitFinalFixupBlock (* force the emission of fixups for all references *)
  406. END;
  407. IF CheckEmptySpillStack() & (spillStack.MaxSize() > 0) THEN
  408. listOfReferences.Init;
  409. oldSpillStackSize := spillStack.MaxSize();
  410. out.Reset;
  411. Section^(in, out); (* pass 3 *)
  412. EmitFinalFixupBlock; (* force the emission of fixups for all references *)
  413. ASSERT(spillStack.MaxSize() = oldSpillStackSize);
  414. END;
  415. IF CheckEmptySpillStack() THEN END
  416. END Section;
  417. (* TODO: complete this *)
  418. (** whether the code generator can generate code for a certain intermediate code intstruction
  419. if not, the location of a runtime is returned **)
  420. PROCEDURE Supported(CONST irInstruction: IntermediateCode.Instruction; VAR moduleName, procedureName: ARRAY OF CHAR): BOOLEAN;
  421. VAR
  422. result: BOOLEAN;
  423. BEGIN
  424. CASE irInstruction.opcode OF
  425. | IntermediateCode.add, IntermediateCode.sub, IntermediateCode.mul, IntermediateCode.abs, IntermediateCode.neg:
  426. IF (irInstruction.opcode = IntermediateCode.mul) & IsInteger(irInstruction.op1) & IsInteger(irInstruction.op2) & (IsComplex(irInstruction.op1) OR IsComplex(irInstruction.op2)) THEN
  427. result := FALSE;
  428. ELSE
  429. result := backend.useFPU & IsSinglePrecisionFloat(irInstruction.op1) OR ~IsFloat(irInstruction.op1)
  430. END;
  431. | IntermediateCode.div:
  432. result := backend.useFPU & IsSinglePrecisionFloat(irInstruction.op1);
  433. (*
  434. result := result OR IntermediateCode.IsConstantInteger(irInstruction.op3,value) & PowerOf2(value,exp)
  435. *)
  436. | IntermediateCode.conv:
  437. result := backend.useFPU & (IsSinglePrecisionFloat(irInstruction.op1) OR IsSinglePrecisionFloat(irInstruction.op2)) OR ~IsFloat(irInstruction.op1) & ~IsFloat(irInstruction.op2) (* if no FPU and either operand is a float *)
  438. | IntermediateCode.mod:
  439. result := FALSE;
  440. (*
  441. result := IntermediateCode.IsConstantInteger(irInstruction.op3,value) & PowerOf2(value,exp)
  442. *)
  443. | IntermediateCode.rol, IntermediateCode.ror:
  444. result := ~IsComplex(irInstruction.op1)
  445. ELSE
  446. result := TRUE
  447. END;
  448. IF ~result THEN
  449. COPY(runtimeModuleName, moduleName);
  450. GetRuntimeProcedureName(irInstruction, procedureName);
  451. END;
  452. RETURN result
  453. END Supported;
  454. (* determines the name of a runtime procedure to handle a certain IR instruction *)
  455. PROCEDURE GetRuntimeProcedureName(CONST irInstruction: IntermediateCode.Instruction; VAR resultingName: ARRAY OF CHAR);
  456. PROCEDURE AppendType(VAR string: ARRAY OF CHAR; type: IntermediateCode.Type);
  457. VAR
  458. sizeString: ARRAY 3 OF CHAR;
  459. BEGIN
  460. CASE type.form OF
  461. | IntermediateCode.SignedInteger: Strings.AppendChar(string, 'S')
  462. | IntermediateCode.UnsignedInteger: Strings.AppendChar(string, 'U')
  463. | IntermediateCode.Float:Strings.AppendChar(string, 'F')
  464. ELSE HALT(200)
  465. END;
  466. Strings.IntToStr(type.sizeInBits, sizeString); Strings.Append(string, sizeString)
  467. END AppendType;
  468. BEGIN
  469. COPY(IntermediateCode.instructionFormat[irInstruction.opcode].name, resultingName);
  470. Strings.UpperCaseChar(resultingName[0]);
  471. AppendType(resultingName, irInstruction.op1.type);
  472. IF irInstruction.op1.mode # IntermediateCode.Undefined THEN
  473. IF (irInstruction.op1.type.form # irInstruction.op2.type.form) OR (irInstruction.op1.type.sizeInBits # irInstruction.op2.type.sizeInBits) THEN
  474. AppendType(resultingName, irInstruction.op2.type);
  475. END
  476. END;
  477. IF Trace THEN D.Ln; D.String(" runtime procedure name: "); D.String(resultingName); D.Ln; D.Update END
  478. END GetRuntimeProcedureName;
  479. (* check whether the instruction modifies the stack pointer (outside of a stack allocation )*)
  480. PROCEDURE CheckStackPointer(CONST destination: Operand);
  481. BEGIN
  482. IF stackSizeKnown & ~inStackAllocation THEN
  483. IF (destination.mode = InstructionSet.modeRegister) & (destination.register = InstructionSet.SP) THEN
  484. IF dump # NIL THEN dump.String("stackSize unkown"); dump.Ln END;
  485. stackSizeKnown := FALSE
  486. END
  487. END
  488. END CheckStackPointer;
  489. (** emit an ARM instruction with an arbitrary amount of operands **)
  490. PROCEDURE Emit(opCode, condition: LONGINT; flags: SET; CONST operands: ARRAY InstructionSet.MaxOperands OF Operand);
  491. VAR
  492. BEGIN
  493. (* check whether the instruction modifies the stack pointer *)
  494. CheckStackPointer(operands[0]);
  495. (*
  496. (* dump the instruction *)
  497. IF Trace THEN
  498. D.String("opCode="); D.Int(opCode, 0); D.Ln;
  499. D.String("condition="); D.Int(condition, 0); D.Ln;
  500. D.String("flags="); D.Set(flags); D.Ln;
  501. FOR i := 0 TO InstructionSet.MaxOperands - 1 DO
  502. D.String("operand #"); D.Int(i, 0); D.String(": ");
  503. InstructionSet.DumpOperand(D.Log, operands[i]);
  504. D.Ln
  505. END;
  506. D.Ln;
  507. D.Ln
  508. END;
  509. *)
  510. (* emit the instruction *)
  511. InstructionSet.Emit(opCode, condition, flags, operands, out)
  512. END Emit;
  513. (** emit an ARM instruction with no operand **)
  514. PROCEDURE Emit0(opCode: LONGINT);
  515. VAR
  516. operands: ARRAY InstructionSet.MaxOperands OF Operand;
  517. BEGIN
  518. ASSERT(InstructionSet.MaxOperands = 6);
  519. operands[0] := emptyOperand;
  520. operands[1] := emptyOperand;
  521. operands[2] := emptyOperand;
  522. operands[3] := emptyOperand;
  523. operands[4] := emptyOperand;
  524. operands[5] := emptyOperand;
  525. Emit(opCode, InstructionSet.unconditional, {}, operands)
  526. END Emit0;
  527. (** emit an ARM instruction with 1 operand **)
  528. PROCEDURE Emit1(opCode: LONGINT; op: Operand);
  529. VAR
  530. operands: ARRAY InstructionSet.MaxOperands OF Operand;
  531. BEGIN
  532. ASSERT(InstructionSet.MaxOperands = 6);
  533. operands[0] := op;
  534. operands[1] := emptyOperand;
  535. operands[2] := emptyOperand;
  536. operands[3] := emptyOperand;
  537. operands[4] := emptyOperand;
  538. operands[5] := emptyOperand;
  539. Emit(opCode, InstructionSet.unconditional, {}, operands)
  540. END Emit1;
  541. (** emit an ARM instruction with 2 operands **)
  542. PROCEDURE Emit2(opCode: LONGINT; op1, op2: Operand);
  543. VAR
  544. operands: ARRAY InstructionSet.MaxOperands OF Operand;
  545. BEGIN
  546. ASSERT(InstructionSet.MaxOperands = 6);
  547. operands[0] := op1;
  548. operands[1] := op2;
  549. operands[2] := emptyOperand;
  550. operands[3] := emptyOperand;
  551. operands[4] := emptyOperand;
  552. operands[5] := emptyOperand;
  553. Emit(opCode, InstructionSet.unconditional, {}, operands)
  554. END Emit2;
  555. (** emit an ARM instruction with 3 operands **)
  556. PROCEDURE Emit3(opCode: LONGINT; op1, op2, op3: Operand);
  557. VAR
  558. operands: ARRAY InstructionSet.MaxOperands OF Operand;
  559. BEGIN
  560. ASSERT(InstructionSet.MaxOperands = 6);
  561. operands[0] := op1;
  562. operands[1] := op2;
  563. operands[2] := op3;
  564. operands[3] := emptyOperand;
  565. operands[4] := emptyOperand;
  566. operands[5] := emptyOperand;
  567. Emit(opCode, InstructionSet.unconditional, {}, operands)
  568. END Emit3;
  569. (** emit an ARM instruction with 4 operands **)
  570. PROCEDURE Emit4(opCode: LONGINT; op1, op2, op3, op4: Operand);
  571. VAR
  572. operands: ARRAY InstructionSet.MaxOperands OF Operand;
  573. BEGIN
  574. ASSERT(InstructionSet.MaxOperands = 6);
  575. operands[0] := op1;
  576. operands[1] := op2;
  577. operands[2] := op3;
  578. operands[3] := op4;
  579. operands[4] := emptyOperand;
  580. operands[5] := emptyOperand;
  581. Emit(opCode, InstructionSet.unconditional, {}, operands)
  582. END Emit4;
  583. (** emit an ARM instruction with 6 operands **)
  584. PROCEDURE Emit6(opCode: LONGINT; op1, op2, op3, op4, op5, op6: Operand);
  585. VAR
  586. operands: ARRAY InstructionSet.MaxOperands OF Operand;
  587. BEGIN
  588. ASSERT(InstructionSet.MaxOperands = 6);
  589. operands[0] := op1;
  590. operands[1] := op2;
  591. operands[2] := op3;
  592. operands[3] := op4;
  593. operands[4] := op5;
  594. operands[5] := op6;
  595. Emit(opCode, InstructionSet.unconditional, {}, operands)
  596. END Emit6;
  597. (** emit an ARM instruction with 2 operands and certain flags **)
  598. PROCEDURE Emit2WithFlags(opCode: LONGINT; op1, op2: Operand; flags: SET);
  599. VAR
  600. operands: ARRAY InstructionSet.MaxOperands OF Operand;
  601. BEGIN
  602. ASSERT(InstructionSet.MaxOperands = 6);
  603. operands[0] := op1;
  604. operands[1] := op2;
  605. operands[2] := emptyOperand;
  606. operands[3] := emptyOperand;
  607. operands[4] := emptyOperand;
  608. operands[5] := emptyOperand;
  609. Emit(opCode, InstructionSet.unconditional, flags, operands)
  610. END Emit2WithFlags;
  611. (** emit an ARM instruction with 3 operands and certain flags **)
  612. PROCEDURE Emit3WithFlags(opCode: LONGINT; op1, op2, op3: Operand; flags: SET);
  613. VAR
  614. operands: ARRAY InstructionSet.MaxOperands OF Operand;
  615. BEGIN
  616. ASSERT(InstructionSet.MaxOperands = 6);
  617. operands[0] := op1;
  618. operands[1] := op2;
  619. operands[2] := op3;
  620. operands[3] := emptyOperand;
  621. operands[4] := emptyOperand;
  622. operands[5] := emptyOperand;
  623. Emit(opCode, InstructionSet.unconditional, flags, operands)
  624. END Emit3WithFlags;
  625. (** emit an ARM instruction with 1 operand and a condition **)
  626. PROCEDURE Emit1WithCondition(opCode: LONGINT; op1: Operand; condition: LONGINT);
  627. VAR
  628. operands: ARRAY InstructionSet.MaxOperands OF Operand;
  629. BEGIN
  630. ASSERT(InstructionSet.MaxOperands = 6);
  631. operands[0] := op1;
  632. operands[1] := emptyOperand;
  633. operands[2] := emptyOperand;
  634. operands[3] := emptyOperand;
  635. operands[4] := emptyOperand;
  636. operands[5] := emptyOperand;
  637. Emit(opCode, condition, {}, operands)
  638. END Emit1WithCondition;
  639. (** emit an ARM instruction with 2 operands and a condition **)
  640. PROCEDURE Emit2WithCondition(opCode: LONGINT; op1, op2: Operand; condition: LONGINT);
  641. VAR
  642. operands: ARRAY InstructionSet.MaxOperands OF Operand;
  643. BEGIN
  644. ASSERT(InstructionSet.MaxOperands = 6);
  645. operands[0] := op1;
  646. operands[1] := op2;
  647. operands[2] := emptyOperand;
  648. operands[3] := emptyOperand;
  649. operands[4] := emptyOperand;
  650. operands[5] := emptyOperand;
  651. Emit(opCode, condition, {}, operands)
  652. END Emit2WithCondition;
  653. (** emit an ARM instruction with 3 operands and a condition **)
  654. PROCEDURE Emit3WithCondition(opCode: LONGINT; op1, op2, op3: Operand; condition: LONGINT);
  655. VAR
  656. operands: ARRAY InstructionSet.MaxOperands OF Operand;
  657. BEGIN
  658. ASSERT(InstructionSet.MaxOperands = 6);
  659. operands[0] := op1;
  660. operands[1] := op2;
  661. operands[2] := op3;
  662. operands[3] := emptyOperand;
  663. operands[4] := emptyOperand;
  664. operands[5] := emptyOperand;
  665. Emit(opCode, condition, {}, operands)
  666. END Emit3WithCondition;
  667. (**
  668. - generate an arbitrary 32 bit value with as few as possible instructions and move the result into a specified target register
  669. - return the number of instructions required
  670. - if 'doEmit' is TRUE, emit the instructions
  671. **)
  672. PROCEDURE ValueComposition(value: LONGINT; doEmit: BOOLEAN; CONST targetRegister: Operand): LONGINT;
  673. VAR
  674. result: LONGINT;
  675. BEGIN
  676. IF doEmit THEN ASSERT(targetRegister.mode = InstructionSet.modeRegister) END;
  677. IF Trace & doEmit THEN D.Ln; D.String("original value: "); DBin(value, -32); D.String(" ("); D.Int(value, 0); D.String(") "); D.Ln; END;
  678. IF ValueComposition2(value, FALSE, emptyOperand) <= ValueComposition2(-value, FALSE, emptyOperand) + 1 THEN
  679. (* more efficient to calculate the value directly *)
  680. result := ValueComposition2(value, doEmit, targetRegister)
  681. ELSE
  682. (* more efficient to calculate the negation of the value and then negate it *)
  683. result := ValueComposition2(-value, doEmit, targetRegister) + 1;
  684. IF doEmit THEN
  685. Emit3(opRSB, targetRegister, targetRegister, InstructionSet.NewImmediate(0))
  686. END
  687. END;
  688. ASSERT((result >= 1) & (result <= 4));
  689. RETURN result
  690. END ValueComposition;
  691. (* note: used by 'ValueComposition'. do not call directly *)
  692. PROCEDURE ValueComposition2(value: LONGINT; doEmit: BOOLEAN; CONST targetRegister: Operand): LONGINT;
  693. VAR
  694. immediateOperand: Operand;
  695. result, position, partialValue, i: LONGINT;
  696. valueAsSet: SET;
  697. isFirst: BOOLEAN;
  698. BEGIN
  699. IF doEmit THEN ASSERT(targetRegister.mode = InstructionSet.modeRegister) END;
  700. IF Trace & doEmit THEN D.String("value to use: "); DBin(value, -32); D.String(" ("); D.Int(value, 0); D.String(") "); D.Ln; END;
  701. IF (value >= 0) & (value <= 255) THEN
  702. (* directly encodable as ARM immediate *)
  703. result := 1;
  704. IF doEmit THEN
  705. Emit2(opMOV, targetRegister, InstructionSet.NewImmediate(value))
  706. END
  707. ELSE
  708. valueAsSet := SYSTEM.VAL(SET, value);
  709. result := 0;
  710. position := 0;
  711. isFirst := TRUE;
  712. WHILE position < 32 DO
  713. IF (position IN valueAsSet) OR (position + 1 IN valueAsSet) THEN
  714. (* determine partial value for the 8 bit block *)
  715. partialValue := 0;
  716. FOR i := 7 TO 0 BY -1 DO
  717. partialValue := partialValue * 2;
  718. IF ((position + i) < 32) & ((position + i) IN valueAsSet) THEN INC(partialValue) END
  719. END;
  720. IF Trace & doEmit THEN
  721. D.String(" block found @ "); D.Int(position, 0); D.Ln;
  722. D.String(" unshifted partialValue: "); DBin(partialValue, -32); D.String(" ("); D.Int(partialValue, 0); D.String(") "); D.Ln;
  723. D.String(" shifted partialValue: "); DBin(ASH(partialValue, position), -32); D.String(" ("); D.Int(ASH(partialValue, position), 0); D.String(") "); D.Ln;
  724. END;
  725. ASSERT(~ODD(position));
  726. INC(result);
  727. IF doEmit THEN
  728. immediateOperand := InstructionSet.NewImmediate(ASH(partialValue, position)); (* TODO: check shift direction *)
  729. IF isFirst THEN
  730. Emit2(opMOV, targetRegister, immediateOperand);
  731. isFirst := FALSE
  732. ELSE
  733. Emit3(opADD, targetRegister, targetRegister, immediateOperand)
  734. END
  735. END;
  736. INC(position, 8)
  737. ELSE
  738. INC(position, 2)
  739. END
  740. END
  741. END;
  742. ASSERT((result >= 1) & (result <= 4));
  743. RETURN result
  744. END ValueComposition2;
  745. (** get the physical register number that corresponds to a virtual register number and part **)
  746. PROCEDURE PhysicalRegisterNumber(virtualRegisterNumber: LONGINT; part: LONGINT): LONGINT;
  747. VAR
  748. ticket: Ticket;
  749. result: LONGINT;
  750. BEGIN
  751. IF virtualRegisterNumber = IntermediateCode.FP THEN
  752. result := InstructionSet.FP
  753. ELSIF virtualRegisterNumber = IntermediateCode.SP THEN
  754. result := InstructionSet.SP
  755. ELSIF virtualRegisterNumber = IntermediateCode.LR THEN
  756. result := InstructionSet.LR
  757. ELSIF virtualRegisterNumber = IntermediateCode.AP THEN
  758. result := InstructionSet.R11
  759. ELSE
  760. ticket := virtualRegisters.Mapped(virtualRegisterNumber, part);
  761. IF ticket = NIL THEN
  762. result := None
  763. ELSE
  764. result := ticket.register
  765. END
  766. END;
  767. RETURN result
  768. END PhysicalRegisterNumber;
  769. (** get an ARM memory operand that represents a spill location (from a ticket) **)
  770. PROCEDURE GetSpillOperand(ticket: Ticket): Operand;
  771. VAR
  772. offset: LONGINT;
  773. result: Operand;
  774. BEGIN
  775. ASSERT(ticket.spilled);
  776. offset := spillStackStart + ticket.offset + 1; (* TODO: check this *)
  777. ASSERT((0 <= offset) & (offset < InstructionSet.Bits12));
  778. result := InstructionSet.NewImmediateOffsetMemory(PhysicalRegisterNumber(IntermediateCode.FP, Low), offset, {InstructionSet.Decrement});
  779. ASSERT(result.mode = InstructionSet.modeMemory);
  780. RETURN result
  781. END GetSpillOperand;
  782. (** get an ARM operand that represents a certain ticket (might be spilled or not) **)
  783. PROCEDURE OperandFromTicket(ticket: Ticket): Operand;
  784. VAR
  785. result: Operand;
  786. BEGIN
  787. ASSERT(ticket # NIL);
  788. IF ticket.spilled THEN
  789. (* the ticket is spilled *)
  790. result := GetSpillOperand(ticket)
  791. ELSE
  792. result := InstructionSet.NewRegister(ticket.register, None, None, 0)
  793. END;
  794. RETURN result
  795. END OperandFromTicket;
  796. (** get a free temporary register that holds data of a certain type **)
  797. PROCEDURE GetFreeRegister(CONST type: IntermediateCode.Type): Operand;
  798. VAR
  799. result: Operand;
  800. BEGIN
  801. result := OperandFromTicket(TemporaryTicket(IntermediateCode.GeneralPurposeRegister, type));
  802. ASSERT(result.mode = InstructionSet.modeRegister);
  803. RETURN result
  804. END GetFreeRegister;
  805. (** get a new free ARM register
  806. - if a register hint is provided that can hold data of the required type, it is returned instead
  807. **)
  808. PROCEDURE GetFreeRegisterOrHint(CONST type: IntermediateCode.Type; CONST registerHint: Operand): Operand;
  809. VAR
  810. result: Operand;
  811. BEGIN
  812. IF (registerHint.mode = InstructionSet.modeRegister) & IsRegisterForType(registerHint.register, type) THEN
  813. result := registerHint
  814. ELSE
  815. result := GetFreeRegister(type)
  816. END;
  817. ASSERT(result.mode = InstructionSet.modeRegister);
  818. RETURN result
  819. END GetFreeRegisterOrHint;
  820. (** whether a register can hold data of a certain IR type **)
  821. PROCEDURE IsRegisterForType(registerNumber: LONGINT; CONST type: IntermediateCode.Type): BOOLEAN;
  822. VAR
  823. result: BOOLEAN;
  824. BEGIN
  825. result := FALSE;
  826. IF type.form IN IntermediateCode.Integer THEN
  827. IF type.sizeInBits <= 32 THEN
  828. result := (registerNumber >= InstructionSet.R0) & (registerNumber <= InstructionSet.R15)
  829. END
  830. ELSIF type.form = IntermediateCode.Float THEN
  831. IF type.sizeInBits = 32 THEN
  832. result := (registerNumber >= InstructionSet.SR0) & (registerNumber <= InstructionSet.SR31)
  833. ELSE
  834. HALT(200)
  835. END
  836. ELSE
  837. HALT(100)
  838. END;
  839. RETURN result
  840. END IsRegisterForType;
  841. (** get an ARM register that that is set off by a certain amount **)
  842. PROCEDURE RegisterAfterAppliedOffset(register: Operand; offset: LONGINT; registerHint: Operand): Operand;
  843. VAR
  844. result, offsetOperand: Operand;
  845. BEGIN
  846. IF offset = 0 THEN
  847. result := register
  848. ELSE
  849. result := GetFreeRegisterOrHint(IntermediateCode.UnsignedIntegerType(32), registerHint);
  850. offsetOperand := OperandFromValue(ABS(offset), result); (* might be immediate operand or register (tempRegister is given as a register hint) *)
  851. IF offset > 0 THEN
  852. Emit3(opADD, result, register, offsetOperand)
  853. ELSE
  854. Emit3(opSUB, result, register, offsetOperand)
  855. END
  856. END;
  857. RETURN result
  858. END RegisterAfterAppliedOffset;
  859. (** get an ARM register from an IR register
  860. - use register hint if provided
  861. **)
  862. PROCEDURE RegisterFromIrRegister(CONST irRegisterOperand: IntermediateCode.Operand; part: LONGINT; registerHint: Operand): Operand;
  863. VAR
  864. result: Operand;
  865. BEGIN
  866. ASSERT(irRegisterOperand.mode = IntermediateCode.ModeRegister);
  867. result := InstructionSet.NewRegister(PhysicalRegisterNumber(irRegisterOperand.register, part), None, None, 0);
  868. result := RegisterAfterAppliedOffset(result, irRegisterOperand.offset, registerHint);
  869. ASSERT(result.mode = InstructionSet.modeRegister);
  870. RETURN result
  871. END RegisterFromIrRegister;
  872. PROCEDURE Load(targetRegister, memoryOperand: Operand; irType: IntermediateCode.Type);
  873. BEGIN
  874. IF (irType.form IN IntermediateCode.Integer) OR ~(backend.useFPU) THEN
  875. CASE irType.sizeInBits OF
  876. | 8: Emit2WithFlags(opLDR, targetRegister, memoryOperand, {InstructionSet.flagB}) (* LDRB *)
  877. | 16: Emit2WithFlags(opLDR, targetRegister, memoryOperand, {InstructionSet.flagH}) (* LDRH *)
  878. | 32: (* TM*)
  879. Emit2(opLDR, targetRegister, memoryOperand)
  880. ELSE HALT(100)
  881. END
  882. ELSIF irType.form = IntermediateCode.Float THEN
  883. ASSERT(irType.sizeInBits = 32, 200);
  884. Emit2(opFLDS, targetRegister, memoryOperand)
  885. ELSE
  886. HALT(100)
  887. END
  888. END Load;
  889. PROCEDURE Store(sourceRegister, memoryOperand: Operand; type: IntermediateCode.Type);
  890. BEGIN
  891. IF (type.form IN IntermediateCode.Integer) OR ~backend.useFPU THEN
  892. CASE type.sizeInBits OF
  893. | 8: Emit2WithFlags(opSTR, sourceRegister, memoryOperand, {InstructionSet.flagB}) (* STRB *)
  894. | 16: Emit2WithFlags(opSTR, sourceRegister, memoryOperand, {InstructionSet.flagH}) (* STRH *)
  895. | 32: Emit2(opSTR, sourceRegister, memoryOperand)
  896. ELSE HALT(100)
  897. END
  898. ELSIF type.form = IntermediateCode.Float THEN
  899. ASSERT(type.sizeInBits = 32, 200);
  900. Emit2(opFSTS, sourceRegister, memoryOperand)
  901. ELSE
  902. HALT(100)
  903. END
  904. END Store;
  905. (** get an ARM register that contains the address of a symbol/section
  906. - use register hint if provided **)
  907. PROCEDURE RegisterFromSymbol(symbol: Sections.SectionName; fingerprint: LONGINT; resolved: Sections.Section; symbolOffset: LONGINT; CONST registerHint: Operand): Operand;
  908. VAR
  909. address: LONGINT;
  910. result: Operand;
  911. irSection: IntermediateCode.Section;
  912. BEGIN
  913. IF resolved # NIL THEN
  914. irSection := resolved(IntermediateCode.Section);
  915. END;
  916. IF (irSection # NIL) & (irSection.resolved # NIL) & (irSection.resolved.os.fixed) THEN
  917. (* optimization: if the IR section is already resolved and positioned at a fixed location, no fixup is required *)
  918. address := irSection.resolved.os.alignment + irSection.instructions[symbolOffset].pc;
  919. result := RegisterFromValue(address, registerHint)
  920. ELSE
  921. result := GetFreeRegisterOrHint(IntermediateCode.UnsignedIntegerType(32), registerHint);
  922. listOfReferences.AddSymbol(symbol, fingerprint, symbolOffset, out.pc);
  923. Emit2(opLDR, result, InstructionSet.NewImmediateOffsetMemory(opPC.register, 0, {InstructionSet.Increment})); (* LDR ..., [PC, #+???] *)
  924. END;
  925. ASSERT(result.mode = InstructionSet.modeRegister);
  926. RETURN result
  927. END RegisterFromSymbol;
  928. (** get an ARM memory operand from an IR memory operand
  929. - note that the constraints on memory operands depend on the type of data (e.g., the allowed offset range is more restricted for memory operands on floating point values)
  930. **)
  931. PROCEDURE MemoryOperandFromIrMemoryOperand(VAR irMemoryOperand: IntermediateCode.Operand; part: LONGINT; CONST registerHint: Operand): Operand;
  932. VAR
  933. baseAddressRegisterNumber, offset: LONGINT;
  934. indexingMode: SET;
  935. result, baseAddressRegister, offsetRegister, tempRegister: Operand;
  936. BEGIN
  937. ASSERT(irMemoryOperand.mode = IntermediateCode.ModeMemory);
  938. (* determine base address register *)
  939. IF irMemoryOperand.register # IntermediateCode.None THEN
  940. (* case 1: [r1] or [r1 + 7] *)
  941. ASSERT(irMemoryOperand.symbol.name = "");
  942. baseAddressRegisterNumber := PhysicalRegisterNumber(irMemoryOperand.register, Low); (* addresses always are in the lower part *)
  943. ELSIF irMemoryOperand.symbol.name # "" THEN
  944. (* case 2: [symbol], [symbol:3], [symbol + 7] or [symbol:3 + 7] *)
  945. Resolve(irMemoryOperand);
  946. baseAddressRegister := RegisterFromSymbol(irMemoryOperand.symbol.name, irMemoryOperand.symbol.fingerprint, irMemoryOperand.resolved, irMemoryOperand.symbolOffset, registerHint);
  947. baseAddressRegisterNumber := baseAddressRegister.register
  948. ELSE
  949. (* case 3: [123456] *)
  950. ASSERT(irMemoryOperand.offset = 0);
  951. baseAddressRegister := RegisterFromValue(LONGINT(irMemoryOperand.intValue), registerHint);
  952. baseAddressRegisterNumber := baseAddressRegister.register
  953. END;
  954. ASSERT(baseAddressRegisterNumber # None);
  955. (* get offset of part in question *)
  956. offset := irMemoryOperand.offset + part * 4;
  957. (* determine indexing mode *)
  958. IF offset >= 0 THEN indexingMode := {InstructionSet.Increment} ELSE indexingMode := {InstructionSet.Decrement} END;
  959. IF irMemoryOperand.type.form IN IntermediateCode.Integer THEN
  960. (* regular ARM memory operand *)
  961. (*! LDRH supports only 8 bits immediates, while LDR and LDRB support 12 bits immediates *)
  962. IF ((irMemoryOperand.type.sizeInBits = 16) & (ABS(offset) < 256)) OR ((irMemoryOperand.type.sizeInBits # 16) & (ABS(offset) < InstructionSet.Bits12)) THEN
  963. (* offset can be encoded directly *)
  964. result := InstructionSet.NewImmediateOffsetMemory(baseAddressRegisterNumber, ABS(offset), indexingMode)
  965. ELSE
  966. (* offset has to be provided in a register *)
  967. offsetRegister := RegisterFromValue(ABS(offset), emptyOperand);
  968. result := InstructionSet.NewRegisterOffsetMemory(baseAddressRegisterNumber, offsetRegister.register, None, 0, indexingMode)
  969. END
  970. ELSIF irMemoryOperand.type.form = IntermediateCode.Float THEN
  971. (* VFP memory operand *)
  972. ASSERT((ABS(offset) MOD 4) = 0);
  973. IF ABS(offset) >= 1024 THEN
  974. (* offset cannot be encoded directly _> it has to be provided by means of an adapted base register *)
  975. tempRegister := RegisterFromValue(ABS(offset), emptyOperand);
  976. IF offset < 0 THEN
  977. Emit3(opSUB, tempRegister, tempRegister, baseAddressRegister)
  978. ELSE
  979. Emit3(opADD, tempRegister, tempRegister, baseAddressRegister)
  980. END;
  981. ReleaseHint(baseAddressRegister.register);
  982. baseAddressRegister := tempRegister;
  983. baseAddressRegisterNumber := baseAddressRegister.register;
  984. offset := 0;
  985. END;
  986. result := InstructionSet.NewImmediateOffsetMemory(baseAddressRegisterNumber, ABS(offset), indexingMode)
  987. ELSE
  988. HALT(100)
  989. END;
  990. ASSERT(result.mode = InstructionSet.modeMemory);
  991. RETURN result
  992. END MemoryOperandFromIrMemoryOperand;
  993. (** get an ARM immediate operand or register from any IR operand
  994. - if possible, the an immediate is returned
  995. - if needed, use register hint if provided
  996. **)
  997. PROCEDURE RegisterOrImmediateFromIrOperand(VAR irOperand: IntermediateCode.Operand; part: LONGINT; registerHint: Operand): Operand;
  998. VAR
  999. result: Operand;
  1000. BEGIN
  1001. IF IrOperandIsDirectlyEncodable(irOperand, part) THEN
  1002. result := InstructionSet.NewImmediate(ValueOfPart(irOperand.intValue, part))
  1003. ELSE
  1004. result := RegisterFromIrOperand(irOperand, part, registerHint)
  1005. END;
  1006. RETURN result
  1007. END RegisterOrImmediateFromIrOperand;
  1008. (** get an ARM register operand from any IR operand
  1009. - use register hint if provided
  1010. **)
  1011. PROCEDURE RegisterFromIrOperand(VAR irOperand: IntermediateCode.Operand; part: LONGINT; registerHint: Operand): Operand;
  1012. VAR
  1013. result: Operand;
  1014. BEGIN
  1015. CASE irOperand.mode OF
  1016. | IntermediateCode.ModeRegister:
  1017. ASSERT((irOperand.intValue = 0) & (irOperand.symbol.name = ""));
  1018. result := RegisterFromIrRegister(irOperand, part, registerHint)
  1019. | IntermediateCode.ModeMemory:
  1020. result := GetFreeRegisterOrHint(PartType(irOperand.type, part), registerHint);
  1021. Load(result, MemoryOperandFromIrMemoryOperand(irOperand, part, result), PartType(irOperand.type, part))
  1022. | IntermediateCode.ModeImmediate:
  1023. ASSERT(irOperand.register = IntermediateCode.None);
  1024. IF irOperand.symbol.name # "" THEN
  1025. Resolve(irOperand);
  1026. result := RegisterFromSymbol(irOperand.symbol.name, irOperand.symbol.fingerprint, irOperand.resolved, irOperand.symbolOffset, emptyOperand);
  1027. result := RegisterAfterAppliedOffset(result, irOperand.offset, registerHint);
  1028. ELSE
  1029. ASSERT(irOperand.offset = 0);
  1030. IF IsInteger(irOperand) THEN result := RegisterFromValue(ValueOfPart(irOperand.intValue, part), registerHint)
  1031. ELSIF ~backend.useFPU THEN
  1032. IF IsSinglePrecisionFloat(irOperand) THEN
  1033. result := RegisterFromValue(BinaryCode.ConvertReal(SHORT(irOperand.floatValue)), registerHint)
  1034. ELSE
  1035. result := RegisterFromValue(ValueOfPart(BinaryCode.ConvertLongreal(irOperand.floatValue),part), registerHint);
  1036. END;
  1037. ELSIF IsSinglePrecisionFloat(irOperand) THEN result := SinglePrecisionFloatRegisterFromValue(REAL(irOperand.floatValue), registerHint)
  1038. ELSE HALT(200)
  1039. END
  1040. END
  1041. ELSE
  1042. HALT(100)
  1043. END;
  1044. ASSERT(result.mode = InstructionSet.modeRegister);
  1045. RETURN result
  1046. END RegisterFromIrOperand;
  1047. (** whether an IR operand is complex, i.e., requires more than one ARM operands to be represented **)
  1048. PROCEDURE IsComplex(CONST irOperand: IntermediateCode.Operand): BOOLEAN;
  1049. VAR
  1050. result: BOOLEAN;
  1051. BEGIN
  1052. IF (irOperand.type.form IN IntermediateCode.Integer) OR ~backend.useFPU THEN
  1053. result := irOperand.type.sizeInBits > 32 (* integers above 32 bits have to be represented in multiple registers *)
  1054. ELSIF irOperand.type.form = IntermediateCode.Float THEN
  1055. result := FALSE (* for all types of floating point numbers there are dedicated VFP registers *)
  1056. ELSE
  1057. HALT(100)
  1058. END;
  1059. RETURN result
  1060. END IsComplex;
  1061. (** whether an IR operand hold a single precision floating point value **)
  1062. PROCEDURE IsSinglePrecisionFloat(CONST irOperand: IntermediateCode.Operand): BOOLEAN;
  1063. BEGIN RETURN (irOperand.type.sizeInBits = 32) & (irOperand.type.form = IntermediateCode.Float)
  1064. END IsSinglePrecisionFloat;
  1065. (** whether an IR operand hold a single precision floating point value **)
  1066. PROCEDURE IsDoublePrecisionFloat(CONST irOperand: IntermediateCode.Operand): BOOLEAN;
  1067. BEGIN RETURN (irOperand.type.sizeInBits = 64) & (irOperand.type.form = IntermediateCode.Float)
  1068. END IsDoublePrecisionFloat;
  1069. PROCEDURE IsFloat(CONST irOperand: IntermediateCode.Operand): BOOLEAN;
  1070. BEGIN
  1071. RETURN irOperand.type.form = IntermediateCode.Float
  1072. END IsFloat;
  1073. (** whether an IR operand hold am integer value **)
  1074. PROCEDURE IsInteger(CONST irOperand: IntermediateCode.Operand): BOOLEAN;
  1075. BEGIN RETURN irOperand.type.form IN IntermediateCode.Integer
  1076. END IsInteger;
  1077. PROCEDURE PartType(CONST type: IntermediateCode.Type; part: LONGINT): IntermediateCode.Type;
  1078. VAR
  1079. result: IntermediateCode.Type;
  1080. BEGIN
  1081. GetPartType(type, part, result);
  1082. RETURN result
  1083. END PartType;
  1084. (* the intermediate code type of a part
  1085. - a part type is by definition directly representable in a register *)
  1086. PROCEDURE GetPartType(CONST type: IntermediateCode.Type; part: LONGINT; VAR partType: IntermediateCode.Type);
  1087. BEGIN
  1088. ASSERT((part = Low) OR (part = High));
  1089. IF (type.form = IntermediateCode.Float) & backend.useFPU THEN
  1090. IF part = Low THEN
  1091. partType := type
  1092. ELSE
  1093. partType := IntermediateCode.undef
  1094. END
  1095. ELSIF (type.form IN IntermediateCode.Integer) OR ~backend.useFPU THEN
  1096. IF type.sizeInBits <= 32 THEN
  1097. IF part = Low THEN
  1098. partType := type
  1099. ELSE
  1100. partType := IntermediateCode.undef
  1101. END
  1102. ELSIF type.sizeInBits = 64 THEN
  1103. IF part = Low THEN
  1104. partType := IntermediateCode.NewType(IntermediateCode.UnsignedInteger, 32) (* conceptually the low part is always unsigned *)
  1105. ELSE
  1106. partType := IntermediateCode.NewType(type.form, 32)
  1107. END
  1108. ELSE
  1109. HALT(100)
  1110. END
  1111. ELSE
  1112. HALT(100)
  1113. END
  1114. END GetPartType;
  1115. (** the value of a 32 bit part **)
  1116. PROCEDURE ValueOfPart(value: HUGEINT; part: LONGINT): LONGINT;
  1117. VAR
  1118. result: LONGINT;
  1119. BEGIN
  1120. IF part = Low THEN
  1121. result := LONGINT(value) (* get the 32 least significant bits *)
  1122. ELSIF part = High THEN
  1123. result := LONGINT(ASH(value, -32)) (* get the 32 most significant bits *)
  1124. ELSE
  1125. HALT(100)
  1126. END;
  1127. RETURN result
  1128. END ValueOfPart;
  1129. (** whether a 32 bit value can be directly encoded as an ARM immediate (using a 8-bit base value and 4-bit half rotation) **)
  1130. PROCEDURE ValueIsDirectlyEncodable(value: LONGINT): BOOLEAN;
  1131. VAR
  1132. baseValue, halfRotation: LONGINT;
  1133. result: BOOLEAN;
  1134. BEGIN
  1135. result := InstructionSet.EncodeImmediate(value, baseValue, halfRotation);
  1136. RETURN result
  1137. END ValueIsDirectlyEncodable;
  1138. (* whether an IR operand (or part thereof) can be directly encoded as an ARM immediate *)
  1139. PROCEDURE IrOperandIsDirectlyEncodable(irOperand: IntermediateCode.Operand; part: LONGINT): BOOLEAN;
  1140. BEGIN RETURN
  1141. (irOperand.mode = IntermediateCode.ModeImmediate) &
  1142. (irOperand.symbol.name = "") &
  1143. (irOperand.type.form IN IntermediateCode.Integer) &
  1144. ValueIsDirectlyEncodable(ValueOfPart(irOperand.intValue, part))
  1145. END IrOperandIsDirectlyEncodable;
  1146. (* whether the negation of an IR operand (or part thereof) can be directly encoded as an ARM immediate *)
  1147. PROCEDURE NegatedIrOperandIsDirectlyEncodable(irOperand: IntermediateCode.Operand; part: LONGINT): BOOLEAN;
  1148. BEGIN RETURN
  1149. (irOperand.mode = IntermediateCode.ModeImmediate) &
  1150. (irOperand.symbol.name = "") &
  1151. (irOperand.type.form IN IntermediateCode.Integer) &
  1152. ValueIsDirectlyEncodable(ValueOfPart(-irOperand.intValue, part)) (* note the minus sign *)
  1153. END NegatedIrOperandIsDirectlyEncodable;
  1154. (** generate code for a certain IR instruction **)
  1155. PROCEDURE Generate(VAR irInstruction: IntermediateCode.Instruction);
  1156. BEGIN
  1157. (* CheckFixups; *)
  1158. EmitFixupBlockIfNeeded;
  1159. (*
  1160. IF ((irInstruction.opcode = IntermediateCode.mov) OR (irInstruction.opcode = IntermediateCode.pop)) & (instruction.op1.register <= IntermediateCode.ParameterRegister) THEN
  1161. hwreg := ParameterRegister(IntermediateCode.ParameterRegister-instruction.op1.register, instruction.op1.type);
  1162. Spill(physicalRegisters.Mapped(hwreg));
  1163. lastUse := inPC+1;
  1164. WHILE (lastUse < in.pc) &
  1165. ((in.instructions[lastUse].opcode # IntermediateCode.push) OR (in.instructions[lastUse].op1.register # instruction.op1.register)) & (in.instructions[lastUse].opcode # IntermediateCode.call) DO
  1166. INC(lastUse)
  1167. END;
  1168. ticket := ReservePhysicalRegister(instruction.op1.type,hwreg,lastUse);
  1169. END;
  1170. *)
  1171. ReserveOperandRegisters(irInstruction.op1, TRUE);
  1172. ReserveOperandRegisters(irInstruction.op2, TRUE);
  1173. ReserveOperandRegisters(irInstruction.op3, TRUE);
  1174. CASE irInstruction.opcode OF
  1175. | IntermediateCode.nop: (* do nothing *)
  1176. | IntermediateCode.mov: EmitMov(irInstruction, Low); IF IsComplex(irInstruction.op1) THEN EmitMov(irInstruction, High) END
  1177. | IntermediateCode.conv: EmitConv(irInstruction)
  1178. | IntermediateCode.call: EmitCall(irInstruction)
  1179. | IntermediateCode.enter: EmitEnter(irInstruction)
  1180. | IntermediateCode.leave: EmitLeave(irInstruction)
  1181. | IntermediateCode.exit: EmitExit(irInstruction)
  1182. | IntermediateCode.return: EmitReturn(irInstruction, Low); IF IsComplex(irInstruction.op1) THEN EmitReturn(irInstruction, High) END;
  1183. | IntermediateCode.result: EmitResult(irInstruction, Low); IF IsComplex(irInstruction.op1) THEN EmitResult(irInstruction, High) END;
  1184. | IntermediateCode.trap: EmitTrap(irInstruction);
  1185. | IntermediateCode.br .. IntermediateCode.brlt: EmitBr(irInstruction)
  1186. | IntermediateCode.pop: EmitPop(irInstruction.op1, Low); IF IsComplex(irInstruction.op1) THEN EmitPop(irInstruction.op1, High) END
  1187. | IntermediateCode.push: IF IsComplex(irInstruction.op1) THEN EmitPush(irInstruction.op1, High) END; EmitPush(irInstruction.op1, Low)
  1188. | IntermediateCode.neg: EmitNeg(irInstruction)
  1189. | IntermediateCode.not: EmitNot(irInstruction, Low); IF IsComplex(irInstruction.op1) THEN EmitNot(irInstruction, High) END
  1190. | IntermediateCode.abs: EmitAbs(irInstruction)
  1191. | IntermediateCode.mul: EmitMul(irInstruction)
  1192. | IntermediateCode.div: EmitDiv(irInstruction)
  1193. | IntermediateCode.mod: EmitMod(irInstruction)
  1194. | IntermediateCode.sub, IntermediateCode.add: EmitAddOrSub(irInstruction)
  1195. | IntermediateCode.and: EmitAnd(irInstruction, Low); IF IsComplex(irInstruction.op1) THEN EmitAnd(irInstruction, High) END
  1196. | IntermediateCode.or: EmitOr(irInstruction, Low); IF IsComplex(irInstruction.op1) THEN EmitOr(irInstruction, High) END
  1197. | IntermediateCode.xor: EmitXor(irInstruction, Low); IF IsComplex(irInstruction.op1) THEN EmitXor(irInstruction, High) END
  1198. | IntermediateCode.shl: EmitShiftOrRotation(irInstruction)
  1199. | IntermediateCode.shr: EmitShiftOrRotation(irInstruction)
  1200. | IntermediateCode.rol: EmitShiftOrRotation(irInstruction)
  1201. | IntermediateCode.ror: EmitShiftOrRotation(irInstruction)
  1202. | IntermediateCode.cas: EmitCas(irInstruction);
  1203. | IntermediateCode.copy: EmitCopy(irInstruction)
  1204. | IntermediateCode.fill: EmitFill(irInstruction, FALSE)
  1205. | IntermediateCode.asm: EmitAsm(irInstruction)
  1206. | IntermediateCode.special: EmitSpecial(irInstruction)
  1207. END;
  1208. ReserveOperandRegisters(irInstruction.op3, FALSE);
  1209. ReserveOperandRegisters(irInstruction.op2 ,FALSE);
  1210. ReserveOperandRegisters(irInstruction.op1, FALSE);
  1211. END Generate;
  1212. PROCEDURE PostGenerate(CONST instruction: IntermediateCode.Instruction);
  1213. VAR ticket: Ticket;
  1214. BEGIN
  1215. TryUnmap(instruction.op3); TryUnmap(instruction.op2); TryUnmap(instruction.op1);
  1216. ticket := tickets.live;
  1217. WHILE (ticket # NIL) & (ticket.lastuse = inPC) DO
  1218. UnmapTicket(ticket);
  1219. ticket := tickets.live
  1220. END;
  1221. END PostGenerate;
  1222. PROCEDURE EmitFinalFixupBlock;
  1223. BEGIN
  1224. IF listOfReferences.referenceCount > 0 THEN
  1225. ASSERT(in.pc > 0);
  1226. IF in.instructions[in.pc - 1].opcode # IntermediateCode.exit THEN
  1227. (* there is no exit instruction at the end of the IR section -> emit a branch that skips the fixup block (in particular used by @BodyStub procedures)*)
  1228. Emit1(opB, InstructionSet.NewImmediate((listOfReferences.referenceCount + 1) * 4 - 8))
  1229. END
  1230. END;
  1231. EmitFixupBlock; (* emit the fixup block *)
  1232. END EmitFinalFixupBlock;
  1233. (* if needed, emit fixup block for all used symbol references
  1234. - the fixup block is skipped by a branch instruction
  1235. - afterwards, the list of references is cleared
  1236. *)
  1237. PROCEDURE EmitFixupBlockIfNeeded;
  1238. BEGIN
  1239. IF out.pc - listOfReferences.pcOfFirstCitation + listOfReferences.referenceCount + 1 > MaximumFixupDistance THEN
  1240. Emit1(opB, InstructionSet.NewImmediate((listOfReferences.referenceCount + 1) * 4 - 8)); (* emit branch instruction that skips the fixup block *)
  1241. EmitFixupBlock; (* emit the fixup block *)
  1242. listOfReferences.Init (* clear the list *)
  1243. END
  1244. END EmitFixupBlockIfNeeded;
  1245. (* emit fixup block for all used symbol references, and clear the list *)
  1246. PROCEDURE EmitFixupBlock;
  1247. VAR
  1248. reference: Reference;
  1249. citation: Citation;
  1250. fixup: BinaryCode.Fixup;
  1251. patchValue: LONGINT;
  1252. identifier: ObjectFile.Identifier;
  1253. BEGIN
  1254. IF listOfReferences.referenceCount > 0 THEN
  1255. IF out.comments # NIL THEN
  1256. out.comments.String("REFERENCES BLOCK"); out.comments.String(" (");
  1257. out.comments.Int(listOfReferences.referenceCount, 0);
  1258. out.comments.String(" references):"); out.comments.Ln; out.comments.Update
  1259. END;
  1260. reference := listOfReferences.firstReference;
  1261. WHILE reference # NIL DO
  1262. (* 1. patch all of the citations, i.e., the LDR instructions that use the symbol reference *)
  1263. citation := reference.firstCitation;
  1264. WHILE citation # NIL DO
  1265. patchValue := out.pc - 8 - citation.pc;
  1266. ASSERT((0 <= patchValue) & (patchValue < InstructionSet.Bits12));
  1267. out.PutBitsAt(citation.pc, patchValue, 12);
  1268. citation := citation.next
  1269. END;
  1270. IF reference IS SymbolReference THEN
  1271. WITH reference: SymbolReference DO
  1272. (* alternative version that relies on the fixup mechanism:
  1273. NEW(fixupPattern12, 1);
  1274. fixupPattern12[0].offset := 0;
  1275. fixupPattern12[0].bits := 12;
  1276. fixup := BinaryCode.NewFixup(BinaryCode.Relative, entry.pc, in, 0, out.pc - 8, 0, fixupPattern12); (* TODO: determine the correct displacement *)
  1277. out.fixupList.AddFixup(fixup);
  1278. *)
  1279. (* 2. add an absolute fixup for the symbol reference and emit space *)
  1280. IF out.comments # NIL THEN
  1281. out.comments.String("fixup location for ");
  1282. Basic.WriteSegmentedName(out.comments, reference.symbol);
  1283. out.comments.String(":"); out.comments.Int(reference.symbolOffset, 0);
  1284. out.comments.String(" :"); out.comments.Ln; out.comments.Update
  1285. END;
  1286. identifier.name := reference.symbol;
  1287. identifier.fingerprint := reference.fingerprint;
  1288. fixup := BinaryCode.NewFixup(BinaryCode.Absolute, out.pc, identifier, reference.symbolOffset, 0, 0, fixupPattern);
  1289. out.fixupList.AddFixup(fixup);
  1290. out.PutBits(0, 32);
  1291. END;
  1292. ELSIF reference IS ImmediateReference THEN
  1293. WITH reference: ImmediateReference DO
  1294. IF out.comments # NIL THEN
  1295. out.comments.String("immediate value"); out.comments.Ln; out.comments.Update;
  1296. END;
  1297. out.PutBits(reference.value,32);
  1298. END
  1299. END;
  1300. reference := reference.next
  1301. END
  1302. END
  1303. END EmitFixupBlock;
  1304. (** get an ARM operand that hold a certain value
  1305. - if possible the value is returned as an ARM immediate operand
  1306. - otherwise a register is returned instead (if a register hint is present, it is used) **)
  1307. PROCEDURE OperandFromValue(value: LONGINT; registerHint: Operand): Operand;
  1308. VAR
  1309. result: Operand;
  1310. BEGIN
  1311. IF ValueIsDirectlyEncodable(value) THEN
  1312. result := InstructionSet.NewImmediate(value)
  1313. ELSE
  1314. result := RegisterFromValue(value, registerHint)
  1315. END;
  1316. RETURN result
  1317. END OperandFromValue;
  1318. (** get a single precision VFP register that holds a certain floating point value **)
  1319. PROCEDURE SinglePrecisionFloatRegisterFromValue(value: REAL; registerHint: Operand): Operand;
  1320. VAR
  1321. intValue, dummy: LONGINT;
  1322. result, temp: Operand;
  1323. BEGIN
  1324. intValue := SYSTEM.VAL(LONGINT, value);
  1325. (* alternative: integerValue := BinaryCode.ConvertReal(value) *)
  1326. temp := GetFreeRegisterOrHint(IntermediateCode.UnsignedIntegerType(32), registerHint);
  1327. dummy := ValueComposition(intValue, TRUE, temp);
  1328. result := GetFreeRegisterOrHint(IntermediateCode.FloatType(32), registerHint);
  1329. Emit2(opFMSR, result, temp);
  1330. ASSERT(result.mode = InstructionSet.modeRegister);
  1331. ASSERT((result.register >= InstructionSet.SR0) & (result.register <= InstructionSet.SR31));
  1332. RETURN result;
  1333. END SinglePrecisionFloatRegisterFromValue;
  1334. (** get an ARM register that holds a certain integer value
  1335. - if a register hint is present, it is used **)
  1336. PROCEDURE RegisterFromValue(value: LONGINT; registerHint: Operand): Operand;
  1337. VAR
  1338. dummy: LONGINT;
  1339. result: Operand;
  1340. BEGIN
  1341. result := GetFreeRegisterOrHint(IntermediateCode.SignedIntegerType(32), registerHint);
  1342. IF ValueComposition(value, FALSE, result) < 3 THEN
  1343. dummy := ValueComposition(value, TRUE, result);
  1344. ELSE
  1345. result := GetFreeRegisterOrHint(IntermediateCode.UnsignedIntegerType(32), registerHint);
  1346. listOfReferences.AddImmediate(value, out.pc);
  1347. Emit2(opLDR, result, InstructionSet.NewImmediateOffsetMemory(opPC.register, 0, {InstructionSet.Increment})); (* LDR ..., [PC, #+???] *)
  1348. END;
  1349. ASSERT(result.mode = InstructionSet.modeRegister);
  1350. ASSERT((result.register >= InstructionSet.R0) & (result.register <= InstructionSet.R15));
  1351. RETURN result
  1352. END RegisterFromValue;
  1353. (** allocate or deallocate on the stack
  1354. - note: updateStackSize is important as intermediate RETURNs should not change stack size
  1355. **)
  1356. PROCEDURE AllocateStack(allocationSize: LONGINT; doUpdateStackSize: BOOLEAN; clear: BOOLEAN);
  1357. VAR
  1358. operand, zero, count: InstructionSet.Operand; i: LONGINT;
  1359. BEGIN
  1360. inStackAllocation := TRUE;
  1361. operand := OperandFromValue(ABS(allocationSize), emptyOperand);
  1362. IF allocationSize > 0 THEN
  1363. IF clear THEN
  1364. zero := InstructionSet.NewRegister(0, None, None, 0);
  1365. Emit2(opMOV, zero , InstructionSet.NewImmediate(0));
  1366. IF allocationSize < 16 THEN
  1367. FOR i := 0 TO allocationSize-1 BY 4 DO
  1368. Emit2(opSTR, InstructionSet.NewRegister(0, None, None, 0), InstructionSet.NewImmediateOffsetMemory(InstructionSet.SP, 4, {InstructionSet.Decrement, InstructionSet.PreIndexed}));
  1369. END;
  1370. ELSE
  1371. count := InstructionSet.NewRegister(1, None, None, 0);
  1372. Emit1(opB, InstructionSet.NewImmediate(0)); (* PC offset = 8 ! Jump over immediate *)
  1373. out.PutBits(allocationSize DIV 4, 32);
  1374. Emit2(opLDR, count, InstructionSet.NewImmediateOffsetMemory(InstructionSet.PC, 8+4, {InstructionSet.Decrement}));
  1375. (* label *)
  1376. Emit2(opSTR, zero, InstructionSet.NewImmediateOffsetMemory(InstructionSet.SP, 4, {InstructionSet.Decrement, InstructionSet.PreIndexed}));
  1377. Emit3WithFlags(opSUB, count, count, InstructionSet.NewImmediate(1),{InstructionSet.flagS});
  1378. Emit1WithCondition(opB, InstructionSet.NewImmediate(-8 -8), InstructionSet.conditionGT); (* label *)
  1379. END;
  1380. ELSE
  1381. Emit3(opSUB, opSP, opSP, operand) (* decreasing SP: allocation *)
  1382. END;
  1383. ELSIF allocationSize < 0 THEN
  1384. Emit3(opADD, opSP, opSP, operand) (* increasing SP: deallocation *)
  1385. END;
  1386. IF doUpdateStackSize THEN stackSize := stackSize + allocationSize END;
  1387. inStackAllocation := FALSE
  1388. END AllocateStack;
  1389. (** whether two ARM operands represent the same physical register **)
  1390. PROCEDURE IsSameRegister(CONST a, b: Operand): BOOLEAN;
  1391. BEGIN RETURN (a.mode = InstructionSet.modeRegister) & (b.mode = InstructionSet.modeRegister) & (a.register = b.register)
  1392. END IsSameRegister;
  1393. (** emit a MOV instruction if the two operands do not represent the same register
  1394. - for moves involving floating point registers special VFP instructions opFCPYS, opFMSR and opFMRS are used
  1395. **)
  1396. PROCEDURE MovIfDifferent(CONST a, b: Operand);
  1397. BEGIN
  1398. IF ~IsSameRegister(a, b) THEN
  1399. ASSERT(a.mode = InstructionSet.modeRegister);
  1400. IF IsRegisterForType(a.register, IntermediateCode.FloatType(32)) THEN
  1401. IF IsRegisterForType(b.register, IntermediateCode.FloatType(32)) THEN
  1402. (* mov float, float: *)
  1403. Emit2(opFCPYS, a, b)
  1404. ELSE
  1405. (* mov float, int: *)
  1406. Emit2(opFMSR, a, b)
  1407. END
  1408. ELSE
  1409. IF IsRegisterForType(b.register, IntermediateCode.FloatType(32)) THEN
  1410. (* mov int, float: *)
  1411. Emit2(opFMRS, a, b)
  1412. ELSE
  1413. (* mov int, int: *)
  1414. Emit2(opMOV, a, b)
  1415. END
  1416. END
  1417. END
  1418. END MovIfDifferent;
  1419. (** acquire an ARM register fr oa IR destination operand part
  1420. - if IR operand is a memory location, get a temporary register (if provided the hinted register is used)
  1421. - if IR operand is an IR register, get the ARM register that is mapped to the corresponding part
  1422. **)
  1423. PROCEDURE AcquireDestinationRegister(CONST irDestinationOperand: IntermediateCode.Operand; part: LONGINT; registerHint: Operand): Operand;
  1424. VAR
  1425. result: Operand;
  1426. BEGIN
  1427. IF irDestinationOperand.mode = IntermediateCode.ModeMemory THEN
  1428. result := GetFreeRegisterOrHint(PartType(irDestinationOperand.type, part), registerHint)
  1429. ELSIF irDestinationOperand.mode = IntermediateCode.ModeRegister THEN
  1430. ASSERT(irDestinationOperand.offset = 0);
  1431. IF virtualRegisters.Mapped(irDestinationOperand.register, part) = NIL THEN TryAllocate(irDestinationOperand, part) END; (* create the mapping if not yet done *)
  1432. result := InstructionSet.NewRegister(PhysicalRegisterNumber(irDestinationOperand.register, part), None, None, 0)
  1433. ELSE
  1434. HALT(100)
  1435. END;
  1436. ASSERT(result.mode = InstructionSet.modeRegister);
  1437. RETURN result
  1438. END AcquireDestinationRegister;
  1439. (** write the content of an ARM register to an IR destination operand (memory location or IR register)
  1440. - afterwards, try to release the register
  1441. **)
  1442. PROCEDURE WriteBack(VAR irDestinationOperand: IntermediateCode.Operand; part: LONGINT; register: Operand);
  1443. VAR
  1444. mappedArmRegister: Operand;
  1445. BEGIN
  1446. ASSERT(register.mode = InstructionSet.modeRegister);
  1447. IF irDestinationOperand.mode = IntermediateCode.ModeMemory THEN
  1448. Store(register, MemoryOperandFromIrMemoryOperand(irDestinationOperand, part, emptyOperand), PartType(irDestinationOperand.type, part))
  1449. ELSIF irDestinationOperand.mode = IntermediateCode.ModeRegister THEN
  1450. ASSERT((virtualRegisters.Mapped(irDestinationOperand.register, part) # NIL)
  1451. OR (irDestinationOperand.register = IntermediateCode.SP)
  1452. OR (irDestinationOperand.register = IntermediateCode.FP)
  1453. OR (irDestinationOperand.register = IntermediateCode.LR)
  1454. OR (irDestinationOperand.register = IntermediateCode.AP));
  1455. mappedArmRegister := InstructionSet.NewRegister(PhysicalRegisterNumber(irDestinationOperand.register, part), None, None, 0);
  1456. MovIfDifferent(mappedArmRegister, register)
  1457. ELSE
  1458. HALT(100)
  1459. END;
  1460. ReleaseHint(register.register)
  1461. END WriteBack;
  1462. PROCEDURE ZeroExtendOperand(operand: Operand; sizeInBits: LONGINT);
  1463. BEGIN
  1464. ASSERT(sizeInBits <= 32);
  1465. IF operand.mode = InstructionSet.modeRegister THEN
  1466. IF sizeInBits = 8 THEN
  1467. Emit3(opAND, operand, operand, InstructionSet.NewImmediate(255)); (* AND reg, reg, 11111111b *)
  1468. ELSIF sizeInBits = 16 THEN
  1469. Emit2(opMOV, operand, InstructionSet.NewRegister(operand.register, InstructionSet.shiftLSL, None, 16));
  1470. Emit2(opMOV, operand, InstructionSet.NewRegister(operand.register, InstructionSet.shiftLSR, None, 16))
  1471. ELSIF sizeInBits = 32 THEN
  1472. (* nothing to do *)
  1473. ELSE
  1474. HALT(100)
  1475. END
  1476. END
  1477. END ZeroExtendOperand;
  1478. PROCEDURE SignExtendOperand(operand: Operand; sizeInBits: LONGINT);
  1479. BEGIN
  1480. ASSERT(sizeInBits <= 32);
  1481. IF operand.mode = InstructionSet.modeRegister THEN
  1482. IF sizeInBits < 32 THEN
  1483. Emit2(opMOV, operand, InstructionSet.NewRegister(operand.register, InstructionSet.shiftLSL, None, 32 - sizeInBits));
  1484. Emit2(opMOV, operand, InstructionSet.NewRegister(operand.register, InstructionSet.shiftASR, None, 32 - sizeInBits))
  1485. END
  1486. END
  1487. END SignExtendOperand;
  1488. (** sign or zero-extends the content of an operand to 32 bits, depending on the IR type **)
  1489. PROCEDURE SignOrZeroExtendOperand(operand: Operand; irType: IntermediateCode.Type);
  1490. BEGIN
  1491. ASSERT(irType.sizeInBits <= 32);
  1492. IF irType.form = IntermediateCode.UnsignedInteger THEN
  1493. ZeroExtendOperand(operand, irType.sizeInBits)
  1494. ELSE
  1495. SignExtendOperand(operand, irType.sizeInBits)
  1496. END
  1497. END SignOrZeroExtendOperand;
  1498. (* ACTUAL CODE GENERATION *)
  1499. PROCEDURE EmitPush(VAR irOperand: IntermediateCode.Operand; part: LONGINT);
  1500. VAR
  1501. register: Operand;
  1502. partType: IntermediateCode.Type;
  1503. (*pc: LONGINT;*)
  1504. BEGIN
  1505. register := RegisterFromIrOperand(irOperand, part, emptyOperand);
  1506. IF ~IsRegisterForType(register.register, IntermediateCode.FloatType(32)) THEN
  1507. Emit2(opSTR, register, InstructionSet.NewImmediateOffsetMemory(InstructionSet.SP, 4, {InstructionSet.Decrement, InstructionSet.PreIndexed}));
  1508. ELSE
  1509. partType := PartType(irOperand.type, part);
  1510. AllocateStack(MAX(4, partType.sizeInBits DIV 8), TRUE,FALSE);
  1511. Store(register, InstructionSet.NewImmediateOffsetMemory(InstructionSet.SP, 0, {InstructionSet.Increment}), PartType(irOperand.type, part));
  1512. END;
  1513. (*
  1514. (* optimization for push chains (THIS DOES NOT WORK IF inEmulation) *)
  1515. IF pushChainLength = 0 THEN
  1516. pc := inPC;
  1517. (* search for consecutive push instructions *)
  1518. WHILE (pc < in.pc) & (in.instructions[pc].opcode = IntermediateCode.push) DO
  1519. ASSERT(in.instructions[pc].op1.mode # IntermediateCode.Undefined);
  1520. INC(pushChainLength, MAX(4, in.instructions[pc].op1.type.sizeInBits DIV 8));
  1521. INC(pc)
  1522. END;
  1523. AllocateStack(pushChainLength, TRUE)
  1524. END;
  1525. DEC(pushChainLength, 4); (* for 64 bit operands, this procedure is executed twice -> the push chain will be decremented by 8 bytes *)
  1526. register := RegisterFromIrOperand(irOperand, part, emptyOperand);
  1527. ASSERT(pushChainLength < InstructionSet.Bits12, 100);
  1528. ASSERT((pushChainLength MOD 4) = 0);
  1529. Store(register, InstructionSet.NewImmediateOffsetMemory(InstructionSet.SP, pushChainLength, {InstructionSet.Increment}), PartType(irOperand.type, part))
  1530. *)
  1531. END EmitPush;
  1532. PROCEDURE EmitPop(VAR irOperand: IntermediateCode.Operand; part: LONGINT);
  1533. VAR
  1534. register: Operand; partType: IntermediateCode.Type;
  1535. BEGIN
  1536. register := AcquireDestinationRegister(irOperand, part, emptyOperand);
  1537. IF ~IsRegisterForType(register.register, IntermediateCode.FloatType(32)) THEN
  1538. (*Emit2(opLDR, register, InstructionSet.NewImmediateOffsetMemory(InstructionSet.SP, 4, {InstructionSet.Increment, InstructionSet.PostIndexed}));*)
  1539. Load(register, InstructionSet.NewImmediateOffsetMemory(InstructionSet.SP, 4, {InstructionSet.Increment, InstructionSet.PostIndexed}), PartType(irOperand.type, part));
  1540. ELSE
  1541. Load(register, InstructionSet.NewImmediateOffsetMemory(InstructionSet.SP, 0, {InstructionSet.Increment}), PartType(irOperand.type, part));
  1542. partType := PartType(irOperand.type, part);
  1543. AllocateStack(-MAX(4, partType.sizeInBits DIV 8), TRUE,FALSE);
  1544. END;
  1545. WriteBack(irOperand, part, register)
  1546. END EmitPop;
  1547. PROCEDURE Resolve(VAR op: IntermediateCode.Operand);
  1548. BEGIN
  1549. IF (op.symbol.name # "") & (op.resolved = NIL) THEN op.resolved := module.allSections.FindByName(op.symbol.name) END
  1550. END Resolve;
  1551. (* call <address>, <parSize> *)
  1552. PROCEDURE EmitCall(VAR irInstruction: IntermediateCode.Instruction);
  1553. VAR
  1554. code: BinaryCode.Section;
  1555. fixup, newFixup: BinaryCode.Fixup;
  1556. BEGIN
  1557. Resolve(irInstruction.op1);
  1558. IF (irInstruction.op1.resolved # NIL) & (irInstruction.op1.resolved.type = Sections.InlineCodeSection) THEN
  1559. (* call of an inline procedure: *)
  1560. code := irInstruction.op1.resolved(IntermediateCode.Section).resolved;
  1561. ASSERT(code # NIL); (* TODO: what if section is not yet resolved, i.e., code has not yet been generated? *)
  1562. IF (out.comments # NIL) THEN
  1563. out.comments.String("inlined code sequence:");
  1564. out.comments.Ln;
  1565. out.comments.Update;
  1566. END;
  1567. (* emit the generated code of the other section *)
  1568. out.CopyBits(code.os.bits, 0, code.os.bits.GetSize());
  1569. (* transfer the fixups *)
  1570. fixup := code.fixupList.firstFixup;
  1571. WHILE fixup # NIL DO
  1572. newFixup := BinaryCode.NewFixup(fixup.mode, fixup.offset + code.pc, fixup.symbol, fixup.symbolOffset, fixup.displacement, fixup.scale, fixup.pattern);
  1573. out.fixupList.AddFixup(newFixup);
  1574. fixup := fixup.nextFixup
  1575. END
  1576. ELSE
  1577. (* store the address of the procedure in a register and branch and link there *)
  1578. Emit1(opBLX, RegisterFromIrOperand(irInstruction.op1, Low, emptyOperand));
  1579. (* remove parameters on stack *)
  1580. AllocateStack(-LONGINT(irInstruction.op2.intValue), TRUE, FALSE)
  1581. END
  1582. END EmitCall;
  1583. (* enter <callingConvention>, <pafSize>, <numRegParams> *)
  1584. PROCEDURE EmitEnter(CONST irInstruction: IntermediateCode.Instruction);
  1585. VAR allocationSize: LONGINT;
  1586. BEGIN
  1587. (* store registers for interrupts, if required *)
  1588. IF (irInstruction.op1.intValue = SyntaxTree.InterruptCallingConvention) THEN (* TODO: needed? *)
  1589. (* push R0-R11, FP and LR *)
  1590. Emit2WithFlags(opSTM, opSP, InstructionSet.NewRegisterList(0, {InstructionSet.FP, InstructionSet.LR, 0..11}), {InstructionSet.flagDB, InstructionSet.flagBaseRegisterUpdate});
  1591. Emit2(opMOV, opFP, opSP);
  1592. END;
  1593. stackSize := 0;
  1594. (* allocate space on stack for local variables *)
  1595. allocationSize := LONGINT(irInstruction.op2.intValue);
  1596. Basic.Align(allocationSize, 4); (* 4 byte alignment *)
  1597. AllocateStack(allocationSize, TRUE, backend.initLocals);
  1598. (* allocate space on stack for register spills *)
  1599. spillStackStart := -stackSize;
  1600. IF spillStack.MaxSize() > 0 THEN AllocateStack(spillStack.MaxSize(), TRUE, FALSE) END
  1601. END EmitEnter;
  1602. (* leave <callingConvention> *)
  1603. PROCEDURE EmitLeave(CONST irInstruction: IntermediateCode.Instruction);
  1604. BEGIN
  1605. (* LDMFD (Full Descending) aka LDMIA (Increment After) *)
  1606. IF (irInstruction.op1.intValue = SyntaxTree.InterruptCallingConvention) THEN
  1607. (* pop R0-R11, FP and LR *)
  1608. Emit2(opMOV, opSP, opFP);
  1609. Emit2WithFlags(opLDM, opSP, InstructionSet.NewRegisterList(0, {InstructionSet.FP, InstructionSet.LR, 0..11}), {InstructionSet.flagIA, InstructionSet.flagBaseRegisterUpdate})
  1610. END
  1611. END EmitLeave;
  1612. (* exit <parSize>, <pcOffset> *)
  1613. PROCEDURE EmitExit(CONST irInstruction: IntermediateCode.Instruction);
  1614. BEGIN
  1615. Emit2(opLDR, opLR, InstructionSet.NewImmediateOffsetMemory(InstructionSet.SP, 4, {InstructionSet.Increment, InstructionSet.PostIndexed}));
  1616. IF (irInstruction.op1.intValue = 0) & (irInstruction.op2.intValue # SyntaxTree.InterruptCallingConvention) THEN
  1617. (* Emit2(opMOV, opPC, opLR) *)
  1618. Emit1(opBX, opLR) (* recommended for better interoperability between ARM and Thumb *)
  1619. ELSE
  1620. IF (irInstruction.op2.intValue = SyntaxTree.InterruptCallingConvention) THEN
  1621. Emit3WithFlags(opSUB, opPC, opLR, InstructionSet.NewImmediate(LONGINT(irInstruction.op1.intValue)),{InstructionSet.flagS})
  1622. ELSE
  1623. (* exit from an ARM interrupt procedure that has a PC offset *)
  1624. Emit3(opSUB, opPC, opLR, InstructionSet.NewImmediate(LONGINT(irInstruction.op1.intValue)))
  1625. END;
  1626. END
  1627. END EmitExit;
  1628. PROCEDURE EmitMov(VAR irInstruction: IntermediateCode.Instruction; part: LONGINT);
  1629. VAR
  1630. destinationRegister, sourceOperand: Operand;
  1631. BEGIN
  1632. IF irInstruction.op1.mode # IntermediateCode.ModeRegister THEN
  1633. (* optimization: mov [?], r? it is more optimal to determine the source operand first *)
  1634. sourceOperand := RegisterOrImmediateFromIrOperand(irInstruction.op2, part, emptyOperand);
  1635. destinationRegister := GetFreeRegisterOrHint(PartType(irInstruction.op2.type, part), sourceOperand) (* note that the source operand (possibly a register) is used as hint *)
  1636. ELSE
  1637. PrepareSingleSourceOpWithImmediate(irInstruction, part, destinationRegister, sourceOperand);
  1638. END;
  1639. MovIfDifferent(destinationRegister, sourceOperand);
  1640. WriteBack(irInstruction.op1, part, destinationRegister)
  1641. END EmitMov;
  1642. (* BITWISE LOGICAL OPERATIONS *)
  1643. PROCEDURE EmitNot(VAR irInstruction: IntermediateCode.Instruction; part: LONGINT);
  1644. VAR
  1645. destination, source: Operand;
  1646. BEGIN
  1647. PrepareSingleSourceOpWithImmediate(irInstruction, part, destination, source);
  1648. Emit2(opMVN, destination, source); (* invert bits *)
  1649. WriteBack(irInstruction.op1, part, destination)
  1650. END EmitNot;
  1651. PROCEDURE EmitAnd(VAR irInstruction: IntermediateCode.Instruction; part: LONGINT);
  1652. VAR
  1653. dummy: BOOLEAN;
  1654. destination, left, right: Operand;
  1655. BEGIN
  1656. PrepareDoubleSourceOpWithImmediate(irInstruction, part, destination, left, right, dummy);
  1657. Emit3(opAND, destination, left, right);
  1658. WriteBack(irInstruction.op1, part, destination)
  1659. END EmitAnd;
  1660. PROCEDURE EmitOr(VAR irInstruction: IntermediateCode.Instruction; part: LONGINT);
  1661. VAR
  1662. dummy: BOOLEAN;
  1663. destination, left, right: Operand;
  1664. BEGIN
  1665. PrepareDoubleSourceOpWithImmediate(irInstruction, part, destination, left, right, dummy);
  1666. Emit3(opORR, destination, left, right);
  1667. WriteBack(irInstruction.op1, part, destination)
  1668. END EmitOr;
  1669. PROCEDURE EmitXor(VAR irInstruction: IntermediateCode.Instruction; part: LONGINT);
  1670. VAR
  1671. dummy: BOOLEAN;
  1672. destination, left, right: Operand;
  1673. BEGIN
  1674. PrepareDoubleSourceOpWithImmediate(irInstruction, part, destination, left, right, dummy);
  1675. Emit3(opEOR, destination, left, right);
  1676. WriteBack(irInstruction.op1, part, destination)
  1677. END EmitXor;
  1678. (* ARITHMETIC OPERATIONS *)
  1679. (*
  1680. - TODO: double precision floats
  1681. - note that for operand sizes 8 and 16, the unused bits of the result might be in a unpredictable state (sign/zero-extension is not done on purpose)
  1682. *)
  1683. PROCEDURE EmitAddOrSub(VAR irInstruction: IntermediateCode.Instruction);
  1684. VAR
  1685. destination, left, right: Operand;
  1686. (* registerSR0, registerSR1, registerSR2: Operand; *)
  1687. BEGIN
  1688. IF IsSinglePrecisionFloat(irInstruction.op1) THEN
  1689. ASSERT(backend.useFPU);
  1690. PrepareDoubleSourceOp(irInstruction, Low, destination, left, right);
  1691. IF irInstruction.opcode = IntermediateCode.add THEN
  1692. Emit3(opFADDS, destination, left, right)
  1693. ELSE
  1694. Emit3(opFSUBS, destination, left, right)
  1695. END;
  1696. WriteBack(irInstruction.op1, Low, destination)
  1697. ELSIF IsInteger(irInstruction.op1) THEN
  1698. IF IsComplex(irInstruction.op1) THEN
  1699. EmitPartialAddOrSub(irInstruction, Low, TRUE);
  1700. EmitPartialAddOrSub(irInstruction, High, FALSE)
  1701. ELSE
  1702. EmitPartialAddOrSub(irInstruction, Low, FALSE)
  1703. END
  1704. ELSE
  1705. HALT(200)
  1706. END
  1707. END EmitAddOrSub;
  1708. PROCEDURE EmitPartialAddOrSub(CONST irInstruction: IntermediateCode.Instruction; part: LONGINT; doUpdateFlags: BOOLEAN);
  1709. VAR
  1710. destination, left, right, hint: Operand;
  1711. irDestination, irLeft, irRight: IntermediateCode.Operand;
  1712. operation: LONGINT;
  1713. doSwap, doNegateRight: BOOLEAN;
  1714. BEGIN
  1715. irDestination := irInstruction.op1; irLeft := irInstruction.op2; irRight := irInstruction.op3;
  1716. doSwap := FALSE; doNegateRight := FALSE; (* defaults *)
  1717. IF irInstruction.opcode = IntermediateCode.add THEN
  1718. IF IrOperandIsDirectlyEncodable(irRight, part) THEN
  1719. (* add r0, r1, 16 ~> ADD R0, R1, #16 *)
  1720. operation := opADD
  1721. ELSIF IrOperandIsDirectlyEncodable(irLeft, part) THEN
  1722. (* add r0, 16, r1 ~> ADD R0, R1, #16 *)
  1723. operation := opADD; doSwap := TRUE
  1724. ELSIF NegatedIrOperandIsDirectlyEncodable(irRight, part) THEN
  1725. (* add r0, r1, -16 ~> SUB R0, R1, #16 *)
  1726. operation := opSUB; doNegateRight := TRUE
  1727. ELSIF NegatedIrOperandIsDirectlyEncodable(irLeft, part) THEN
  1728. (* add r0, -16, r1 ~> SUB R0, R1, #16 *)
  1729. operation := opSUB; doSwap := TRUE; doNegateRight := TRUE
  1730. ELSE
  1731. operation := opADD
  1732. END
  1733. ELSIF irInstruction.opcode = IntermediateCode.sub THEN
  1734. IF IrOperandIsDirectlyEncodable(irRight, part) THEN
  1735. (* sub r0, r1, 16 ~> SUB R0, R1, #16 *)
  1736. operation := opSUB
  1737. ELSIF IrOperandIsDirectlyEncodable(irLeft, part) THEN
  1738. (* sub r0, 16, r1 ~> RSB R0, R1, #16 *)
  1739. operation := opRSB; doSwap := TRUE
  1740. ELSIF NegatedIrOperandIsDirectlyEncodable(irRight, part) THEN
  1741. (* sub r0, r1, -16 ~> ADD R0, R1, #16 *)
  1742. operation := opADD; doNegateRight := TRUE
  1743. ELSE
  1744. operation := opSUB
  1745. END
  1746. ELSE
  1747. HALT(100)
  1748. END;
  1749. (* get destination operand *)
  1750. destination := AcquireDestinationRegister(irDestination, part, emptyOperand);
  1751. (* get source operands *)
  1752. IF doSwap THEN SwapIrOperands(irLeft, irRight) END; (* if needed, swap operands *)
  1753. (* TODO: revise this! *)
  1754. IF IsSameRegister(right, destination) THEN hint := destination ELSE hint := emptyOperand END;
  1755. left := RegisterFromIrOperand(irLeft, part, hint);
  1756. IF doNegateRight THEN
  1757. ASSERT(NegatedIrOperandIsDirectlyEncodable(irRight, part));
  1758. right := InstructionSet.NewImmediate(-ValueOfPart(irRight.intValue, part))
  1759. ELSE
  1760. right := RegisterOrImmediateFromIrOperand(irRight, part, emptyOperand)
  1761. END;
  1762. (* if needed, use operation that incorporates carry *)
  1763. IF part # Low THEN
  1764. CASE operation OF
  1765. | opADD: operation := opADC
  1766. | opSUB: operation := opSBC
  1767. | opRSB: operation := opRSC
  1768. ELSE HALT(100)
  1769. END
  1770. END;
  1771. IF doUpdateFlags THEN
  1772. Emit3WithFlags(operation, destination, left, right, {InstructionSet.flagS})
  1773. ELSE
  1774. Emit3(operation, destination, left, right)
  1775. END;
  1776. WriteBack(irDestination, part, destination)
  1777. END EmitPartialAddOrSub;
  1778. PROCEDURE EmitMul(VAR irInstruction: IntermediateCode.Instruction);
  1779. VAR
  1780. destination, left, right: ARRAY 2 OF Operand;
  1781. BEGIN
  1782. IF IsSinglePrecisionFloat(irInstruction.op1) THEN
  1783. ASSERT(backend.useFPU);
  1784. PrepareDoubleSourceOp(irInstruction, Low, destination[Low], left[Low], right[Low]);
  1785. Emit3(opFMULS, destination[Low], left[Low], right[Low]);
  1786. WriteBack(irInstruction.op1, Low, destination[Low])
  1787. ELSIF IsInteger(irInstruction.op1) THEN
  1788. IF IsComplex(irInstruction.op1) THEN
  1789. ASSERT(irInstruction.op1.type.form = IntermediateCode.SignedInteger);
  1790. HALT(200);
  1791. (* TODO: fix signed 64 bit integer multiplication:
  1792. PrepareDoubleSourceOp(irInstruction, Low, destination[Low], left[Low], right[Low]);
  1793. PrepareDoubleSourceOp(irInstruction, High, destination[High], left[High], right[High]);
  1794. Emit4(opSMULL, destination[Low], destination[High], left[Low], right[Low]); (* signed long multiplication *)
  1795. Emit3(opMLA, destination[High], left[Low], right[High]); (* multiply and accumulate *)
  1796. Emit3(opMLA, destination[High], left[High], right[Low]);
  1797. WriteBack(irInstruction.op1, Low, destination[Low]);
  1798. WriteBack(irInstruction.op1, High, destination[High]);
  1799. *)
  1800. ELSE
  1801. (* signed or unsigned integer multiplication: *)
  1802. PrepareDoubleSourceOp(irInstruction, Low, destination[Low], left[Low], right[Low]);
  1803. SignOrZeroExtendOperand(left[Low], irInstruction.op2.type);
  1804. SignOrZeroExtendOperand(right[Low], irInstruction.op3.type);
  1805. Emit3(opMUL, destination[Low], left[Low], right[Low]); (* note that the sign does not matter for the least 32 significant bits *)
  1806. WriteBack(irInstruction.op1, Low, destination[Low])
  1807. END
  1808. ELSE
  1809. HALT(200)
  1810. END
  1811. END EmitMul;
  1812. PROCEDURE EmitDiv(VAR irInstruction: IntermediateCode.Instruction);
  1813. VAR
  1814. destination, left, right: Operand;
  1815. BEGIN
  1816. IF IsSinglePrecisionFloat(irInstruction.op1) THEN
  1817. ASSERT(backend.useFPU);
  1818. PrepareDoubleSourceOp(irInstruction, Low, destination, left, right);
  1819. Emit3(opFDIVS, destination, left, right);
  1820. WriteBack(irInstruction.op1, Low, destination)
  1821. ELSE
  1822. HALT(200)
  1823. END
  1824. END EmitDiv;
  1825. PROCEDURE EmitMod(CONST irInstruction: IntermediateCode.Instruction);
  1826. BEGIN HALT(100) (* handled by a runtime call *)
  1827. END EmitMod;
  1828. PROCEDURE EmitAbs(VAR irInstruction: IntermediateCode.Instruction);
  1829. VAR
  1830. destination, source: ARRAY 2 OF Operand;
  1831. zero: Operand;
  1832. BEGIN
  1833. IF IsInteger(irInstruction.op1) THEN
  1834. zero := InstructionSet.NewImmediate(0);
  1835. IF IsComplex(irInstruction.op1) THEN
  1836. PrepareSingleSourceOpWithImmediate(irInstruction, Low, destination[Low], source[Low]);
  1837. PrepareSingleSourceOpWithImmediate(irInstruction, High, destination[High], source[High]);
  1838. MovIfDifferent(destination[Low], source[Low]);
  1839. MovIfDifferent(destination[High], source[High]);
  1840. (* negate the value if it is negative *)
  1841. IF irInstruction.op2.type.form = IntermediateCode.SignedInteger THEN
  1842. Emit2(opCMP, destination[High], zero); (* note that only the high part has to be looked at to determine the sign *)
  1843. Emit1WithCondition(opB, InstructionSet.NewImmediate(4), InstructionSet.conditionGE); (* BGE #4 = skip the following two instructions if greater or equal *)
  1844. Emit3WithFlags(opRSB, destination[Low], destination[Low], zero, {InstructionSet.flagS}); (* RSBS *)
  1845. Emit3(opRSC, destination[High], destination[High], zero); (* RSC - reverse subtraction with carry *)
  1846. END;
  1847. WriteBack(irInstruction.op1, Low, destination[Low]);
  1848. WriteBack(irInstruction.op1, High, destination[High])
  1849. ELSE
  1850. PrepareSingleSourceOpWithImmediate(irInstruction, Low, destination[Low], source[Low]);
  1851. SignOrZeroExtendOperand(source[Low], irInstruction.op2.type);
  1852. MovIfDifferent(destination[Low], source[Low]);
  1853. (* negate the value if it is negative *)
  1854. IF irInstruction.op2.type.form = IntermediateCode.SignedInteger THEN
  1855. SignExtendOperand(destination[Low], irInstruction.op2.type.sizeInBits);
  1856. Emit2(opCMP, destination[Low], zero);
  1857. Emit3WithCondition(opRSB, destination[Low], destination[Low], zero, InstructionSet.conditionLT)
  1858. END;
  1859. WriteBack(irInstruction.op1, Low, destination[Low])
  1860. END
  1861. ELSIF IsSinglePrecisionFloat(irInstruction.op1) THEN
  1862. ASSERT(backend.useFPU);
  1863. PrepareSingleSourceOp(irInstruction, Low, destination[Low], source[Low]);
  1864. Emit2(opFABSS, destination[Low], source[Low]);
  1865. WriteBack(irInstruction.op1, Low, destination[Low])
  1866. ELSE
  1867. HALT(200)
  1868. END
  1869. END EmitAbs;
  1870. (* TODO: floats *)
  1871. PROCEDURE EmitNeg(VAR irInstruction: IntermediateCode.Instruction);
  1872. VAR
  1873. destination, source: ARRAY 2 OF Operand;
  1874. zero: Operand;
  1875. BEGIN
  1876. IF IsInteger(irInstruction.op1) THEN
  1877. zero := InstructionSet.NewImmediate(0);
  1878. IF IsComplex(irInstruction.op1) THEN
  1879. PrepareSingleSourceOpWithImmediate(irInstruction, Low, destination[Low], source[Low]);
  1880. PrepareSingleSourceOpWithImmediate(irInstruction, High, destination[High], source[High]);
  1881. Emit3WithFlags(opRSB, destination[Low], source[Low], zero, {InstructionSet.flagS}); (* RSBS *)
  1882. Emit3(opRSC, destination[High], source[High], zero); (* RSC - reverse subtraction with carry *)
  1883. WriteBack(irInstruction.op1, Low, destination[Low]);
  1884. WriteBack(irInstruction.op1, High, destination[High])
  1885. ELSE
  1886. PrepareSingleSourceOpWithImmediate(irInstruction, Low, destination[Low], source[Low]);
  1887. SignOrZeroExtendOperand(source[Low], irInstruction.op2.type);
  1888. Emit3(opRSB, destination[Low], source[Low], zero); (* reverse subtraction with zero *)
  1889. WriteBack(irInstruction.op1, Low, destination[Low])
  1890. END
  1891. ELSIF IsSinglePrecisionFloat(irInstruction.op1) THEN
  1892. ASSERT(backend.useFPU);
  1893. PrepareSingleSourceOp(irInstruction, Low, destination[Low], source[Low]);
  1894. Emit2(opFNEGS, destination[Low], source[Low]);
  1895. WriteBack(irInstruction.op1, Low, destination[Low])
  1896. ELSE
  1897. HALT(200)
  1898. END
  1899. END EmitNeg;
  1900. (*
  1901. - note that the ARM instructions ASR, LSL, LSR, ROR, etc. are actually aliases for a MOV with a shifted register operand
  1902. - note that ARM does not support LSL by 32 bits
  1903. - note that for operand sizes 8 and 16, the unused bits of the result might be in a unpredictable state (sign/zero-extension is not done on purpose)
  1904. *)
  1905. PROCEDURE EmitShiftOrRotation(VAR irInstruction: IntermediateCode.Instruction);
  1906. VAR
  1907. shiftAmountImmediate, shiftMode: LONGINT;
  1908. destination, source: ARRAY 2 OF Operand;
  1909. irShiftOperand: IntermediateCode.Operand;
  1910. temp, shiftAmountRegister: Operand;
  1911. BEGIN
  1912. ASSERT(IsInteger(irInstruction.op1), 100); (* shifts are only allowed on integers *)
  1913. destination[Low] := AcquireDestinationRegister(irInstruction.op1, Low, emptyOperand);
  1914. source[Low] := RegisterFromIrOperand(irInstruction.op2, Low, emptyOperand); (* note that the destination register cannot be used as hint for the source *)
  1915. IF IsComplex(irInstruction.op1) THEN
  1916. destination[High] := AcquireDestinationRegister(irInstruction.op1, High, emptyOperand);
  1917. source[High] := RegisterFromIrOperand(irInstruction.op2, High, emptyOperand); (* note that the destination register cannot be used as hint for the source *)
  1918. END;
  1919. irShiftOperand := irInstruction.op3;
  1920. ASSERT((irShiftOperand.type.form = IntermediateCode.UnsignedInteger) & ~IsComplex(irShiftOperand)); (* the shift operand is assumed to be a single part unsigned integer *)
  1921. (* use ARM register or shift immediate to represent IR shift operand *)
  1922. IF (irShiftOperand.mode = IntermediateCode.ModeImmediate) & (irShiftOperand.symbol.name = "") THEN
  1923. shiftAmountImmediate := LONGINT(irShiftOperand.intValue); (* note that at this point the shift amount could also be >= 32 *)
  1924. shiftAmountRegister := emptyOperand;
  1925. ASSERT(shiftAmountImmediate >= 0);
  1926. ELSE
  1927. shiftAmountImmediate := 0;
  1928. shiftAmountRegister := RegisterFromIrOperand(irShiftOperand, Low, emptyOperand);
  1929. ZeroExtendOperand(shiftAmountRegister, irShiftOperand.type.sizeInBits)
  1930. END;
  1931. CASE irInstruction.opcode OF
  1932. | IntermediateCode.ror, IntermediateCode.rol:
  1933. (* rotation: *)
  1934. IF IsComplex(irInstruction.op1) THEN HALT(100) END; (* complex rotations are handled as runtime calls *)
  1935. IF irInstruction.opcode = IntermediateCode.rol THEN
  1936. (* simple left rotation: rotate right with complementary rotation amount, since ARM does not support left rotations *)
  1937. IF shiftAmountRegister.register = None THEN
  1938. shiftAmountImmediate := 32 - shiftAmountImmediate
  1939. ELSE
  1940. IF IsSameRegister(destination[Low], source[Low]) THEN temp := GetFreeRegister(IntermediateCode.UnsignedIntegerType(32)) ELSE temp := destination[Low] END;
  1941. Emit3(opRSB, temp, shiftAmountRegister, InstructionSet.NewImmediate(32));
  1942. shiftAmountRegister := temp
  1943. END
  1944. END;
  1945. shiftAmountImmediate := shiftAmountImmediate MOD 32; (* make sure rotation amount is in range 0..31 *)
  1946. IF (shiftAmountRegister.register = None) & (shiftAmountImmediate = 0) THEN
  1947. (* simple rotation by 0: *)
  1948. Emit2(opMOV, destination[Low], source[Low])
  1949. ELSE
  1950. IF irInstruction.op1.type.sizeInBits = 8 THEN
  1951. (* simple 8 bit rotation: *)
  1952. ZeroExtendOperand(source[Low], 8);
  1953. IF IsSameRegister(destination[Low], source[Low]) THEN temp := GetFreeRegister(IntermediateCode.UnsignedIntegerType(32)) ELSE temp := destination[Low] END;
  1954. Emit2(opMOV, temp, InstructionSet.NewRegister(source[Low].register, InstructionSet.shiftROR, shiftAmountRegister.register, shiftAmountImmediate));
  1955. Emit3(opORR, temp, temp, InstructionSet.NewRegister(temp.register, InstructionSet.shiftLSR, None, 8));
  1956. Emit3(opORR, temp, temp, InstructionSet.NewRegister(temp.register, InstructionSet.shiftLSR, None, 16));
  1957. Emit3(opORR, destination[Low], temp, InstructionSet.NewRegister(temp.register, InstructionSet.shiftLSR, None, 24))
  1958. ELSIF irInstruction.op1.type.sizeInBits = 16 THEN
  1959. (* simple 16 bit rotation: *)
  1960. ZeroExtendOperand(source[Low], 16);
  1961. IF IsSameRegister(destination[Low], source[Low]) THEN temp := GetFreeRegister(IntermediateCode.UnsignedIntegerType(32)) ELSE temp := destination[Low] END;
  1962. Emit2(opMOV, temp, InstructionSet.NewRegister(source[Low].register, InstructionSet.shiftROR, shiftAmountRegister.register, shiftAmountImmediate));
  1963. Emit3(opORR, destination[Low], temp, InstructionSet.NewRegister(temp.register, InstructionSet.shiftLSR, None, 16))
  1964. ELSIF irInstruction.op1.type.sizeInBits = 32 THEN
  1965. (* simple 32 bit rotation: *)
  1966. Emit2(opMOV, destination[Low], InstructionSet.NewRegister(source[Low].register, InstructionSet.shiftROR, shiftAmountRegister.register, shiftAmountImmediate))
  1967. ELSE
  1968. HALT(100)
  1969. END
  1970. END
  1971. | IntermediateCode.shl:
  1972. (* left shift: *)
  1973. IF IsComplex(irInstruction.op1) THEN
  1974. (* complex left shift: *)
  1975. IF shiftAmountRegister.register = None THEN
  1976. (* complex left immediate shift: *)
  1977. IF shiftAmountImmediate = 0 THEN
  1978. Emit2(opMOV, destination[High], source[High]);
  1979. Emit2(opMOV, destination[Low], source[Low])
  1980. ELSIF (shiftAmountImmediate > 0) & (shiftAmountImmediate < 32) THEN
  1981. IF ~IsSameRegister(destination[High], source[High]) THEN temp := destination[High] ELSE temp := GetFreeRegister(IntermediateCode.UnsignedIntegerType(32)) END;
  1982. Emit2(opMOV, temp, InstructionSet.NewRegister(source[Low].register, InstructionSet.shiftLSR, None, 32 - shiftAmountImmediate));
  1983. Emit3(opORR, destination[High], temp, InstructionSet.NewRegister(source[High].register, InstructionSet.shiftLSL, None, shiftAmountImmediate));
  1984. Emit2(opMOV, destination[Low], InstructionSet.NewRegister(source[Low].register, InstructionSet.shiftLSL, None, shiftAmountImmediate))
  1985. ELSIF (shiftAmountImmediate >= 32) & (shiftAmountImmediate < 64) THEN
  1986. Emit2(opMOV, destination[High], InstructionSet.NewRegister(source[Low].register, InstructionSet.shiftLSL, None, shiftAmountImmediate - 32));
  1987. Emit2(opMOV, destination[Low], InstructionSet.NewImmediate(0))
  1988. ELSIF shiftAmountImmediate >= 64 THEN
  1989. Emit2(opMOV, destination[High], InstructionSet.NewImmediate(0));
  1990. Emit2(opMOV, destination[Low], InstructionSet.NewImmediate(0))
  1991. ELSE
  1992. HALT(100)
  1993. END
  1994. ELSE
  1995. (* complex left register shift: *)
  1996. IF ~IsSameRegister(destination[Low], source[Low]) THEN temp := destination[Low] ELSE temp := GetFreeRegister(IntermediateCode.UnsignedIntegerType(32)) END;
  1997. Emit2(opCMP, shiftAmountRegister, InstructionSet.NewImmediate(32));
  1998. (* shiftAmount < 32: *)
  1999. Emit3WithCondition(opRSB, temp, shiftAmountRegister, InstructionSet.NewImmediate(32), InstructionSet.conditionLT);
  2000. Emit2WithCondition(opMOV, temp, InstructionSet.NewRegister(source[Low].register, InstructionSet.shiftLSR, temp.register, 0), InstructionSet.conditionLT);
  2001. Emit3WithCondition(opORR, destination[High], temp, InstructionSet.NewRegister(source[High].register, InstructionSet.shiftLSL, shiftAmountRegister.register, 0), InstructionSet.conditionLT);
  2002. Emit2WithCondition(opMOV, destination[Low], InstructionSet.NewRegister(source[Low].register, InstructionSet.shiftLSL, shiftAmountRegister.register, 0), InstructionSet.conditionLT);
  2003. (* shift amount >= 32: *)
  2004. Emit3WithCondition(opSUB, temp, shiftAmountRegister, InstructionSet.NewImmediate(32), InstructionSet.conditionGE);
  2005. Emit2WithCondition(opMOV, destination[High], InstructionSet.NewRegister(source[Low].register, InstructionSet.shiftLSL, temp.register, 0), InstructionSet.conditionGE);
  2006. Emit2WithCondition(opMOV, destination[Low], InstructionSet.NewImmediate(0), InstructionSet.conditionGE)
  2007. END
  2008. ELSE
  2009. (* simple left shift: *)
  2010. IF shiftAmountRegister.register = None THEN
  2011. (* simple left immediate shift *)
  2012. IF (shiftAmountImmediate >= 0) & (shiftAmountImmediate < 32) THEN
  2013. Emit2(opMOV, destination[Low], InstructionSet.NewRegister(source[Low].register, InstructionSet.shiftLSL, None, shiftAmountImmediate)) (* note: LSL has to be in the range 0..31 *)
  2014. ELSIF shiftAmountImmediate >= 32 THEN
  2015. Emit2(opMOV, destination[Low], InstructionSet.NewImmediate(0))
  2016. ELSE
  2017. HALT(100)
  2018. END
  2019. ELSE
  2020. (* simple left register shift: *)
  2021. Emit2(opMOV, destination[Low], InstructionSet.NewRegister(source[Low].register, InstructionSet.shiftLSL, shiftAmountRegister.register, 0))
  2022. END
  2023. END
  2024. | IntermediateCode.shr:
  2025. (* right shift: *)
  2026. (* determine shift mode (depends on if source operand is signed) *)
  2027. IF irInstruction.op1.type.form = IntermediateCode.UnsignedInteger THEN
  2028. (* logical right shift: *)
  2029. shiftMode := InstructionSet.shiftLSR
  2030. ELSE
  2031. (* arithmetic right shift: *)
  2032. shiftMode := InstructionSet.shiftASR
  2033. END;
  2034. IF IsComplex(irInstruction.op1) THEN
  2035. (* complex right shift: *)
  2036. IF shiftAmountRegister.register = None THEN
  2037. (* complex right immediate shift: *)
  2038. IF shiftAmountImmediate = 0 THEN
  2039. Emit2(opMOV, destination[High], source[High]);
  2040. Emit2(opMOV, destination[Low], source[Low])
  2041. ELSIF (shiftAmountImmediate > 0) & (shiftAmountImmediate < 32) THEN
  2042. IF ~IsSameRegister(destination[High], source[High]) THEN temp := destination[High] ELSE temp := GetFreeRegister(IntermediateCode.UnsignedIntegerType(32)) END;
  2043. Emit2(opMOV, temp, InstructionSet.NewRegister(source[High].register, InstructionSet.shiftLSL, None, 32 - shiftAmountImmediate));
  2044. Emit3(opORR, destination[Low], temp, InstructionSet.NewRegister(source[Low].register, InstructionSet.shiftLSR, None, shiftAmountImmediate));
  2045. Emit2(opMOV, destination[High], InstructionSet.NewRegister(source[High].register, shiftMode, None, shiftAmountImmediate))
  2046. ELSIF shiftAmountImmediate >= 32 THEN
  2047. IF shiftAmountImmediate > 64 THEN shiftAmountImmediate := 64 END;
  2048. Emit2(opMOV, destination[Low], InstructionSet.NewRegister(source[High].register, shiftMode, None, shiftAmountImmediate - 32));
  2049. Emit2(opMOV, destination[High], InstructionSet.NewRegister(source[High].register, shiftMode, None, 32))
  2050. ELSE
  2051. HALT(100)
  2052. END
  2053. ELSE
  2054. (* complex right register shift: *)
  2055. IF ~IsSameRegister(destination[High], source[High]) THEN temp := destination[High] ELSE temp := GetFreeRegister(IntermediateCode.UnsignedIntegerType(32)) END;
  2056. Emit2(opCMP, shiftAmountRegister, InstructionSet.NewImmediate(32));
  2057. (* shiftAmount < 32: *)
  2058. Emit3WithCondition(opRSB, temp, shiftAmountRegister, InstructionSet.NewImmediate(32), InstructionSet.conditionLT);
  2059. Emit2WithCondition(opMOV, temp, InstructionSet.NewRegister(source[High].register, InstructionSet.shiftLSL, temp.register, 0), InstructionSet.conditionLT);
  2060. Emit3WithCondition(opORR, destination[Low], temp, InstructionSet.NewRegister(source[Low].register, InstructionSet.shiftLSR, shiftAmountRegister.register, 0), InstructionSet.conditionLT);
  2061. Emit2WithCondition(opMOV, destination[High], InstructionSet.NewRegister(source[High].register, shiftMode, shiftAmountRegister.register, 0), InstructionSet.conditionLT);
  2062. (* shift amount >= 32: *)
  2063. Emit3WithCondition(opSUB, temp, shiftAmountRegister, InstructionSet.NewImmediate(32), InstructionSet.conditionGE);
  2064. Emit2WithCondition(opMOV, destination[Low], InstructionSet.NewRegister(source[High].register, shiftMode, temp.register, 0), InstructionSet.conditionGE);
  2065. Emit2WithCondition(opMOV, destination[High], InstructionSet.NewRegister(source[High].register, shiftMode, shiftAmountRegister.register, 0), InstructionSet.conditionGE)
  2066. END
  2067. ELSE
  2068. (* simple right shift: *)
  2069. SignOrZeroExtendOperand(source[Low], irInstruction.op1.type);
  2070. IF shiftAmountRegister.register = None THEN
  2071. (* simple right immediate shift: *)
  2072. IF shiftAmountImmediate > 32 THEN shiftAmountImmediate := 32 END;
  2073. Emit2(opMOV, destination[Low], InstructionSet.NewRegister(source[Low].register, shiftMode, None, shiftAmountImmediate))
  2074. ELSE
  2075. (* simple right register shift: *)
  2076. Emit2(opMOV, destination[Low], InstructionSet.NewRegister(source[Low].register, shiftMode, shiftAmountRegister.register, 0))
  2077. END
  2078. END
  2079. ELSE
  2080. HALT(100)
  2081. END;
  2082. WriteBack(irInstruction.op1, Low, destination[Low]);
  2083. IF IsComplex(irInstruction.op1) THEN WriteBack(irInstruction.op1, High, destination[High]) END
  2084. END EmitShiftOrRotation;
  2085. PROCEDURE EmitAsm(CONST irInstruction: IntermediateCode.Instruction);
  2086. VAR
  2087. reader: Streams.StringReader;
  2088. procedure: SyntaxTree.Procedure;
  2089. scope: SyntaxTree.Scope;
  2090. symbol: SyntaxTree.Symbol;
  2091. assembler: Assembler.Assembler;
  2092. scanner: Scanner.AssemblerScanner;
  2093. len: LONGINT;
  2094. BEGIN
  2095. len := Strings.Length(irInstruction.op1.string^);
  2096. NEW(reader, len);
  2097. reader.Set(irInstruction.op1.string^);
  2098. (* determine scope of the section *)
  2099. symbol := in.symbol;
  2100. IF symbol = NIL THEN
  2101. scope := NIL
  2102. ELSE
  2103. procedure := symbol(SyntaxTree.Procedure);
  2104. scope := procedure.procedureScope
  2105. END;
  2106. NEW(assembler, diagnostics);
  2107. scanner := Scanner.NewAssemblerScanner(module.moduleName(*module.module.sourceName*), reader, LONGINT(irInstruction.op1.intValue) (* ? *), diagnostics);
  2108. assembler.InlineAssemble(scanner, in, scope, module);
  2109. error := error OR assembler.error
  2110. END EmitAsm;
  2111. PROCEDURE EmitSpecial(VAR instruction: IntermediateCode.Instruction);
  2112. VAR
  2113. psrNumber, code, a, b, c, d: LONGINT;
  2114. register, register2, register3, register4, temp, cpOperand, cpRegister1, cpRegister2, opCode1Operand, opCode2Operand: Operand;
  2115. BEGIN
  2116. CASE instruction.subtype OF
  2117. | GetSP: Emit2(opMOV, opRES, opSP)
  2118. | SetSP: Emit2(opMOV, opSP, RegisterOrImmediateFromIrOperand(instruction.op1, Low, emptyOperand))
  2119. | GetFP: Emit2(opMOV, opRES, opFP)
  2120. | SetFP: Emit2(opMOV, opFP, RegisterOrImmediateFromIrOperand(instruction.op1, Low, emptyOperand))
  2121. | GetLNK: Emit2(opMOV, opRES, opLR)
  2122. | SetLNK: Emit2(opMOV, opLR, RegisterOrImmediateFromIrOperand(instruction.op1, Low, emptyOperand))
  2123. | GetPC: Emit2(opMOV, opRES, opPC)
  2124. | SetPC: Emit2(opMOV, opPC, RegisterOrImmediateFromIrOperand(instruction.op1, Low, emptyOperand))
  2125. | LDPSR, STPSR:
  2126. ASSERT(instruction.op1.type.form IN IntermediateCode.Integer);
  2127. IF instruction.op1.mode # IntermediateCode.ModeImmediate THEN
  2128. Error(instruction.textPosition,"first operand must be immediate")
  2129. ELSIF (instruction.op1.intValue < 0) OR (instruction.op1.intValue > 1) THEN
  2130. Error(instruction.textPosition,"first operand must be 0 or 1")
  2131. ELSE
  2132. IF instruction.op1.intValue = 0 THEN
  2133. psrNumber := InstructionSet.CPSR
  2134. ELSE
  2135. psrNumber := InstructionSet.SPSR
  2136. END;
  2137. register := RegisterFromIrOperand(instruction.op2, Low, emptyOperand);
  2138. IF instruction.subtype = LDPSR THEN
  2139. Emit2(opMSR, InstructionSet.NewRegisterWithFields(psrNumber, {InstructionSet.fieldF, InstructionSet.fieldC}), register)
  2140. ELSE
  2141. temp := GetFreeRegister(IntermediateCode.UnsignedIntegerType(32));
  2142. Emit2(opMRS, temp, InstructionSet.NewRegister(psrNumber, None, None, 0));
  2143. Emit2(opSTR, temp, InstructionSet.NewImmediateOffsetMemory(register.register, 0, {InstructionSet.Increment}))
  2144. END
  2145. END
  2146. | LDCPR, STCPR:
  2147. IF instruction.op1.mode # IntermediateCode.ModeImmediate THEN
  2148. Error(instruction.textPosition,"first operand must be immediate")
  2149. ELSIF (instruction.op2.mode # IntermediateCode.ModeImmediate) THEN
  2150. Error(instruction.textPosition,"second operand must be immediate")
  2151. ELSIF (instruction.op2.intValue < 0) OR (instruction.op2.intValue > 15) THEN
  2152. Error(instruction.textPosition,"second operand must be between 0 or 15")
  2153. ELSE
  2154. code := LONGINT(instruction.op1.intValue); (* code = a00bcdH *)
  2155. a := (code DIV 100000H) MOD 10H; (* opcode1 * 2 *)
  2156. b := (code DIV 100H) MOD 10H; (* coprocessor number *)
  2157. c := (code DIV 10H) MOD 10H; (* opcode2 * 2 *)
  2158. d := code MOD 10H; (* coprocessor register2 number *)
  2159. InstructionSet.InitCoprocessor(cpOperand, InstructionSet.CP0 + b);
  2160. InstructionSet.InitOpcode(opCode1Operand, a DIV 2);
  2161. register := RegisterFromIrOperand(instruction.op3, Low, emptyOperand);
  2162. InstructionSet.InitRegister(cpRegister1, InstructionSet.CR0 + LONGINT(instruction.op2.intValue), None, None, 0);
  2163. InstructionSet.InitRegister(cpRegister2, InstructionSet.CR0 + d, None, None, 0);
  2164. InstructionSet.InitOpcode(opCode2Operand, c DIV 2);
  2165. IF instruction.subtype = LDCPR THEN
  2166. Emit6(opMCR, cpOperand, opCode1Operand, register, cpRegister1, cpRegister2, opCode2Operand)
  2167. ELSE
  2168. temp := GetFreeRegister(IntermediateCode.UnsignedIntegerType(32));
  2169. Emit6(opMRC, cpOperand, opCode1Operand, temp, cpRegister1, cpRegister2, opCode2Operand);
  2170. Emit2(opSTR, temp, InstructionSet.NewImmediateOffsetMemory(register.register, 0, {InstructionSet.Increment}))
  2171. END
  2172. END
  2173. | FLUSH:
  2174. IF instruction.op1.mode # IntermediateCode.ModeImmediate THEN
  2175. Error(instruction.textPosition,"first operand must be immediate")
  2176. ELSIF (instruction.op1.intValue < 0) OR (instruction.op2.intValue > 0FFH) THEN
  2177. Error(instruction.textPosition,"first operand must be between 0 and 255")
  2178. ELSE
  2179. code := LONGINT(instruction.op1.intValue); (* code = aaa1bbbbB *)
  2180. a := (code DIV 20H) MOD 8; (* coprocessor opcode 2 *)
  2181. b := (code MOD 10H); (* coprocessor register2 number *)
  2182. (* examples:
  2183. 9AH = 10011000B -> MCR p15, 0, R0, c7, c10, 4
  2184. 17H = 00010111B -> MCR p15, 0, R0, c7, c7, 0
  2185. *)
  2186. InstructionSet.InitCoprocessor(cpOperand, InstructionSet.CP15);
  2187. InstructionSet.InitOpcode(opCode1Operand, 0);
  2188. InstructionSet.InitRegister(register, InstructionSet.R0, None, None, 0);
  2189. InstructionSet.InitRegister(cpRegister1, InstructionSet.CR7, None, None, 0);
  2190. InstructionSet.InitRegister(cpRegister2, InstructionSet.CR0 + b, None, None, 0);
  2191. InstructionSet.InitOpcode(opCode2Operand, a);
  2192. Emit6(opMCR, cpOperand, opCode1Operand, register, cpRegister1, cpRegister2, opCode2Operand);
  2193. Emit2(opMOV, register, register); (* NOP (register = R0) *)
  2194. Emit2(opMOV, register, register); (* NOP *)
  2195. Emit2(opMOV, register, register); (* NOP *)
  2196. Emit2(opMOV, register, register) (* NOP *)
  2197. END
  2198. | NULL:
  2199. register := RegisterFromIrOperand(instruction.op1, Low, emptyOperand);
  2200. Emit3(opBIC, register, register, InstructionSet.NewImmediate(LONGINT(80000000H)));
  2201. Emit2(opCMP, register, InstructionSet.NewImmediate(0));
  2202. Emit2WithCondition(opMOV, opRES, InstructionSet.NewImmediate(1), InstructionSet.conditionEQ);
  2203. Emit2WithCondition(opMOV, opRES, InstructionSet.NewImmediate(0), InstructionSet.conditionNE);
  2204. | XOR:
  2205. register := RegisterFromIrOperand(instruction.op1, Low, emptyOperand);
  2206. register2 := RegisterFromIrOperand(instruction.op2, Low, emptyOperand);
  2207. (*
  2208. register3 := RegisterFromIrOperand(instruction.op3, Low, emptyOperand);
  2209. *)
  2210. Emit3(opEOR, opRES, register, register2);
  2211. | MULD:
  2212. register := RegisterFromIrOperand(instruction.op1, Low, emptyOperand); (* note that 'register' contains an address *)
  2213. register2 := RegisterFromIrOperand(instruction.op2, Low, emptyOperand);
  2214. register3 := RegisterFromIrOperand(instruction.op3, Low, emptyOperand);
  2215. Emit4(opUMULL, opRES, opRESHI, register2, register3);
  2216. Emit2(opSTR, opRES, InstructionSet.NewImmediateOffsetMemory(register.register, 0, {InstructionSet.Increment})); (* JCH: 15.05.2012 *)
  2217. Emit2(opSTR, opRESHI, InstructionSet.NewImmediateOffsetMemory(register.register, 4, {InstructionSet.Increment}))
  2218. | ADDC:
  2219. register := RegisterFromIrOperand(instruction.op1, Low, emptyOperand);
  2220. register2 := RegisterFromIrOperand(instruction.op2, Low, emptyOperand);
  2221. Emit3(opADC, opRES, register, register2)
  2222. | PACK:
  2223. (* PACK(x, y):
  2224. add y to the binary exponent of y. PACK(x, y) is equivalent to x := x * 2^y. *)
  2225. register := RegisterFromIrOperand(instruction.op1, Low, emptyOperand); (* register = address of x *)
  2226. register2 := RegisterFromIrOperand(instruction.op2, Low, emptyOperand); (* register2 = value of y *)
  2227. register3 := GetFreeRegister(IntermediateCode.UnsignedIntegerType(32)); (* a temporary INTEGER (!) register that is used to store a float *)
  2228. Emit2(opLDR, register3, InstructionSet.NewImmediateOffsetMemory(register.register, 0, {InstructionSet.Increment})); (* register3 = value of x *)
  2229. Emit3(opADD, register3, register3, InstructionSet.NewRegister(register2.register, InstructionSet.shiftLSL, None, 23)); (* increase the (biased) exponent of x by y*)
  2230. Emit2(opSTR, register3, InstructionSet.NewImmediateOffsetMemory(register.register, 0, {InstructionSet.Increment})) (* store new value of x *)
  2231. | UNPK:
  2232. (* UNPK(x, y):
  2233. remove the binary exponent on x and put it into y. UNPK is the reverse operation of PACK. The resulting x is normalized, i.e. 1.0 <= x < 2.0.
  2234. *)
  2235. register := RegisterFromIrOperand(instruction.op1, Low, emptyOperand); (* register = address of x *)
  2236. register2 := RegisterFromIrOperand(instruction.op2, Low, emptyOperand); (* register2 = address of y *)
  2237. register3 := GetFreeRegister(IntermediateCode.UnsignedIntegerType(32)); (* a temporary INTEGER (!) register that is used to store a float *)
  2238. Emit2(opLDR, register3, InstructionSet.NewImmediateOffsetMemory(register.register, 0, {InstructionSet.Increment})); (* register3 = value of x *)
  2239. register4 := GetFreeRegister(IntermediateCode.UnsignedIntegerType(32));
  2240. Emit2(opMOV, register4, InstructionSet.NewRegister(register3.register, InstructionSet.shiftLSR, None, 23)); (* register4 = biased exponent (and sign) of x *)
  2241. Emit3(opSUB, register4, register4, InstructionSet.NewImmediate(127)); (* register4 = exponent of x (biased exponent - 127) *)
  2242. Emit2(opSTR, register4, InstructionSet.NewImmediateOffsetMemory(register2.register, 0, {InstructionSet.Increment})); (* store exponent of x as value for y *)
  2243. Emit3(opSUB, register3, register3, InstructionSet.NewRegister(register4.register, InstructionSet.shiftLSL, None, 23)); (* reduce the biased exponent of x by the value of y *)
  2244. Emit2(opSTR, register3, InstructionSet.NewImmediateOffsetMemory(register.register, 0, {InstructionSet.Increment})) (* store new value of x *)
  2245. ELSE
  2246. HALT(100)
  2247. END
  2248. END EmitSpecial;
  2249. PROCEDURE EmitBr(VAR irInstruction: IntermediateCode.Instruction);
  2250. VAR
  2251. branchDistance: LONGINT;
  2252. isSwapped: BOOLEAN;
  2253. left, right: ARRAY 2 OF Operand;
  2254. temp: Operand;
  2255. irLeft, irRight: IntermediateCode.Operand;
  2256. fixup,failFixup: BinaryCode.Fixup;
  2257. fixupPatternList: ObjectFile.FixupPatterns;
  2258. identifier: ObjectFile.Identifier;
  2259. hiHit, hiFail, lowHit: LONGINT;
  2260. PROCEDURE JmpDest(branchConditionCode: LONGINT);
  2261. BEGIN
  2262. IF (irInstruction.op1.mode = IntermediateCode.ModeImmediate) & (irInstruction.op1.symbol.name = in.name) & (irInstruction.op1.offset = 0) THEN
  2263. (* branch within same section at a certain IR offset *)
  2264. (* optimization: abort if branch is to the next instruction *)
  2265. IF irInstruction.op1.symbolOffset = inPC + 1 THEN
  2266. IF dump # NIL THEN dump.String("branch to next instruction ignored"); dump.Ln END;
  2267. RETURN
  2268. END;
  2269. IF irInstruction.op1.symbolOffset <= inPC THEN
  2270. (* backward branch: calculate the branch distance *)
  2271. branchDistance := in.instructions[irInstruction.op1.symbolOffset].pc - out.pc - 8;
  2272. ASSERT((-33554432 <= branchDistance) & (branchDistance <= 0) & ((ABS(branchDistance) MOD 4) = 0), 200);
  2273. ELSE
  2274. (* forward branch: the distance is not yet known, use some placeholder and add a relative fixup *)
  2275. branchDistance := -4;
  2276. (* TODO: what about a branch to the next instruction? this would require the fixup meachnism to patch a negative value! (-> -4) *)
  2277. NEW(fixupPatternList, 1);
  2278. fixupPatternList[0].offset := 0;
  2279. fixupPatternList[0].bits := 24;
  2280. identifier.name := in.name;
  2281. identifier.fingerprint := in.fingerprint;
  2282. fixup := BinaryCode.NewFixup(BinaryCode.Relative, out.pc, identifier, irInstruction.op1.symbolOffset, -8, -2, fixupPatternList);
  2283. out.fixupList.AddFixup(fixup)
  2284. END;
  2285. Emit1WithCondition(opB, InstructionSet.NewImmediate(branchDistance), branchConditionCode)
  2286. ELSE
  2287. (* any other type of branch -> do register branch *)
  2288. Emit1WithCondition(opBX, RegisterFromIrOperand(irInstruction.op1, Low, emptyOperand), branchConditionCode)
  2289. END;
  2290. END JmpDest;
  2291. PROCEDURE Cmp(CONST left, right: InstructionSet.Operand; float: BOOLEAN);
  2292. BEGIN
  2293. IF float THEN
  2294. IF ~backend.useFPU OR IsComplex(irLeft) (* 64 bit *) THEN
  2295. (* floating point comparisons without VFP unit *)
  2296. temp := GetFreeRegister(IntermediateCode.UnsignedIntegerType(32));
  2297. Emit3WithFlags(opAND, temp, left, right, {InstructionSet.flagS});
  2298. Emit2(opCMP, temp, InstructionSet.NewImmediate(0));
  2299. Emit1WithCondition(opB, InstructionSet.NewImmediate(4), InstructionSet.conditionLT); (* skip two instructions *)
  2300. Emit2(opCMP, left, right);
  2301. Emit1(opB, InstructionSet.NewImmediate(0)); (* skip one instructions *)
  2302. Emit2(opCMP, right, left);
  2303. ELSE
  2304. Emit2(opFCMPS, left, right);
  2305. Emit0(opFMSTAT); (* transfer the VFP flags to the standard ARM flags *)
  2306. END
  2307. ELSE
  2308. Emit2(opCMP, left, right);
  2309. END;
  2310. END Cmp;
  2311. BEGIN
  2312. hiFail := None;
  2313. hiHit := None;
  2314. IF irInstruction.opcode = IntermediateCode.br THEN
  2315. (* unconditional branch: *)
  2316. lowHit := InstructionSet.conditionAL
  2317. ELSE
  2318. (* conditional branch: *)
  2319. irLeft := irInstruction.op2; irRight := irInstruction.op3;
  2320. ASSERT((irLeft.type.form = irRight.type.form) & (irLeft.type.sizeInBits = irRight.type.sizeInBits));
  2321. IF IsInteger(irLeft) THEN
  2322. IF IsComplex(irLeft) THEN
  2323. CASE irInstruction.opcode OF
  2324. | IntermediateCode.breq, IntermediateCode.brne: (* left = right, left # right *)
  2325. lowHit := InstructionSet.conditionEQ;
  2326. left[High] := RegisterFromIrOperand(irLeft, High, emptyOperand);
  2327. right[High] := RegisterOrImmediateFromIrOperand(irRight, High, emptyOperand);
  2328. Emit2(opCMP, left[High], right[High]);
  2329. left[Low] := RegisterFromIrOperand(irLeft, Low, left[High]);
  2330. right[Low] := RegisterOrImmediateFromIrOperand(irRight, Low, right[High]);
  2331. Emit2WithCondition(opCMP, left[Low], right[Low], lowHit);
  2332. IF irInstruction.opcode = IntermediateCode.brne THEN lowHit := InstructionSet.conditionNE END;
  2333. | IntermediateCode.brlt, IntermediateCode.brge: (* left < right, left >= right *)
  2334. IF irInstruction.opcode = IntermediateCode.brlt THEN lowHit := InstructionSet.conditionLT ELSE lowHit := InstructionSet.conditionGE END;
  2335. ASSERT(irLeft.type.form = IntermediateCode.SignedInteger);
  2336. left[Low] := RegisterFromIrOperand(irLeft, Low, emptyOperand);
  2337. right[Low] := RegisterOrImmediateFromIrOperand(irRight, Low, emptyOperand);
  2338. temp := GetFreeRegister(IntermediateCode.UnsignedIntegerType(32));
  2339. Emit3WithFlags(opSUB, temp, left[Low], right[Low], {InstructionSet.flagS});
  2340. left[High] := RegisterFromIrOperand(irLeft, High, left[Low]);
  2341. right[High] := RegisterOrImmediateFromIrOperand(irRight, High, right[Low]);
  2342. Emit3WithFlags(opSBC, temp, left[High], right[High], {InstructionSet.flagS}) (* the high part of the subtraction determines the sign *)
  2343. ELSE
  2344. HALT(100)
  2345. END
  2346. ELSE
  2347. ASSERT((irLeft.type.form IN IntermediateCode.Integer) & (irLeft.type.sizeInBits <= 32));
  2348. (* swap operands if beneficial *)
  2349. IF ~IrOperandIsDirectlyEncodable(irRight, Low) & IrOperandIsDirectlyEncodable(irLeft, Low) THEN
  2350. isSwapped := TRUE;
  2351. SwapIrOperands(irLeft, irRight)
  2352. END;
  2353. left[Low] := RegisterFromIrOperand(irLeft, Low, emptyOperand);
  2354. right[Low] := RegisterOrImmediateFromIrOperand(irRight, Low, emptyOperand);
  2355. SignOrZeroExtendOperand(left[Low], irLeft.type);
  2356. SignOrZeroExtendOperand(right[Low], irRight.type);
  2357. Cmp(left[Low], right[Low], FALSE);
  2358. (* determine condition code for the branch (take into consideration that operands could have been swapped) *)
  2359. CASE irInstruction.opcode OF
  2360. | IntermediateCode.breq: (* left = right *) lowHit := InstructionSet.conditionEQ
  2361. | IntermediateCode.brne: (* left # right *) lowHit := InstructionSet.conditionNE
  2362. | IntermediateCode.brlt: (* left < right *)
  2363. IF irInstruction.op2.type.form = IntermediateCode.UnsignedInteger THEN
  2364. IF isSwapped THEN lowHit := InstructionSet.conditionHI ELSE lowHit := InstructionSet.conditionLO END
  2365. ELSE
  2366. IF isSwapped THEN lowHit := InstructionSet.conditionGT ELSE lowHit := InstructionSet.conditionLT END
  2367. END
  2368. | IntermediateCode.brge: (* left >= right *)
  2369. IF irInstruction.op2.type.form = IntermediateCode.UnsignedInteger THEN
  2370. IF isSwapped THEN lowHit := InstructionSet.conditionLS ELSE lowHit := InstructionSet.conditionHS END
  2371. ELSE
  2372. IF isSwapped THEN lowHit := InstructionSet.conditionLE ELSE lowHit := InstructionSet.conditionGE END
  2373. END
  2374. ELSE HALT(100)
  2375. END
  2376. END
  2377. ELSIF IsSinglePrecisionFloat(irLeft) THEN
  2378. left[Low] := RegisterFromIrOperand(irLeft, Low, emptyOperand);
  2379. right[Low] := RegisterFromIrOperand(irRight, Low, emptyOperand);
  2380. Cmp(left[Low], right[Low], TRUE);
  2381. CASE irInstruction.opcode OF
  2382. | IntermediateCode.breq: (* left = right *) lowHit := InstructionSet.conditionEQ
  2383. | IntermediateCode.brne: (* left # right *) lowHit := InstructionSet.conditionNE
  2384. | IntermediateCode.brlt: (* left < right *) lowHit := InstructionSet.conditionLT
  2385. | IntermediateCode.brge: (* left >= right *) lowHit := InstructionSet.conditionGE
  2386. ELSE HALT(100)
  2387. END
  2388. ELSIF IsDoublePrecisionFloat(irLeft) THEN
  2389. CASE irInstruction.opcode OF
  2390. IntermediateCode.breq:
  2391. hiHit := None; hiFail := InstructionSet.conditionNE; lowHit := InstructionSet.conditionEQ
  2392. |IntermediateCode.brne:
  2393. hiHit := InstructionSet.conditionNE; hiFail := None; lowHit := InstructionSet.conditionNE
  2394. |IntermediateCode.brge:
  2395. IF isSwapped THEN
  2396. hiHit := InstructionSet.conditionLT; hiFail := InstructionSet.conditionGT; lowHit := InstructionSet.conditionLS
  2397. ELSE
  2398. hiHit := InstructionSet.conditionGT; hiFail := InstructionSet.conditionLT; lowHit := InstructionSet.conditionHS
  2399. END;
  2400. |IntermediateCode.brlt:
  2401. IF isSwapped THEN
  2402. hiHit := InstructionSet.conditionGT; hiFail := InstructionSet.conditionLT; lowHit := InstructionSet.conditionHI
  2403. ELSE
  2404. hiHit := InstructionSet.conditionLT; hiFail := InstructionSet.conditionGT; lowHit := InstructionSet.conditionLO
  2405. END;
  2406. END;
  2407. (*
  2408. compare hi part (as float)
  2409. if hiHit then br dest
  2410. elsif hiFail then br fail
  2411. else compare low part (as unsigned int)
  2412. if lowHit then br dest
  2413. end
  2414. end,
  2415. fail:
  2416. *)
  2417. (* hi part *)
  2418. left[High] := RegisterFromIrOperand(irLeft, High, emptyOperand);
  2419. right[High] := RegisterOrImmediateFromIrOperand(irRight, High, emptyOperand);
  2420. Cmp(left[High], right[High], TRUE);
  2421. IF hiHit # None THEN
  2422. JmpDest(hiHit)
  2423. END;
  2424. IF hiFail # None THEN
  2425. NEW(fixupPatternList, 1);
  2426. fixupPatternList[0].offset := 0;
  2427. fixupPatternList[0].bits := 24;
  2428. identifier.name := in.name;
  2429. identifier.fingerprint := in.fingerprint;
  2430. failFixup := BinaryCode.NewFixup(BinaryCode.Relative, out.pc, identifier, irInstruction.op1.symbolOffset, -8, -2, fixupPatternList);
  2431. out.fixupList.AddFixup(failFixup);
  2432. Emit1WithCondition(opB, InstructionSet.NewImmediate(branchDistance), hiFail)
  2433. END;
  2434. (* low part *)
  2435. left[Low] := RegisterFromIrOperand(irLeft, Low, emptyOperand);
  2436. right[Low] := RegisterFromIrOperand(irRight, Low, emptyOperand);
  2437. Cmp(left[Low], right[Low], FALSE);
  2438. ELSE
  2439. HALT(200)
  2440. END
  2441. END;
  2442. JmpDest(lowHit);
  2443. IF failFixup # NIL THEN
  2444. failFixup.SetSymbol(in.name, in.fingerprint, 0, out.pc+failFixup.displacement (* displacement offset computed during operand emission, typically -1 *) );
  2445. failFixup.resolved := in;
  2446. END;
  2447. END EmitBr;
  2448. (* TODO: floats *)
  2449. PROCEDURE EmitConv(VAR irInstruction: IntermediateCode.Instruction);
  2450. VAR
  2451. irDestination, irSource: IntermediateCode.Operand;
  2452. destination, source: ARRAY 2 OF Operand;
  2453. temp: Operand;
  2454. partType: IntermediateCode.Type;
  2455. BEGIN
  2456. irDestination := irInstruction.op1; irSource := irInstruction.op2;
  2457. (* prepare operands *)
  2458. destination[Low] := AcquireDestinationRegister(irDestination, Low, emptyOperand); (* TODO: find more optimal register allocation *)
  2459. source[Low] := RegisterOrImmediateFromIrOperand(irSource, Low, destination[Low]);
  2460. IF IsComplex(irDestination) THEN destination[High]:= AcquireDestinationRegister(irDestination, High, emptyOperand) END;
  2461. IF IsComplex(irSource) THEN source[High] := RegisterOrImmediateFromIrOperand(irSource, High, destination[High]) END; (* note that the corresponding destination register is used as hint *)
  2462. IF IsInteger(irDestination) THEN
  2463. (* to integer: *)
  2464. IF IsComplex(irDestination) THEN
  2465. (* to complex integer: *)
  2466. IF IsInteger(irSource) THEN
  2467. (* integer to complex integer: *)
  2468. IF IsComplex(irSource) THEN
  2469. (* complex integer to complex integer: *)
  2470. MovIfDifferent(destination[Low], source[Low]);
  2471. MovIfDifferent(destination[High], source[High]);
  2472. ELSE
  2473. (* non-complex integer to complex integer: *)
  2474. SignOrZeroExtendOperand(source[Low], irSource.type);
  2475. MovIfDifferent(destination[Low], source[Low]);
  2476. IF irDestination.type.form = IntermediateCode.UnsignedInteger THEN
  2477. Emit2(opMOV, destination[High], InstructionSet.NewImmediate(0));
  2478. ELSE
  2479. (* for signed values the high part is set to 0...0 or 1...1, depending on the sign of the low part *)
  2480. Emit2(opMOV, destination[High], InstructionSet.NewRegister(source[Low].register, InstructionSet.shiftASR, None, 32))
  2481. END
  2482. END
  2483. ELSIF IsSinglePrecisionFloat(irSource) THEN
  2484. ASSERT(backend.useFPU);
  2485. (* single precision float to complex integer: *)
  2486. temp := GetFreeRegister(IntermediateCode.FloatType(32));
  2487. IF irDestination.type.form = IntermediateCode.UnsignedInteger THEN
  2488. (* single precision float to non-complex unsigned integer: *)
  2489. Emit2(opFTOUIS, temp, source[Low]);
  2490. ELSE
  2491. (* single precision float to non-complex signed integer: *)
  2492. Emit2(opFTOSIS, temp, source[Low]);
  2493. END;
  2494. Emit2(opFMRS, destination[Low], temp);
  2495. IF irDestination.type.form = IntermediateCode.UnsignedInteger THEN
  2496. Emit2(opMOV, destination[High], InstructionSet.NewImmediate(0));
  2497. ELSE
  2498. (* for signed values the high part is set to 0...0 or 1...1, depending on the sign of the low part *)
  2499. Emit2(opMOV, destination[High], InstructionSet.NewRegister(destination[Low].register, InstructionSet.shiftASR, None, 32))
  2500. END
  2501. ELSE
  2502. (* anything else to complex-integer: *)
  2503. HALT(200)
  2504. END
  2505. ELSE
  2506. (* to non-complex integer: *)
  2507. IF IsInteger(irSource) THEN
  2508. (* integer to non-complex integer: ignore high part of source *)
  2509. GetPartType(irSource.type, Low, partType);
  2510. SignOrZeroExtendOperand(source[Low], partType);
  2511. MovIfDifferent(destination[Low], source[Low])
  2512. ELSIF IsSinglePrecisionFloat(irSource) THEN
  2513. ASSERT(backend.useFPU);
  2514. (* single precision float to non-complex integer: *)
  2515. temp := GetFreeRegister(IntermediateCode.FloatType(32));
  2516. IF irDestination.type.form = IntermediateCode.UnsignedInteger THEN
  2517. (* single precision float to non-complex unsigned integer: *)
  2518. Emit2(opFTOUIS, temp, source[Low]);
  2519. ELSE
  2520. (* single precision float to non-complex signed integer: *)
  2521. Emit2(opFTOSIS, temp, source[Low]);
  2522. END;
  2523. Emit2(opFMRS, destination[Low], temp)
  2524. ELSE
  2525. (* anything to non-complex integer: *)
  2526. HALT(200)
  2527. END
  2528. END
  2529. ELSIF IsSinglePrecisionFloat(irDestination) THEN
  2530. (* to single precision float: *)
  2531. IF IsInteger(irSource) THEN
  2532. (* integer to single precision float: ignore high part of source *)
  2533. temp := GetFreeRegister(IntermediateCode.FloatType(32));
  2534. Emit2(opFMSR, temp, source[Low]);
  2535. IF irSource.type.form = IntermediateCode.UnsignedInteger THEN
  2536. (* non-complex unsigned integer to single precision float: *)
  2537. Emit2(opFUITOS, destination[Low], temp)
  2538. ELSE
  2539. (* non-complex signed integer to single precision float: *)
  2540. Emit2(opFSITOS, destination[Low], temp)
  2541. END
  2542. ELSIF IsSinglePrecisionFloat(irSource) THEN
  2543. (* single precision float to single precision float: *)
  2544. MovIfDifferent(destination[Low], source[Low])
  2545. ELSE
  2546. (* anything else to single precision float: *)
  2547. HALT(200)
  2548. END
  2549. ELSE
  2550. (* to anything else: *)
  2551. HALT(200)
  2552. END;
  2553. WriteBack(irDestination, Low, destination[Low]);
  2554. IF IsComplex(irDestination) THEN WriteBack(irInstruction.op1, High, destination[High]) END
  2555. END EmitConv;
  2556. (** get the register that is dedicated to store a return value of a function **)
  2557. PROCEDURE ResultRegister(part: LONGINT; type: IntermediateCode.Type): InstructionSet.Operand;
  2558. VAR
  2559. result: Operand;
  2560. BEGIN
  2561. IF (type.form IN IntermediateCode.Integer) OR ~(backend.useFPU) THEN
  2562. IF part = Low THEN result := opRES
  2563. ELSIF part = High THEN result := opRESHI
  2564. ELSE HALT(200)
  2565. END
  2566. ELSIF type.form = IntermediateCode.Float THEN
  2567. ASSERT(type.sizeInBits = 32, 200);
  2568. result := opRESFS
  2569. END;
  2570. RETURN result
  2571. END ResultRegister;
  2572. PROCEDURE EmitReturn(VAR irInstruction: IntermediateCode.Instruction; part: LONGINT);
  2573. VAR
  2574. source: Operand;
  2575. BEGIN
  2576. source := RegisterOrImmediateFromIrOperand(irInstruction.op1, part, ResultRegister(part, irInstruction.op1.type)); (* note: the result register is given as a hint *)
  2577. MovIfDifferent(ResultRegister(part, irInstruction.op1.type), source)
  2578. END EmitReturn;
  2579. PROCEDURE EmitResult(VAR irInstruction: IntermediateCode.Instruction; part: LONGINT);
  2580. VAR
  2581. destinationRegister: Operand;
  2582. BEGIN
  2583. destinationRegister := AcquireDestinationRegister(irInstruction.op1, part, emptyOperand);
  2584. MovIfDifferent(destinationRegister, ResultRegister(part, irInstruction.op1.type));
  2585. WriteBack(irInstruction.op1, part, destinationRegister)
  2586. END EmitResult;
  2587. PROCEDURE EmitTrap(CONST irInstruction: IntermediateCode.Instruction);
  2588. BEGIN
  2589. ASSERT(irInstruction.op1.mode = IntermediateCode.ModeNumber);
  2590. Emit1(opSWI, InstructionSet.NewImmediate(LONGINT(irInstruction.op1.intValue))) (* software interrupt *)
  2591. END EmitTrap;
  2592. PROCEDURE EmitCas(VAR irInstruction: IntermediateCode.Instruction);
  2593. VAR
  2594. addressReg, addressBaseReg, comparandReg, comparandBaseReg, comparatorReg, comparatorBaseReg, tempReg: Operand
  2595. BEGIN
  2596. addressReg := GetFreeRegister(IntermediateCode.UnsignedIntegerType(32));
  2597. addressBaseReg := RegisterFromIrOperand(irInstruction.op1, Low, addressReg);
  2598. MovIfDifferent(addressReg, addressBaseReg);
  2599. IF IntermediateCode.OperandEquals (irInstruction.op2, irInstruction.op3) THEN
  2600. Emit2(opLDR, opRES, InstructionSet.NewImmediateOffsetMemory(addressReg.register, 0, {InstructionSet.Increment}));
  2601. ELSE
  2602. comparandReg := GetFreeRegister(IntermediateCode.UnsignedIntegerType(32));
  2603. comparandBaseReg := RegisterFromIrOperand(irInstruction.op2, Low, comparandReg);
  2604. MovIfDifferent(comparandReg, comparandBaseReg);
  2605. comparatorReg := GetFreeRegister(IntermediateCode.UnsignedIntegerType(32));
  2606. comparatorBaseReg := RegisterFromIrOperand(irInstruction.op3, Low, comparatorReg);
  2607. MovIfDifferent(comparatorReg, comparatorBaseReg);
  2608. Emit2(opLDREX, opRES, addressReg);
  2609. Emit2(opCMP, opRES, comparandReg);
  2610. tempReg := GetFreeRegister(IntermediateCode.UnsignedIntegerType(32));
  2611. Emit3WithCondition(opSTREX, tempReg, comparatorReg, addressReg, InstructionSet.conditionEQ);
  2612. Emit2WithCondition(opCMP, tempReg, InstructionSet.NewImmediate(1), InstructionSet.conditionEQ);
  2613. Emit1WithCondition(opB, InstructionSet.NewImmediate (-24), InstructionSet.conditionEQ);
  2614. END;
  2615. END EmitCas;
  2616. (* possible optimization: use a combination of LDR and LDRB (would be 4x faster on average) *)
  2617. PROCEDURE EmitCopy(VAR irInstruction: IntermediateCode.Instruction);
  2618. VAR
  2619. targetBaseReg, sourceBaseReg, length, lastSourceAddress, currentTargetReg, currentSourceReg, tempReg: Operand;
  2620. BEGIN
  2621. ASSERT((irInstruction.op1.type.form = IntermediateCode.UnsignedInteger) & (irInstruction.op1.type.sizeInBits = 32));
  2622. ASSERT((irInstruction.op2.type.form = IntermediateCode.UnsignedInteger) & (irInstruction.op2.type.sizeInBits = 32));
  2623. ASSERT((irInstruction.op3.type.form = IntermediateCode.UnsignedInteger) & (irInstruction.op3.type.sizeInBits = 32));
  2624. currentTargetReg := GetFreeRegister(IntermediateCode.UnsignedIntegerType(32));
  2625. currentSourceReg := GetFreeRegister(IntermediateCode.UnsignedIntegerType(32));
  2626. (* note that the registers that store the current addresses are used as hints: *)
  2627. targetBaseReg := RegisterFromIrOperand(irInstruction.op1, Low, currentTargetReg);
  2628. sourceBaseReg := RegisterFromIrOperand(irInstruction.op2, Low, currentSourceReg);
  2629. MovIfDifferent(currentTargetReg, targetBaseReg);
  2630. MovIfDifferent(currentSourceReg, sourceBaseReg);
  2631. lastSourceAddress := GetFreeRegister(IntermediateCode.UnsignedIntegerType(32));
  2632. length := RegisterOrImmediateFromIrOperand(irInstruction.op3, Low, lastSourceAddress); (* note that the last source address register is used as hint*)
  2633. Emit3(opADD, lastSourceAddress, sourceBaseReg, length);
  2634. tempReg := GetFreeRegister(IntermediateCode.UnsignedIntegerType(32));
  2635. Emit2WithFlags(opLDR, tempReg, InstructionSet.NewImmediateOffsetMemory(currentSourceReg.register, 1, {InstructionSet.Increment, InstructionSet.PostIndexed}), {InstructionSet.flagB});
  2636. Emit2WithFlags(opSTR, tempReg, InstructionSet.NewImmediateOffsetMemory(currentTargetReg.register, 1, {InstructionSet.Increment, InstructionSet.PostIndexed}), {InstructionSet.flagB});
  2637. Emit2(opCMP, currentSourceReg, lastSourceAddress);
  2638. Emit1WithCondition(opB, InstructionSet.NewImmediate(-20), InstructionSet.conditionLT)
  2639. END EmitCopy;
  2640. PROCEDURE EmitFill(CONST irInstruction: IntermediateCode.Instruction; down: BOOLEAN);
  2641. BEGIN
  2642. HALT(200) (* note that this instruction is not used at the moment *)
  2643. END EmitFill;
  2644. (* PREPARATION OF OPERATIONS *)
  2645. (** swap a pair of IR operands **)
  2646. PROCEDURE SwapIrOperands(VAR left, right: IntermediateCode.Operand);
  2647. VAR
  2648. temp: IntermediateCode.Operand;
  2649. BEGIN
  2650. temp := left;
  2651. left := right;
  2652. right := temp
  2653. END SwapIrOperands;
  2654. PROCEDURE PrepareSingleSourceOp(VAR irInstruction: IntermediateCode.Instruction; part: LONGINT; VAR destinationRegister, sourceOperand: Operand);
  2655. BEGIN
  2656. destinationRegister := AcquireDestinationRegister(irInstruction.op1, part, emptyOperand);
  2657. sourceOperand := RegisterFromIrOperand(irInstruction.op2, part, destinationRegister); (* note that the destination register is used as hint *)
  2658. END PrepareSingleSourceOp;
  2659. PROCEDURE PrepareSingleSourceOpWithImmediate(VAR irInstruction: IntermediateCode.Instruction; part: LONGINT; VAR destinationRegister, sourceOperand: Operand);
  2660. BEGIN
  2661. destinationRegister := AcquireDestinationRegister(irInstruction.op1, part, emptyOperand);
  2662. sourceOperand := RegisterOrImmediateFromIrOperand(irInstruction.op2, part, destinationRegister); (* note that the destination register is used as hint *)
  2663. END PrepareSingleSourceOpWithImmediate;
  2664. PROCEDURE PrepareDoubleSourceOpWithImmediate(CONST irInstruction: IntermediateCode.Instruction; part: LONGINT; VAR destinationRegister, leftSourceOperand, rightSourceOperand: Operand; VAR isSwapped: BOOLEAN);
  2665. VAR
  2666. irDestination, irLeft, irRight: IntermediateCode.Operand;
  2667. BEGIN
  2668. irDestination := irInstruction.op1;
  2669. irLeft := irInstruction.op2;
  2670. irRight := irInstruction.op3;
  2671. destinationRegister:= AcquireDestinationRegister(irDestination, part, emptyOperand);
  2672. (* swap operands such that the right one is an immediate *)
  2673. IF IrOperandIsDirectlyEncodable(irLeft, part) & ~IrOperandIsDirectlyEncodable(irRight, part) THEN
  2674. SwapIrOperands(irLeft, irRight);
  2675. isSwapped := TRUE
  2676. ELSIF IntermediateCode.OperandEquals(irRight, irDestination) THEN
  2677. SwapIrOperands(irLeft, irRight);
  2678. isSwapped := TRUE
  2679. ELSE
  2680. isSwapped := FALSE
  2681. END;
  2682. leftSourceOperand := RegisterFromIrOperand(irLeft, part, destinationRegister); (* the destination register is used as hint *)
  2683. IF IsSameRegister(leftSourceOperand, destinationRegister) THEN
  2684. rightSourceOperand := RegisterOrImmediateFromIrOperand(irRight, part, emptyOperand) (* no hint is provided *)
  2685. ELSE
  2686. rightSourceOperand := RegisterOrImmediateFromIrOperand(irRight, part, destinationRegister) (* the destination register is again used as hint *)
  2687. END
  2688. END PrepareDoubleSourceOpWithImmediate;
  2689. PROCEDURE PrepareDoubleSourceOp(CONST irInstruction: IntermediateCode.Instruction; part: LONGINT; VAR destinationRegister, leftSourceOperand, rightSourceOperand: Operand);
  2690. VAR
  2691. irDestination, irLeft, irRight: IntermediateCode.Operand;
  2692. BEGIN
  2693. irDestination := irInstruction.op1;
  2694. irLeft := irInstruction.op2;
  2695. irRight := irInstruction.op3;
  2696. destinationRegister:= AcquireDestinationRegister(irDestination, part, emptyOperand);
  2697. IF IntermediateCode.OperandEquals(irRight, irDestination) THEN
  2698. leftSourceOperand := RegisterFromIrOperand(irLeft, part, emptyOperand); (* do not use destination register as hint *)
  2699. ELSE
  2700. leftSourceOperand := RegisterFromIrOperand(irLeft, part, destinationRegister); (* the destination register is used as hint *)
  2701. END;
  2702. IF IsSameRegister(leftSourceOperand, destinationRegister) OR IntermediateCode.OperandEquals(irRight, irDestination) THEN
  2703. rightSourceOperand := RegisterFromIrOperand(irRight, part, emptyOperand) (* no hint is provided *)
  2704. ELSE
  2705. rightSourceOperand := RegisterFromIrOperand(irRight, part, destinationRegister) (* the destination register is again used as hint *)
  2706. END
  2707. END PrepareDoubleSourceOp;
  2708. END CodeGeneratorARM;
  2709. BackendARM = OBJECT(IntermediateBackend.IntermediateBackend)
  2710. VAR
  2711. cg: CodeGeneratorARM;
  2712. system: Global.System;
  2713. useFPU: BOOLEAN;
  2714. initLocals: BOOLEAN;
  2715. PROCEDURE & InitBackendARM;
  2716. BEGIN
  2717. useFPU := FALSE;
  2718. InitIntermediateBackend;
  2719. SetRuntimeModuleName(DefaultRuntimeModuleName);
  2720. SetNewObjectFile(TRUE,FALSE);
  2721. system := NIL;
  2722. initLocals := TRUE;
  2723. SetHasLinkRegister;
  2724. END InitBackendARM;
  2725. PROCEDURE Initialize(diagnostics: Diagnostics.Diagnostics; log: Streams.Writer; flags: SET; checker: SemanticChecker.Checker; system: Global.System);
  2726. BEGIN
  2727. Initialize^(diagnostics, log, flags, checker, system);
  2728. NEW(cg, runtimeModuleName, diagnostics, SELF)
  2729. END Initialize;
  2730. PROCEDURE EnterCustomBuiltins;
  2731. VAR
  2732. procedureType: SyntaxTree.ProcedureType;
  2733. parameter: SyntaxTree.Parameter;
  2734. PROCEDURE New;
  2735. BEGIN procedureType := SyntaxTree.NewProcedureType(-1, NIL)
  2736. END New;
  2737. PROCEDURE BoolRet;
  2738. BEGIN procedureType.SetReturnType(system.booleanType)
  2739. END BoolRet;
  2740. PROCEDURE IntRet;
  2741. BEGIN procedureType.SetReturnType(Global.Integer32)
  2742. END IntRet;
  2743. PROCEDURE IntPar;
  2744. BEGIN
  2745. parameter := SyntaxTree.NewParameter(-1, procedureType, SyntaxTree.NewIdentifier(""), SyntaxTree.ValueParameter);
  2746. parameter.SetType(Global.Integer32); procedureType.AddParameter(parameter)
  2747. END IntPar;
  2748. PROCEDURE AddressPar;
  2749. BEGIN
  2750. parameter := SyntaxTree.NewParameter(-1, procedureType, SyntaxTree.NewIdentifier(""), SyntaxTree.ValueParameter);
  2751. parameter.SetType(Global.Unsigned32); procedureType.AddParameter(parameter)
  2752. END AddressPar;
  2753. PROCEDURE IntVarPar;
  2754. BEGIN
  2755. parameter := SyntaxTree.NewParameter(-1, procedureType, SyntaxTree.NewIdentifier(""), SyntaxTree.VarParameter);
  2756. parameter.SetType(Global.Integer32); procedureType.AddParameter(parameter)
  2757. END IntVarPar;
  2758. PROCEDURE RealVarPar;
  2759. BEGIN
  2760. parameter := SyntaxTree.NewParameter(-1, procedureType, SyntaxTree.NewIdentifier(""), SyntaxTree.VarParameter);
  2761. parameter.SetType(Global.Float32); procedureType.AddParameter(parameter)
  2762. END RealVarPar;
  2763. PROCEDURE Finish(CONST name: ARRAY OF CHAR; number: SHORTINT);
  2764. BEGIN Global.NewCustomBuiltin(name, system.systemScope, number, procedureType);
  2765. END Finish;
  2766. BEGIN
  2767. New; IntRet; Finish("SP", GetSP);
  2768. New; AddressPar; Finish("SetSP", SetSP);
  2769. New; IntRet; Finish("FP", GetFP);
  2770. New; AddressPar; Finish("SetFP", SetFP);
  2771. New; IntRet; Finish("PC", GetPC);
  2772. New; AddressPar; Finish("SetPC", SetPC);
  2773. New; IntRet; Finish("LNK", GetLNK);
  2774. New; AddressPar; Finish("SetLNK", SetLNK);
  2775. New; IntPar; IntPar; Finish("LDPSR", LDPSR);
  2776. New; IntPar; IntVarPar; Finish("STPSR", STPSR);
  2777. New; IntPar; IntPar; IntPar; Finish("LDCPR", LDCPR);
  2778. New; IntPar; IntPar; IntVarPar; Finish("STCPR", STCPR);
  2779. New; IntPar; Finish("FLUSH", FLUSH);
  2780. New; BoolRet; IntPar; Finish("NULL", NULL);
  2781. New; IntRet; IntPar; IntPar; Finish("XOR", XOR);
  2782. New; IntVarPar; IntPar; IntPar; Finish("MULD", MULD);
  2783. New; IntVarPar; IntPar; IntPar; Finish("ADDC", ADDC);
  2784. New; RealVarPar; IntPar; Finish("PACK", PACK);
  2785. New; RealVarPar; IntVarPar; Finish("UNPK", UNPK);
  2786. END EnterCustomBuiltins;
  2787. PROCEDURE GetSystem(): Global.System;
  2788. BEGIN
  2789. (* create system object if not yet existing *)
  2790. IF system = NIL THEN
  2791. (* used stack frame layout:
  2792. param 1
  2793. param 2
  2794. ...
  2795. param n-1
  2796. FP+8 -> param n
  2797. FP+4 -> old LR
  2798. FP -> old FP
  2799. FP-4 -> local 1
  2800. local 2
  2801. ...
  2802. spill 1
  2803. spill 2
  2804. ....
  2805. *)
  2806. (*
  2807. codeUnit, dataUnit = 8, 8
  2808. addressSize = 32
  2809. minVarAlign, maxVarAlign = 32, 32
  2810. minParAlign, maxParAlign = 8, 32
  2811. offsetFirstPar = 32 * 2
  2812. registerParameters = 0
  2813. *)
  2814. NEW(system, 8, 8, 32, (*32*) 8, 32, 8, 32, 32 * 2, cooperative);
  2815. IF oberon07 THEN
  2816. IF Trace THEN D.String("Oberon07"); D.Ln END;
  2817. Global.SetDefaultDeclarations(system, 32) (* each basic type uses at least 32 bits -> INTEGER will be 32 bits long *)
  2818. ELSE
  2819. IF Trace THEN D.String("not Oberon07"); D.Ln END;
  2820. Global.SetDefaultDeclarations(system, 8) (* INTEGER will be 16 bits long *)
  2821. END;
  2822. Global.SetDefaultOperators(system);
  2823. EnterCustomBuiltins
  2824. END;
  2825. RETURN system
  2826. END GetSystem;
  2827. (** whether the code generator can generate code for a certain IR instruction
  2828. if not, where to find the runtime procedure that is to be called instead **)
  2829. PROCEDURE SupportedInstruction(CONST irInstruction: IntermediateCode.Instruction; VAR moduleName, procedureName: ARRAY OF CHAR): BOOLEAN;
  2830. BEGIN
  2831. (* only necessary for binary object file format for symbol / module entry in IntermediateBackend *)
  2832. RETURN cg.Supported(irInstruction, moduleName, procedureName);
  2833. END SupportedInstruction;
  2834. (** whether a certain intermediate code immediate value can be directly appear in code
  2835. if not, the value is stored in a const section and loaded from there **)
  2836. PROCEDURE SupportedImmediate(CONST irImmediateOperand: IntermediateCode.Operand): BOOLEAN;
  2837. VAR
  2838. result: BOOLEAN;
  2839. BEGIN
  2840. (* TODO: remove this *)
  2841. RETURN TRUE; (* tentatively generate all immediates, as symbol fixups are not yet implemented *)
  2842. result := FALSE;
  2843. IF (irImmediateOperand.type.form IN IntermediateCode.Integer) & (irImmediateOperand.type.sizeInBits <= 32) THEN
  2844. (* 32 bit integers *)
  2845. IF cg.ValueIsDirectlyEncodable(LONGINT(irImmediateOperand.intValue)) THEN
  2846. (* the value can be directly encoded as an ARM immediate operand *)
  2847. result := TRUE
  2848. ELSIF cg.ValueComposition(LONGINT(irImmediateOperand.intValue), FALSE, emptyOperand) <= 2 THEN (* TODO: find reasonable limit *)
  2849. (* the value can be generated using a limited amount of intructions *)
  2850. result := TRUE
  2851. END
  2852. END;
  2853. RETURN result
  2854. END SupportedImmediate;
  2855. PROCEDURE GenerateBinary(module: Sections.Module; dump: Streams.Writer);
  2856. VAR
  2857. in: Sections.Section;
  2858. out: BinaryCode.Section;
  2859. name: Basic.SectionName;
  2860. procedure: SyntaxTree.Procedure;
  2861. i, j, initialSectionCount: LONGINT;
  2862. (* recompute fixup positions and assign binary sections *)
  2863. PROCEDURE PatchFixups(section: BinaryCode.Section);
  2864. VAR resolved: BinaryCode.Section; fixup: BinaryCode.Fixup; displacement,symbolOffset: LONGINT; in: IntermediateCode.Section;
  2865. symbol: Sections.Section;
  2866. BEGIN
  2867. fixup := section.fixupList.firstFixup;
  2868. WHILE fixup # NIL DO
  2869. symbol := module.allSections.FindByName(fixup.symbol.name);
  2870. IF (symbol # NIL) & (symbol(IntermediateCode.Section).resolved # NIL) THEN
  2871. resolved := symbol(IntermediateCode.Section).resolved(BinaryCode.Section);
  2872. in := symbol(IntermediateCode.Section);
  2873. symbolOffset := fixup.symbolOffset;
  2874. IF symbolOffset = in.pc THEN
  2875. displacement := resolved.pc
  2876. ELSIF (symbolOffset # 0) THEN
  2877. ASSERT(in.pc > symbolOffset);
  2878. displacement := in.instructions[symbolOffset].pc;
  2879. ELSE
  2880. displacement := 0;
  2881. END;
  2882. fixup.SetSymbol(fixup.symbol.name,fixup.symbol.fingerprint,0,fixup.displacement+displacement);
  2883. END;
  2884. fixup := fixup.nextFixup;
  2885. END;
  2886. END PatchFixups;
  2887. (*
  2888. PROCEDURE Resolve(VAR fixup: BinaryCode.Fixup);
  2889. BEGIN
  2890. IF (fixup.symbol.name # "") & (fixup.resolved = NIL) THEN fixup.resolved := module.allSections.FindByName(fixup.symbol.name) END;
  2891. END Resolve;
  2892. (* recompute fixup positions and assign binary sections *)
  2893. PROCEDURE PatchFixups(section: BinaryCode.Section);
  2894. VAR resolved: BinaryCode.Section; fixup: BinaryCode.Fixup; symbolOffset, offsetWithinSection: LONGINT; in: IntermediateCode.Section;
  2895. BEGIN
  2896. fixup := section.fixupList.firstFixup;
  2897. WHILE fixup # NIL DO
  2898. Resolve(fixup);
  2899. IF (fixup.resolved # NIL) & (fixup.resolved(IntermediateCode.Section).resolved # NIL) THEN
  2900. resolved := fixup.resolved(IntermediateCode.Section).resolved(BinaryCode.Section);
  2901. in := fixup.resolved(IntermediateCode.Section);
  2902. (* TODO: is this correct? *)
  2903. symbolOffset := fixup.symbolOffset;
  2904. ASSERT(fixup.symbolOffset < in.pc);
  2905. IF (fixup.symbolOffset # 0) & (symbolOffset < in.pc) THEN
  2906. offsetWithinSection := in.instructions[fixup.symbolOffset].pc;
  2907. (*
  2908. (* TENTATIVE *)
  2909. D.String("FIXUP PATCH:"); D.Ln;
  2910. D.String(" symbol name: "); fixup.symbol.DumpName(D.Log); D.String("/");
  2911. D.String(" symbol offset: "); D.Int(fixup.symbolOffset, 0); D.Ln;
  2912. D.String(" offsetWithinSection"); D.Int(offsetWithinSection, 0); D.Ln;
  2913. D.String(" fixup.displacement (before)"); D.Int(fixup.displacement, 0); D.Ln; ; D.Ln;
  2914. D.Update;
  2915. *)
  2916. (* remove the fixup's symbol offset (in IR units) and change the displacement (in system units) accordingly: *)
  2917. fixup.SetSymbol(fixup.symbol.name, fixup.symbol.fingerprint, 0, offsetWithinSection + fixup.displacement)
  2918. END
  2919. END;
  2920. fixup := fixup.nextFixup;
  2921. END;
  2922. END PatchFixups;
  2923. *)
  2924. BEGIN
  2925. cg.SetModule(module);
  2926. cg.dump := dump;
  2927. FOR i := 0 TO module.allSections.Length() - 1 DO
  2928. in := module.allSections.GetSection(i);
  2929. IF in.type = Sections.InlineCodeSection THEN
  2930. Basic.SegmentedNameToString(in.name, name);
  2931. out := ResolvedSection(in(IntermediateCode.Section));
  2932. cg.dump := out.comments;
  2933. cg.Section(in(IntermediateCode.Section), out);
  2934. IF in.symbol # NIL THEN
  2935. procedure := in.symbol(SyntaxTree.Procedure);
  2936. procedure.procedureScope.body.code.SetBinaryCode(out.os.bits);
  2937. END;
  2938. END
  2939. END;
  2940. initialSectionCount := 0;
  2941. REPEAT
  2942. j := initialSectionCount;
  2943. initialSectionCount := module.allSections.Length() ;
  2944. FOR i := j TO initialSectionCount - 1 DO
  2945. in := module.allSections.GetSection(i);
  2946. Basic.SegmentedNameToString(in.name, name);
  2947. IF (in.type # Sections.InlineCodeSection) (*& (in(IntermediateCode.Section).resolved = NIL) *) THEN
  2948. out := ResolvedSection(in(IntermediateCode.Section));
  2949. cg.Section(in(IntermediateCode.Section),out);
  2950. END
  2951. END
  2952. UNTIL initialSectionCount = module.allSections.Length(); (* process remaining sections that have been added during traversal of sections *)
  2953. FOR i := 0 TO module.allSections.Length() - 1 DO
  2954. in := module.allSections.GetSection(i);
  2955. Basic.SegmentedNameToString(in.name, name);
  2956. in := module.allSections.GetSection(i);
  2957. PatchFixups(in(IntermediateCode.Section).resolved)
  2958. END;
  2959. IF cg.error THEN Error("", Diagnostics.Invalid, Diagnostics.Invalid, "") END
  2960. END GenerateBinary;
  2961. (** create an ARM code module from an intermediate code module **)
  2962. PROCEDURE ProcessIntermediateCodeModule*(intermediateCodeModule: Formats.GeneratedModule): Formats.GeneratedModule;
  2963. VAR
  2964. result: Formats.GeneratedModule;
  2965. BEGIN
  2966. ASSERT(intermediateCodeModule IS Sections.Module);
  2967. result := ProcessIntermediateCodeModule^(intermediateCodeModule);
  2968. IF ~error THEN
  2969. GenerateBinary(result(Sections.Module), dump);
  2970. IF dump # NIL THEN
  2971. dump.Ln; dump.Ln;
  2972. dump.String("------------------ binary code -------------------"); dump.Ln;
  2973. IF (traceString="") OR (traceString="*") THEN
  2974. result.Dump(dump);
  2975. dump.Update
  2976. ELSE
  2977. Sections.DumpFiltered(dump, result(Sections.Module), traceString);
  2978. dump.Update;
  2979. END
  2980. END;
  2981. END;
  2982. RETURN result
  2983. FINALLY
  2984. IF dump # NIL THEN
  2985. dump.Ln; dump.Ln;
  2986. dump.String("------------------ rescued code (code generation trapped) -------------------"); dump.Ln;
  2987. IF (traceString="") OR (traceString="*") THEN
  2988. result.Dump(dump);
  2989. dump.Update
  2990. ELSE
  2991. Sections.DumpFiltered(dump,result(Sections.Module),traceString);
  2992. dump.Update;
  2993. END
  2994. END;
  2995. RETURN result
  2996. END ProcessIntermediateCodeModule;
  2997. PROCEDURE DefineOptions(options: Options.Options);
  2998. BEGIN
  2999. options.Add(0X, UseFPUFlag, Options.Flag);
  3000. options.Add(0X, "noInitLocals", Options.Flag);
  3001. DefineOptions^(options);
  3002. END DefineOptions;
  3003. PROCEDURE GetOptions(options: Options.Options);
  3004. BEGIN
  3005. IF options.GetFlag(UseFPUFlag) THEN useFPU := TRUE END;
  3006. IF options.GetFlag("noInitLocals") THEN initLocals := FALSE END;
  3007. GetOptions^(options);
  3008. END GetOptions;
  3009. PROCEDURE DefaultObjectFileFormat(): Formats.ObjectFileFormat;
  3010. BEGIN RETURN ObjectFileFormat.Get();
  3011. END DefaultObjectFileFormat;
  3012. PROCEDURE DefaultSymbolFileFormat(): Formats.SymbolFileFormat;
  3013. BEGIN RETURN NIL
  3014. END DefaultSymbolFileFormat;
  3015. (** get the name of the backend **)
  3016. PROCEDURE GetDescription(VAR instructionSet: ARRAY OF CHAR);
  3017. BEGIN instructionSet := "ARM"
  3018. END GetDescription;
  3019. PROCEDURE FindPC(x: SyntaxTree.Module; CONST sectionName: ARRAY OF CHAR; sectionOffset: LONGINT);
  3020. VAR
  3021. section: Sections.Section; binarySection: BinaryCode.Section; label: BinaryCode.LabelList; module: Formats.GeneratedModule;
  3022. i: LONGINT; pooledName: Basic.SegmentedName;
  3023. BEGIN
  3024. module := ProcessSyntaxTreeModule(x);
  3025. Basic.ToSegmentedName(sectionName, pooledName);
  3026. i := 0;
  3027. REPEAT
  3028. section := module(Sections.Module).allSections.GetSection(i);
  3029. INC(i);
  3030. UNTIL (i = module(Sections.Module).allSections.Length()) OR (section.name = pooledName);
  3031. IF section.name # pooledName THEN
  3032. diagnostics.Error(module.module.sourceName,Diagnostics.Invalid,Diagnostics.Invalid," could not locate pc");
  3033. ELSE
  3034. binarySection := section(IntermediateCode.Section).resolved;
  3035. label := binarySection.labels;
  3036. WHILE (label # NIL) & (label.offset >= sectionOffset) DO
  3037. label := label.prev;
  3038. END;
  3039. IF label # NIL THEN
  3040. diagnostics.Information(module.module.sourceName,label.position,Diagnostics.Invalid," pc position");
  3041. ELSE
  3042. diagnostics.Error(module.module.sourceName,Diagnostics.Invalid,Diagnostics.Invalid," could not locate pc");
  3043. END;
  3044. END;
  3045. END FindPC;
  3046. END BackendARM;
  3047. VAR
  3048. emptyOperand: Operand;
  3049. PROCEDURE Assert(condition: BOOLEAN; CONST message: ARRAY OF CHAR);
  3050. BEGIN ASSERT(condition, 100)
  3051. END Assert;
  3052. PROCEDURE Halt(CONST message: ARRAY OF CHAR);
  3053. BEGIN HALT(100)
  3054. END Halt;
  3055. PROCEDURE PowerOf2(val: HUGEINT; VAR exp: LONGINT): BOOLEAN;
  3056. BEGIN
  3057. IF val <= 0 THEN RETURN FALSE END;
  3058. exp := 0;
  3059. WHILE ~ODD(val) DO
  3060. val := val DIV 2;
  3061. INC(exp)
  3062. END;
  3063. RETURN val = 1
  3064. END PowerOf2;
  3065. (** get the ARM code section that corresponds to an intermediate code section **)
  3066. PROCEDURE ResolvedSection(irSection: IntermediateCode.Section): BinaryCode.Section;
  3067. VAR
  3068. result: BinaryCode.Section;
  3069. BEGIN
  3070. IF irSection.resolved = NIL THEN
  3071. NEW(result, irSection.type, irSection.priority, 8, irSection.name, irSection.comments # NIL, FALSE);
  3072. (* set fixed position or alignment
  3073. (also make sure that any section has an alignment of at least 4 bytes) *)
  3074. IF ~irSection.fixed & (irSection.positionOrAlignment < 4) THEN
  3075. result.SetAlignment(FALSE, 4)
  3076. ELSE
  3077. result.SetAlignment(irSection.fixed, irSection.positionOrAlignment);
  3078. END;
  3079. irSection.SetResolved(result)
  3080. ELSE
  3081. result := irSection.resolved
  3082. END;
  3083. RETURN result
  3084. END ResolvedSection;
  3085. (** initialize the module **)
  3086. PROCEDURE Init;
  3087. BEGIN InstructionSet.InitOperand(emptyOperand)
  3088. END Init;
  3089. (** get an instance of the ARM backend **)
  3090. PROCEDURE Get*(): Backend.Backend;
  3091. VAR
  3092. result: BackendARM;
  3093. BEGIN
  3094. NEW(result);
  3095. RETURN result
  3096. END Get;
  3097. (* only for testing purposes *)
  3098. PROCEDURE Test*;
  3099. VAR
  3100. codeGenerator: CodeGeneratorARM;
  3101. value, count: LONGINT;
  3102. BEGIN
  3103. NEW(codeGenerator, "", NIL, NIL);
  3104. FOR value := 0 TO 300 BY 1 DO
  3105. count := codeGenerator.ValueComposition(value, FALSE, emptyOperand);
  3106. D.String("value: "); D.Int(value, 0); D.String(" -> "); D.Int(count, 0); D.String(" instructions"); D.Ln;
  3107. END;
  3108. D.Ln; D.Update
  3109. END Test;
  3110. (* TODO: move this to Debugging.Mod or even Streams.Mod *)
  3111. (** write an integer in binary right-justified in a field of at least ABS(w) characters.
  3112. If w < 0 THEN ABS(w) least significant hex digits of 'value' are written (potentially including leading zeros or ones)
  3113. **)
  3114. PROCEDURE DBin*(value: HUGEINT; numberDigits: LONGINT);
  3115. CONST
  3116. MaxBitSize = SIZEOF(HUGEINT) * 8;
  3117. VAR
  3118. i, firstRelevantPos: LONGINT;
  3119. prefixWithSpaces: BOOLEAN;
  3120. chars: ARRAY MaxBitSize OF CHAR;
  3121. prefixChar: CHAR;
  3122. BEGIN
  3123. prefixWithSpaces := numberDigits >= 0;
  3124. numberDigits := ABS(numberDigits);
  3125. (*
  3126. - calculate an array containing the full bitstring
  3127. - determine the position of the first relevant digit
  3128. *)
  3129. firstRelevantPos := 0;
  3130. FOR i := MaxBitSize - 1 TO 0 BY -1 DO
  3131. IF ODD(value) THEN
  3132. chars[i] := '1';
  3133. firstRelevantPos := i (* occurence of a '1' -> changes the first relevant position *)
  3134. ELSE
  3135. chars[i] := '0'
  3136. END;
  3137. value := value DIV 2
  3138. END;
  3139. (* if space prefixing is enabled, limit the number of digits to the relevant digits *)
  3140. IF prefixWithSpaces THEN numberDigits := MAX(numberDigits, MaxBitSize - firstRelevantPos) END;
  3141. IF numberDigits > MaxBitSize THEN
  3142. IF prefixWithSpaces THEN prefixChar := ' ' ELSE prefixChar := chars[0] END; (* use spaces or sign bit *)
  3143. FOR i := 1 TO numberDigits - MaxBitSize DO D.Char(prefixChar) END;
  3144. numberDigits := MaxBitSize
  3145. END;
  3146. ASSERT((numberDigits >= 0) & (numberDigits <= MaxBitSize));
  3147. FOR i := MaxBitSize - numberDigits TO MaxBitSize - 1 DO
  3148. IF prefixWithSpaces & (i < firstRelevantPos) THEN D.Char(' ') ELSE D.Char(chars[i]) END
  3149. END;
  3150. D.Ln;
  3151. END DBin;
  3152. BEGIN
  3153. Init;
  3154. END FoxARMBackend.
  3155. SystemTools.FreeDownTo FoxARMBackend ~