FoxARMBackend.Mod 147 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583
  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.AP));
  1454. mappedArmRegister := InstructionSet.NewRegister(PhysicalRegisterNumber(irDestinationOperand.register, part), None, None, 0);
  1455. MovIfDifferent(mappedArmRegister, register)
  1456. ELSE
  1457. HALT(100)
  1458. END;
  1459. ReleaseHint(register.register)
  1460. END WriteBack;
  1461. PROCEDURE ZeroExtendOperand(operand: Operand; sizeInBits: LONGINT);
  1462. BEGIN
  1463. ASSERT(sizeInBits <= 32);
  1464. IF operand.mode = InstructionSet.modeRegister THEN
  1465. IF sizeInBits = 8 THEN
  1466. Emit3(opAND, operand, operand, InstructionSet.NewImmediate(255)); (* AND reg, reg, 11111111b *)
  1467. ELSIF sizeInBits = 16 THEN
  1468. Emit2(opMOV, operand, InstructionSet.NewRegister(operand.register, InstructionSet.shiftLSL, None, 16));
  1469. Emit2(opMOV, operand, InstructionSet.NewRegister(operand.register, InstructionSet.shiftLSR, None, 16))
  1470. ELSIF sizeInBits = 32 THEN
  1471. (* nothing to do *)
  1472. ELSE
  1473. HALT(100)
  1474. END
  1475. END
  1476. END ZeroExtendOperand;
  1477. PROCEDURE SignExtendOperand(operand: Operand; sizeInBits: LONGINT);
  1478. BEGIN
  1479. ASSERT(sizeInBits <= 32);
  1480. IF operand.mode = InstructionSet.modeRegister THEN
  1481. IF sizeInBits < 32 THEN
  1482. Emit2(opMOV, operand, InstructionSet.NewRegister(operand.register, InstructionSet.shiftLSL, None, 32 - sizeInBits));
  1483. Emit2(opMOV, operand, InstructionSet.NewRegister(operand.register, InstructionSet.shiftASR, None, 32 - sizeInBits))
  1484. END
  1485. END
  1486. END SignExtendOperand;
  1487. (** sign or zero-extends the content of an operand to 32 bits, depending on the IR type **)
  1488. PROCEDURE SignOrZeroExtendOperand(operand: Operand; irType: IntermediateCode.Type);
  1489. BEGIN
  1490. ASSERT(irType.sizeInBits <= 32);
  1491. IF irType.form = IntermediateCode.UnsignedInteger THEN
  1492. ZeroExtendOperand(operand, irType.sizeInBits)
  1493. ELSE
  1494. SignExtendOperand(operand, irType.sizeInBits)
  1495. END
  1496. END SignOrZeroExtendOperand;
  1497. (* ACTUAL CODE GENERATION *)
  1498. PROCEDURE EmitPush(VAR irOperand: IntermediateCode.Operand; part: LONGINT);
  1499. VAR
  1500. register: Operand;
  1501. partType: IntermediateCode.Type;
  1502. (*pc: LONGINT;*)
  1503. BEGIN
  1504. register := RegisterFromIrOperand(irOperand, part, emptyOperand);
  1505. IF ~IsRegisterForType(register.register, IntermediateCode.FloatType(32)) THEN
  1506. Emit2(opSTR, register, InstructionSet.NewImmediateOffsetMemory(InstructionSet.SP, 4, {InstructionSet.Decrement, InstructionSet.PreIndexed}));
  1507. ELSE
  1508. partType := PartType(irOperand.type, part);
  1509. AllocateStack(MAX(4, partType.sizeInBits DIV 8), TRUE,FALSE);
  1510. Store(register, InstructionSet.NewImmediateOffsetMemory(InstructionSet.SP, 0, {InstructionSet.Increment}), PartType(irOperand.type, part));
  1511. END;
  1512. (*
  1513. (* optimization for push chains (THIS DOES NOT WORK IF inEmulation) *)
  1514. IF pushChainLength = 0 THEN
  1515. pc := inPC;
  1516. (* search for consecutive push instructions *)
  1517. WHILE (pc < in.pc) & (in.instructions[pc].opcode = IntermediateCode.push) DO
  1518. ASSERT(in.instructions[pc].op1.mode # IntermediateCode.Undefined);
  1519. INC(pushChainLength, MAX(4, in.instructions[pc].op1.type.sizeInBits DIV 8));
  1520. INC(pc)
  1521. END;
  1522. AllocateStack(pushChainLength, TRUE)
  1523. END;
  1524. DEC(pushChainLength, 4); (* for 64 bit operands, this procedure is executed twice -> the push chain will be decremented by 8 bytes *)
  1525. register := RegisterFromIrOperand(irOperand, part, emptyOperand);
  1526. ASSERT(pushChainLength < InstructionSet.Bits12, 100);
  1527. ASSERT((pushChainLength MOD 4) = 0);
  1528. Store(register, InstructionSet.NewImmediateOffsetMemory(InstructionSet.SP, pushChainLength, {InstructionSet.Increment}), PartType(irOperand.type, part))
  1529. *)
  1530. END EmitPush;
  1531. PROCEDURE EmitPop(VAR irOperand: IntermediateCode.Operand; part: LONGINT);
  1532. VAR
  1533. register: Operand; partType: IntermediateCode.Type;
  1534. BEGIN
  1535. register := AcquireDestinationRegister(irOperand, part, emptyOperand);
  1536. IF ~IsRegisterForType(register.register, IntermediateCode.FloatType(32)) THEN
  1537. (*Emit2(opLDR, register, InstructionSet.NewImmediateOffsetMemory(InstructionSet.SP, 4, {InstructionSet.Increment, InstructionSet.PostIndexed}));*)
  1538. Load(register, InstructionSet.NewImmediateOffsetMemory(InstructionSet.SP, 4, {InstructionSet.Increment, InstructionSet.PostIndexed}), PartType(irOperand.type, part));
  1539. ELSE
  1540. Load(register, InstructionSet.NewImmediateOffsetMemory(InstructionSet.SP, 0, {InstructionSet.Increment}), PartType(irOperand.type, part));
  1541. partType := PartType(irOperand.type, part);
  1542. AllocateStack(-MAX(4, partType.sizeInBits DIV 8), TRUE,FALSE);
  1543. END;
  1544. WriteBack(irOperand, part, register)
  1545. END EmitPop;
  1546. PROCEDURE Resolve(VAR op: IntermediateCode.Operand);
  1547. BEGIN
  1548. IF (op.symbol.name # "") & (op.resolved = NIL) THEN op.resolved := module.allSections.FindByName(op.symbol.name) END
  1549. END Resolve;
  1550. (* call <address>, <parSize> *)
  1551. PROCEDURE EmitCall(VAR irInstruction: IntermediateCode.Instruction);
  1552. VAR
  1553. code: BinaryCode.Section;
  1554. fixup, newFixup: BinaryCode.Fixup;
  1555. BEGIN
  1556. Resolve(irInstruction.op1);
  1557. IF (irInstruction.op1.resolved # NIL) & (irInstruction.op1.resolved.type = Sections.InlineCodeSection) THEN
  1558. (* call of an inline procedure: *)
  1559. code := irInstruction.op1.resolved(IntermediateCode.Section).resolved;
  1560. ASSERT(code # NIL); (* TODO: what if section is not yet resolved, i.e., code has not yet been generated? *)
  1561. IF (out.comments # NIL) THEN
  1562. out.comments.String("inlined code sequence:");
  1563. out.comments.Ln;
  1564. out.comments.Update;
  1565. END;
  1566. (* emit the generated code of the other section *)
  1567. out.CopyBits(code.os.bits, 0, code.os.bits.GetSize());
  1568. (* transfer the fixups *)
  1569. fixup := code.fixupList.firstFixup;
  1570. WHILE fixup # NIL DO
  1571. newFixup := BinaryCode.NewFixup(fixup.mode, fixup.offset + code.pc, fixup.symbol, fixup.symbolOffset, fixup.displacement, fixup.scale, fixup.pattern);
  1572. out.fixupList.AddFixup(newFixup);
  1573. fixup := fixup.nextFixup
  1574. END
  1575. ELSE
  1576. (* store the address of the procedure in a register and branch and link there *)
  1577. Emit1(opBLX, RegisterFromIrOperand(irInstruction.op1, Low, emptyOperand));
  1578. (* remove parameters on stack *)
  1579. AllocateStack(-LONGINT(irInstruction.op2.intValue), TRUE, FALSE)
  1580. END
  1581. END EmitCall;
  1582. (* enter <callingConvention>, <pafSize>, <numRegParams> *)
  1583. PROCEDURE EmitEnter(CONST irInstruction: IntermediateCode.Instruction);
  1584. VAR allocationSize: LONGINT;
  1585. BEGIN
  1586. (* store registers for interrupts, if required *)
  1587. IF (irInstruction.op1.intValue = SyntaxTree.InterruptCallingConvention) THEN (* TODO: needed? *)
  1588. (* push R0-R11, FP and LR *)
  1589. Emit2WithFlags(opSTM, opSP, InstructionSet.NewRegisterList(0, {InstructionSet.FP, InstructionSet.LR, 0..11}), {InstructionSet.flagDB, InstructionSet.flagBaseRegisterUpdate});
  1590. Emit2(opMOV, opFP, opSP);
  1591. END;
  1592. stackSize := 0;
  1593. (* allocate space on stack for local variables *)
  1594. allocationSize := LONGINT(irInstruction.op2.intValue);
  1595. Basic.Align(allocationSize, 4); (* 4 byte alignment *)
  1596. AllocateStack(allocationSize, TRUE, backend.initLocals);
  1597. (* allocate space on stack for register spills *)
  1598. spillStackStart := -stackSize;
  1599. IF spillStack.MaxSize() > 0 THEN AllocateStack(spillStack.MaxSize(), TRUE, FALSE) END
  1600. END EmitEnter;
  1601. (* leave <callingConvention> *)
  1602. PROCEDURE EmitLeave(CONST irInstruction: IntermediateCode.Instruction);
  1603. BEGIN
  1604. (* LDMFD (Full Descending) aka LDMIA (Increment After) *)
  1605. IF (irInstruction.op1.intValue = SyntaxTree.InterruptCallingConvention) THEN
  1606. (* pop R0-R11, FP and LR *)
  1607. Emit2(opMOV, opSP, opFP);
  1608. Emit2WithFlags(opLDM, opSP, InstructionSet.NewRegisterList(0, {InstructionSet.FP, InstructionSet.LR, 0..11}), {InstructionSet.flagIA, InstructionSet.flagBaseRegisterUpdate})
  1609. END
  1610. END EmitLeave;
  1611. (* exit <parSize>, <pcOffset> *)
  1612. PROCEDURE EmitExit(CONST irInstruction: IntermediateCode.Instruction);
  1613. BEGIN
  1614. Emit2(opLDR, opLR, InstructionSet.NewImmediateOffsetMemory(InstructionSet.SP, 4, {InstructionSet.Increment, InstructionSet.PostIndexed}));
  1615. IF (irInstruction.op1.intValue = 0) & (irInstruction.op2.intValue # SyntaxTree.InterruptCallingConvention) THEN
  1616. (* Emit2(opMOV, opPC, opLR) *)
  1617. Emit1(opBX, opLR) (* recommended for better interoperability between ARM and Thumb *)
  1618. ELSE
  1619. IF (irInstruction.op2.intValue = SyntaxTree.InterruptCallingConvention) THEN
  1620. Emit3WithFlags(opSUB, opPC, opLR, InstructionSet.NewImmediate(LONGINT(irInstruction.op1.intValue)),{InstructionSet.flagS})
  1621. ELSE
  1622. (* exit from an ARM interrupt procedure that has a PC offset *)
  1623. Emit3(opSUB, opPC, opLR, InstructionSet.NewImmediate(LONGINT(irInstruction.op1.intValue)))
  1624. END;
  1625. END
  1626. END EmitExit;
  1627. PROCEDURE EmitMov(VAR irInstruction: IntermediateCode.Instruction; part: LONGINT);
  1628. VAR
  1629. destinationRegister, sourceOperand: Operand;
  1630. BEGIN
  1631. IF irInstruction.op1.mode # IntermediateCode.ModeRegister THEN
  1632. (* optimization: mov [?], r? it is more optimal to determine the source operand first *)
  1633. sourceOperand := RegisterOrImmediateFromIrOperand(irInstruction.op2, part, emptyOperand);
  1634. destinationRegister := GetFreeRegisterOrHint(PartType(irInstruction.op2.type, part), sourceOperand) (* note that the source operand (possibly a register) is used as hint *)
  1635. ELSE
  1636. PrepareSingleSourceOpWithImmediate(irInstruction, part, destinationRegister, sourceOperand);
  1637. END;
  1638. MovIfDifferent(destinationRegister, sourceOperand);
  1639. WriteBack(irInstruction.op1, part, destinationRegister)
  1640. END EmitMov;
  1641. (* BITWISE LOGICAL OPERATIONS *)
  1642. PROCEDURE EmitNot(VAR irInstruction: IntermediateCode.Instruction; part: LONGINT);
  1643. VAR
  1644. destination, source: Operand;
  1645. BEGIN
  1646. PrepareSingleSourceOpWithImmediate(irInstruction, part, destination, source);
  1647. Emit2(opMVN, destination, source); (* invert bits *)
  1648. WriteBack(irInstruction.op1, part, destination)
  1649. END EmitNot;
  1650. PROCEDURE EmitAnd(VAR irInstruction: IntermediateCode.Instruction; part: LONGINT);
  1651. VAR
  1652. dummy: BOOLEAN;
  1653. destination, left, right: Operand;
  1654. BEGIN
  1655. PrepareDoubleSourceOpWithImmediate(irInstruction, part, destination, left, right, dummy);
  1656. Emit3(opAND, destination, left, right);
  1657. WriteBack(irInstruction.op1, part, destination)
  1658. END EmitAnd;
  1659. PROCEDURE EmitOr(VAR irInstruction: IntermediateCode.Instruction; part: LONGINT);
  1660. VAR
  1661. dummy: BOOLEAN;
  1662. destination, left, right: Operand;
  1663. BEGIN
  1664. PrepareDoubleSourceOpWithImmediate(irInstruction, part, destination, left, right, dummy);
  1665. Emit3(opORR, destination, left, right);
  1666. WriteBack(irInstruction.op1, part, destination)
  1667. END EmitOr;
  1668. PROCEDURE EmitXor(VAR irInstruction: IntermediateCode.Instruction; part: LONGINT);
  1669. VAR
  1670. dummy: BOOLEAN;
  1671. destination, left, right: Operand;
  1672. BEGIN
  1673. PrepareDoubleSourceOpWithImmediate(irInstruction, part, destination, left, right, dummy);
  1674. Emit3(opEOR, destination, left, right);
  1675. WriteBack(irInstruction.op1, part, destination)
  1676. END EmitXor;
  1677. (* ARITHMETIC OPERATIONS *)
  1678. (*
  1679. - TODO: double precision floats
  1680. - 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)
  1681. *)
  1682. PROCEDURE EmitAddOrSub(VAR irInstruction: IntermediateCode.Instruction);
  1683. VAR
  1684. destination, left, right: Operand;
  1685. (* registerSR0, registerSR1, registerSR2: Operand; *)
  1686. BEGIN
  1687. IF IsSinglePrecisionFloat(irInstruction.op1) THEN
  1688. ASSERT(backend.useFPU);
  1689. PrepareDoubleSourceOp(irInstruction, Low, destination, left, right);
  1690. IF irInstruction.opcode = IntermediateCode.add THEN
  1691. Emit3(opFADDS, destination, left, right)
  1692. ELSE
  1693. Emit3(opFSUBS, destination, left, right)
  1694. END;
  1695. WriteBack(irInstruction.op1, Low, destination)
  1696. ELSIF IsInteger(irInstruction.op1) THEN
  1697. IF IsComplex(irInstruction.op1) THEN
  1698. EmitPartialAddOrSub(irInstruction, Low, TRUE);
  1699. EmitPartialAddOrSub(irInstruction, High, FALSE)
  1700. ELSE
  1701. EmitPartialAddOrSub(irInstruction, Low, FALSE)
  1702. END
  1703. ELSE
  1704. HALT(200)
  1705. END
  1706. END EmitAddOrSub;
  1707. PROCEDURE EmitPartialAddOrSub(CONST irInstruction: IntermediateCode.Instruction; part: LONGINT; doUpdateFlags: BOOLEAN);
  1708. VAR
  1709. destination, left, right, hint: Operand;
  1710. irDestination, irLeft, irRight: IntermediateCode.Operand;
  1711. operation: LONGINT;
  1712. doSwap, doNegateRight: BOOLEAN;
  1713. BEGIN
  1714. irDestination := irInstruction.op1; irLeft := irInstruction.op2; irRight := irInstruction.op3;
  1715. doSwap := FALSE; doNegateRight := FALSE; (* defaults *)
  1716. IF irInstruction.opcode = IntermediateCode.add THEN
  1717. IF IrOperandIsDirectlyEncodable(irRight, part) THEN
  1718. (* add r0, r1, 16 ~> ADD R0, R1, #16 *)
  1719. operation := opADD
  1720. ELSIF IrOperandIsDirectlyEncodable(irLeft, part) THEN
  1721. (* add r0, 16, r1 ~> ADD R0, R1, #16 *)
  1722. operation := opADD; doSwap := TRUE
  1723. ELSIF NegatedIrOperandIsDirectlyEncodable(irRight, part) THEN
  1724. (* add r0, r1, -16 ~> SUB R0, R1, #16 *)
  1725. operation := opSUB; doNegateRight := TRUE
  1726. ELSIF NegatedIrOperandIsDirectlyEncodable(irLeft, part) THEN
  1727. (* add r0, -16, r1 ~> SUB R0, R1, #16 *)
  1728. operation := opSUB; doSwap := TRUE; doNegateRight := TRUE
  1729. ELSE
  1730. operation := opADD
  1731. END
  1732. ELSIF irInstruction.opcode = IntermediateCode.sub THEN
  1733. IF IrOperandIsDirectlyEncodable(irRight, part) THEN
  1734. (* sub r0, r1, 16 ~> SUB R0, R1, #16 *)
  1735. operation := opSUB
  1736. ELSIF IrOperandIsDirectlyEncodable(irLeft, part) THEN
  1737. (* sub r0, 16, r1 ~> RSB R0, R1, #16 *)
  1738. operation := opRSB; doSwap := TRUE
  1739. ELSIF NegatedIrOperandIsDirectlyEncodable(irRight, part) THEN
  1740. (* sub r0, r1, -16 ~> ADD R0, R1, #16 *)
  1741. operation := opADD; doNegateRight := TRUE
  1742. ELSE
  1743. operation := opSUB
  1744. END
  1745. ELSE
  1746. HALT(100)
  1747. END;
  1748. (* get destination operand *)
  1749. destination := AcquireDestinationRegister(irDestination, part, emptyOperand);
  1750. (* get source operands *)
  1751. IF doSwap THEN SwapIrOperands(irLeft, irRight) END; (* if needed, swap operands *)
  1752. (* TODO: revise this! *)
  1753. IF IsSameRegister(right, destination) THEN hint := destination ELSE hint := emptyOperand END;
  1754. left := RegisterFromIrOperand(irLeft, part, hint);
  1755. IF doNegateRight THEN
  1756. ASSERT(NegatedIrOperandIsDirectlyEncodable(irRight, part));
  1757. right := InstructionSet.NewImmediate(-ValueOfPart(irRight.intValue, part))
  1758. ELSE
  1759. right := RegisterOrImmediateFromIrOperand(irRight, part, emptyOperand)
  1760. END;
  1761. (* if needed, use operation that incorporates carry *)
  1762. IF part # Low THEN
  1763. CASE operation OF
  1764. | opADD: operation := opADC
  1765. | opSUB: operation := opSBC
  1766. | opRSB: operation := opRSC
  1767. ELSE HALT(100)
  1768. END
  1769. END;
  1770. IF doUpdateFlags THEN
  1771. Emit3WithFlags(operation, destination, left, right, {InstructionSet.flagS})
  1772. ELSE
  1773. Emit3(operation, destination, left, right)
  1774. END;
  1775. WriteBack(irDestination, part, destination)
  1776. END EmitPartialAddOrSub;
  1777. PROCEDURE EmitMul(VAR irInstruction: IntermediateCode.Instruction);
  1778. VAR
  1779. destination, left, right: ARRAY 2 OF Operand;
  1780. BEGIN
  1781. IF IsSinglePrecisionFloat(irInstruction.op1) THEN
  1782. ASSERT(backend.useFPU);
  1783. PrepareDoubleSourceOp(irInstruction, Low, destination[Low], left[Low], right[Low]);
  1784. Emit3(opFMULS, destination[Low], left[Low], right[Low]);
  1785. WriteBack(irInstruction.op1, Low, destination[Low])
  1786. ELSIF IsInteger(irInstruction.op1) THEN
  1787. IF IsComplex(irInstruction.op1) THEN
  1788. ASSERT(irInstruction.op1.type.form = IntermediateCode.SignedInteger);
  1789. HALT(200);
  1790. (* TODO: fix signed 64 bit integer multiplication:
  1791. PrepareDoubleSourceOp(irInstruction, Low, destination[Low], left[Low], right[Low]);
  1792. PrepareDoubleSourceOp(irInstruction, High, destination[High], left[High], right[High]);
  1793. Emit4(opSMULL, destination[Low], destination[High], left[Low], right[Low]); (* signed long multiplication *)
  1794. Emit3(opMLA, destination[High], left[Low], right[High]); (* multiply and accumulate *)
  1795. Emit3(opMLA, destination[High], left[High], right[Low]);
  1796. WriteBack(irInstruction.op1, Low, destination[Low]);
  1797. WriteBack(irInstruction.op1, High, destination[High]);
  1798. *)
  1799. ELSE
  1800. (* signed or unsigned integer multiplication: *)
  1801. PrepareDoubleSourceOp(irInstruction, Low, destination[Low], left[Low], right[Low]);
  1802. SignOrZeroExtendOperand(left[Low], irInstruction.op2.type);
  1803. SignOrZeroExtendOperand(right[Low], irInstruction.op3.type);
  1804. Emit3(opMUL, destination[Low], left[Low], right[Low]); (* note that the sign does not matter for the least 32 significant bits *)
  1805. WriteBack(irInstruction.op1, Low, destination[Low])
  1806. END
  1807. ELSE
  1808. HALT(200)
  1809. END
  1810. END EmitMul;
  1811. PROCEDURE EmitDiv(VAR irInstruction: IntermediateCode.Instruction);
  1812. VAR
  1813. destination, left, right: Operand;
  1814. BEGIN
  1815. IF IsSinglePrecisionFloat(irInstruction.op1) THEN
  1816. ASSERT(backend.useFPU);
  1817. PrepareDoubleSourceOp(irInstruction, Low, destination, left, right);
  1818. Emit3(opFDIVS, destination, left, right);
  1819. WriteBack(irInstruction.op1, Low, destination)
  1820. ELSE
  1821. HALT(200)
  1822. END
  1823. END EmitDiv;
  1824. PROCEDURE EmitMod(CONST irInstruction: IntermediateCode.Instruction);
  1825. BEGIN HALT(100) (* handled by a runtime call *)
  1826. END EmitMod;
  1827. PROCEDURE EmitAbs(VAR irInstruction: IntermediateCode.Instruction);
  1828. VAR
  1829. destination, source: ARRAY 2 OF Operand;
  1830. zero: Operand;
  1831. BEGIN
  1832. IF IsInteger(irInstruction.op1) THEN
  1833. zero := InstructionSet.NewImmediate(0);
  1834. IF IsComplex(irInstruction.op1) THEN
  1835. PrepareSingleSourceOpWithImmediate(irInstruction, Low, destination[Low], source[Low]);
  1836. PrepareSingleSourceOpWithImmediate(irInstruction, High, destination[High], source[High]);
  1837. MovIfDifferent(destination[Low], source[Low]);
  1838. MovIfDifferent(destination[High], source[High]);
  1839. (* negate the value if it is negative *)
  1840. IF irInstruction.op2.type.form = IntermediateCode.SignedInteger THEN
  1841. Emit2(opCMP, destination[High], zero); (* note that only the high part has to be looked at to determine the sign *)
  1842. Emit1WithCondition(opB, InstructionSet.NewImmediate(4), InstructionSet.conditionGE); (* BGE #4 = skip the following two instructions if greater or equal *)
  1843. Emit3WithFlags(opRSB, destination[Low], destination[Low], zero, {InstructionSet.flagS}); (* RSBS *)
  1844. Emit3(opRSC, destination[High], destination[High], zero); (* RSC - reverse subtraction with carry *)
  1845. END;
  1846. WriteBack(irInstruction.op1, Low, destination[Low]);
  1847. WriteBack(irInstruction.op1, High, destination[High])
  1848. ELSE
  1849. PrepareSingleSourceOpWithImmediate(irInstruction, Low, destination[Low], source[Low]);
  1850. SignOrZeroExtendOperand(source[Low], irInstruction.op2.type);
  1851. MovIfDifferent(destination[Low], source[Low]);
  1852. (* negate the value if it is negative *)
  1853. IF irInstruction.op2.type.form = IntermediateCode.SignedInteger THEN
  1854. SignExtendOperand(destination[Low], irInstruction.op2.type.sizeInBits);
  1855. Emit2(opCMP, destination[Low], zero);
  1856. Emit3WithCondition(opRSB, destination[Low], destination[Low], zero, InstructionSet.conditionLT)
  1857. END;
  1858. WriteBack(irInstruction.op1, Low, destination[Low])
  1859. END
  1860. ELSIF IsSinglePrecisionFloat(irInstruction.op1) THEN
  1861. ASSERT(backend.useFPU);
  1862. PrepareSingleSourceOp(irInstruction, Low, destination[Low], source[Low]);
  1863. Emit2(opFABSS, destination[Low], source[Low]);
  1864. WriteBack(irInstruction.op1, Low, destination[Low])
  1865. ELSE
  1866. HALT(200)
  1867. END
  1868. END EmitAbs;
  1869. (* TODO: floats *)
  1870. PROCEDURE EmitNeg(VAR irInstruction: IntermediateCode.Instruction);
  1871. VAR
  1872. destination, source: ARRAY 2 OF Operand;
  1873. zero: Operand;
  1874. BEGIN
  1875. IF IsInteger(irInstruction.op1) THEN
  1876. zero := InstructionSet.NewImmediate(0);
  1877. IF IsComplex(irInstruction.op1) THEN
  1878. PrepareSingleSourceOpWithImmediate(irInstruction, Low, destination[Low], source[Low]);
  1879. PrepareSingleSourceOpWithImmediate(irInstruction, High, destination[High], source[High]);
  1880. Emit3WithFlags(opRSB, destination[Low], source[Low], zero, {InstructionSet.flagS}); (* RSBS *)
  1881. Emit3(opRSC, destination[High], source[High], zero); (* RSC - reverse subtraction with carry *)
  1882. WriteBack(irInstruction.op1, Low, destination[Low]);
  1883. WriteBack(irInstruction.op1, High, destination[High])
  1884. ELSE
  1885. PrepareSingleSourceOpWithImmediate(irInstruction, Low, destination[Low], source[Low]);
  1886. SignOrZeroExtendOperand(source[Low], irInstruction.op2.type);
  1887. Emit3(opRSB, destination[Low], source[Low], zero); (* reverse subtraction with zero *)
  1888. WriteBack(irInstruction.op1, Low, destination[Low])
  1889. END
  1890. ELSIF IsSinglePrecisionFloat(irInstruction.op1) THEN
  1891. ASSERT(backend.useFPU);
  1892. PrepareSingleSourceOp(irInstruction, Low, destination[Low], source[Low]);
  1893. Emit2(opFNEGS, destination[Low], source[Low]);
  1894. WriteBack(irInstruction.op1, Low, destination[Low])
  1895. ELSE
  1896. HALT(200)
  1897. END
  1898. END EmitNeg;
  1899. (*
  1900. - note that the ARM instructions ASR, LSL, LSR, ROR, etc. are actually aliases for a MOV with a shifted register operand
  1901. - note that ARM does not support LSL by 32 bits
  1902. - 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)
  1903. *)
  1904. PROCEDURE EmitShiftOrRotation(VAR irInstruction: IntermediateCode.Instruction);
  1905. VAR
  1906. shiftAmountImmediate, shiftMode: LONGINT;
  1907. destination, source: ARRAY 2 OF Operand;
  1908. irShiftOperand: IntermediateCode.Operand;
  1909. temp, shiftAmountRegister: Operand;
  1910. BEGIN
  1911. ASSERT(IsInteger(irInstruction.op1), 100); (* shifts are only allowed on integers *)
  1912. destination[Low] := AcquireDestinationRegister(irInstruction.op1, Low, emptyOperand);
  1913. source[Low] := RegisterFromIrOperand(irInstruction.op2, Low, emptyOperand); (* note that the destination register cannot be used as hint for the source *)
  1914. IF IsComplex(irInstruction.op1) THEN
  1915. destination[High] := AcquireDestinationRegister(irInstruction.op1, High, emptyOperand);
  1916. source[High] := RegisterFromIrOperand(irInstruction.op2, High, emptyOperand); (* note that the destination register cannot be used as hint for the source *)
  1917. END;
  1918. irShiftOperand := irInstruction.op3;
  1919. ASSERT((irShiftOperand.type.form = IntermediateCode.UnsignedInteger) & ~IsComplex(irShiftOperand)); (* the shift operand is assumed to be a single part unsigned integer *)
  1920. (* use ARM register or shift immediate to represent IR shift operand *)
  1921. IF (irShiftOperand.mode = IntermediateCode.ModeImmediate) & (irShiftOperand.symbol.name = "") THEN
  1922. shiftAmountImmediate := LONGINT(irShiftOperand.intValue); (* note that at this point the shift amount could also be >= 32 *)
  1923. shiftAmountRegister := emptyOperand;
  1924. ASSERT(shiftAmountImmediate >= 0);
  1925. ELSE
  1926. shiftAmountImmediate := 0;
  1927. shiftAmountRegister := RegisterFromIrOperand(irShiftOperand, Low, emptyOperand);
  1928. ZeroExtendOperand(shiftAmountRegister, irShiftOperand.type.sizeInBits)
  1929. END;
  1930. CASE irInstruction.opcode OF
  1931. | IntermediateCode.ror, IntermediateCode.rol:
  1932. (* rotation: *)
  1933. IF IsComplex(irInstruction.op1) THEN HALT(100) END; (* complex rotations are handled as runtime calls *)
  1934. IF irInstruction.opcode = IntermediateCode.rol THEN
  1935. (* simple left rotation: rotate right with complementary rotation amount, since ARM does not support left rotations *)
  1936. IF shiftAmountRegister.register = None THEN
  1937. shiftAmountImmediate := 32 - shiftAmountImmediate
  1938. ELSE
  1939. IF IsSameRegister(destination[Low], source[Low]) THEN temp := GetFreeRegister(IntermediateCode.UnsignedIntegerType(32)) ELSE temp := destination[Low] END;
  1940. Emit3(opRSB, temp, shiftAmountRegister, InstructionSet.NewImmediate(32));
  1941. shiftAmountRegister := temp
  1942. END
  1943. END;
  1944. shiftAmountImmediate := shiftAmountImmediate MOD 32; (* make sure rotation amount is in range 0..31 *)
  1945. IF (shiftAmountRegister.register = None) & (shiftAmountImmediate = 0) THEN
  1946. (* simple rotation by 0: *)
  1947. Emit2(opMOV, destination[Low], source[Low])
  1948. ELSE
  1949. IF irInstruction.op1.type.sizeInBits = 8 THEN
  1950. (* simple 8 bit rotation: *)
  1951. ZeroExtendOperand(source[Low], 8);
  1952. IF IsSameRegister(destination[Low], source[Low]) THEN temp := GetFreeRegister(IntermediateCode.UnsignedIntegerType(32)) ELSE temp := destination[Low] END;
  1953. Emit2(opMOV, temp, InstructionSet.NewRegister(source[Low].register, InstructionSet.shiftROR, shiftAmountRegister.register, shiftAmountImmediate));
  1954. Emit3(opORR, temp, temp, InstructionSet.NewRegister(temp.register, InstructionSet.shiftLSR, None, 8));
  1955. Emit3(opORR, temp, temp, InstructionSet.NewRegister(temp.register, InstructionSet.shiftLSR, None, 16));
  1956. Emit3(opORR, destination[Low], temp, InstructionSet.NewRegister(temp.register, InstructionSet.shiftLSR, None, 24))
  1957. ELSIF irInstruction.op1.type.sizeInBits = 16 THEN
  1958. (* simple 16 bit rotation: *)
  1959. ZeroExtendOperand(source[Low], 16);
  1960. IF IsSameRegister(destination[Low], source[Low]) THEN temp := GetFreeRegister(IntermediateCode.UnsignedIntegerType(32)) ELSE temp := destination[Low] END;
  1961. Emit2(opMOV, temp, InstructionSet.NewRegister(source[Low].register, InstructionSet.shiftROR, shiftAmountRegister.register, shiftAmountImmediate));
  1962. Emit3(opORR, destination[Low], temp, InstructionSet.NewRegister(temp.register, InstructionSet.shiftLSR, None, 16))
  1963. ELSIF irInstruction.op1.type.sizeInBits = 32 THEN
  1964. (* simple 32 bit rotation: *)
  1965. Emit2(opMOV, destination[Low], InstructionSet.NewRegister(source[Low].register, InstructionSet.shiftROR, shiftAmountRegister.register, shiftAmountImmediate))
  1966. ELSE
  1967. HALT(100)
  1968. END
  1969. END
  1970. | IntermediateCode.shl:
  1971. (* left shift: *)
  1972. IF IsComplex(irInstruction.op1) THEN
  1973. (* complex left shift: *)
  1974. IF shiftAmountRegister.register = None THEN
  1975. (* complex left immediate shift: *)
  1976. IF shiftAmountImmediate = 0 THEN
  1977. Emit2(opMOV, destination[High], source[High]);
  1978. Emit2(opMOV, destination[Low], source[Low])
  1979. ELSIF (shiftAmountImmediate > 0) & (shiftAmountImmediate < 32) THEN
  1980. IF ~IsSameRegister(destination[High], source[High]) THEN temp := destination[High] ELSE temp := GetFreeRegister(IntermediateCode.UnsignedIntegerType(32)) END;
  1981. Emit2(opMOV, temp, InstructionSet.NewRegister(source[Low].register, InstructionSet.shiftLSR, None, 32 - shiftAmountImmediate));
  1982. Emit3(opORR, destination[High], temp, InstructionSet.NewRegister(source[High].register, InstructionSet.shiftLSL, None, shiftAmountImmediate));
  1983. Emit2(opMOV, destination[Low], InstructionSet.NewRegister(source[Low].register, InstructionSet.shiftLSL, None, shiftAmountImmediate))
  1984. ELSIF (shiftAmountImmediate >= 32) & (shiftAmountImmediate < 64) THEN
  1985. Emit2(opMOV, destination[High], InstructionSet.NewRegister(source[Low].register, InstructionSet.shiftLSL, None, shiftAmountImmediate - 32));
  1986. Emit2(opMOV, destination[Low], InstructionSet.NewImmediate(0))
  1987. ELSIF shiftAmountImmediate >= 64 THEN
  1988. Emit2(opMOV, destination[High], InstructionSet.NewImmediate(0));
  1989. Emit2(opMOV, destination[Low], InstructionSet.NewImmediate(0))
  1990. ELSE
  1991. HALT(100)
  1992. END
  1993. ELSE
  1994. (* complex left register shift: *)
  1995. IF ~IsSameRegister(destination[Low], source[Low]) THEN temp := destination[Low] ELSE temp := GetFreeRegister(IntermediateCode.UnsignedIntegerType(32)) END;
  1996. Emit2(opCMP, shiftAmountRegister, InstructionSet.NewImmediate(32));
  1997. (* shiftAmount < 32: *)
  1998. Emit3WithCondition(opRSB, temp, shiftAmountRegister, InstructionSet.NewImmediate(32), InstructionSet.conditionLT);
  1999. Emit2WithCondition(opMOV, temp, InstructionSet.NewRegister(source[Low].register, InstructionSet.shiftLSR, temp.register, 0), InstructionSet.conditionLT);
  2000. Emit3WithCondition(opORR, destination[High], temp, InstructionSet.NewRegister(source[High].register, InstructionSet.shiftLSL, shiftAmountRegister.register, 0), InstructionSet.conditionLT);
  2001. Emit2WithCondition(opMOV, destination[Low], InstructionSet.NewRegister(source[Low].register, InstructionSet.shiftLSL, shiftAmountRegister.register, 0), InstructionSet.conditionLT);
  2002. (* shift amount >= 32: *)
  2003. Emit3WithCondition(opSUB, temp, shiftAmountRegister, InstructionSet.NewImmediate(32), InstructionSet.conditionGE);
  2004. Emit2WithCondition(opMOV, destination[High], InstructionSet.NewRegister(source[Low].register, InstructionSet.shiftLSL, temp.register, 0), InstructionSet.conditionGE);
  2005. Emit2WithCondition(opMOV, destination[Low], InstructionSet.NewImmediate(0), InstructionSet.conditionGE)
  2006. END
  2007. ELSE
  2008. (* simple left shift: *)
  2009. IF shiftAmountRegister.register = None THEN
  2010. (* simple left immediate shift *)
  2011. IF (shiftAmountImmediate >= 0) & (shiftAmountImmediate < 32) THEN
  2012. Emit2(opMOV, destination[Low], InstructionSet.NewRegister(source[Low].register, InstructionSet.shiftLSL, None, shiftAmountImmediate)) (* note: LSL has to be in the range 0..31 *)
  2013. ELSIF shiftAmountImmediate >= 32 THEN
  2014. Emit2(opMOV, destination[Low], InstructionSet.NewImmediate(0))
  2015. ELSE
  2016. HALT(100)
  2017. END
  2018. ELSE
  2019. (* simple left register shift: *)
  2020. Emit2(opMOV, destination[Low], InstructionSet.NewRegister(source[Low].register, InstructionSet.shiftLSL, shiftAmountRegister.register, 0))
  2021. END
  2022. END
  2023. | IntermediateCode.shr:
  2024. (* right shift: *)
  2025. (* determine shift mode (depends on if source operand is signed) *)
  2026. IF irInstruction.op1.type.form = IntermediateCode.UnsignedInteger THEN
  2027. (* logical right shift: *)
  2028. shiftMode := InstructionSet.shiftLSR
  2029. ELSE
  2030. (* arithmetic right shift: *)
  2031. shiftMode := InstructionSet.shiftASR
  2032. END;
  2033. IF IsComplex(irInstruction.op1) THEN
  2034. (* complex right shift: *)
  2035. IF shiftAmountRegister.register = None THEN
  2036. (* complex right immediate shift: *)
  2037. IF shiftAmountImmediate = 0 THEN
  2038. Emit2(opMOV, destination[High], source[High]);
  2039. Emit2(opMOV, destination[Low], source[Low])
  2040. ELSIF (shiftAmountImmediate > 0) & (shiftAmountImmediate < 32) THEN
  2041. IF ~IsSameRegister(destination[High], source[High]) THEN temp := destination[High] ELSE temp := GetFreeRegister(IntermediateCode.UnsignedIntegerType(32)) END;
  2042. Emit2(opMOV, temp, InstructionSet.NewRegister(source[High].register, InstructionSet.shiftLSL, None, 32 - shiftAmountImmediate));
  2043. Emit3(opORR, destination[Low], temp, InstructionSet.NewRegister(source[Low].register, InstructionSet.shiftLSR, None, shiftAmountImmediate));
  2044. Emit2(opMOV, destination[High], InstructionSet.NewRegister(source[High].register, shiftMode, None, shiftAmountImmediate))
  2045. ELSIF shiftAmountImmediate >= 32 THEN
  2046. IF shiftAmountImmediate > 64 THEN shiftAmountImmediate := 64 END;
  2047. Emit2(opMOV, destination[Low], InstructionSet.NewRegister(source[High].register, shiftMode, None, shiftAmountImmediate - 32));
  2048. Emit2(opMOV, destination[High], InstructionSet.NewRegister(source[High].register, shiftMode, None, 32))
  2049. ELSE
  2050. HALT(100)
  2051. END
  2052. ELSE
  2053. (* complex right register shift: *)
  2054. IF ~IsSameRegister(destination[High], source[High]) THEN temp := destination[High] ELSE temp := GetFreeRegister(IntermediateCode.UnsignedIntegerType(32)) END;
  2055. Emit2(opCMP, shiftAmountRegister, InstructionSet.NewImmediate(32));
  2056. (* shiftAmount < 32: *)
  2057. Emit3WithCondition(opRSB, temp, shiftAmountRegister, InstructionSet.NewImmediate(32), InstructionSet.conditionLT);
  2058. Emit2WithCondition(opMOV, temp, InstructionSet.NewRegister(source[High].register, InstructionSet.shiftLSL, temp.register, 0), InstructionSet.conditionLT);
  2059. Emit3WithCondition(opORR, destination[Low], temp, InstructionSet.NewRegister(source[Low].register, InstructionSet.shiftLSR, shiftAmountRegister.register, 0), InstructionSet.conditionLT);
  2060. Emit2WithCondition(opMOV, destination[High], InstructionSet.NewRegister(source[High].register, shiftMode, shiftAmountRegister.register, 0), InstructionSet.conditionLT);
  2061. (* shift amount >= 32: *)
  2062. Emit3WithCondition(opSUB, temp, shiftAmountRegister, InstructionSet.NewImmediate(32), InstructionSet.conditionGE);
  2063. Emit2WithCondition(opMOV, destination[Low], InstructionSet.NewRegister(source[High].register, shiftMode, temp.register, 0), InstructionSet.conditionGE);
  2064. Emit2WithCondition(opMOV, destination[High], InstructionSet.NewRegister(source[High].register, shiftMode, shiftAmountRegister.register, 0), InstructionSet.conditionGE)
  2065. END
  2066. ELSE
  2067. (* simple right shift: *)
  2068. SignOrZeroExtendOperand(source[Low], irInstruction.op1.type);
  2069. IF shiftAmountRegister.register = None THEN
  2070. (* simple right immediate shift: *)
  2071. IF shiftAmountImmediate > 32 THEN shiftAmountImmediate := 32 END;
  2072. Emit2(opMOV, destination[Low], InstructionSet.NewRegister(source[Low].register, shiftMode, None, shiftAmountImmediate))
  2073. ELSE
  2074. (* simple right register shift: *)
  2075. Emit2(opMOV, destination[Low], InstructionSet.NewRegister(source[Low].register, shiftMode, shiftAmountRegister.register, 0))
  2076. END
  2077. END
  2078. ELSE
  2079. HALT(100)
  2080. END;
  2081. WriteBack(irInstruction.op1, Low, destination[Low]);
  2082. IF IsComplex(irInstruction.op1) THEN WriteBack(irInstruction.op1, High, destination[High]) END
  2083. END EmitShiftOrRotation;
  2084. PROCEDURE EmitAsm(CONST irInstruction: IntermediateCode.Instruction);
  2085. VAR
  2086. reader: Streams.StringReader;
  2087. procedure: SyntaxTree.Procedure;
  2088. scope: SyntaxTree.Scope;
  2089. symbol: SyntaxTree.Symbol;
  2090. assembler: Assembler.Assembler;
  2091. scanner: Scanner.AssemblerScanner;
  2092. len: LONGINT;
  2093. BEGIN
  2094. len := Strings.Length(irInstruction.op1.string^);
  2095. NEW(reader, len);
  2096. reader.Set(irInstruction.op1.string^);
  2097. (* determine scope of the section *)
  2098. symbol := in.symbol;
  2099. IF symbol = NIL THEN
  2100. scope := NIL
  2101. ELSE
  2102. procedure := symbol(SyntaxTree.Procedure);
  2103. scope := procedure.procedureScope
  2104. END;
  2105. NEW(assembler, diagnostics);
  2106. scanner := Scanner.NewAssemblerScanner(module.moduleName(*module.module.sourceName*), reader, LONGINT(irInstruction.op1.intValue) (* ? *), diagnostics);
  2107. assembler.InlineAssemble(scanner, in, scope, module);
  2108. error := error OR assembler.error
  2109. END EmitAsm;
  2110. PROCEDURE EmitSpecial(VAR instruction: IntermediateCode.Instruction);
  2111. VAR
  2112. psrNumber, code, a, b, c, d: LONGINT;
  2113. register, register2, register3, register4, temp, cpOperand, cpRegister1, cpRegister2, opCode1Operand, opCode2Operand: Operand;
  2114. BEGIN
  2115. CASE instruction.subtype OF
  2116. | GetSP: Emit2(opMOV, opRES, opSP)
  2117. | SetSP: Emit2(opMOV, opSP, RegisterOrImmediateFromIrOperand(instruction.op1, Low, emptyOperand))
  2118. | GetFP: Emit2(opMOV, opRES, opFP)
  2119. | SetFP: Emit2(opMOV, opFP, RegisterOrImmediateFromIrOperand(instruction.op1, Low, emptyOperand))
  2120. | GetLNK: Emit2(opMOV, opRES, opLR)
  2121. | SetLNK: Emit2(opMOV, opLR, RegisterOrImmediateFromIrOperand(instruction.op1, Low, emptyOperand))
  2122. | GetPC: Emit2(opMOV, opRES, opPC)
  2123. | SetPC: Emit2(opMOV, opPC, RegisterOrImmediateFromIrOperand(instruction.op1, Low, emptyOperand))
  2124. | LDPSR, STPSR:
  2125. ASSERT(instruction.op1.type.form IN IntermediateCode.Integer);
  2126. IF instruction.op1.mode # IntermediateCode.ModeImmediate THEN
  2127. Error(instruction.textPosition,"first operand must be immediate")
  2128. ELSIF (instruction.op1.intValue < 0) OR (instruction.op1.intValue > 1) THEN
  2129. Error(instruction.textPosition,"first operand must be 0 or 1")
  2130. ELSE
  2131. IF instruction.op1.intValue = 0 THEN
  2132. psrNumber := InstructionSet.CPSR
  2133. ELSE
  2134. psrNumber := InstructionSet.SPSR
  2135. END;
  2136. register := RegisterFromIrOperand(instruction.op2, Low, emptyOperand);
  2137. IF instruction.subtype = LDPSR THEN
  2138. Emit2(opMSR, InstructionSet.NewRegisterWithFields(psrNumber, {InstructionSet.fieldF, InstructionSet.fieldC}), register)
  2139. ELSE
  2140. temp := GetFreeRegister(IntermediateCode.UnsignedIntegerType(32));
  2141. Emit2(opMRS, temp, InstructionSet.NewRegister(psrNumber, None, None, 0));
  2142. Emit2(opSTR, temp, InstructionSet.NewImmediateOffsetMemory(register.register, 0, {InstructionSet.Increment}))
  2143. END
  2144. END
  2145. | LDCPR, STCPR:
  2146. IF instruction.op1.mode # IntermediateCode.ModeImmediate THEN
  2147. Error(instruction.textPosition,"first operand must be immediate")
  2148. ELSIF (instruction.op2.mode # IntermediateCode.ModeImmediate) THEN
  2149. Error(instruction.textPosition,"second operand must be immediate")
  2150. ELSIF (instruction.op2.intValue < 0) OR (instruction.op2.intValue > 15) THEN
  2151. Error(instruction.textPosition,"second operand must be between 0 or 15")
  2152. ELSE
  2153. code := LONGINT(instruction.op1.intValue); (* code = a00bcdH *)
  2154. a := (code DIV 100000H) MOD 10H; (* opcode1 * 2 *)
  2155. b := (code DIV 100H) MOD 10H; (* coprocessor number *)
  2156. c := (code DIV 10H) MOD 10H; (* opcode2 * 2 *)
  2157. d := code MOD 10H; (* coprocessor register2 number *)
  2158. InstructionSet.InitCoprocessor(cpOperand, InstructionSet.CP0 + b);
  2159. InstructionSet.InitOpcode(opCode1Operand, a DIV 2);
  2160. register := RegisterFromIrOperand(instruction.op3, Low, emptyOperand);
  2161. InstructionSet.InitRegister(cpRegister1, InstructionSet.CR0 + LONGINT(instruction.op2.intValue), None, None, 0);
  2162. InstructionSet.InitRegister(cpRegister2, InstructionSet.CR0 + d, None, None, 0);
  2163. InstructionSet.InitOpcode(opCode2Operand, c DIV 2);
  2164. IF instruction.subtype = LDCPR THEN
  2165. Emit6(opMCR, cpOperand, opCode1Operand, register, cpRegister1, cpRegister2, opCode2Operand)
  2166. ELSE
  2167. temp := GetFreeRegister(IntermediateCode.UnsignedIntegerType(32));
  2168. Emit6(opMRC, cpOperand, opCode1Operand, temp, cpRegister1, cpRegister2, opCode2Operand);
  2169. Emit2(opSTR, temp, InstructionSet.NewImmediateOffsetMemory(register.register, 0, {InstructionSet.Increment}))
  2170. END
  2171. END
  2172. | FLUSH:
  2173. IF instruction.op1.mode # IntermediateCode.ModeImmediate THEN
  2174. Error(instruction.textPosition,"first operand must be immediate")
  2175. ELSIF (instruction.op1.intValue < 0) OR (instruction.op2.intValue > 0FFH) THEN
  2176. Error(instruction.textPosition,"first operand must be between 0 and 255")
  2177. ELSE
  2178. code := LONGINT(instruction.op1.intValue); (* code = aaa1bbbbB *)
  2179. a := (code DIV 20H) MOD 8; (* coprocessor opcode 2 *)
  2180. b := (code MOD 10H); (* coprocessor register2 number *)
  2181. (* examples:
  2182. 9AH = 10011000B -> MCR p15, 0, R0, c7, c10, 4
  2183. 17H = 00010111B -> MCR p15, 0, R0, c7, c7, 0
  2184. *)
  2185. InstructionSet.InitCoprocessor(cpOperand, InstructionSet.CP15);
  2186. InstructionSet.InitOpcode(opCode1Operand, 0);
  2187. InstructionSet.InitRegister(register, InstructionSet.R0, None, None, 0);
  2188. InstructionSet.InitRegister(cpRegister1, InstructionSet.CR7, None, None, 0);
  2189. InstructionSet.InitRegister(cpRegister2, InstructionSet.CR0 + b, None, None, 0);
  2190. InstructionSet.InitOpcode(opCode2Operand, a);
  2191. Emit6(opMCR, cpOperand, opCode1Operand, register, cpRegister1, cpRegister2, opCode2Operand);
  2192. Emit2(opMOV, register, register); (* NOP (register = R0) *)
  2193. Emit2(opMOV, register, register); (* NOP *)
  2194. Emit2(opMOV, register, register); (* NOP *)
  2195. Emit2(opMOV, register, register) (* NOP *)
  2196. END
  2197. | NULL:
  2198. register := RegisterFromIrOperand(instruction.op1, Low, emptyOperand);
  2199. Emit3(opBIC, register, register, InstructionSet.NewImmediate(LONGINT(80000000H)));
  2200. Emit2(opCMP, register, InstructionSet.NewImmediate(0));
  2201. Emit2WithCondition(opMOV, opRES, InstructionSet.NewImmediate(1), InstructionSet.conditionEQ);
  2202. Emit2WithCondition(opMOV, opRES, InstructionSet.NewImmediate(0), InstructionSet.conditionNE);
  2203. | XOR:
  2204. register := RegisterFromIrOperand(instruction.op1, Low, emptyOperand);
  2205. register2 := RegisterFromIrOperand(instruction.op2, Low, emptyOperand);
  2206. (*
  2207. register3 := RegisterFromIrOperand(instruction.op3, Low, emptyOperand);
  2208. *)
  2209. Emit3(opEOR, opRES, register, register2);
  2210. | MULD:
  2211. register := RegisterFromIrOperand(instruction.op1, Low, emptyOperand); (* note that 'register' contains an address *)
  2212. register2 := RegisterFromIrOperand(instruction.op2, Low, emptyOperand);
  2213. register3 := RegisterFromIrOperand(instruction.op3, Low, emptyOperand);
  2214. Emit4(opUMULL, opRES, opRESHI, register2, register3);
  2215. Emit2(opSTR, opRES, InstructionSet.NewImmediateOffsetMemory(register.register, 0, {InstructionSet.Increment})); (* JCH: 15.05.2012 *)
  2216. Emit2(opSTR, opRESHI, InstructionSet.NewImmediateOffsetMemory(register.register, 4, {InstructionSet.Increment}))
  2217. | ADDC:
  2218. register := RegisterFromIrOperand(instruction.op1, Low, emptyOperand);
  2219. register2 := RegisterFromIrOperand(instruction.op2, Low, emptyOperand);
  2220. Emit3(opADC, opRES, register, register2)
  2221. | PACK:
  2222. (* PACK(x, y):
  2223. add y to the binary exponent of y. PACK(x, y) is equivalent to x := x * 2^y. *)
  2224. register := RegisterFromIrOperand(instruction.op1, Low, emptyOperand); (* register = address of x *)
  2225. register2 := RegisterFromIrOperand(instruction.op2, Low, emptyOperand); (* register2 = value of y *)
  2226. register3 := GetFreeRegister(IntermediateCode.UnsignedIntegerType(32)); (* a temporary INTEGER (!) register that is used to store a float *)
  2227. Emit2(opLDR, register3, InstructionSet.NewImmediateOffsetMemory(register.register, 0, {InstructionSet.Increment})); (* register3 = value of x *)
  2228. Emit3(opADD, register3, register3, InstructionSet.NewRegister(register2.register, InstructionSet.shiftLSL, None, 23)); (* increase the (biased) exponent of x by y*)
  2229. Emit2(opSTR, register3, InstructionSet.NewImmediateOffsetMemory(register.register, 0, {InstructionSet.Increment})) (* store new value of x *)
  2230. | UNPK:
  2231. (* UNPK(x, y):
  2232. 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.
  2233. *)
  2234. register := RegisterFromIrOperand(instruction.op1, Low, emptyOperand); (* register = address of x *)
  2235. register2 := RegisterFromIrOperand(instruction.op2, Low, emptyOperand); (* register2 = address of y *)
  2236. register3 := GetFreeRegister(IntermediateCode.UnsignedIntegerType(32)); (* a temporary INTEGER (!) register that is used to store a float *)
  2237. Emit2(opLDR, register3, InstructionSet.NewImmediateOffsetMemory(register.register, 0, {InstructionSet.Increment})); (* register3 = value of x *)
  2238. register4 := GetFreeRegister(IntermediateCode.UnsignedIntegerType(32));
  2239. Emit2(opMOV, register4, InstructionSet.NewRegister(register3.register, InstructionSet.shiftLSR, None, 23)); (* register4 = biased exponent (and sign) of x *)
  2240. Emit3(opSUB, register4, register4, InstructionSet.NewImmediate(127)); (* register4 = exponent of x (biased exponent - 127) *)
  2241. Emit2(opSTR, register4, InstructionSet.NewImmediateOffsetMemory(register2.register, 0, {InstructionSet.Increment})); (* store exponent of x as value for y *)
  2242. Emit3(opSUB, register3, register3, InstructionSet.NewRegister(register4.register, InstructionSet.shiftLSL, None, 23)); (* reduce the biased exponent of x by the value of y *)
  2243. Emit2(opSTR, register3, InstructionSet.NewImmediateOffsetMemory(register.register, 0, {InstructionSet.Increment})) (* store new value of x *)
  2244. ELSE
  2245. HALT(100)
  2246. END
  2247. END EmitSpecial;
  2248. PROCEDURE EmitBr(VAR irInstruction: IntermediateCode.Instruction);
  2249. VAR
  2250. branchDistance: LONGINT;
  2251. isSwapped: BOOLEAN;
  2252. left, right: ARRAY 2 OF Operand;
  2253. temp: Operand;
  2254. irLeft, irRight: IntermediateCode.Operand;
  2255. fixup,failFixup: BinaryCode.Fixup;
  2256. fixupPatternList: ObjectFile.FixupPatterns;
  2257. identifier: ObjectFile.Identifier;
  2258. hiHit, hiFail, lowHit: LONGINT;
  2259. PROCEDURE JmpDest(branchConditionCode: LONGINT);
  2260. BEGIN
  2261. IF (irInstruction.op1.mode = IntermediateCode.ModeImmediate) & (irInstruction.op1.symbol.name = in.name) & (irInstruction.op1.offset = 0) THEN
  2262. (* branch within same section at a certain IR offset *)
  2263. (* optimization: abort if branch is to the next instruction *)
  2264. IF irInstruction.op1.symbolOffset = inPC + 1 THEN
  2265. IF dump # NIL THEN dump.String("branch to next instruction ignored"); dump.Ln END;
  2266. RETURN
  2267. END;
  2268. IF irInstruction.op1.symbolOffset <= inPC THEN
  2269. (* backward branch: calculate the branch distance *)
  2270. branchDistance := in.instructions[irInstruction.op1.symbolOffset].pc - out.pc - 8;
  2271. ASSERT((-33554432 <= branchDistance) & (branchDistance <= 0) & ((ABS(branchDistance) MOD 4) = 0), 200);
  2272. ELSE
  2273. (* forward branch: the distance is not yet known, use some placeholder and add a relative fixup *)
  2274. branchDistance := -4;
  2275. (* TODO: what about a branch to the next instruction? this would require the fixup meachnism to patch a negative value! (-> -4) *)
  2276. NEW(fixupPatternList, 1);
  2277. fixupPatternList[0].offset := 0;
  2278. fixupPatternList[0].bits := 24;
  2279. identifier.name := in.name;
  2280. identifier.fingerprint := in.fingerprint;
  2281. fixup := BinaryCode.NewFixup(BinaryCode.Relative, out.pc, identifier, irInstruction.op1.symbolOffset, -8, -2, fixupPatternList);
  2282. out.fixupList.AddFixup(fixup)
  2283. END;
  2284. Emit1WithCondition(opB, InstructionSet.NewImmediate(branchDistance), branchConditionCode)
  2285. ELSE
  2286. (* any other type of branch -> do register branch *)
  2287. Emit1WithCondition(opBX, RegisterFromIrOperand(irInstruction.op1, Low, emptyOperand), branchConditionCode)
  2288. END;
  2289. END JmpDest;
  2290. PROCEDURE Cmp(CONST left, right: InstructionSet.Operand; float: BOOLEAN);
  2291. BEGIN
  2292. IF float THEN
  2293. IF ~backend.useFPU OR IsComplex(irLeft) (* 64 bit *) THEN
  2294. (* floating point comparisons without VFP unit *)
  2295. temp := GetFreeRegister(IntermediateCode.UnsignedIntegerType(32));
  2296. Emit3WithFlags(opAND, temp, left, right, {InstructionSet.flagS});
  2297. Emit2(opCMP, temp, InstructionSet.NewImmediate(0));
  2298. Emit1WithCondition(opB, InstructionSet.NewImmediate(4), InstructionSet.conditionLT); (* skip two instructions *)
  2299. Emit2(opCMP, left, right);
  2300. Emit1(opB, InstructionSet.NewImmediate(0)); (* skip one instructions *)
  2301. Emit2(opCMP, right, left);
  2302. ELSE
  2303. Emit2(opFCMPS, left, right);
  2304. Emit0(opFMSTAT); (* transfer the VFP flags to the standard ARM flags *)
  2305. END
  2306. ELSE
  2307. Emit2(opCMP, left, right);
  2308. END;
  2309. END Cmp;
  2310. BEGIN
  2311. hiFail := None;
  2312. hiHit := None;
  2313. IF irInstruction.opcode = IntermediateCode.br THEN
  2314. (* unconditional branch: *)
  2315. lowHit := InstructionSet.conditionAL
  2316. ELSE
  2317. (* conditional branch: *)
  2318. irLeft := irInstruction.op2; irRight := irInstruction.op3;
  2319. ASSERT((irLeft.type.form = irRight.type.form) & (irLeft.type.sizeInBits = irRight.type.sizeInBits));
  2320. IF IsInteger(irLeft) THEN
  2321. IF IsComplex(irLeft) THEN
  2322. CASE irInstruction.opcode OF
  2323. | IntermediateCode.breq, IntermediateCode.brne: (* left = right, left # right *)
  2324. lowHit := InstructionSet.conditionEQ;
  2325. left[High] := RegisterFromIrOperand(irLeft, High, emptyOperand);
  2326. right[High] := RegisterOrImmediateFromIrOperand(irRight, High, emptyOperand);
  2327. Emit2(opCMP, left[High], right[High]);
  2328. left[Low] := RegisterFromIrOperand(irLeft, Low, left[High]);
  2329. right[Low] := RegisterOrImmediateFromIrOperand(irRight, Low, right[High]);
  2330. Emit2WithCondition(opCMP, left[Low], right[Low], lowHit);
  2331. IF irInstruction.opcode = IntermediateCode.brne THEN lowHit := InstructionSet.conditionNE END;
  2332. | IntermediateCode.brlt, IntermediateCode.brge: (* left < right, left >= right *)
  2333. IF irInstruction.opcode = IntermediateCode.brlt THEN lowHit := InstructionSet.conditionLT ELSE lowHit := InstructionSet.conditionGE END;
  2334. ASSERT(irLeft.type.form = IntermediateCode.SignedInteger);
  2335. left[Low] := RegisterFromIrOperand(irLeft, Low, emptyOperand);
  2336. right[Low] := RegisterOrImmediateFromIrOperand(irRight, Low, emptyOperand);
  2337. temp := GetFreeRegister(IntermediateCode.UnsignedIntegerType(32));
  2338. Emit3WithFlags(opSUB, temp, left[Low], right[Low], {InstructionSet.flagS});
  2339. left[High] := RegisterFromIrOperand(irLeft, High, left[Low]);
  2340. right[High] := RegisterOrImmediateFromIrOperand(irRight, High, right[Low]);
  2341. Emit3WithFlags(opSBC, temp, left[High], right[High], {InstructionSet.flagS}) (* the high part of the subtraction determines the sign *)
  2342. ELSE
  2343. HALT(100)
  2344. END
  2345. ELSE
  2346. ASSERT((irLeft.type.form IN IntermediateCode.Integer) & (irLeft.type.sizeInBits <= 32));
  2347. (* swap operands if beneficial *)
  2348. IF ~IrOperandIsDirectlyEncodable(irRight, Low) & IrOperandIsDirectlyEncodable(irLeft, Low) THEN
  2349. isSwapped := TRUE;
  2350. SwapIrOperands(irLeft, irRight)
  2351. END;
  2352. left[Low] := RegisterFromIrOperand(irLeft, Low, emptyOperand);
  2353. right[Low] := RegisterOrImmediateFromIrOperand(irRight, Low, emptyOperand);
  2354. SignOrZeroExtendOperand(left[Low], irLeft.type);
  2355. SignOrZeroExtendOperand(right[Low], irRight.type);
  2356. Cmp(left[Low], right[Low], FALSE);
  2357. (* determine condition code for the branch (take into consideration that operands could have been swapped) *)
  2358. CASE irInstruction.opcode OF
  2359. | IntermediateCode.breq: (* left = right *) lowHit := InstructionSet.conditionEQ
  2360. | IntermediateCode.brne: (* left # right *) lowHit := InstructionSet.conditionNE
  2361. | IntermediateCode.brlt: (* left < right *)
  2362. IF irInstruction.op2.type.form = IntermediateCode.UnsignedInteger THEN
  2363. IF isSwapped THEN lowHit := InstructionSet.conditionHI ELSE lowHit := InstructionSet.conditionLO END
  2364. ELSE
  2365. IF isSwapped THEN lowHit := InstructionSet.conditionGT ELSE lowHit := InstructionSet.conditionLT END
  2366. END
  2367. | IntermediateCode.brge: (* left >= right *)
  2368. IF irInstruction.op2.type.form = IntermediateCode.UnsignedInteger THEN
  2369. IF isSwapped THEN lowHit := InstructionSet.conditionLS ELSE lowHit := InstructionSet.conditionHS END
  2370. ELSE
  2371. IF isSwapped THEN lowHit := InstructionSet.conditionLE ELSE lowHit := InstructionSet.conditionGE END
  2372. END
  2373. ELSE HALT(100)
  2374. END
  2375. END
  2376. ELSIF IsSinglePrecisionFloat(irLeft) THEN
  2377. left[Low] := RegisterFromIrOperand(irLeft, Low, emptyOperand);
  2378. right[Low] := RegisterFromIrOperand(irRight, Low, emptyOperand);
  2379. Cmp(left[Low], right[Low], TRUE);
  2380. CASE irInstruction.opcode OF
  2381. | IntermediateCode.breq: (* left = right *) lowHit := InstructionSet.conditionEQ
  2382. | IntermediateCode.brne: (* left # right *) lowHit := InstructionSet.conditionNE
  2383. | IntermediateCode.brlt: (* left < right *) lowHit := InstructionSet.conditionLT
  2384. | IntermediateCode.brge: (* left >= right *) lowHit := InstructionSet.conditionGE
  2385. ELSE HALT(100)
  2386. END
  2387. ELSIF IsDoublePrecisionFloat(irLeft) THEN
  2388. CASE irInstruction.opcode OF
  2389. IntermediateCode.breq:
  2390. hiHit := None; hiFail := InstructionSet.conditionNE; lowHit := InstructionSet.conditionEQ
  2391. |IntermediateCode.brne:
  2392. hiHit := InstructionSet.conditionNE; hiFail := None; lowHit := InstructionSet.conditionNE
  2393. |IntermediateCode.brge:
  2394. IF isSwapped THEN
  2395. hiHit := InstructionSet.conditionLT; hiFail := InstructionSet.conditionGT; lowHit := InstructionSet.conditionLS
  2396. ELSE
  2397. hiHit := InstructionSet.conditionGT; hiFail := InstructionSet.conditionLT; lowHit := InstructionSet.conditionHS
  2398. END;
  2399. |IntermediateCode.brlt:
  2400. IF isSwapped THEN
  2401. hiHit := InstructionSet.conditionGT; hiFail := InstructionSet.conditionLT; lowHit := InstructionSet.conditionHI
  2402. ELSE
  2403. hiHit := InstructionSet.conditionLT; hiFail := InstructionSet.conditionGT; lowHit := InstructionSet.conditionLO
  2404. END;
  2405. END;
  2406. (*
  2407. compare hi part (as float)
  2408. if hiHit then br dest
  2409. elsif hiFail then br fail
  2410. else compare low part (as unsigned int)
  2411. if lowHit then br dest
  2412. end
  2413. end,
  2414. fail:
  2415. *)
  2416. (* hi part *)
  2417. left[High] := RegisterFromIrOperand(irLeft, High, emptyOperand);
  2418. right[High] := RegisterOrImmediateFromIrOperand(irRight, High, emptyOperand);
  2419. Cmp(left[High], right[High], TRUE);
  2420. IF hiHit # None THEN
  2421. JmpDest(hiHit)
  2422. END;
  2423. IF hiFail # None THEN
  2424. NEW(fixupPatternList, 1);
  2425. fixupPatternList[0].offset := 0;
  2426. fixupPatternList[0].bits := 24;
  2427. identifier.name := in.name;
  2428. identifier.fingerprint := in.fingerprint;
  2429. failFixup := BinaryCode.NewFixup(BinaryCode.Relative, out.pc, identifier, irInstruction.op1.symbolOffset, -8, -2, fixupPatternList);
  2430. out.fixupList.AddFixup(failFixup);
  2431. Emit1WithCondition(opB, InstructionSet.NewImmediate(branchDistance), hiFail)
  2432. END;
  2433. (* low part *)
  2434. left[Low] := RegisterFromIrOperand(irLeft, Low, emptyOperand);
  2435. right[Low] := RegisterFromIrOperand(irRight, Low, emptyOperand);
  2436. Cmp(left[Low], right[Low], FALSE);
  2437. ELSE
  2438. HALT(200)
  2439. END
  2440. END;
  2441. JmpDest(lowHit);
  2442. IF failFixup # NIL THEN
  2443. failFixup.SetSymbol(in.name, in.fingerprint, 0, out.pc+failFixup.displacement (* displacement offset computed during operand emission, typically -1 *) );
  2444. failFixup.resolved := in;
  2445. END;
  2446. END EmitBr;
  2447. (* TODO: floats *)
  2448. PROCEDURE EmitConv(VAR irInstruction: IntermediateCode.Instruction);
  2449. VAR
  2450. irDestination, irSource: IntermediateCode.Operand;
  2451. destination, source: ARRAY 2 OF Operand;
  2452. temp: Operand;
  2453. partType: IntermediateCode.Type;
  2454. BEGIN
  2455. irDestination := irInstruction.op1; irSource := irInstruction.op2;
  2456. (* prepare operands *)
  2457. destination[Low] := AcquireDestinationRegister(irDestination, Low, emptyOperand); (* TODO: find more optimal register allocation *)
  2458. source[Low] := RegisterOrImmediateFromIrOperand(irSource, Low, destination[Low]);
  2459. IF IsComplex(irDestination) THEN destination[High]:= AcquireDestinationRegister(irDestination, High, emptyOperand) END;
  2460. IF IsComplex(irSource) THEN source[High] := RegisterOrImmediateFromIrOperand(irSource, High, destination[High]) END; (* note that the corresponding destination register is used as hint *)
  2461. IF IsInteger(irDestination) THEN
  2462. (* to integer: *)
  2463. IF IsComplex(irDestination) THEN
  2464. (* to complex integer: *)
  2465. IF IsInteger(irSource) THEN
  2466. (* integer to complex integer: *)
  2467. IF IsComplex(irSource) THEN
  2468. (* complex integer to complex integer: *)
  2469. MovIfDifferent(destination[Low], source[Low]);
  2470. MovIfDifferent(destination[High], source[High]);
  2471. ELSE
  2472. (* non-complex integer to complex integer: *)
  2473. SignOrZeroExtendOperand(source[Low], irSource.type);
  2474. MovIfDifferent(destination[Low], source[Low]);
  2475. IF irDestination.type.form = IntermediateCode.UnsignedInteger THEN
  2476. Emit2(opMOV, destination[High], InstructionSet.NewImmediate(0));
  2477. ELSE
  2478. (* for signed values the high part is set to 0...0 or 1...1, depending on the sign of the low part *)
  2479. Emit2(opMOV, destination[High], InstructionSet.NewRegister(source[Low].register, InstructionSet.shiftASR, None, 32))
  2480. END
  2481. END
  2482. ELSIF IsSinglePrecisionFloat(irSource) THEN
  2483. ASSERT(backend.useFPU);
  2484. (* single precision float to complex integer: *)
  2485. temp := GetFreeRegister(IntermediateCode.FloatType(32));
  2486. IF irDestination.type.form = IntermediateCode.UnsignedInteger THEN
  2487. (* single precision float to non-complex unsigned integer: *)
  2488. Emit2(opFTOUIS, temp, source[Low]);
  2489. ELSE
  2490. (* single precision float to non-complex signed integer: *)
  2491. Emit2(opFTOSIS, temp, source[Low]);
  2492. END;
  2493. Emit2(opFMRS, destination[Low], temp);
  2494. IF irDestination.type.form = IntermediateCode.UnsignedInteger THEN
  2495. Emit2(opMOV, destination[High], InstructionSet.NewImmediate(0));
  2496. ELSE
  2497. (* for signed values the high part is set to 0...0 or 1...1, depending on the sign of the low part *)
  2498. Emit2(opMOV, destination[High], InstructionSet.NewRegister(destination[Low].register, InstructionSet.shiftASR, None, 32))
  2499. END
  2500. ELSE
  2501. (* anything else to complex-integer: *)
  2502. HALT(200)
  2503. END
  2504. ELSE
  2505. (* to non-complex integer: *)
  2506. IF IsInteger(irSource) THEN
  2507. (* integer to non-complex integer: ignore high part of source *)
  2508. GetPartType(irSource.type, Low, partType);
  2509. SignOrZeroExtendOperand(source[Low], partType);
  2510. MovIfDifferent(destination[Low], source[Low])
  2511. ELSIF IsSinglePrecisionFloat(irSource) THEN
  2512. ASSERT(backend.useFPU);
  2513. (* single precision float to non-complex integer: *)
  2514. temp := GetFreeRegister(IntermediateCode.FloatType(32));
  2515. IF irDestination.type.form = IntermediateCode.UnsignedInteger THEN
  2516. (* single precision float to non-complex unsigned integer: *)
  2517. Emit2(opFTOUIS, temp, source[Low]);
  2518. ELSE
  2519. (* single precision float to non-complex signed integer: *)
  2520. Emit2(opFTOSIS, temp, source[Low]);
  2521. END;
  2522. Emit2(opFMRS, destination[Low], temp)
  2523. ELSE
  2524. (* anything to non-complex integer: *)
  2525. HALT(200)
  2526. END
  2527. END
  2528. ELSIF IsSinglePrecisionFloat(irDestination) THEN
  2529. (* to single precision float: *)
  2530. IF IsInteger(irSource) THEN
  2531. (* integer to single precision float: ignore high part of source *)
  2532. temp := GetFreeRegister(IntermediateCode.FloatType(32));
  2533. Emit2(opFMSR, temp, source[Low]);
  2534. IF irSource.type.form = IntermediateCode.UnsignedInteger THEN
  2535. (* non-complex unsigned integer to single precision float: *)
  2536. Emit2(opFUITOS, destination[Low], temp)
  2537. ELSE
  2538. (* non-complex signed integer to single precision float: *)
  2539. Emit2(opFSITOS, destination[Low], temp)
  2540. END
  2541. ELSIF IsSinglePrecisionFloat(irSource) THEN
  2542. (* single precision float to single precision float: *)
  2543. MovIfDifferent(destination[Low], source[Low])
  2544. ELSE
  2545. (* anything else to single precision float: *)
  2546. HALT(200)
  2547. END
  2548. ELSE
  2549. (* to anything else: *)
  2550. HALT(200)
  2551. END;
  2552. WriteBack(irDestination, Low, destination[Low]);
  2553. IF IsComplex(irDestination) THEN WriteBack(irInstruction.op1, High, destination[High]) END
  2554. END EmitConv;
  2555. (** get the register that is dedicated to store a return value of a function **)
  2556. PROCEDURE ResultRegister(part: LONGINT; type: IntermediateCode.Type): InstructionSet.Operand;
  2557. VAR
  2558. result: Operand;
  2559. BEGIN
  2560. IF (type.form IN IntermediateCode.Integer) OR ~(backend.useFPU) THEN
  2561. IF part = Low THEN result := opRES
  2562. ELSIF part = High THEN result := opRESHI
  2563. ELSE HALT(200)
  2564. END
  2565. ELSIF type.form = IntermediateCode.Float THEN
  2566. ASSERT(type.sizeInBits = 32, 200);
  2567. result := opRESFS
  2568. END;
  2569. RETURN result
  2570. END ResultRegister;
  2571. PROCEDURE EmitReturn(VAR irInstruction: IntermediateCode.Instruction; part: LONGINT);
  2572. VAR
  2573. source: Operand;
  2574. BEGIN
  2575. source := RegisterOrImmediateFromIrOperand(irInstruction.op1, part, ResultRegister(part, irInstruction.op1.type)); (* note: the result register is given as a hint *)
  2576. MovIfDifferent(ResultRegister(part, irInstruction.op1.type), source)
  2577. END EmitReturn;
  2578. PROCEDURE EmitResult(VAR irInstruction: IntermediateCode.Instruction; part: LONGINT);
  2579. VAR
  2580. destinationRegister: Operand;
  2581. BEGIN
  2582. destinationRegister := AcquireDestinationRegister(irInstruction.op1, part, emptyOperand);
  2583. MovIfDifferent(destinationRegister, ResultRegister(part, irInstruction.op1.type));
  2584. WriteBack(irInstruction.op1, part, destinationRegister)
  2585. END EmitResult;
  2586. PROCEDURE EmitTrap(CONST irInstruction: IntermediateCode.Instruction);
  2587. BEGIN
  2588. ASSERT(irInstruction.op1.mode = IntermediateCode.ModeNumber);
  2589. Emit1(opSWI, InstructionSet.NewImmediate(LONGINT(irInstruction.op1.intValue))) (* software interrupt *)
  2590. END EmitTrap;
  2591. PROCEDURE EmitCas(VAR irInstruction: IntermediateCode.Instruction);
  2592. VAR
  2593. addressReg, addressBaseReg, comparandReg, comparandBaseReg, comparatorReg, comparatorBaseReg, tempReg: Operand
  2594. BEGIN
  2595. addressReg := GetFreeRegister(IntermediateCode.UnsignedIntegerType(32));
  2596. addressBaseReg := RegisterFromIrOperand(irInstruction.op1, Low, addressReg);
  2597. MovIfDifferent(addressReg, addressBaseReg);
  2598. IF IntermediateCode.OperandEquals (irInstruction.op2, irInstruction.op3) THEN
  2599. Emit2(opLDR, opRES, InstructionSet.NewImmediateOffsetMemory(addressReg.register, 0, {InstructionSet.Increment}));
  2600. ELSE
  2601. comparandReg := GetFreeRegister(IntermediateCode.UnsignedIntegerType(32));
  2602. comparandBaseReg := RegisterFromIrOperand(irInstruction.op2, Low, comparandReg);
  2603. MovIfDifferent(comparandReg, comparandBaseReg);
  2604. comparatorReg := GetFreeRegister(IntermediateCode.UnsignedIntegerType(32));
  2605. comparatorBaseReg := RegisterFromIrOperand(irInstruction.op3, Low, comparatorReg);
  2606. MovIfDifferent(comparatorReg, comparatorBaseReg);
  2607. Emit2(opLDREX, opRES, addressReg);
  2608. Emit2(opCMP, opRES, comparandReg);
  2609. tempReg := GetFreeRegister(IntermediateCode.UnsignedIntegerType(32));
  2610. Emit3WithCondition(opSTREX, tempReg, comparatorReg, addressReg, InstructionSet.conditionEQ);
  2611. Emit2WithCondition(opCMP, tempReg, InstructionSet.NewImmediate(1), InstructionSet.conditionEQ);
  2612. Emit1WithCondition(opB, InstructionSet.NewImmediate (-24), InstructionSet.conditionEQ);
  2613. END;
  2614. END EmitCas;
  2615. (* possible optimization: use a combination of LDR and LDRB (would be 4x faster on average) *)
  2616. PROCEDURE EmitCopy(VAR irInstruction: IntermediateCode.Instruction);
  2617. VAR
  2618. targetBaseReg, sourceBaseReg, length, lastSourceAddress, currentTargetReg, currentSourceReg, tempReg: Operand;
  2619. BEGIN
  2620. ASSERT((irInstruction.op1.type.form = IntermediateCode.UnsignedInteger) & (irInstruction.op1.type.sizeInBits = 32));
  2621. ASSERT((irInstruction.op2.type.form = IntermediateCode.UnsignedInteger) & (irInstruction.op2.type.sizeInBits = 32));
  2622. ASSERT((irInstruction.op3.type.form = IntermediateCode.UnsignedInteger) & (irInstruction.op3.type.sizeInBits = 32));
  2623. currentTargetReg := GetFreeRegister(IntermediateCode.UnsignedIntegerType(32));
  2624. currentSourceReg := GetFreeRegister(IntermediateCode.UnsignedIntegerType(32));
  2625. (* note that the registers that store the current addresses are used as hints: *)
  2626. targetBaseReg := RegisterFromIrOperand(irInstruction.op1, Low, currentTargetReg);
  2627. sourceBaseReg := RegisterFromIrOperand(irInstruction.op2, Low, currentSourceReg);
  2628. MovIfDifferent(currentTargetReg, targetBaseReg);
  2629. MovIfDifferent(currentSourceReg, sourceBaseReg);
  2630. lastSourceAddress := GetFreeRegister(IntermediateCode.UnsignedIntegerType(32));
  2631. length := RegisterOrImmediateFromIrOperand(irInstruction.op3, Low, lastSourceAddress); (* note that the last source address register is used as hint*)
  2632. Emit3(opADD, lastSourceAddress, sourceBaseReg, length);
  2633. tempReg := GetFreeRegister(IntermediateCode.UnsignedIntegerType(32));
  2634. Emit2WithFlags(opLDR, tempReg, InstructionSet.NewImmediateOffsetMemory(currentSourceReg.register, 1, {InstructionSet.Increment, InstructionSet.PostIndexed}), {InstructionSet.flagB});
  2635. Emit2WithFlags(opSTR, tempReg, InstructionSet.NewImmediateOffsetMemory(currentTargetReg.register, 1, {InstructionSet.Increment, InstructionSet.PostIndexed}), {InstructionSet.flagB});
  2636. Emit2(opCMP, currentSourceReg, lastSourceAddress);
  2637. Emit1WithCondition(opB, InstructionSet.NewImmediate(-20), InstructionSet.conditionLT)
  2638. END EmitCopy;
  2639. PROCEDURE EmitFill(CONST irInstruction: IntermediateCode.Instruction; down: BOOLEAN);
  2640. BEGIN
  2641. HALT(200) (* note that this instruction is not used at the moment *)
  2642. END EmitFill;
  2643. (* PREPARATION OF OPERATIONS *)
  2644. (** swap a pair of IR operands **)
  2645. PROCEDURE SwapIrOperands(VAR left, right: IntermediateCode.Operand);
  2646. VAR
  2647. temp: IntermediateCode.Operand;
  2648. BEGIN
  2649. temp := left;
  2650. left := right;
  2651. right := temp
  2652. END SwapIrOperands;
  2653. PROCEDURE PrepareSingleSourceOp(VAR irInstruction: IntermediateCode.Instruction; part: LONGINT; VAR destinationRegister, sourceOperand: Operand);
  2654. BEGIN
  2655. destinationRegister := AcquireDestinationRegister(irInstruction.op1, part, emptyOperand);
  2656. sourceOperand := RegisterFromIrOperand(irInstruction.op2, part, destinationRegister); (* note that the destination register is used as hint *)
  2657. END PrepareSingleSourceOp;
  2658. PROCEDURE PrepareSingleSourceOpWithImmediate(VAR irInstruction: IntermediateCode.Instruction; part: LONGINT; VAR destinationRegister, sourceOperand: Operand);
  2659. BEGIN
  2660. destinationRegister := AcquireDestinationRegister(irInstruction.op1, part, emptyOperand);
  2661. sourceOperand := RegisterOrImmediateFromIrOperand(irInstruction.op2, part, destinationRegister); (* note that the destination register is used as hint *)
  2662. END PrepareSingleSourceOpWithImmediate;
  2663. PROCEDURE PrepareDoubleSourceOpWithImmediate(CONST irInstruction: IntermediateCode.Instruction; part: LONGINT; VAR destinationRegister, leftSourceOperand, rightSourceOperand: Operand; VAR isSwapped: BOOLEAN);
  2664. VAR
  2665. irDestination, irLeft, irRight: IntermediateCode.Operand;
  2666. BEGIN
  2667. irDestination := irInstruction.op1;
  2668. irLeft := irInstruction.op2;
  2669. irRight := irInstruction.op3;
  2670. destinationRegister:= AcquireDestinationRegister(irDestination, part, emptyOperand);
  2671. (* swap operands such that the right one is an immediate *)
  2672. IF IrOperandIsDirectlyEncodable(irLeft, part) & ~IrOperandIsDirectlyEncodable(irRight, part) THEN
  2673. SwapIrOperands(irLeft, irRight);
  2674. isSwapped := TRUE
  2675. ELSIF IntermediateCode.OperandEquals(irRight, irDestination) THEN
  2676. SwapIrOperands(irLeft, irRight);
  2677. isSwapped := TRUE
  2678. ELSE
  2679. isSwapped := FALSE
  2680. END;
  2681. leftSourceOperand := RegisterFromIrOperand(irLeft, part, destinationRegister); (* the destination register is used as hint *)
  2682. IF IsSameRegister(leftSourceOperand, destinationRegister) THEN
  2683. rightSourceOperand := RegisterOrImmediateFromIrOperand(irRight, part, emptyOperand) (* no hint is provided *)
  2684. ELSE
  2685. rightSourceOperand := RegisterOrImmediateFromIrOperand(irRight, part, destinationRegister) (* the destination register is again used as hint *)
  2686. END
  2687. END PrepareDoubleSourceOpWithImmediate;
  2688. PROCEDURE PrepareDoubleSourceOp(CONST irInstruction: IntermediateCode.Instruction; part: LONGINT; VAR destinationRegister, leftSourceOperand, rightSourceOperand: Operand);
  2689. VAR
  2690. irDestination, irLeft, irRight: IntermediateCode.Operand;
  2691. BEGIN
  2692. irDestination := irInstruction.op1;
  2693. irLeft := irInstruction.op2;
  2694. irRight := irInstruction.op3;
  2695. destinationRegister:= AcquireDestinationRegister(irDestination, part, emptyOperand);
  2696. IF IntermediateCode.OperandEquals(irRight, irDestination) THEN
  2697. leftSourceOperand := RegisterFromIrOperand(irLeft, part, emptyOperand); (* do not use destination register as hint *)
  2698. ELSE
  2699. leftSourceOperand := RegisterFromIrOperand(irLeft, part, destinationRegister); (* the destination register is used as hint *)
  2700. END;
  2701. IF IsSameRegister(leftSourceOperand, destinationRegister) OR IntermediateCode.OperandEquals(irRight, irDestination) THEN
  2702. rightSourceOperand := RegisterFromIrOperand(irRight, part, emptyOperand) (* no hint is provided *)
  2703. ELSE
  2704. rightSourceOperand := RegisterFromIrOperand(irRight, part, destinationRegister) (* the destination register is again used as hint *)
  2705. END
  2706. END PrepareDoubleSourceOp;
  2707. END CodeGeneratorARM;
  2708. BackendARM = OBJECT(IntermediateBackend.IntermediateBackend)
  2709. VAR
  2710. cg: CodeGeneratorARM;
  2711. system: Global.System;
  2712. useFPU: BOOLEAN;
  2713. initLocals: BOOLEAN;
  2714. PROCEDURE & InitBackendARM;
  2715. BEGIN
  2716. useFPU := FALSE;
  2717. InitIntermediateBackend;
  2718. SetRuntimeModuleName(DefaultRuntimeModuleName);
  2719. SetNewObjectFile(TRUE,FALSE);
  2720. system := NIL;
  2721. initLocals := TRUE;
  2722. SetHasLinkRegister;
  2723. END InitBackendARM;
  2724. PROCEDURE Initialize(diagnostics: Diagnostics.Diagnostics; log: Streams.Writer; flags: SET; checker: SemanticChecker.Checker; system: Global.System);
  2725. BEGIN
  2726. Initialize^(diagnostics, log, flags, checker, system);
  2727. NEW(cg, runtimeModuleName, diagnostics, SELF)
  2728. END Initialize;
  2729. PROCEDURE EnterCustomBuiltins;
  2730. VAR
  2731. procedureType: SyntaxTree.ProcedureType;
  2732. parameter: SyntaxTree.Parameter;
  2733. PROCEDURE New;
  2734. BEGIN procedureType := SyntaxTree.NewProcedureType(-1, NIL)
  2735. END New;
  2736. PROCEDURE BoolRet;
  2737. BEGIN procedureType.SetReturnType(system.booleanType)
  2738. END BoolRet;
  2739. PROCEDURE IntRet;
  2740. BEGIN procedureType.SetReturnType(Global.Integer32)
  2741. END IntRet;
  2742. PROCEDURE IntPar;
  2743. BEGIN
  2744. parameter := SyntaxTree.NewParameter(-1, procedureType, SyntaxTree.NewIdentifier(""), SyntaxTree.ValueParameter);
  2745. parameter.SetType(Global.Integer32); procedureType.AddParameter(parameter)
  2746. END IntPar;
  2747. PROCEDURE AddressPar;
  2748. BEGIN
  2749. parameter := SyntaxTree.NewParameter(-1, procedureType, SyntaxTree.NewIdentifier(""), SyntaxTree.ValueParameter);
  2750. parameter.SetType(Global.Unsigned32); procedureType.AddParameter(parameter)
  2751. END AddressPar;
  2752. PROCEDURE IntVarPar;
  2753. BEGIN
  2754. parameter := SyntaxTree.NewParameter(-1, procedureType, SyntaxTree.NewIdentifier(""), SyntaxTree.VarParameter);
  2755. parameter.SetType(Global.Integer32); procedureType.AddParameter(parameter)
  2756. END IntVarPar;
  2757. PROCEDURE RealVarPar;
  2758. BEGIN
  2759. parameter := SyntaxTree.NewParameter(-1, procedureType, SyntaxTree.NewIdentifier(""), SyntaxTree.VarParameter);
  2760. parameter.SetType(Global.Float32); procedureType.AddParameter(parameter)
  2761. END RealVarPar;
  2762. PROCEDURE Finish(CONST name: ARRAY OF CHAR; number: SHORTINT);
  2763. BEGIN Global.NewCustomBuiltin(name, system.systemScope, number, procedureType);
  2764. END Finish;
  2765. BEGIN
  2766. New; IntRet; Finish("SP", GetSP);
  2767. New; AddressPar; Finish("SetSP", SetSP);
  2768. New; IntRet; Finish("FP", GetFP);
  2769. New; AddressPar; Finish("SetFP", SetFP);
  2770. New; IntRet; Finish("PC", GetPC);
  2771. New; AddressPar; Finish("SetPC", SetPC);
  2772. New; IntRet; Finish("LNK", GetLNK);
  2773. New; AddressPar; Finish("SetLNK", SetLNK);
  2774. New; IntPar; IntPar; Finish("LDPSR", LDPSR);
  2775. New; IntPar; IntVarPar; Finish("STPSR", STPSR);
  2776. New; IntPar; IntPar; IntPar; Finish("LDCPR", LDCPR);
  2777. New; IntPar; IntPar; IntVarPar; Finish("STCPR", STCPR);
  2778. New; IntPar; Finish("FLUSH", FLUSH);
  2779. New; BoolRet; IntPar; Finish("NULL", NULL);
  2780. New; IntRet; IntPar; IntPar; Finish("XOR", XOR);
  2781. New; IntVarPar; IntPar; IntPar; Finish("MULD", MULD);
  2782. New; IntVarPar; IntPar; IntPar; Finish("ADDC", ADDC);
  2783. New; RealVarPar; IntPar; Finish("PACK", PACK);
  2784. New; RealVarPar; IntVarPar; Finish("UNPK", UNPK);
  2785. END EnterCustomBuiltins;
  2786. PROCEDURE GetSystem(): Global.System;
  2787. BEGIN
  2788. (* create system object if not yet existing *)
  2789. IF system = NIL THEN
  2790. (* used stack frame layout:
  2791. param 1
  2792. param 2
  2793. ...
  2794. param n-1
  2795. FP+8 -> param n
  2796. FP+4 -> old LR
  2797. FP -> old FP
  2798. FP-4 -> local 1
  2799. local 2
  2800. ...
  2801. spill 1
  2802. spill 2
  2803. ....
  2804. *)
  2805. (*
  2806. codeUnit, dataUnit = 8, 8
  2807. addressSize = 32
  2808. minVarAlign, maxVarAlign = 32, 32
  2809. minParAlign, maxParAlign = 8, 32
  2810. offsetFirstPar = 32 * 2
  2811. registerParameters = 0
  2812. *)
  2813. NEW(system, 8, 8, 32, (*32*) 8, 32, 8, 32, 32 * 2, 0, cooperative);
  2814. IF oberon07 THEN
  2815. IF Trace THEN D.String("Oberon07"); D.Ln END;
  2816. Global.SetDefaultDeclarations(system, 32) (* each basic type uses at least 32 bits -> INTEGER will be 32 bits long *)
  2817. ELSE
  2818. IF Trace THEN D.String("not Oberon07"); D.Ln END;
  2819. Global.SetDefaultDeclarations(system, 8) (* INTEGER will be 16 bits long *)
  2820. END;
  2821. Global.SetDefaultOperators(system);
  2822. EnterCustomBuiltins
  2823. END;
  2824. RETURN system
  2825. END GetSystem;
  2826. (** whether the code generator can generate code for a certain IR instruction
  2827. if not, where to find the runtime procedure that is to be called instead **)
  2828. PROCEDURE SupportedInstruction(CONST irInstruction: IntermediateCode.Instruction; VAR moduleName, procedureName: ARRAY OF CHAR): BOOLEAN;
  2829. BEGIN
  2830. (* only necessary for binary object file format for symbol / module entry in IntermediateBackend *)
  2831. RETURN cg.Supported(irInstruction, moduleName, procedureName);
  2832. END SupportedInstruction;
  2833. (** whether a certain intermediate code immediate value can be directly appear in code
  2834. if not, the value is stored in a const section and loaded from there **)
  2835. PROCEDURE SupportedImmediate(CONST irImmediateOperand: IntermediateCode.Operand): BOOLEAN;
  2836. VAR
  2837. result: BOOLEAN;
  2838. BEGIN
  2839. (* TODO: remove this *)
  2840. RETURN TRUE; (* tentatively generate all immediates, as symbol fixups are not yet implemented *)
  2841. result := FALSE;
  2842. IF (irImmediateOperand.type.form IN IntermediateCode.Integer) & (irImmediateOperand.type.sizeInBits <= 32) THEN
  2843. (* 32 bit integers *)
  2844. IF cg.ValueIsDirectlyEncodable(LONGINT(irImmediateOperand.intValue)) THEN
  2845. (* the value can be directly encoded as an ARM immediate operand *)
  2846. result := TRUE
  2847. ELSIF cg.ValueComposition(LONGINT(irImmediateOperand.intValue), FALSE, emptyOperand) <= 2 THEN (* TODO: find reasonable limit *)
  2848. (* the value can be generated using a limited amount of intructions *)
  2849. result := TRUE
  2850. END
  2851. END;
  2852. RETURN result
  2853. END SupportedImmediate;
  2854. PROCEDURE GenerateBinary(module: Sections.Module; dump: Streams.Writer);
  2855. VAR
  2856. in: Sections.Section;
  2857. out: BinaryCode.Section;
  2858. name: Basic.SectionName;
  2859. procedure: SyntaxTree.Procedure;
  2860. i, j, initialSectionCount: LONGINT;
  2861. (* recompute fixup positions and assign binary sections *)
  2862. PROCEDURE PatchFixups(section: BinaryCode.Section);
  2863. VAR resolved: BinaryCode.Section; fixup: BinaryCode.Fixup; displacement,symbolOffset: LONGINT; in: IntermediateCode.Section;
  2864. symbol: Sections.Section;
  2865. BEGIN
  2866. fixup := section.fixupList.firstFixup;
  2867. WHILE fixup # NIL DO
  2868. symbol := module.allSections.FindByName(fixup.symbol.name);
  2869. IF (symbol # NIL) & (symbol(IntermediateCode.Section).resolved # NIL) THEN
  2870. resolved := symbol(IntermediateCode.Section).resolved(BinaryCode.Section);
  2871. in := symbol(IntermediateCode.Section);
  2872. symbolOffset := fixup.symbolOffset;
  2873. IF symbolOffset = in.pc THEN
  2874. displacement := resolved.pc
  2875. ELSIF (symbolOffset # 0) THEN
  2876. ASSERT(in.pc > symbolOffset);
  2877. displacement := in.instructions[symbolOffset].pc;
  2878. ELSE
  2879. displacement := 0;
  2880. END;
  2881. fixup.SetSymbol(fixup.symbol.name,fixup.symbol.fingerprint,0,fixup.displacement+displacement);
  2882. END;
  2883. fixup := fixup.nextFixup;
  2884. END;
  2885. END PatchFixups;
  2886. (*
  2887. PROCEDURE Resolve(VAR fixup: BinaryCode.Fixup);
  2888. BEGIN
  2889. IF (fixup.symbol.name # "") & (fixup.resolved = NIL) THEN fixup.resolved := module.allSections.FindByName(fixup.symbol.name) END;
  2890. END Resolve;
  2891. (* recompute fixup positions and assign binary sections *)
  2892. PROCEDURE PatchFixups(section: BinaryCode.Section);
  2893. VAR resolved: BinaryCode.Section; fixup: BinaryCode.Fixup; symbolOffset, offsetWithinSection: LONGINT; in: IntermediateCode.Section;
  2894. BEGIN
  2895. fixup := section.fixupList.firstFixup;
  2896. WHILE fixup # NIL DO
  2897. Resolve(fixup);
  2898. IF (fixup.resolved # NIL) & (fixup.resolved(IntermediateCode.Section).resolved # NIL) THEN
  2899. resolved := fixup.resolved(IntermediateCode.Section).resolved(BinaryCode.Section);
  2900. in := fixup.resolved(IntermediateCode.Section);
  2901. (* TODO: is this correct? *)
  2902. symbolOffset := fixup.symbolOffset;
  2903. ASSERT(fixup.symbolOffset < in.pc);
  2904. IF (fixup.symbolOffset # 0) & (symbolOffset < in.pc) THEN
  2905. offsetWithinSection := in.instructions[fixup.symbolOffset].pc;
  2906. (*
  2907. (* TENTATIVE *)
  2908. D.String("FIXUP PATCH:"); D.Ln;
  2909. D.String(" symbol name: "); fixup.symbol.DumpName(D.Log); D.String("/");
  2910. D.String(" symbol offset: "); D.Int(fixup.symbolOffset, 0); D.Ln;
  2911. D.String(" offsetWithinSection"); D.Int(offsetWithinSection, 0); D.Ln;
  2912. D.String(" fixup.displacement (before)"); D.Int(fixup.displacement, 0); D.Ln; ; D.Ln;
  2913. D.Update;
  2914. *)
  2915. (* remove the fixup's symbol offset (in IR units) and change the displacement (in system units) accordingly: *)
  2916. fixup.SetSymbol(fixup.symbol.name, fixup.symbol.fingerprint, 0, offsetWithinSection + fixup.displacement)
  2917. END
  2918. END;
  2919. fixup := fixup.nextFixup;
  2920. END;
  2921. END PatchFixups;
  2922. *)
  2923. BEGIN
  2924. cg.SetModule(module);
  2925. cg.dump := dump;
  2926. FOR i := 0 TO module.allSections.Length() - 1 DO
  2927. in := module.allSections.GetSection(i);
  2928. IF in.type = Sections.InlineCodeSection THEN
  2929. Basic.SegmentedNameToString(in.name, name);
  2930. out := ResolvedSection(in(IntermediateCode.Section));
  2931. cg.dump := out.comments;
  2932. cg.Section(in(IntermediateCode.Section), out);
  2933. IF in.symbol # NIL THEN
  2934. procedure := in.symbol(SyntaxTree.Procedure);
  2935. procedure.procedureScope.body.code.SetBinaryCode(out.os.bits);
  2936. END;
  2937. END
  2938. END;
  2939. initialSectionCount := 0;
  2940. REPEAT
  2941. j := initialSectionCount;
  2942. initialSectionCount := module.allSections.Length() ;
  2943. FOR i := j TO initialSectionCount - 1 DO
  2944. in := module.allSections.GetSection(i);
  2945. Basic.SegmentedNameToString(in.name, name);
  2946. IF (in.type # Sections.InlineCodeSection) & (in(IntermediateCode.Section).resolved = NIL) THEN
  2947. out := ResolvedSection(in(IntermediateCode.Section));
  2948. cg.Section(in(IntermediateCode.Section),out);
  2949. END
  2950. END
  2951. UNTIL initialSectionCount = module.allSections.Length(); (* process remaining sections that have been added during traversal of sections *)
  2952. FOR i := 0 TO module.allSections.Length() - 1 DO
  2953. in := module.allSections.GetSection(i);
  2954. Basic.SegmentedNameToString(in.name, name);
  2955. in := module.allSections.GetSection(i);
  2956. PatchFixups(in(IntermediateCode.Section).resolved)
  2957. END;
  2958. IF cg.error THEN Error("", Diagnostics.Invalid, Diagnostics.Invalid, "") END
  2959. END GenerateBinary;
  2960. (** create an ARM code module from an intermediate code module **)
  2961. PROCEDURE ProcessIntermediateCodeModule*(intermediateCodeModule: Formats.GeneratedModule): Formats.GeneratedModule;
  2962. VAR
  2963. result: Formats.GeneratedModule;
  2964. BEGIN
  2965. ASSERT(intermediateCodeModule IS Sections.Module);
  2966. result := ProcessIntermediateCodeModule^(intermediateCodeModule);
  2967. IF ~error THEN
  2968. GenerateBinary(result(Sections.Module), dump);
  2969. IF dump # NIL THEN
  2970. dump.Ln; dump.Ln;
  2971. dump.String("------------------ binary code -------------------"); dump.Ln;
  2972. IF (traceString="") OR (traceString="*") THEN
  2973. result.Dump(dump);
  2974. dump.Update
  2975. ELSE
  2976. Sections.DumpFiltered(dump, result(Sections.Module), traceString);
  2977. dump.Update;
  2978. END
  2979. END;
  2980. END;
  2981. RETURN result
  2982. FINALLY
  2983. IF dump # NIL THEN
  2984. dump.Ln; dump.Ln;
  2985. dump.String("------------------ rescued code (code generation trapped) -------------------"); dump.Ln;
  2986. IF (traceString="") OR (traceString="*") THEN
  2987. result.Dump(dump);
  2988. dump.Update
  2989. ELSE
  2990. Sections.DumpFiltered(dump,result(Sections.Module),traceString);
  2991. dump.Update;
  2992. END
  2993. END;
  2994. RETURN result
  2995. END ProcessIntermediateCodeModule;
  2996. PROCEDURE DefineOptions(options: Options.Options);
  2997. BEGIN
  2998. options.Add(0X, UseFPUFlag, Options.Flag);
  2999. options.Add(0X, "noInitLocals", Options.Flag);
  3000. DefineOptions^(options);
  3001. END DefineOptions;
  3002. PROCEDURE GetOptions(options: Options.Options);
  3003. BEGIN
  3004. IF options.GetFlag(UseFPUFlag) THEN useFPU := TRUE END;
  3005. IF options.GetFlag("noInitLocals") THEN initLocals := FALSE END;
  3006. GetOptions^(options);
  3007. END GetOptions;
  3008. PROCEDURE DefaultObjectFileFormat(): Formats.ObjectFileFormat;
  3009. BEGIN RETURN ObjectFileFormat.Get();
  3010. END DefaultObjectFileFormat;
  3011. PROCEDURE DefaultSymbolFileFormat(): Formats.SymbolFileFormat;
  3012. BEGIN RETURN NIL
  3013. END DefaultSymbolFileFormat;
  3014. (** get the name of the backend **)
  3015. PROCEDURE GetDescription(VAR instructionSet: ARRAY OF CHAR);
  3016. BEGIN instructionSet := "ARM"
  3017. END GetDescription;
  3018. PROCEDURE FindPC(x: SyntaxTree.Module; CONST sectionName: ARRAY OF CHAR; sectionOffset: LONGINT);
  3019. VAR
  3020. section: Sections.Section; binarySection: BinaryCode.Section; label: BinaryCode.LabelList; module: Formats.GeneratedModule;
  3021. i: LONGINT; pooledName: Basic.SegmentedName;
  3022. BEGIN
  3023. module := ProcessSyntaxTreeModule(x);
  3024. Basic.ToSegmentedName(sectionName, pooledName);
  3025. i := 0;
  3026. REPEAT
  3027. section := module(Sections.Module).allSections.GetSection(i);
  3028. INC(i);
  3029. UNTIL (i = module(Sections.Module).allSections.Length()) OR (section.name = pooledName);
  3030. IF section.name # pooledName THEN
  3031. diagnostics.Error(module.module.sourceName,Diagnostics.Invalid,Diagnostics.Invalid," could not locate pc");
  3032. ELSE
  3033. binarySection := section(IntermediateCode.Section).resolved;
  3034. label := binarySection.labels;
  3035. WHILE (label # NIL) & (label.offset >= sectionOffset) DO
  3036. label := label.prev;
  3037. END;
  3038. IF label # NIL THEN
  3039. diagnostics.Information(module.module.sourceName,label.position,Diagnostics.Invalid," pc position");
  3040. ELSE
  3041. diagnostics.Error(module.module.sourceName,Diagnostics.Invalid,Diagnostics.Invalid," could not locate pc");
  3042. END;
  3043. END;
  3044. END FindPC;
  3045. END BackendARM;
  3046. VAR
  3047. emptyOperand: Operand;
  3048. PROCEDURE Assert(condition: BOOLEAN; CONST message: ARRAY OF CHAR);
  3049. BEGIN ASSERT(condition, 100)
  3050. END Assert;
  3051. PROCEDURE Halt(CONST message: ARRAY OF CHAR);
  3052. BEGIN HALT(100)
  3053. END Halt;
  3054. PROCEDURE PowerOf2(val: HUGEINT; VAR exp: LONGINT): BOOLEAN;
  3055. BEGIN
  3056. IF val <= 0 THEN RETURN FALSE END;
  3057. exp := 0;
  3058. WHILE ~ODD(val) DO
  3059. val := val DIV 2;
  3060. INC(exp)
  3061. END;
  3062. RETURN val = 1
  3063. END PowerOf2;
  3064. (** get the ARM code section that corresponds to an intermediate code section **)
  3065. PROCEDURE ResolvedSection(irSection: IntermediateCode.Section): BinaryCode.Section;
  3066. VAR
  3067. result: BinaryCode.Section;
  3068. BEGIN
  3069. IF irSection.resolved = NIL THEN
  3070. NEW(result, irSection.type, irSection.priority, 8, irSection.name, irSection.comments # NIL, FALSE);
  3071. (* set fixed position or alignment
  3072. (also make sure that any section has an alignment of at least 4 bytes) *)
  3073. IF ~irSection.fixed & (irSection.positionOrAlignment < 4) THEN
  3074. result.SetAlignment(FALSE, 4)
  3075. ELSE
  3076. result.SetAlignment(irSection.fixed, irSection.positionOrAlignment);
  3077. END;
  3078. irSection.SetResolved(result)
  3079. ELSE
  3080. result := irSection.resolved
  3081. END;
  3082. RETURN result
  3083. END ResolvedSection;
  3084. (** initialize the module **)
  3085. PROCEDURE Init;
  3086. BEGIN InstructionSet.InitOperand(emptyOperand)
  3087. END Init;
  3088. (** get an instance of the ARM backend **)
  3089. PROCEDURE Get*(): Backend.Backend;
  3090. VAR
  3091. result: BackendARM;
  3092. BEGIN
  3093. NEW(result);
  3094. RETURN result
  3095. END Get;
  3096. (* only for testing purposes *)
  3097. PROCEDURE Test*;
  3098. VAR
  3099. codeGenerator: CodeGeneratorARM;
  3100. value, count: LONGINT;
  3101. BEGIN
  3102. NEW(codeGenerator, "", NIL, NIL);
  3103. FOR value := 0 TO 300 BY 1 DO
  3104. count := codeGenerator.ValueComposition(value, FALSE, emptyOperand);
  3105. D.String("value: "); D.Int(value, 0); D.String(" -> "); D.Int(count, 0); D.String(" instructions"); D.Ln;
  3106. END;
  3107. D.Ln; D.Update
  3108. END Test;
  3109. (* TODO: move this to Debugging.Mod or even Streams.Mod *)
  3110. (** write an integer in binary right-justified in a field of at least ABS(w) characters.
  3111. If w < 0 THEN ABS(w) least significant hex digits of 'value' are written (potentially including leading zeros or ones)
  3112. **)
  3113. PROCEDURE DBin*(value: HUGEINT; numberDigits: LONGINT);
  3114. CONST
  3115. MaxBitSize = SIZEOF(HUGEINT) * 8;
  3116. VAR
  3117. i, firstRelevantPos: LONGINT;
  3118. prefixWithSpaces: BOOLEAN;
  3119. chars: ARRAY MaxBitSize OF CHAR;
  3120. prefixChar: CHAR;
  3121. BEGIN
  3122. prefixWithSpaces := numberDigits >= 0;
  3123. numberDigits := ABS(numberDigits);
  3124. (*
  3125. - calculate an array containing the full bitstring
  3126. - determine the position of the first relevant digit
  3127. *)
  3128. firstRelevantPos := 0;
  3129. FOR i := MaxBitSize - 1 TO 0 BY -1 DO
  3130. IF ODD(value) THEN
  3131. chars[i] := '1';
  3132. firstRelevantPos := i (* occurence of a '1' -> changes the first relevant position *)
  3133. ELSE
  3134. chars[i] := '0'
  3135. END;
  3136. value := value DIV 2
  3137. END;
  3138. (* if space prefixing is enabled, limit the number of digits to the relevant digits *)
  3139. IF prefixWithSpaces THEN numberDigits := MAX(numberDigits, MaxBitSize - firstRelevantPos) END;
  3140. IF numberDigits > MaxBitSize THEN
  3141. IF prefixWithSpaces THEN prefixChar := ' ' ELSE prefixChar := chars[0] END; (* use spaces or sign bit *)
  3142. FOR i := 1 TO numberDigits - MaxBitSize DO D.Char(prefixChar) END;
  3143. numberDigits := MaxBitSize
  3144. END;
  3145. ASSERT((numberDigits >= 0) & (numberDigits <= MaxBitSize));
  3146. FOR i := MaxBitSize - numberDigits TO MaxBitSize - 1 DO
  3147. IF prefixWithSpaces & (i < firstRelevantPos) THEN D.Char(' ') ELSE D.Char(chars[i]) END
  3148. END;
  3149. D.Ln;
  3150. END DBin;
  3151. BEGIN
  3152. Init;
  3153. END FoxARMBackend.
  3154. SystemTools.FreeDownTo FoxARMBackend ~