prog.tex 130 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589
  1. %
  2. % $Id$
  3. % This file is part of the FPC documentation.
  4. % Copyright (C) 1997, by Michael Van Canneyt
  5. %
  6. % The FPC documentation is free text; you can redistribute it and/or
  7. % modify it under the terms of the GNU Library General Public License as
  8. % published by the Free Software Foundation; either version 2 of the
  9. % License, or (at your option) any later version.
  10. %
  11. % The FPC Documentation is distributed in the hope that it will be useful,
  12. % but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  14. % Library General Public License for more details.
  15. %
  16. % You should have received a copy of the GNU Library General Public
  17. % License along with the FPC documentation; see the file COPYING.LIB. If not,
  18. % write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
  19. % Boston, MA 02111-1307, USA.
  20. %
  21. \documentclass{report}
  22. \usepackage{a4}
  23. \usepackage{html}
  24. \latex{\usepackage{multicol}}
  25. \latex{\usepackage{fpcman}}
  26. \usepackage{fancyheadings}
  27. \pagestyle{fancy}
  28. \renewcommand{\chaptermark}[1]{\markboth{#1}{}}
  29. \html{\input{fpc-html.tex}}
  30. % define the version number here, and not in the fpc.sty !!!
  31. \newcommand{\remark}[1]{\par$\rightarrow$\textbf{#1}\par}
  32. \newcommand{\olabel}[1]{\label{option:#1}}
  33. % We should change this to something better. See \seef etc.
  34. \begin{document}
  35. \title{Free Pascal \\ Programmers' manual}
  36. \docdescription{Programmers' manual for \fpc, version \fpcversion}
  37. \docversion{1.5}
  38. \input{date.inc}
  39. \author{Micha\"el Van Canneyt}
  40. \maketitle
  41. \tableofcontents
  42. \newpage
  43. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  44. % Introduction
  45. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  46. \section*{About this document}
  47. This is the programmer's manual for \fpc.
  48. It describes some of the peculiarities of the \fpc compiler, and provides a
  49. glimpse of how the compiler generates its code, and how you can change the
  50. generated code. It will not, however, provide you with a detailed account of
  51. the inner workings of the compiler, nor will it tell you how to use the
  52. compiler (described in the \userref). It also will not describe the inner
  53. workings of the Run-Time Library (RTL). The best way to learn about the way
  54. the RTL is implemented is from the sources themselves.
  55. The things described here are useful if you want to do things which need
  56. greater flexibility than the standard Pascal language constructs.
  57. (described in the \refref)
  58. Since the compiler is continuously under development, this document may get
  59. out of date. Wherever possible, the information in this manual will be
  60. updated. If you find something which isn't correct, or you think something
  61. is missing, feel free to contact me\footnote{at
  62. \var{[email protected]}}.
  63. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  64. % Compiler switches
  65. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  66. \chapter{Compiler directives}
  67. \label{ch:CompSwitch}
  68. \fpc supports compiler directives in your source file. They are not the same
  69. as Turbo Pascal directives, although some are supported for compatibility.
  70. There is a distinction between local and global directives; local directives
  71. take effect from the moment they are encountered, global directives have an
  72. effect on all of the compiled code.
  73. Many switches have a long form also. If they do, then the name of the
  74. long form is given also. For long switches, the + or - character to switch
  75. the option on or off, may be replaced by \var{ON} or \var{OFF} keywords.
  76. Thus \verb|{$I+}| is equivalent to \verb|{$IOCHECKS ON}| or
  77. \verb|{$IOCHECKS +}| and
  78. \verb|{$C-}| is equivalent to \verb|{$ASSERTIONS OFF}| or
  79. \verb|{$ASSERTIONS -}|
  80. The long forms of the switches are the same as their Delphi
  81. counterparts.
  82. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  83. % Local switches
  84. \section{Local directives}
  85. \label{se:LocalSwitch}
  86. Local directives have no command-line counterpart. They influence the
  87. compiler's behaviour from the moment they're encountered until the moment
  88. another switch annihilates their behaviour, or the end of the unit or
  89. program is reached.
  90. \subsection{\var{\$A} or \var{\$ALIGN}: Align Data}
  91. This switch is recognized for Turbo Pascal Compatibility, but is not
  92. yet implemented. The alignment of data will be different in any case, since
  93. \fpc is a 32-bit compiler.
  94. \subsection{\var{\$ASMMODE} : Assembler mode}
  95. \label{se:AsmReader}
  96. The \var{\{\$ASMMODE XXX} directive informs the compiler what kind of assembler
  97. it can expect in an \var{asm} block. The \var{XXX} should be replaced by one
  98. of the following:
  99. \begin{description}
  100. \item [att\ ] Indicates that \var{asm} blocks contain AT\&T syntax assembler.
  101. \item [intel\ ] Indicates that \var{asm} blocks contain Intel syntax
  102. assembler.
  103. \item [direct\ ] Tells the compiler that asm blocks should be copied
  104. directly to the assembler file.
  105. \end{description}
  106. These switches are local, and retain their value to the end of the unit that
  107. is compiled, unless they are replaced by another directive of the same type.
  108. The command-line switch that corresponds to this switch is \var{-R}.
  109. \subsection{\var{\$B} or \var{\$BOOLEVAL}: Complete boolean evaluation}
  110. This switch is understood by the \fpc compiler, but is ignored. The compiler
  111. always uses shortcut evaluation, i.e. the evaluation of a boolean expression
  112. is stopped once the result of the total exression is known with certainty.
  113. So, in the following example, the function \var{Bofu}, which has a boolean
  114. result, will never get called.
  115. \begin{verbatim}
  116. If False and Bofu then
  117. ...
  118. \end{verbatim}
  119. \subsection{\var{\$C} or \var{\$ASSERTIONS} : Assertion support}
  120. This switch is recognised for Delphi compatibility only. Assertions are not
  121. yet supported by the compiler, but will be implemented in the future.
  122. \subsection{\var{\$DEFINE} : Define a symbol}
  123. The directive
  124. \begin{verbatim}
  125. {$DEFINE name}
  126. \end{verbatim}
  127. defines the symbol \var{name}. This symbol remains defined until the end of
  128. the current module, or until a \var{\$UNDEF name} directive is encountered.
  129. If \var{name} is already defined, this has no effect. \var{Name} is case
  130. insensitive.
  131. \subsection{\var{\$ELSE} : Switch conditional compilation}
  132. The \var{\{\$ELSE \}} switches between compiling and ignoting the source
  133. text delimited by the preceding \var{\{\$IFxxx\}} and following
  134. \var{\{\$ENDIF\}}. Any text after the \var{ELSE} keyword but before the
  135. brace is ignored:
  136. \begin{verbatim}
  137. {$ELSE some ignored text}
  138. \end{verbatim}
  139. is the same as
  140. \begin{verbatim}
  141. {$ELSE}
  142. \end{verbatim}
  143. This is useful for indication what switch is meant.
  144. \subsection{\var{\$ENDIF} : End conditional compilation}
  145. The \var{\{\$ENDIF\}} directive ends the conditional compilation initiated by the
  146. last \var{\{\$IFxxx\}} directive. Any text after the \var{ENDIF} keyword but
  147. before the closing brace is ignored:
  148. \begin{verbatim}
  149. {$ENDIF some ignored text}
  150. \end{verbatim}
  151. is the same as
  152. \begin{verbatim}
  153. {$ENDIF}
  154. \end{verbatim}
  155. This is useful for indication what switch is meant to be ended.
  156. \subsection{\var{\$ERROR} : Generate error message}
  157. The following code
  158. \begin{verbatim}
  159. {$ERROR This code is erroneous !}
  160. \end{verbatim}
  161. will display an error message when the compiler encounters it,
  162. and increase the error count of the compiler.
  163. The compiler will continue to compile, but no code will be emitted.
  164. \subsection{\var{\$F} : Far or near functions}
  165. This directive is recognized for compatibility with Turbo Pascal. Under the
  166. 32-bit programming model, the concept of near and far calls have no meaning,
  167. hence the directive is ignored. A warning is printed to the screen, telling
  168. you so.
  169. As an example, : the following piece of code :
  170. \begin{verbatim}
  171. {$F+}
  172. Procedure TestProc;
  173. begin
  174. Writeln ('Hello From TestProc');
  175. end;
  176. begin
  177. testProc
  178. end.
  179. \end{verbatim}
  180. Generates the following compiler output:
  181. \begin{verbatim}
  182. malpertuus: >pp -vw testf
  183. Compiler: ppc386
  184. Units are searched in: /home/michael;/usr/bin/;/usr/lib/ppc/0.9.1/linuxunits
  185. Target OS: Linux
  186. Compiling testf.pp
  187. testf.pp(1) Warning: illegal compiler switch
  188. 7739 kB free
  189. Calling assembler...
  190. Assembled...
  191. Calling linker...
  192. 12 lines compiled,
  193. 1.00000000000000E+0000
  194. \end{verbatim}
  195. You can see that the verbosity level was set to display warnings.
  196. If you declare a function as \var{Far} (this has the same effect as setting it
  197. between \var{\{\$F+\}...\{\$F-\}} directives), the compiler also generates a
  198. warning :
  199. \begin{verbatim}
  200. testf.pp(3) Warning: FAR ignored
  201. \end{verbatim}
  202. The same story is true for procedures declared as \var{Near}. The warning
  203. displayed in that case is:
  204. \begin{verbatim}
  205. testf.pp(3) Warning: NEAR ignored
  206. \end{verbatim}
  207. \subsection{\var{\$FATAL} : Generate fatal error message}
  208. The following code
  209. \begin{verbatim}
  210. {$FATAL This code is erroneous !}
  211. \end{verbatim}
  212. will display an error message when the compiler encounters it, and trigger
  213. and increase the error count of the compiler.
  214. The compiler will immediatly stop the compilation process.
  215. \subsection{\var{\$H} or \var{\$LONGSTRINGS} : Use AnsiStrings}
  216. If \var{\{\$LONGSTRINGS ON\}} is specified, the keyword \var{String} (no
  217. length specifier) will be treated as \var{AnsiString}, and the compiler
  218. will treat the corresponding varible as an ansistring, and will
  219. generate corresponding code.
  220. By default, the use of ansistrings is off, corresponding to \var{\{\$H-\}}.
  221. This feature is still experimental, and should be used with caution for the
  222. time being.
  223. \subsection{\var{\$HINT} : Generate hint message}
  224. If the generation of hints is turned on, through the \var{-vh} command-line
  225. option or the \var{\{\$HINTS ON\}} directive, then
  226. \begin{verbatim}
  227. {$Hint This code should be optimized }
  228. \end{verbatim}
  229. will display a hint message when the compiler encounters it.
  230. \subsection{\var{\$HINTS} : Emit hints}
  231. \var{\{\$HINTS ON\}} switches the generation of hints on.
  232. \var{\{\$HINTS OFF\}} switches the generation of hints off.
  233. Contrary to the command-line option \var{-vh} this is a local switch,
  234. this is useful for checking parts of your code.
  235. \subsection{\var{\$IF} : Start conditional compilation}
  236. The directive \var{\{\$IF expr\}} will continue the compilation
  237. if the boolean expression \var{expr} evaluates to \var{true}. If the
  238. compilation evaluates to false, then the source are skipped to the first
  239. \var{\{\$ELSE\}} or \var{\{\$ENDIF\}} directive.
  240. The compiler must be able to evaluate the expression at compile time.
  241. This means that you cannot use variables or constants that are defined in
  242. the source. Macros and symbols may be used, however.
  243. More information on this can be found in the section about
  244. conditionals.
  245. \subsection{\var{\$IFDEF} : Start conditional compilation}
  246. The \var{\{\$IFDEF name\}} will skip the compilation of the text that
  247. follows it if the symbol \var{name} is not defined. If it is defined, then
  248. compilation continues as if the directive wasn't there.
  249. \subsection{\var{\$IFNDEF} : Start conditional compilation}
  250. The \var{\{\$IFNDEF name\}} will skip the compilation of the text that
  251. follows it if the symbol \var{name} is defined. If it is not defined, then
  252. compilation continues as if the directive wasn't there.
  253. \subsection{\var{\$IFOPT} : Start conditional compilation}
  254. The \var{\{\$IFOPT switch\}} will skip the compilation of the text that
  255. follows it if the switch \var{switch} is currently not in the specified
  256. state. If it is in the specified state, then compilation continues as if the directive
  257. wasn't there.
  258. As an example:
  259. \begin{verbatim}
  260. {$IFOPT M+}
  261. Writeln ('Compiled with type information');
  262. {$ENDIF}
  263. \end{verbatim}
  264. Will compile the writeln statement if generation of type information is on.
  265. \subsection{\var{\$INFO} : Generate info message}
  266. If the generation of info is turned on, through the \var{-vi} command-line
  267. option, then
  268. \begin{verbatim}
  269. {$INFO This was coded on a rainy day by Bugs Bunny }
  270. \end{verbatim}
  271. will display an info message when the compiler encounters it.
  272. \subsection{\var{\$I} or \var{\$IOCHECK} : Input/Output checking}
  273. The \var{\{\$I-\}} or \var{\{\$IOCHECK OFF\}} directive tells the compiler
  274. not to generate input/output checking code in your program. By default, the
  275. compiler does not generate this code, you must switch it on using the
  276. \var{-Ci} command-lne switch.
  277. If you compile using the \var{-Ci} compiler switch, the \fpc compiler inserts input/output
  278. checking code after every input/output call in your program. If an error
  279. occurred during input or output, then a run-time error will be generated.
  280. Use this switch if you wish to avoid this behavior.
  281. If you still want to check if something went wrong, you can use the
  282. \var{IOResult} function to see if everything went without problems.
  283. Conversely, \var{\{\$I+\}} will turn error-checking back on, until another
  284. directive is encountered which turns it off again.
  285. The most common use for this switch is to check if the opening of a file
  286. went without problems, as in the following piece of code:
  287. \begin{verbatim}
  288. ...
  289. assign (f,'file.txt');
  290. {$I-}
  291. rewrite (f);
  292. {$I+}
  293. if IOResult<>0 then
  294. begin
  295. Writeln ('Error opening file : "file.txt"');
  296. exit
  297. end;
  298. ...
  299. \end{verbatim}
  300. \subsection{\var{\$I} or \var{\$INCLUDE} : Include file }
  301. The \var{\{\$I filename\}} or \var{\{\$INCLUDE filename\}} directive
  302. tells the compiler to read further statements from the file \var{filename}.
  303. The statements read there will be inserted as if they occurred in the
  304. current file.
  305. The compiler will append the \file{.pp} extension to the file if you don't
  306. specify an extension yourself. Do not put the filename between quotes, as
  307. they will be regarded as part of the file's name.
  308. You can nest included files, but not infinitely deep. The number of files is
  309. restricted to the number of file descriptors available to the \fpc compiler.
  310. Contrary to Turbo Pascal, include files can cross blocks. I.e. you can start
  311. a block in one file (with a \var{Begin} keyword) and end it in another (with
  312. a \var{End} keyword). The smallest entity in an include file must be a token,
  313. i.e. an identifier, keyword or operator.
  314. The compiler will look for the file to include in the following places:
  315. \begin{enumerate}
  316. \item It will look in the path specified in the incude file name.
  317. \item It will look in the directory where the current source file is.
  318. \item it will look in all directories specified in the include file search
  319. path.
  320. \end{enumerate}
  321. You can add files to the include file search path with the \var{-I}
  322. command-line option.
  323. \subsection{\var{\$I} or \var{\$INCLUDE} : Include compiler info}
  324. In this form:
  325. \begin{verbatim}
  326. {$INCLUDE %xxx%}
  327. \end{verbatim}
  328. where \var{xxx} is one of \var{TIME}, \var{DATE}, \var{FPCVERSION} or
  329. \var{FPCTARGET}, will generate a macro with the value of these things.
  330. If \var{xxx} is none of the above, then it is assumed to be the value of
  331. an environment variable. It's value will be fetched, and inserted in the coe
  332. as if it were a srtring.
  333. For example, the following program
  334. \begin{verbatim}
  335. Program InfoDemo;
  336. Const User = {$I %USER%};
  337. begin
  338. Write ('This program was comilped at ',{$I %TIME%});
  339. Writeln (' on ',{$I %DATE%});
  340. Writeln ('By ',User);
  341. Writeln ('Compiler version : ',{$I %FPCVERSION%});
  342. Writeln ('Target CPU : ',{$I %FPCTARGET%});
  343. end.
  344. \end{verbatim}
  345. Creates the following output :
  346. \begin{verbatim}
  347. This program was comilped at 17:40:18 on 1998/09/09
  348. By michael
  349. Compiler version : 0.99.7
  350. Target CPU : i386
  351. \end{verbatim}
  352. % Assembler type
  353. \subsection{\var{\$I386\_XXX} : Specify assembler format}
  354. This switch selects the assembler reader. \var{\{\$I386\_XXX\}}
  355. has the same effect as \var{\{\$ASMMODE XXX\}}, \sees{AsmReader}
  356. \subsection{\var{\$L} or \var{\$LINK} : Link object file}
  357. The \var{\{\$L filename\}} or \var{\{\$LINK filename\}} directive
  358. tells the compiler that the file \file{filename} should be linked to
  359. your program.
  360. the compiler will look for this file in the following way:
  361. \begin{enumerate}
  362. \item It will look in the path specified in the object file name.
  363. \item It will look in the directory where the current source file is.
  364. \item it will look in all directories specified in the object file search path.
  365. \end{enumerate}
  366. You can add files to the object file search path with the \var{-Fo}
  367. option.
  368. On \linux systems, the name is case sensitive, and must be typed
  369. exactly as it appears on your system.
  370. {\em Remark :} Take care that the object file you're linking is in a
  371. format the linker understands. Which format this is, depends on the platform
  372. you're on. Typing \var{ld} on the command line gives a list of formats
  373. \var{ld} knows about.
  374. You can pass other files and options to the linker using the \var{-k}
  375. command-line option. You can specify more than one of these options, and
  376. they will be passed to the linker, in the order that you specified them on
  377. the command line, just before the names of the object files that must be
  378. linked.
  379. \subsection{\var{\$LINKLIB} : Link to a library}
  380. The \var{\{\$LINKLIB name\}} will link to a library \file{name}.
  381. This has the effect of passing \var{-lname} to the linker.
  382. As an example, consider the following unit:
  383. \begin{verbatim}
  384. unit getlen;
  385. interface
  386. {$LINKLIB c}
  387. function strlen (P : pchar) : longint;cdecl;
  388. implementation
  389. function strlen (P : pchar) : longint;cdecl;external;
  390. end.
  391. \end{verbatim}
  392. If one would issue the command the command
  393. \begin{verbatim}
  394. ppc386 foo.pp
  395. \end{verbatim}
  396. where foo.pp has the above unit in its \var{uses} clause,
  397. then the compiler would link your program to the c library, by passing the
  398. linker the \var{-lc} option.
  399. The same effect could be obtained by removing the linklib directive in the
  400. above unit, and specify \var{-k-lc} on the command-line:
  401. \begin{verbatim}
  402. ppc386 -k-lc foo.pp
  403. \end{verbatim}
  404. \subsection{\var{\$M} or \var{\$TYPEINFO} : Generate type info}
  405. This switch is recognized for Delphi compatibility only since the generation
  406. of type information isn't fully implemented yet.
  407. \subsection{\var{\$MESSAGE} : Generate info message}
  408. If the generation of info is turned on, through the \var{-vi} command-line
  409. option, then
  410. \begin{verbatim}
  411. {$MESSAGE This was coded on a rainy day by Bugs Bunny }
  412. \end{verbatim}
  413. will display an info message when the compiler encounters it. The effect is
  414. the same as the \var{\{\$INFO\}} directive.
  415. \subsection{\var{\$MMX} : Intel MMX support}
  416. As of version 0.9.8, \fpc supports optimization for the \textbf{MMX} Intel
  417. processor (see also \ref{ch:MMXSupport}). This optimizes certain code parts for the \textbf{MMX} Intel
  418. processor, thus greatly improving speed. The speed is noticed mostly when
  419. moving large amounts of data. Things that change are
  420. \begin{itemize}
  421. \item Data with a size that is a multiple of 8 bytes is moved using the
  422. \var{movq} assembler instruction, which moves 8 bytes at a time
  423. \end{itemize}
  424. When \textbf{MMX} support is on, you aren't allowed to do floating point
  425. arithmetic. You are allowed to move floating point data, but no arithmetic
  426. can be done. If you wish to do floating point math anyway, you must first
  427. switch of \textbf{MMX} support and clear the FPU using the \var{emms}
  428. function of the \file{cpu} unit.
  429. The following example will make this more clear:
  430. \begin{verbatim}
  431. Program MMXDemo;
  432. uses cpu;
  433. var
  434. d1 : double;
  435. a : array[0..10000] of double;
  436. i : longint;
  437. begin
  438. d1:=1.0;
  439. {$mmx+}
  440. { floating point data is used, but we do _no_ arithmetic }
  441. for i:=0 to 10000 do
  442. a[i]:=d2; { this is done with 64 bit moves }
  443. {$mmx-}
  444. emms; { clear fpu }
  445. { now we can do floating point arithmetic }
  446. ....
  447. end.
  448. \end{verbatim}
  449. See, however, the chapter on MMX (\ref{ch:MMXSupport}) for more information
  450. on this topic.
  451. \subsection{\var{\$NOTE} : Generate note message}
  452. If the generation of notes is turned on, through the \var{-vn} command-line
  453. option or the \var{\{\$NOTES ON\}} directive, then
  454. \begin{verbatim}
  455. {$NOTE Ask Santa Claus to look at this code }
  456. \end{verbatim}
  457. will display a note message when the compiler encounters it.
  458. \subsection{\var{\$NOTES} : Emit notes}
  459. \var{\{\$NOTES ON\}} switches the generation of notes on.
  460. \var{\{\$NOTES OFF\}} switches the generation of notes off.
  461. Contrary to the command-line option \var{-vn} this
  462. is a local switch, this is useful for checking parts of your code.
  463. \subsection{\var{\$OUTPUT\_FORMAT} : Specify the output format}
  464. \var{\{\$OUTPUT\_FORMAT format\}} has the same functionality as the \var{-A}
  465. command-line option : It tells the compiler what kind of object file must be
  466. generated. You can specify this switch \textbf{only} befor the \var{Program}
  467. or \var{Unit} clause in your source file. The different kinds of formats are
  468. shown in \seet{Formats}.
  469. \begin{FPCltable}{ll}{Formats generated by the x86 compiler}{Formats} \hline
  470. Switch value & Generated format \\ \hline
  471. att & AT\&T assembler file. \\
  472. o & Unix object file.\\
  473. obj & OMF file.\\
  474. wasm & assembler for the Watcom assembler. \\ \hline
  475. \end{FPCltable}
  476. \subsection{\var{\$P} or \var{\$OPENSTRINGS} : Use open strings}
  477. This switch is provided for compatibility only, as open strings aren't
  478. implemented yet.
  479. \subsection{\var{\$PACKENUM} : Minimum enumeration type size}
  480. This directive tells the compiler the minimum number of bytes it should
  481. use when storing enumerated types. It is of the following form:
  482. \begin{verbatim}
  483. {$PACKENUM xxx}
  484. {$MINENUMSIZE xxx}
  485. \end{verbatim}
  486. Where the form with \var{\$MINENUMSIZE} is for Delphi compatibility.
  487. var{xxx} can be one of \var{1,2} or \var{4}, or \var{NORMAL} or
  488. \var{DEFAULT}, corresponding to the default value of 4.
  489. As an alternative form one can use \var{\{\$Z1\}}, \var{\{\$Z2\}}
  490. \var{\{\$Z4\}}. Contrary to Delphi, the default size is 4 bytes
  491. (\var{\{\$Z4\}}).
  492. So the follwoing code
  493. \begin{verbatim}
  494. {$PACKENUM 1}
  495. Type
  496. Days = (monday, tuesday, wednesday, thursday, friday,
  497. saturday, sunday);
  498. \end{verbatim}
  499. will use 1 byte to store a variable of type \var{Days}, wheras it nomally
  500. would use 4 bytes. The above code is equivalent to
  501. \begin{verbatim}
  502. {$Z1}
  503. Type
  504. Days = (monday, tuesday, wednesday, thursday, friday,
  505. saturday, sunday);
  506. \end{verbatim}
  507. {\em Remark:}
  508. Sets are always put in 32 bit or 32 bytes, this cannot be changed
  509. \subsection{\var{\$PACKRECORDS} : Alignment of record elements}
  510. This directive controls the byte alignment of the elements in a record,
  511. object or class type definition.
  512. It is of the following form:
  513. \begin{verbatim}
  514. {$PACKRECORDS n}
  515. \end{verbatim}
  516. Where \var{n} is one of 1,2,4,16 or \var{NORMAL} or \var{DEFAULT}.
  517. This means that the elements of a record that have size greater than \var{n}
  518. will be aligned on \var{n} byte boundaries. Elements with size less than or
  519. equal to \var{n} will be aligned to a natural boundary, i.e. to a power of
  520. two that is equal to or larger than the element's size.
  521. The default alignment (which can be selected with \var{DEFAULT}) is 2,
  522. contrary to Turbo Pascal, where it is 1.
  523. More information on this and an exmple program can be found in the reference
  524. guide, in the section about record types.
  525. {\em Remark:}
  526. Sets are always put in 32 bit or 32 bytes, this cannot be changed
  527. \subsection{\var{\$Q} \var{\$OVERFLOWCHECKS}: Overflow checking}
  528. The \var{\{\$Q+\}} or \var{\{\$OVERFLOWCHECKS ON\}} directive turns on
  529. integer overflow checking. This means that the compiler inserts code
  530. to check for overflow when doing computations with integers.
  531. When an overflow occurs, the run-time library will print a message
  532. \var{Overflow at xxx}, and exit the program with exit code 215.
  533. \emph{ Remark: } Overflow checking behaviour is not the same as in
  534. Turbo Pascal since all arithmetic operations are done via 32-bit
  535. values. Furthermore, the Inc() and Dec() standard system procedures
  536. \emph{ are } checked for overflow in \fpc, while in Turbo Pascal they
  537. are not.
  538. Using the \var{\{\$Q-\}} switch switches off the overflow checking code
  539. generation.
  540. The generation of overflow checking code can also be controlled
  541. using the \var{-Co} command line compiler option (see \userref).
  542. \subsection{\var{\$R} or \var{\$RANGECHECKS} : Range checking}
  543. By default, the computer doesn't generate code to check the ranges of array
  544. indices, enumeration types, subrange types, etc. Specifying the
  545. \var{\{\$R+\}} switch tells the computer to generate code to check these
  546. indices. If, at run-time, an index or enumeration type is specified that is
  547. out of the declared range of the compiler, then a run-time error is
  548. generated, and the program exits with exit code 201.
  549. The \var{\{\$RANGECHECKS OFF\}} switch tells the compiler not to generate range checking
  550. code. This may result in faulty program behaviour, but no run-time errors
  551. will be generated.
  552. {\em Remark: } Range checking for sets and enumerations are not yet fully
  553. implemented.
  554. \subsection{\var{\$SATURATION} : Saturation operations}
  555. This works only on the intel compiler, and MMX support must be on
  556. (\var{\{\$MMX +\}}) for this to have any effect. See the section on
  557. saturation support (\sees{SaturationSupport}) for more information
  558. on the effect of this directive.
  559. \subsection{\var{\$STOP} : Generate fatal error message}
  560. The following code
  561. \begin{verbatim}
  562. {$STOP This code is erroneous !}
  563. \end{verbatim}
  564. will display an error message when the compiler encounters it.
  565. The compiler will immediatly stop the compilation process.
  566. It has the same effect as the \var{\{\$FATAL\}} directive.
  567. \subsection{\var{\$T} or \var{\$TYPEDADDRESS} : Typed address operator (@)}
  568. In the \var{\{\$T+\}} or \var{\{\$TYPEDADDRESS ON\}} state the @ operator,
  569. when applied to a variable, returns a result of type \var{\^{}T}, if the
  570. type of the variable is \var{T}. In the \var{\{\$T-\}} state, the result is
  571. always an untyped pointer, which is assignment compatible with all other
  572. pointer types.
  573. \subsection{\var{\$UNDEF} : Undefine a symbol}
  574. The directive
  575. \begin{verbatim}
  576. {$UNDEF name}
  577. \end{verbatim}
  578. un-defines the symbol \var{name} if it was previously defined.
  579. \var{Name} is case insensitive.
  580. \subsection{\var{\$V} or \var{\$VARSTRINGCHECKS} : Var-string checking}
  581. When in the \var{+} or \var{ON} state, the compiler checks that strings
  582. passed as parameters are of the same, identical, string type as the declared
  583. parameters of the procedure.
  584. \subsection{\var{\$WAIT} : Wait for enter key press}
  585. If the compiler encaounters a
  586. \begin{verbatim}
  587. {$WAIT }
  588. \end{verbatim}
  589. directive, it will resume compiling only after the user has pressed the
  590. enter key. If the generation of info messages is turned on, then the compiler
  591. will display the follwing message:
  592. \begin{verbatim}
  593. Press <return> to continue
  594. \end{verbatim}
  595. before waiting for a keypress. Careful ! this may interfere with automatic
  596. compilation processes. It should be used for debuggig purposes only.
  597. \subsection{\var{\$WARNING} : Generate warning message}
  598. If the generation of warnings is turned on, through the \var{-vw}
  599. command-line option or the \var{\{\$WARNINGS ON\}} directive, then
  600. \begin{verbatim}
  601. {$WARNING This is dubious code }
  602. \end{verbatim}
  603. will display a warning message when the compiler encounters it.
  604. \subsection{\var{\$WARNINGS} : Emit warnings}
  605. \var{\{\$WARNINGS ON\}} switches the generation of warnings on.
  606. \var{\{\$WARNINGS OFF\}} switches the generation of warnings off.
  607. Contrary to the command-line option \var{-vw} this
  608. is a local switch, this is useful for checking parts of your code.
  609. \subsection{\var{\$X} or \var{\$EXTENDEDSYNTAX} : Extended syntax}
  610. Extended syntax allows you to drop the result of a function. This means that
  611. you can use a function call as if it were a procedure. Standard this feature
  612. is on. You can switch it off using the \var{\{\$X-\}} or
  613. \var{\{\$EXTENDEDSYNTAX OFF\}}directive.
  614. The following, for instance, will not compile :
  615. \begin{verbatim}
  616. function Func (var Arg : sometype) : longint;
  617. begin
  618. ... { declaration of Func }
  619. end;
  620. ...
  621. {$X-}
  622. Func (A);
  623. \end{verbatim}
  624. The reason this construct is supported is that you may wish to call a
  625. function for certain side-effects it has, but you don't need the function
  626. result. In this case you don't need to assign the function result, saving
  627. you an extra variable.
  628. The command-line compiler switch \var{-Sa1} has the same effect as the
  629. \var{\{\$X+\}} directive.
  630. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  631. % Global switches
  632. \section{Global directives}
  633. \label{se:GlobalSwitch}
  634. Global directives affect the whole of the compilation process. That is why
  635. they also have a command - line counterpart. The command-line counterpart is
  636. given for each of the directives.
  637. \subsection{\var{\$D} or \var{\$DEBUGINFO}: Debugging symbols}
  638. When this switch is on (\var{\{\$DEBUGINFO ON\}}),
  639. the compiler inserts GNU debugging information in
  640. the executable. The effect of this switch is the same as the command-line
  641. switch \var{-g}. By default, insertion of debugging information is off.
  642. \subsection{\var{\$E} : Emulation of coprocessor}
  643. This directive controls the emulation of the coprocessor. There is no
  644. command-line counterpart for this directive.
  645. \subsubsection{ Intel x86 version }
  646. When this switch is enabled, all floating point instructions
  647. which are not supported by standard coprocessor emulators will give out
  648. a warning.
  649. The compiler itself doesn't do the emulation of the coprocessor.
  650. To use coprocessor emulation under \dos go32v1 there is nothing special
  651. required, as it is handled automatically. (As of version 0.99.10, the
  652. go32v1 platform will no longer be supported)
  653. To use coprocessor emulation under \dos go32v2 you must use the
  654. emu387 unit, which contains correct initialization code for the
  655. emulator.
  656. Under \linux, the kernel takes care of the coprocessor support.
  657. \subsubsection{ Motorola 680x0 version }
  658. When the switch is on, no floating point opcodes are emitted
  659. by the code generator. Instead, internal run-time library routines
  660. are called to do the necessary calculations. In this case all
  661. real types are mapped to the single IEEE floating point type.
  662. \emph{ Remark : } By default, emulation is on. It is possible to
  663. intermix emulation code with real floating point opcodes, as
  664. long as the only type used is single or real.
  665. \subsection{\var{\$G} : Generate 80286 code}
  666. This option is recognised for Turbo Pascal compatibility, but is ignored,
  667. \subsection{\var{\$L} or \var{\$LOCALSYMBOLS}: Local symbol information}
  668. This switch (not to be confused with the \var{\{\$L file\}} file linking
  669. directive) is recognised for Turbo Pascal compatibility, but is ignored.
  670. generation of symbol information is controlled by the \var{\$D} switch.
  671. \subsection{\var{\$M} or \var{\$MEMORY}: Memory sizes}
  672. This switch can be used to set the heap and stacksize. It's format is as
  673. follows:
  674. \begin{verbatim}
  675. {$M StackSize,HeapSize}
  676. \end{verbatim}
  677. Wher \var{StackSize} and \var{HeapSize} should be two integer values,
  678. greater than 1024. The first number sets the size of the stack, and the
  679. second the size of the heap. (Stack setting is ignored under \linux).
  680. The two numbers can be set on the command line using the \var{-Ch}
  681. (and \var{-Cs} switches.
  682. \subsection{\var{\$N} : Numeric processing }
  683. This switch is recognised for Turbo Pascal compatibility, but is otherwise
  684. ignored, since the compiler always uses the coprocessor for floating point
  685. mathematics.
  686. \subsection{\var{\$O} : Overlay code generation }
  687. This switch is recognised for Turbo Pascal compatibility, but is otherwise
  688. ignored.
  689. \subsection{\var{\$S} : Stack checking}
  690. The \var{\{\$S+\}} directive tells the compiler to generate stack checking
  691. code. This generates code to check if a stack overflow occurred, i.e. to see
  692. whether the stack has grown beyond its maximally allowed size. If the stack
  693. grows beyond the maximum size, then a run-time error is generated, and the
  694. program will exit with exit code 202.
  695. Specifying \var{\{\$S-\}} will turn generation of stack-checking code off.
  696. The command-line compiler switch \var{-Ct} has the same effect as the
  697. \var{\{\$S+\}} directive.
  698. \subsection{\var{\$W} or \var{\$STACKFRAMES} : Generate stackframes}
  699. The \var{\{\$W\}} switch directove controls the generation of stackframes.
  700. In the on state (\var{\{\$STACKFRAMES ON\}}), the compiler will generate a
  701. stackframe for every procedure or function.
  702. In the off state, the compiler will omit the generation of a stackframe if
  703. the following conditions are satisfied:
  704. \begin{itemize}
  705. \item The procedure has no parameters.
  706. \item The procedure has no local variables.
  707. \item If the procedure is not an \var{assembler} procedure, it must not have
  708. a \var{asm ... end;} block.
  709. \item it is not a constuctor or desctructor.
  710. \end{itemize}
  711. If these conditions are satisfied, the stack frame will be omitted.
  712. \subsection{\var{\$Y} or \var{\$REFERENCEINFO} : Insert Browser information}
  713. This switch controls the generation of browser inforation. It is recognized
  714. for compatibility with Turbo Pascal and Delphi only, as Browser information
  715. generation is not yet fully supported.
  716. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  717. % Using conditionals and macros
  718. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  719. \chapter{Using conditionals, Messages and macros}
  720. \label{ch:CondMessageMacro}
  721. The \fpc compiler supports conditionals as in normal Turbo Pascal. It does,
  722. however, more than that. It allows you to make macros which can be used in
  723. your code, and it allows you to define messages or errors which will be
  724. displayed when compiling.
  725. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  726. % Conditionals
  727. \section{Conditionals}
  728. \label{se:Conditionals}
  729. The rules for using conditional symbols are the same as under Turbo Pascal.
  730. Defining a symbol goes as follows:
  731. \begin{verbatim}
  732. {$Define Symbol }
  733. \end{verbatim}
  734. From this point on in your code, the compiler know the symbol \var{Symbol}
  735. Symbols are, like the Pascal language, case insensitive.
  736. You can also define a symbol on the command line. the \var{-dSymbol} option
  737. defines the symbol \var{Symbol}. You can specify as many symbols on the
  738. command line as you want.
  739. Undefining an existing symbol is done in a similar way:
  740. \begin{verbatim}
  741. {$Undef Symbol }
  742. \end{verbatim}
  743. If the symbol didn't exist yet, this doesn't do anything. If the symbol
  744. existed previously, the symbol will be erased, and will not be recognized
  745. any more in the code following the \verb|{$Undef ...}| statement.
  746. You can also undefine symbols from the command line with the \var{-u}
  747. command-line switch..
  748. To compile code conditionally, depending on whether a symbol is defined or
  749. not, you can enclose the code in a \verb|{$ifdef Symbol}| .. \verb|{$endif}|
  750. pair. For instance the following code will never be compiled :
  751. \begin{verbatim}
  752. {$Undef MySymbol}
  753. {$ifdef Mysymbol}
  754. DoSomething;
  755. ...
  756. {$endif}
  757. \end{verbatim}
  758. Similarly, you can enclose your code in a \verb|{$Ifndef Symbol}| .. \verb|{$endif}|
  759. pair. Then the code between the pair will only be compiled when the used
  760. symbol doesn't exist. For example, in the following example, the call to the
  761. \var{DoSomething} will always be compiled:
  762. \begin{verbatim}
  763. {$Undef MySymbol}
  764. {$ifndef Mysymbol}
  765. DoSomething;
  766. ...
  767. {$endif}
  768. \end{verbatim}
  769. You can combine the two alternatives in one structure, namely as follows
  770. \begin{verbatim}
  771. {$ifdef Mysymbol}
  772. DoSomething;
  773. {$else}
  774. DoSomethingElse
  775. {$endif}
  776. \end{verbatim}
  777. In this example, if \var{MySymbol} exists, then the call to \var{DoSomething}
  778. will be compiled. If it doesn't exist, the call to \var{DoSomethingElse} is
  779. compiled.
  780. The \fpc compiler defines some symbols before starting to compile your
  781. program or unit. You can use these symbols to differentiate between
  782. different versions of the compiler, and between different compilers.
  783. In \seet{Symbols}, a list of pre-defined symbols is given\footnote{Remark:
  784. The \var{FPK} symbol is still defined for compatibility with older versions.}. In that table,
  785. you should change \var{v} with the version number of the compiler
  786. you're using, \var{r} with the release number and \var{p}
  787. with the patch-number of the compiler. 'OS' needs to be changed by the type
  788. of operating system. Currently this can be one of \var{DOS}, \var{GO32V2},
  789. \var{LINUX}, \var{OS2}, \var{WIN32}, \var{MACOS}, \var{AMIGA} or \var{ATARI}. This symbol is undefined if you
  790. specify a target that is different from the platform you're compiling on.
  791. the \var{-TSomeOS} option on the command line will define the \var{SomeOS} symbol,
  792. and will undefined the existing platform symbol\footnote{In versions prior to
  793. 0.9.4, this didn't happen, thus making Cross-compiling impossible.}.
  794. \begin{FPCltable}{c}{Symbols defined by the compiler.}{Symbols} \hline
  795. Free \\
  796. VER\var{v} \\
  797. VER\var{v}\_\var{r} \\
  798. VER\var{v}\_\var{r}\_\var{p} \\
  799. OS \\ \hline
  800. \end{FPCltable}
  801. As an example : Version 0.9.1 of the compiler, running on a Linux system,
  802. defines the following symbols before reading the command line arguments:
  803. \var{FPC}, \var{VER0}, \var{VER0\_9}, \var{VER0\_9\_1} and \var{LINUX}.
  804. Specifying \var{-TOS2} on the command-line will undefine the \var{LINUX}
  805. symbol, and will define the \var{OS2} symbol.
  806. {\em Remark: } Symbols, even when they're defined in the interface part of
  807. a unit, are not available outside that unit.
  808. \fpc supports the \var{\{\$IFOPT \}} directive for Turbo Pascal
  809. compatibility, but doesn't act on it. It always rejects the condition, so
  810. code between \var{\{\$IFOPT \}} and \var{\{\$Endif\}} is never compiled.
  811. Except for the Turbo Pascal constructs, from version 0.9.8 and higher,
  812. the \fpc compiler also supports a stronger conditional compile mechanism:
  813. The \var{\{\$If \}} construct.
  814. The prototype of this construct is as follows :
  815. \begin{verbatim}
  816. {$If expr}
  817. CompileTheseLines;
  818. {$else}
  819. BetterCompileTheseLines;
  820. {$endif}
  821. \end{verbatim}
  822. In this directive \var{expr} is a Pascal expression which is evaluated using
  823. strings, unless both parts of a comparision can be evaluated as numbers,
  824. in which case they are evaluated using numbers\footnote{Otherwise
  825. \var{\{\$If 8>54} would evaluate to \var{True}}.
  826. If the complemete expression evaluates to \var{'0'}, then it is considered
  827. false and rejected. Otherwise it is considered true and accepted. This may
  828. have unsexpected consequences :
  829. \begin{verbatim}
  830. {$If 0}
  831. \end{verbatim}
  832. Will evaluate to \var{False} and be rejected, while
  833. \begin{verbatim}
  834. {$If 00}
  835. \end{verbatim}
  836. Will evaluate to \var{True}.
  837. You can use any Pascal operator to construct your expression : \var{=, <>,
  838. >, <, >=, <=, AND, NOT, OR} and you can use round brackets to change the
  839. precedence of the operators.
  840. The following example shows you many of the possibilities:
  841. \begin{verbatim}
  842. {$ifdef fpc}
  843. var
  844. y : longint;
  845. {$else fpc}
  846. var
  847. z : longint;
  848. {$endif fpc}
  849. var
  850. x : longint;
  851. begin
  852. {$if (fpc_version=0) and (fpc_release>6) and (fpc_patch>4)}
  853. {$info At least this is version 0.9.5}
  854. {$else}
  855. {$fatalerror Problem with version check}
  856. {$endif}
  857. {$define x:=1234}
  858. {$if x=1234}
  859. {$info x=1234}
  860. {$else}
  861. {$fatalerror x should be 1234}
  862. {$endif}
  863. {$if 12asdf and 12asdf}
  864. {$info $if 12asdf and 12asdf is ok}
  865. {$else}
  866. {$fatalerror $if 12asdf and 12asdf rejected}
  867. {$endif}
  868. {$if 0 or 1}
  869. {$info $if 0 or 1 is ok}
  870. {$else}
  871. {$fatalerror $if 0 or 1 rejected}
  872. {$endif}
  873. {$if 0}
  874. {$fatalerror $if 0 accepted}
  875. {$else}
  876. {$info $if 0 is ok}
  877. {$endif}
  878. {$if 12=12}
  879. {$info $if 12=12 is ok}
  880. {$else}
  881. {$fatalerror $if 12=12 rejected}
  882. {$endif}
  883. {$if 12<>312}
  884. {$info $if 12<>312 is ok}
  885. {$else}
  886. {$fatalerror $if 12<>312 rejected}
  887. {$endif}
  888. {$if 12<=312}
  889. {$info $if 12<=312 is ok}
  890. {$else}
  891. {$fatalerror $if 12<=312 rejected}
  892. {$endif}
  893. {$if 12<312}
  894. {$info $if 12<312 is ok}
  895. {$else}
  896. {$fatalerror $if 12<312 rejected}
  897. {$endif}
  898. {$if a12=a12}
  899. {$info $if a12=a12 is ok}
  900. {$else}
  901. {$fatalerror $if a12=a12 rejected}
  902. {$endif}
  903. {$if a12<=z312}
  904. {$info $if a12<=z312 is ok}
  905. {$else}
  906. {$fatalerror $if a12<=z312 rejected}
  907. {$endif}
  908. {$if a12<z312}
  909. {$info $if a12<z312 is ok}
  910. {$else}
  911. {$fatalerror $if a12<z312 rejected}
  912. {$endif}
  913. {$if not(0)}
  914. {$info $if not(0) is OK}
  915. {$else}
  916. {$fatalerror $if not(0) rejected}
  917. {$endif}
  918. {$info *************************************************}
  919. {$info * Now have to follow at least 2 error messages: *}
  920. {$info *************************************************}
  921. {$if not(0}
  922. {$endif}
  923. {$if not(<}
  924. {$endif}
  925. end.
  926. \end{verbatim}
  927. As you can see from the example, this construct isn't useful when used
  928. with normal symbols, but it is if you use macros, which are explained in
  929. \sees{Macros}, they can be very useful. When trying this example, you must
  930. switch on macro support, with the \var{-Sm} command-line switch.
  931. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  932. % Macros
  933. \section{Messages}
  934. \label{se:Messages}
  935. \fpc lets you define normal, warning and error messages in your code.
  936. Messages can be used to display useful information, such as copyright
  937. notices, a list of symbols that your code reacts on etc.
  938. Warnings can be used if you think some part of your code is still buggy, or
  939. if you think that a certain combination of symbols isn't useful. In general
  940. anything which may cause problems when compiling.
  941. Error messages can be useful if you need a certain symbol to be defined
  942. to warn that a certain variable isn't defined or so, or when the compiler
  943. version isn't suitable for your code.
  944. The compiler treats these messages as if they were generated by the
  945. compiler. This means that if you haven't turned on warning messages, the
  946. warning will not e displayed. Errors are always displayed, and the compiler
  947. stops as if an error had occurred.
  948. For messages, the syntax is as follows :
  949. \begin{verbatim}
  950. {$Message Message text }
  951. \end{verbatim}
  952. Or
  953. \begin{verbatim}
  954. {$Info Message text }
  955. \end{verbatim}
  956. For notes:
  957. \begin{verbatim}
  958. {$Note Message text }
  959. \end{verbatim}
  960. For warnings:
  961. \begin{verbatim}
  962. {$Warning Warning Message text }
  963. \end{verbatim}
  964. For errors :
  965. \begin{verbatim}
  966. {$Error Error Message text }
  967. \end{verbatim}
  968. Lastly, for fatal errors :
  969. \begin{verbatim}
  970. {$FatalError Error Message text }
  971. \end{verbatim}
  972. or
  973. \begin{verbatim}
  974. {$Stop Error Message text }
  975. \end{verbatim}
  976. The difference between \var{\$Error} and \var{\$FatalError} or \var{\$Stop}
  977. messages is that when the compiler encounters an error, it still continues
  978. to compile. With a fatal error, the compiler stops.
  979. {\em Remark :} You cannot use the '\var{\}}' character in your message, since
  980. this will be treated as the closing brace of the message.
  981. As an example, the following piece of code will generate an error when
  982. the symbol \var{RequiredVar} isn't defined:
  983. \begin{verbatim}
  984. {$ifndef RequiredVar}
  985. {$Error Requiredvar isn't defined !}
  986. {$endif}
  987. \end{verbatim}
  988. But the compiler will continue to compile. It will not, however, generate a
  989. unit file or a program (since an error occurred).
  990. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  991. % Macros
  992. \section{Macros}
  993. \label{se:Macros}
  994. Macros are very much like symbols in their syntax, the difference is that
  995. macros have a value whereas a symbol simply is defined or is not defined.
  996. If you want macro support, you need to specify the \var{-Sm} command-line
  997. switch, otherwise your macro will be regarded as a symbol.
  998. Defining a macro in your program is done in the same way as defining a symbol;
  999. in a \var{\{\$define \}} preprocessor statement\footnote{In compiler
  1000. versions older than 0.9.8, the assignment operator for a macros wasn't
  1001. \var{:=}, but \var{=}}:
  1002. \begin{verbatim}
  1003. {$define ident:=expr}
  1004. \end{verbatim}
  1005. If the compiler encounters \var{ident} in the rest of the source file, it
  1006. will be replaced immediately by \var{expr}. This replacement works
  1007. recursive, meaning that when the compiler expanded one of your macros, it
  1008. will look at the resulting expression again to see if another replacement
  1009. can be made. You need to be careful with this, because an infinite loop can
  1010. occur in this manner.
  1011. Here are two examples which illustrate the use of macros:
  1012. \begin{verbatim}
  1013. {$define sum:=a:=a+b;}
  1014. ...
  1015. sum { will be expanded to 'a:=a+b;'
  1016. remark the absence of the semicolon}
  1017. ...
  1018. {$define b:=100}
  1019. sum { Will be expanded recursively to a:=a+100; }
  1020. ...
  1021. \end{verbatim}
  1022. The previous example could go wrong :
  1023. \begin{verbatim}
  1024. {$define sum:=a:=a+b;}
  1025. ...
  1026. sum { will be expanded to 'a:=a+b;'
  1027. remark the absence of the semicolon}
  1028. ...
  1029. {$define b=sum} { DON'T do this !!!}
  1030. sum { Will be infinitely recursively expanded... }
  1031. ...
  1032. \end{verbatim}
  1033. On my system, the last example results in a heap error, causing the compiler
  1034. to exit with a run-time error 203.
  1035. {\em Remark: } Macros defined in the interface part of a unit are not
  1036. available outside that unit ! They can just be used as a notational
  1037. convenience, or in conditional compiles.
  1038. By default, from version 0.9.8 of the compiler on, the compiler predefines three
  1039. macros, containing the version number, the release number and the patch
  1040. number. They are listed in \seet{DefMacros}.
  1041. \begin{FPCltable}{ll}{Predefined macros}{DefMacros} \hline
  1042. Symbol & Contains \\ \hline
  1043. \var{FPC\_VERSION} & The version number of the compiler. \\
  1044. \var{FPC\_RELEASE} & The release number of the compiler. \\
  1045. \var{FPC\_PATCH} & The patch number of the compiler. \\
  1046. \hline
  1047. \end{FPCltable}
  1048. {\em Remark: } Don't forget that macros support isn't on by default. You
  1049. need to compile with the \var{-Sm} command-line switch.
  1050. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1051. % Using assembly language
  1052. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1053. \chapter{Using Assembly language}
  1054. \label{ch:AsmLang}
  1055. \fpc supports inserting of assembler instructions in your code. The
  1056. mechanism for this is the same as under Turbo Pascal. There are, however
  1057. some substantial differences, as will be explained in the following.
  1058. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1059. % Intel syntax
  1060. \section{Intel syntax}
  1061. \label{se:Intel}
  1062. As of version 0.9.7, \fpc supports Intel syntax for the Intel family of Ix86
  1063. processors in it's \var{asm} blocks.
  1064. The Intel syntax in your \var{asm} block is converted to AT\&T syntax by the
  1065. compiler, after which it is inserted in the compiled source.
  1066. The supported assembler constructs are a subset of the normal assembly
  1067. syntax. In what follows we specify what constructs are not supported in
  1068. \fpc, but which exist in Turbo Pascal:
  1069. \begin{itemize}
  1070. \item The \var{TBYTE} qualifier is not supported.
  1071. \item The \var{\&} identifier override is not supported.
  1072. \item The \var{HIGH} operator is not supported.
  1073. \item The \var{LOW} operator is not supported.
  1074. \item The \var{OFFSET} and \var{SEG} operators are not supported.
  1075. use \var{LEA} and the various \var{Lxx} instructions instead.
  1076. \item Expressions with constant strings are not allowed.
  1077. \item Access to record fields via parenthesis is not allowed
  1078. \item Typecasts with normal pascal types are not allowed, only
  1079. recognized assembler typecasts are allowed.\\ Example:
  1080. \begin{verbatim}
  1081. mov al, byte ptr MyWord -- allowed,
  1082. mov al, byte(MyWord) -- allowed,
  1083. mov al, shortint(MyWord) -- not allowed.
  1084. \end{verbatim}
  1085. \item Pascal type typecasts on constants are not allowed. \\
  1086. Example:
  1087. \begin{verbatim}
  1088. const s= 10; const t = 32767;
  1089. \end{verbatim}
  1090. in Turbo Pascal:
  1091. \begin{verbatim}
  1092. mov al, byte(s) -- useless typecast.
  1093. mov al, byte(t) -- syntax error!
  1094. \end{verbatim}
  1095. In this parser, either of those cases will give out a syntax error.
  1096. \item Constant references expressions with constants only are not
  1097. allowed (in all cases they do not work in protected mode,
  1098. under linux i386). \\ Examples:
  1099. \begin{verbatim}
  1100. mov al,byte ptr ['c'] -- not allowed.
  1101. mov al,byte ptr [100h] -- not allowed.
  1102. \end{verbatim}
  1103. (This is due to the limitation of Turbo Assembler).
  1104. \item Brackets within brackets are not allowed
  1105. \item Expressions with segment overrides fully in brackets are
  1106. presently not supported, but they can easily be implemented
  1107. in BuildReference if requested. \\ Example:
  1108. \begin{verbatim}
  1109. mov al,[ds:bx] -- not allowed
  1110. \end{verbatim}
  1111. use instead:
  1112. \begin{verbatim}
  1113. mov al,ds:[bx]
  1114. \end{verbatim}
  1115. \item Possible allowed indexing are as follows:
  1116. \begin{itemize}
  1117. \item \var{Sreg:[REG+REG*SCALING+/-disp]}
  1118. \item \var{SReg:[REG+/-disp]}
  1119. \item \var{SReg:[REG]}
  1120. \item \var{SReg:[REG+REG+/-disp]}
  1121. \item \var{SReg:[REG+REG*SCALING]}
  1122. \end{itemize}
  1123. Where \var{Sreg} is optional and specifies the segment override.
  1124. {\em Notes:}
  1125. \begin{enumerate}
  1126. \item The order of terms is important contrary to Turbo Pascal.
  1127. \item The Scaling value must be a value, and not an identifier
  1128. to a symbol.\\ Examples:
  1129. \begin{verbatim}
  1130. const myscale = 1;
  1131. ...
  1132. mov al,byte ptr [esi+ebx*myscale] -- not allowed.
  1133. \end{verbatim}
  1134. use:
  1135. \begin{verbatim}
  1136. mov al, byte ptr [esi+ebx*1]
  1137. \end{verbatim}
  1138. \end{enumerate}
  1139. \item Possible variable identifier syntax is as follows:
  1140. (Id = Variable or typed constant identifier.)
  1141. \begin{enumerate}
  1142. \item \var{ID}
  1143. \item \var{[ID]}
  1144. \item \var{[ID+expr]}
  1145. \item \var{ID[expr]}
  1146. \end{enumerate}
  1147. Possible fields are as follow:
  1148. \begin{enumerate}
  1149. \item \var{ID.subfield.subfield ...}
  1150. \item \var{[ref].ID.subfield.subfield ...}
  1151. \item \var{[ref].typename.subfield ...}
  1152. \end{enumerate}
  1153. \item Local Labels: Contrary to Turbo Pascal, local labels, must
  1154. at least contain one character after the local symbol indicator.\\
  1155. Example:
  1156. \begin{verbatim}
  1157. @: -- not allowed
  1158. \end{verbatim}
  1159. use instead, for example:
  1160. \begin{verbatim}
  1161. @1: -- allowed
  1162. \end{verbatim}
  1163. \item Contrary to Turbo Pascal local references cannot be used as references,
  1164. only as displacements. \\ example:
  1165. \begin{verbatim}
  1166. lds si,@mylabel -- not allowed
  1167. \end{verbatim}
  1168. \item Contrary to Turbo Pascal, \var{SEGCS}, \var{SEGDS}, \var{SEGES} and
  1169. \var{SEGSS} segment overrides are presently not supported.
  1170. (This is a planned addition though).
  1171. \item Contrary to Turbo Pascal where memory sizes specifiers can
  1172. be practically anywhere, the \fpc Intel inline assembler requires
  1173. memory size specifiers to be outside the brackets. \\
  1174. example:
  1175. \begin{verbatim}
  1176. mov al,[byte ptr myvar] -- not allowed.
  1177. \end{verbatim}
  1178. use:
  1179. \begin{verbatim}
  1180. mov al,byte ptr [myvar] -- allowed.
  1181. \end{verbatim}
  1182. \item Base and Index registers must be 32-bit registers.
  1183. (limitation of the GNU Assembler).
  1184. \item \var{XLAT} is equivalent to \var{XLATB}.
  1185. \item Only Single and Double FPU opcodes are supported.
  1186. \item Floating point opcodes are currently not supported
  1187. (except those which involve only floating point registers).
  1188. \end{itemize}
  1189. The Intel inline assembler supports the following macros :
  1190. \begin{description}
  1191. \item [@Result] represents the function result return value.
  1192. \item [Self] represents the object method pointer in methods.
  1193. \end{description}
  1194. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1195. % AT&T syntax
  1196. \section{AT\&T Syntax}
  1197. \label{se:AttSyntax}
  1198. \fpc uses the \gnu \var{as} assembler to generate its object files for
  1199. the Intel Ix86 processors . Since
  1200. the \gnu assembler uses AT\&T assembly syntax, the code you write should
  1201. use the same syntax. The differences between AT\&T and Intel syntax as used
  1202. in Turbo Pascal are summarized in the following:
  1203. \begin{itemize}
  1204. \item The opcode names include the size of the operand. In general, one can
  1205. say that the AT\&T opcode name is the Intel opcode name, suffixed with a
  1206. '\var{l}', '\var{w}' or '\var{b}' for, respectively, longint (32 bit),
  1207. word (16 bit) and byte (8 bit) memory or register references. As an example,
  1208. the Intel construct \mbox{'\var{mov al bl}} is equivalent to the AT\&T style '\var{movb
  1209. \%bl,\%al}' instruction.
  1210. \item AT\&T immediate operands are designated with '\$', while Intel syntax
  1211. doesn't use a prefix for immediate operands. Thus the Intel construct
  1212. '\var{mov ax, 2}' becomes '\var{movb \$2, \%al}' in AT\&T syntax.
  1213. \item AT\&T register names are preceded by a '\var{\%}' sign.
  1214. They are undelimited in Intel syntax.
  1215. \item AT\&T indicates absolute jump/call operands with '\var{*}', Intel
  1216. syntax doesn't delimit these addresses.
  1217. \item The order of the source and destination operands are switched. AT\&T
  1218. syntax uses '\var{Source, Dest}', while Intel syntax features '\var{Dest,
  1219. Source}'. Thus the Intel construct '\var{add eax, 4}' transforms to
  1220. '\var{addl \$4, \%eax}' in the AT\&T dialect.
  1221. \item Immediate long jumps are prefixed with the '\var{l}' prefix. Thus the
  1222. Intel '\var{call/jmp section:offset'} is transformed to '\var{lcall/ljmp
  1223. \$section,\$offset}'. Similarly the far return is '\var{lret}', instead of the
  1224. Intel '\var{ret far}'.
  1225. \item Memory references are specified differently in AT\&T and Intel
  1226. assembly. The Intel indirect memory reference
  1227. \begin{quote}
  1228. \var{Section:[Base + Index*Scale + Offs]}
  1229. \end{quote}
  1230. is written in AT\&T syntax as :
  1231. \begin{quote}
  1232. \var{Section:Offs(Base,Index,Scale)}
  1233. \end{quote}
  1234. Where \var{Base} and \var{Index} are optional 32-bit base and index
  1235. registers, and \var{Scale} is used to multiply \var{Index}. It can take the
  1236. values 1,2,4 and 8. The \var{Section} is used to specify an optional section
  1237. register for the memory operand.
  1238. \end{itemize}
  1239. More information about the AT\&T syntax can be found in the \var{as} manual,
  1240. although the following differences with normal AT\&T assembly must be taken
  1241. into account :
  1242. \begin{itemize}
  1243. \item Only the following directives are presently supported:
  1244. \begin{description}
  1245. \item[.byte]
  1246. \item[.word]
  1247. \item[.long]
  1248. \item[.ascii]
  1249. \item[.asciz]
  1250. \item[.globl]
  1251. \end{description}
  1252. \item The following directives are recognized but are not
  1253. supported:
  1254. \begin{description}
  1255. \item[.align]
  1256. \item[.lcomm]
  1257. \end{description}
  1258. Eventually they will be supported.
  1259. \item Directives are case sensitive, other identifiers are not case sensitive.
  1260. \item Contrary to GAS local labels/symbols {\em must} start with \var{.L}
  1261. \item The nor operator \var{'!'} is not supported.
  1262. \item String expressions in operands are not supported.
  1263. \item CBTW,CWTL,CWTD and CLTD are not supported, use the normal intel
  1264. equivalents instead.
  1265. \item Constant expressions which represent memory references are not
  1266. allowed even though constant immediate value expressions are supported. \\
  1267. examples:
  1268. \begin{verbatim}
  1269. const myid = 10;
  1270. ...
  1271. movl $myid,%eax -- allowed
  1272. movl myid(%esi),%eax -- not allowed.
  1273. \end{verbatim}
  1274. \item When the \var{.globl} directive is found, the symbol following
  1275. it is made public and is immediately emitted.
  1276. Therefore label names with this name will be ignored.
  1277. \item Only Single and Double FPU opcodes are supported.
  1278. \end{itemize}
  1279. The AT\&T inline assembler supports the following macros :
  1280. \begin{description}
  1281. \item [\_\_RESULT] represents the function result return value.
  1282. \item [\_\_SELF] represents the object method pointer in methods.
  1283. \item [\_\_OLDEBP] represents the old base pointer in recusrive routines.
  1284. \end{description}
  1285. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1286. % Calling mechanism
  1287. \section{Calling mechanism}
  1288. \label{se:Calling}
  1289. Procedures and Functions are called with their parameters on the stack.
  1290. Contrary to Turbo Pascal, {\em all} parameters are pushed on the stack, and
  1291. they are pushed {\em right} to {\em left}, instead of left to right for
  1292. Turbo Pascal. This is especially important if you have some assembly
  1293. subroutines in Turbo Pascal which you would like to translate to \fpc.
  1294. Function results are returned in the accumulator, if they fit in the
  1295. register.
  1296. The registers are {\em not} saved when calling a function or procedure. If
  1297. you want to call a procedure or function from assembly language, you must
  1298. save any registers you wish to preserve.
  1299. The first thing a procedure does is saving the base pointer, and setting the
  1300. base pointer equal to the stack pointer. References to the pushed parameters
  1301. and local variables are constructed using the base pointer.
  1302. When the procedure or function exits, it clears the stack.
  1303. When you want your code to be called by a C library or used in a C
  1304. program, you will run into trouble because of this calling mechanism. In C,
  1305. the calling procedure is expected to clear the stack, not the called
  1306. procedure. In other words, the arguments still are on the stack when the
  1307. procedure exits. To avoid this problem, \fpc supports the \var{export}
  1308. modifier. Procedures that are defined using the export modifier, use a
  1309. C-compatible calling mechanism. This means that they can be called from a
  1310. C program or library, or that you can use them as a callback function.
  1311. This also means that you cannot call this procedure or function from your
  1312. own program, since your program uses the Pascal calling convention.
  1313. However, in the exported function, you can of course call other Pascal
  1314. routines.
  1315. As of version 0.9.8, the \fpc compiler supports also the \var{cdecl} and
  1316. \var{stdcall} modifiers, as found in Delphi. The \var{cdecl} modifier does
  1317. the same as the \var{export} modifier, and \var{stdcall} does nothing, since
  1318. \fpc pushes the paramaters from right to left by default.
  1319. In addition to the Delphi \var{cdecl} construct, \fpc also supports the
  1320. \var{popstack} directive; it is nearly the same a the \var{cdecl} directive,
  1321. only it still mangles the name, i.e. makes it into a name such as the
  1322. compiler uses internally.
  1323. All this is summarized in \seet{Calling}. The first column lists the
  1324. modifier you specify for a procedure declaration. The second one lists the
  1325. order the paramaters are pushed on the stack. The third column specifies who
  1326. is responsible for cleaning the stack: the caller or the called function.
  1327. Finally, the last column specifies if registers are used to pass parameters
  1328. to the function.
  1329. \begin{FPCltable}{llll}{Calling mechanisms in \fpc}{Calling}\hline
  1330. Modifier & Pushing order & Stack cleaned by & Parameters in registers \\
  1331. \hline
  1332. (none) & Right-to-left & Function & No \\
  1333. cdecl & Right-to-left & Caller & No \\
  1334. export & Right-to-left & Caller & No \\
  1335. stdcall & Right-to-left & Function & No \\
  1336. popstack & Right-to-left & Caller & No \\ \hline
  1337. \end{FPCltable}
  1338. More about this can be found in \seec{Linking} on linking.
  1339. \subsection{ Ix86 calling conventions }
  1340. Standard entry code for procedures and functions is as follows on the
  1341. x86 architecture:
  1342. \begin{verbatim}
  1343. pushl %ebp
  1344. movl %esp,%ebp
  1345. \end{verbatim}
  1346. The generated exit sequence for procedure and functions looks as follows:
  1347. \begin{verbatim}
  1348. leave
  1349. ret $xx
  1350. \end{verbatim}
  1351. Where \var{xx} is the total size of the pushed parameters.
  1352. To have more information on function return values take a look at the
  1353. \sees{RegConvs} section.
  1354. \subsection{ M680x0 calling conventions }
  1355. Standard entry code for procedures and functions is as follows on the
  1356. 680x0 architecture:
  1357. \begin{verbatim}
  1358. move.l a6,-(sp)
  1359. move.l sp,a6
  1360. \end{verbatim}
  1361. The generated exit sequence for procedure and functions looks as follows:
  1362. \begin{verbatim}
  1363. unlk a6
  1364. move.l (sp)+,a0 ; Get return address
  1365. add.l #xx,sp ; Remove allocated stack
  1366. move.l a0,-(sp) ; Put back return address on top of the stack
  1367. \end{verbatim}
  1368. Where \var{xx} is the total size of the pushed parameters.
  1369. To have more information on function return values take a look at the
  1370. \sees{RegConvs} section.
  1371. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1372. % Telling the compiler what registers have changed
  1373. \section{Signalling changed registers}
  1374. \label{se:RegChanges}
  1375. When the compiler uses variables, it sometimes stores them, or the result of
  1376. some calculations, in the processor registers. If you insert assembler code
  1377. in your program that modifies the processor registers, then this may
  1378. interfere with the compiler's idea about the registers. To avoid this
  1379. problem, \fpc allows you to tell the compiler which registers have changed.
  1380. The compiler will then avoid using these registers. Telling the compiler
  1381. which registers have changed, is done by specifying a set of register names
  1382. behind an assembly block, as follows:
  1383. \begin{verbatim}
  1384. asm
  1385. ...
  1386. end ['R1',...,'Rn'];
  1387. \end{verbatim}
  1388. Here \var{R1} to \var{Rn} are the names of the 32-bit registers you
  1389. modify in your assembly code.
  1390. As an example :
  1391. \begin{verbatim}
  1392. asm
  1393. movl BP,%eax
  1394. movl 4(%eax),%eax
  1395. movl %eax,__RESULT
  1396. end ['EAX'];
  1397. \end{verbatim}
  1398. This example tells the compiler that the \var{EAX} register was modified.
  1399. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1400. % Register conventions
  1401. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1402. \section{Register Conventions}
  1403. \label{se:RegConvs}
  1404. The compiler has different register conventions, depending on the
  1405. target processor used.
  1406. \subsection{ Intel x86 version }
  1407. When optimizations are on, no register can be freely modified, without
  1408. first being saved and then restored. Otherwise, EDI is usually used as
  1409. a scratch register and can be freely used in assembler blocks.
  1410. \subsection{ Motorola 680x0 version }
  1411. Registers which can be freely modified without saving are registers
  1412. D0, D1, D6, A0, A1, and floating point registers FP2 to FP7. All other
  1413. registers are to be considered reserved and should be saved and then
  1414. restored when used in assembler blocks.
  1415. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1416. % Linking issues
  1417. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1418. \chapter{Linking issues}
  1419. \label{ch:Linking}
  1420. When you only use Pascal code, and Pascal units, then you will not see much
  1421. of the part that the linker plays in creating your executable.
  1422. The linker is only called when you compile a program. When compiling units,
  1423. the linker isn't invoked.
  1424. However, there are times that you want to C libraries, or to external
  1425. object files that are generated using a C compiler (or even another pascal
  1426. compiler). The \fpc compiler can generate calls to a C function,
  1427. and can generate functions that can be called from C (exported functions).
  1428. More on these calling conventions can be found in \sees{Calling}.
  1429. In general, there are 2 things you must do to use a function that resides in
  1430. an external library or object file:
  1431. \begin{enumerate}
  1432. \item You must make a pascal declaration of the function or procedure you
  1433. want to use.
  1434. \item You must tell the compiler where the function resides, i.e. in what
  1435. object file or what library, so the compiler can link the necessary code in.
  1436. \end{enumerate}
  1437. The same holds for variables. To access a variable that resides in an
  1438. external object file, you ust declare it, and tell the compiler where to
  1439. find it.
  1440. The following sections attempt to explain how to do this.
  1441. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1442. % Declaring an external function or procedure
  1443. \section{Using external functions or procedures}
  1444. \label{se:ExternalFunction}
  1445. The first step in using external code blocks is declaring the function you
  1446. want to use. \fpc supports Delphi syntax, i.e. you must use the
  1447. \var{external} directive. The \var{external} directive replaces, in effect,
  1448. the code block of the function. As such, It cannot be used in an interface
  1449. section of a unit, but must always reside in the implementation section.
  1450. There exist four variants of the external direcive :
  1451. \begin{enumerate}
  1452. \item A simple external declaration:
  1453. \begin{verbatim}
  1454. Procedure ProcName (Args : TPRocArgs); external;
  1455. \end{verbatim}
  1456. The \var{external} directive tells the compiler that the function resides in
  1457. an external block of code. You can use this together with the \var{\{\$L \}}
  1458. or \var{\{\$LinkLib \}} directives to link to a function or procedure in a
  1459. library or external object file.
  1460. \item You can give the \var{external} directive a library name as an
  1461. argument:
  1462. \begin{verbatim}
  1463. Procedure ProcName (Args : TPRocArgs); external 'Name';
  1464. \end{verbatim}
  1465. This tells the compiler that the procedure resides in a library with name
  1466. \var{'Name'}. This method is equivalent to the following:
  1467. \begin{verbatim}
  1468. Procedure ProcName (Args : TPRocArgs);external;
  1469. {$LinkLib 'Name'}
  1470. \end{verbatim}
  1471. \item The \var{external} can also be used with two arguments:
  1472. \begin{verbatim}
  1473. Procedure ProcName (Args : TPRocArgs); external 'Name'
  1474. name 'OtherProcName';
  1475. \end{verbatim}
  1476. This has the same meaning as the previous declaration, only the compiler
  1477. will use the name \var{'OtherProcName'} when linking to the library. This
  1478. can be used to give different names to procedures and functions in an
  1479. external library.
  1480. This method is equivalent to the following code:
  1481. \begin{verbatim}
  1482. Procedure OtherProcName (Args : TProcArgs); external;
  1483. {$LinkLib 'Name'}
  1484. Procedure ProcName (Args : TPRocArgs);
  1485. begin
  1486. OtherProcName (Args);
  1487. end;
  1488. \end{verbatim}
  1489. \item Lastly, onder \windows and \ostwo, there is a fourth possibility
  1490. to specify an external function: In \file{.DLL} files, functionas also have
  1491. a unique number (their index). It is possible to refer to these fuctions
  1492. using their index:
  1493. \begin{verbatim}
  1494. Procedure ProcName (Args : TPRocArgs); external 'Name' Index SomeIndex;
  1495. \end{verbatim}
  1496. This tells the compiler that the procedure \var{ProcName} resides in a
  1497. dynamic link library, with index {SomeIndex}.
  1498. \em{Remark:} Note that this is ONLY available under \windows and \ostwo.
  1499. \end{enumerate}
  1500. In earlier versions of the \fpc compiler, the following construct was
  1501. also possible :
  1502. \begin{verbatim}
  1503. Procedure ProcName (Args : TPRocArgs); [ C ];
  1504. \end{verbatim}
  1505. This method is equivalent to the following statement:
  1506. \begin{verbatim}
  1507. Procedure ProcName (Args : TPRocArgs); cdecl; external;
  1508. \end{verbatim}
  1509. However, the \var{[ C ]} directive is no longer supported as of version
  1510. 0.99.5 of \fpc, therefore you should use the \var{external} directive,
  1511. with the \var{cdecl} directive, if needed.
  1512. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1513. % Declaring an external variabl
  1514. \section{Using external variables}
  1515. \label{se:ExternalVars}
  1516. Some libaries or code blocks have variables which they export. You can access
  1517. these variables much in the same way as external functions. To access an
  1518. external variable, you declare it as follows:
  1519. \begin{verbatim}
  1520. Var
  1521. MyVar : MyType; external name 'varname';
  1522. \end{verbatim}
  1523. The effect of this declaration is twofold:
  1524. \begin{enumerate}
  1525. \item No space is allocated for this variable.
  1526. \item The name of the variable used in the assebler code is \var{varname}.
  1527. This is a case sensitive name, so you must be careful.
  1528. \end{enumerate}
  1529. The variable will be
  1530. accessible with it's declared name, i.e. \var{MyVar} in this case.
  1531. A second possibility is the declaration:
  1532. \begin{verbatim}
  1533. Var
  1534. varname : MyType; cvar; external;
  1535. \end{verbatim}
  1536. The effect of this declaration is twofold as in the previous case:
  1537. \begin{enumerate}
  1538. \item The \var{external} modifier ensures that no space is allocated for
  1539. this variable.
  1540. \item The \var{cvar} modifier tells the compiler that the name of the
  1541. variable used in the assebler code is exactly as specified in the
  1542. declaration. This is a case sensitive name, so you must be careful.
  1543. \end{enumerate}
  1544. In this case, you access the variable with it's C name, but case
  1545. insensitive. The first possibility allows you to change the name of the
  1546. external variable for internal use.
  1547. In order to be able to compile such statements, the compiler switch \var{-Sv}
  1548. must be used.
  1549. As an example, let's look at the following C file (in \file{extvar.c}):
  1550. \begin{verbatim}
  1551. /*
  1552. Declare a variable, allocate storage
  1553. */
  1554. int extvar = 12;
  1555. \end{verbatim}
  1556. And the following program (in \file{extdemo.pp}):
  1557. \begin{verbatim}
  1558. Program ExtDemo;
  1559. {$L extvar.o}
  1560. Var { Case sensitive declaration !! }
  1561. extvar : longint; cvar;external;
  1562. I : longint; external name 'extvar';
  1563. begin
  1564. { Extvar can be used case insensitive !! }
  1565. Writeln ('Variable ''extvar'' has value : ',ExtVar);
  1566. Writeln ('Variable ''I'' has value : ',i);
  1567. end.
  1568. \end{verbatim}
  1569. Compiling the C file, and the pascal program:
  1570. \begin{verbatim}
  1571. gcc -c -o extvar.o extvar.c
  1572. ppc386 -Sv extdemo
  1573. \end{verbatim}
  1574. Will produce a program \file{extdemo} which will print
  1575. \begin{verbatim}
  1576. Variable 'extvar' has value : 12
  1577. Variable 'I' has value : 12
  1578. \end{verbatim}
  1579. on your screen.
  1580. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1581. % Linking an object file in your program
  1582. \section{Linking to an object file}
  1583. \label{se:LinkIn}
  1584. Having declared the external function or variable that resides in an object file,
  1585. you can use it as if it was defined in your own program or unit.
  1586. To produce an executable, you must still link the object file in.
  1587. This can be done with the \var{\{\$L file.o\}} directive.
  1588. This will cause the linker to link in the object file \file{file.o}. On
  1589. \linux systems, this filename is case sensitive. Under \dos, case isn't
  1590. important. Note that \var{file.o} must be in the current directory if you
  1591. don't specify a path. The linker will not search for \file{file.o} if it
  1592. isn't found.
  1593. You cannot specify libraries in this way, it is for object files only.
  1594. Here we present an example. Consider that you have some assembly routine that
  1595. calculates the nth Fibonacci number :
  1596. \begin{verbatim}
  1597. .text
  1598. .align 4
  1599. .globl Fibonacci
  1600. .type Fibonacci,@function
  1601. Fibonacci:
  1602. pushl %ebp
  1603. movl %esp,%ebp
  1604. movl 8(%ebp),%edx
  1605. xorl %ecx,%ecx
  1606. xorl %eax,%eax
  1607. movl $1,%ebx
  1608. incl %edx
  1609. loop:
  1610. decl %edx
  1611. je endloop
  1612. movl %ecx,%eax
  1613. addl %ebx,%eax
  1614. movl %ebx,%ecx
  1615. movl %eax,%ebx
  1616. jmp loop
  1617. endloop:
  1618. movl %ebp,%esp
  1619. popl %ebp
  1620. ret
  1621. \end{verbatim}
  1622. Then you can call this function with the following Pascal Program:
  1623. \begin{verbatim}
  1624. Program FibonacciDemo;
  1625. var i : longint;
  1626. Function Fibonacci (L : longint):longint;cdecl;external;
  1627. {$L fib.o}
  1628. begin
  1629. For I:=1 to 40 do
  1630. writeln ('Fib(',i,') : ',Fibonacci (i));
  1631. end.
  1632. \end{verbatim}
  1633. With just two commands, this can be made into a program :
  1634. \begin{verbatim}
  1635. as -o fib.o fib.s
  1636. ppc386 fibo.pp
  1637. \end{verbatim}
  1638. This example supposes that you have your assembler routine in \file{fib.s},
  1639. and your Pascal program in \file{fibo.pp}.
  1640. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1641. % Linking your program to a library
  1642. \section{Linking to a library}
  1643. \label{se:LinkOut}
  1644. To link your program to a library, the procedure depends on how you declared
  1645. the external procedure.
  1646. %If you used thediffers a little from the
  1647. %procedure when you link in an object file. although the declaration step
  1648. %remains the same (see \ref{se:ExternalFunction} on how to do that).
  1649. In case you used the follwing syntax to declare your procedure:
  1650. \begin{verbatim}
  1651. Procedure ProcName (Args : TPRocArgs); external 'Name';
  1652. \end{verbatim}
  1653. You don't need to take additional steps to link your file in, the compiler
  1654. will do all that is needed for you. On \windowsnt it will link to
  1655. \file{Name.dll}, on \linux your program will be linked to library
  1656. \file{libname}, which can be a static or dynamic library.
  1657. In case you used
  1658. \begin{verbatim}
  1659. Procedure ProcName (Args : TPRocArgs); external;
  1660. \end{verbatim}
  1661. You still need to explicity link to the library. This can be done in 2 ways:
  1662. \begin{enumerate}
  1663. \item You can tell the compiler in the source file what library to link to
  1664. using the \var{\{\$LinkLib 'Name'\}} directive:
  1665. \begin{verbatim}
  1666. {$LinkLib 'gpm'}
  1667. \end{verbatim}
  1668. This will link to the \file{gpm} library. On \linux systems, you needn't
  1669. specify the extension or 'lib' prefix of the library. The compiler takes
  1670. care of that. On \dos or \windows systems, you need to specify the full
  1671. name.
  1672. \item You can also tell the compiler on the command-line to link in a
  1673. library: The \var{-k} option can be used for that. For example
  1674. \begin{verbatim}
  1675. ppc386 -k'-lgpm' myprog.pp
  1676. \end{verbatim}
  1677. Is equivalent to the above method, and tells the linker to link to the
  1678. \file{gpm} library.
  1679. \end{enumerate}
  1680. As an example; consider the following program :
  1681. \begin{verbatim}
  1682. program printlength;
  1683. {$linklib c} { Case sensitive }
  1684. { Declaration for the standard C function strlen }
  1685. Function strlen (P : pchar) : longint; cdecl;external;
  1686. begin
  1687. Writeln (strlen('Programming is easy !'));
  1688. end.
  1689. \end{verbatim}
  1690. This program can be compiled with :
  1691. \begin{verbatim}
  1692. ppc386 prlen.pp
  1693. \end{verbatim}
  1694. Supposing, of course, that the program source resides in \file{prlen.pp}.
  1695. You cannot use procedures or functions that have a variable number of
  1696. arguments in C. Pascal doesn't support this feature of C.
  1697. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1698. % Making a shared library
  1699. \section{Making libraries}
  1700. \label{se:SharedLib}
  1701. \fpc supports making shared or static libraries in a straightforward and
  1702. easy manner.
  1703. If you want to make libraries for other \fpc programmers, you just need to
  1704. provide a command line switch. If you want C programmers to be able to use
  1705. your code as well, you will need to adapt your code a little. This process
  1706. is described first.
  1707. % Exporting functions.
  1708. \subsection{Exporting functions}
  1709. When exporting functions from a library, there are 2 things you must take in
  1710. account:
  1711. \begin{enumerate}
  1712. \item Calling conventions.
  1713. \item Naming scheme.
  1714. \end{enumerate}
  1715. The calling conventions are controlled by the modifiers \var{cdecl},
  1716. \var{popstack}, \var{pascal}, \var{stdcall}. See \sees{Calling} for more
  1717. information on the different kinds of calling scheme.
  1718. The naming conventions can be controlled by 3 modifiers:
  1719. \begin{description}
  1720. \item [cdecl:\ ] A function that has a \var{cdecl} modifier, will used
  1721. with C calling conventions, that is, the caller clears the stack. Also
  1722. the mangled name will be the name {\em exactly} as in the declaration.
  1723. \var{cdecl} is part of the function declaration, and hence must be present
  1724. both in the interface and implementation section of a unit.
  1725. \item [export:\ ] A function that has an export modifier, uses also the
  1726. exact declaration name as its mangled name. Under \windowsnt and \ostwo,
  1727. this modifier signals a function that is exported from a DLL.
  1728. The calling conventions used by a \var{export} procedure depend on the OS.
  1729. this keyword can be used only in the implementation section.
  1730. \item [Alias: ] The \var{alias} modifier can be used to give a supplementary
  1731. assembler name to your function. This doesn't modify the calling conventions
  1732. of the function.
  1733. \end{description}
  1734. If you want to make your procedures and functions available to C
  1735. programmers, you can do this very easily. All you need to do is declare the
  1736. functions and procedures that you want to make available as \var{export}, as
  1737. follows:
  1738. \begin{verbatim}
  1739. Procedure ExportedProcedure; export;
  1740. \end{verbatim}
  1741. {\em Remark :} You can only declare a function as exported in the
  1742. \var{Implementation} section of a unit. This function may {\em not} appear
  1743. in the interface part of a unit. This is logical, since a Pascal routine
  1744. cannot call an exported function, anyway.
  1745. However, the generated object file will not contain the name of the function
  1746. as you declared it. The \fpc compiler ''mangles'' the name you give your
  1747. function. It makes the name all-uppercase, and adds the types of all
  1748. parameters to it. There are cases when you want to provide a mangled name
  1749. without changing the calling convention. In such cases, you can use the
  1750. \var{Alias} modifier.
  1751. The \var{Alias} modifier allows you to specify
  1752. another name (a nickname) for your function or procedure.
  1753. The prototype for an aliased function or procedure is as follows :
  1754. \begin{verbatim}
  1755. Procedure AliasedProc; [ Alias : 'AliasName'];
  1756. \end{verbatim}
  1757. The procedure \var{AliasedProc} will also be known as \var{AliasName}. Take
  1758. care, the name you specify is case sensitive (as C is).
  1759. {\em Remark: }
  1760. If you use in your unit functions that are in other units, or
  1761. system functions, then the C program will need to link in the object files
  1762. from the units too.
  1763. % Exporting variable.
  1764. \subsection{Exporting variables}
  1765. Similarly as when you export functions, you can export variables.
  1766. when exportig variables, one should only consider the names of the
  1767. variables. To declare a variable that should be used by a C program,
  1768. one declares it with the \var{cvar} modifier:
  1769. \begin{verbatim}
  1770. Var MyVar : MyTpe; cvar;
  1771. \end{verbatim}
  1772. This will tell the compiler that the assembler name of the variable (the one
  1773. which is used by C programs) should be exactly as specified in the
  1774. declaration, i.e., case sensitive.
  1775. It is not allowed to declare multiple variables as \var{cvar} in one
  1776. statement, i.e. the following code will produce an error:
  1777. \begin{verbatim}
  1778. var Z1,Z2 : longint;cvar;
  1779. \end{verbatim}
  1780. % Compiling libraries
  1781. \subsection {Compiling libraries}
  1782. Once you have your (adapted) code, with exported and other functions,
  1783. you can compile your unit, and tell the compiler to make it into a library.
  1784. The compiler will simply compile your unit, and perform the necessary steps
  1785. to transform it into a \var{static} or \var{shared} (\var{dynamical}) library.
  1786. You can do this as follows, for a dynamical library:
  1787. \begin{verbatim}
  1788. ppc386 -CD myunit
  1789. \end{verbatim}
  1790. On \linux this will leave you with a file \file{libmyunit.so}. On \windows
  1791. and \ostwo, this will leave you with \file{myunit.dll}.
  1792. If you want a static library, you can do
  1793. \begin{verbatim}
  1794. ppc386 -CS myunit
  1795. \end{verbatim}
  1796. This will leave you with \file{libmyunit.a} and a file \file{myunit.ppu}.
  1797. The \file{myunit.ppu} is the unit file needed by the \fpc compiler.
  1798. The resulting files are then libraries. To make static libraries, you need
  1799. the \file{ranlib} or \var{ar} program on your system. It is standard on any
  1800. \linux system, and is provided with the \file{GCC} compiler under \dos.
  1801. For the dos distribution, a copy of ar is included in the file
  1802. \file{gnuutils.zip}.
  1803. {\em BEWARE:} This command doesn't include anything but the current unit in
  1804. the library. Other units are left out, so if you use code from other units,
  1805. you must deploy them together with your library.
  1806. % Moving units
  1807. \subsection{Moving units into a library}
  1808. You can put multiple units into a library with the \var{ppumove} command, as
  1809. follows:
  1810. \begin{verbatim}
  1811. ppumove -e ppl -o name unit1 unit2 unit3
  1812. \end{verbatim}
  1813. This will move 3 units in 1 library (called \file{libname.so} on linux,
  1814. \file{name.dll} on \windows) and it will create 3 files \file{unit1.ppl},
  1815. \file{unit2.ppl} and \file{file3.ppl}, which are unit files, but which tell
  1816. the compiler to look in library \var{name} when linking your executable.
  1817. The \var{ppumove} program has options to create statical or dynammical
  1818. libraries. It is provided with the compiler.
  1819. % unit searching
  1820. \subsection{Unit searching strategy}
  1821. When you compile a program or unit, the compiler will by
  1822. default always look for \file{.ppl} files. If it doesn't find one, it will
  1823. look for a \file{.ppu} file.
  1824. To be able to differentiate between units that have been compiled as static
  1825. or dynamic libraries, there are 2 switches:
  1826. \begin{description}
  1827. \item [-XD:\ ] This will define the symbol \var{FPC\_LINK\_DYNAMIC}
  1828. \item [-XS:\ ] This will define the symbol \var{FPC\_LINK\_STATIC}
  1829. \end{description}
  1830. Definition of one symbol will automatically undefine the other.
  1831. These two switches can be used in conjunction with the configuration file
  1832. \file{ppc386.cfg}. The existence of one of these symbols can be used to
  1833. decide which unit search path to set. For example:
  1834. \begin{verbatim}
  1835. # Set unit paths
  1836. #IFDEF FPC_LINK_STATIC
  1837. -Up/usr/lib/fpc/linuxunits/staticunits
  1838. #ENDIF
  1839. #IFDEF FPC_LINK_DYNAMIC
  1840. -Up/usr/lib/fpc/linuxunits/sharedunits
  1841. #ENDIF
  1842. \end{verbatim}
  1843. With such a configuration file, the compiler will look for it's units in
  1844. different directories, depending on whether \var{-XD} or \var{-XS} is used.
  1845. \section{Using smart linking}
  1846. \label{se:SmartLinking}
  1847. You can compile your units using smart linking. When you use smartl linking,
  1848. the compiler creates a series of code blocks that are as small as possible,
  1849. i.e. a code block will contain only the code for one procedure or function.
  1850. When you compile a program that uses a smart-linked unit, the compiler will
  1851. only link in the code that you actually need, and will leave out all other
  1852. code. This will result in a smaller binary, which is loaded in memory
  1853. faster, thus speeding up execution.
  1854. To enable smartlinking, one can give the smartlink option on the command
  1855. line : \var{-Cx}, or one can put the \var{\{\$SMARTLINK ON\}} directive in
  1856. the unit file:
  1857. \begin{verbatim}
  1858. Unit Testunit
  1859. {SMARTLINK ON}
  1860. Interface
  1861. ...
  1862. \end{verbatim}
  1863. Smartlinking will slow down the compilation process, expecially for large
  1864. units.
  1865. When a unit \file{foo.pp} is smartlinked, the name of the codefile is
  1866. changed to \file{libfoo.a}.
  1867. Technically speaking, the compiler makes small assembler files for each
  1868. procedure and function in the unit, as well as for all global defined
  1869. variables (whether they're in the interface section or not). It then
  1870. assembles all these small files, and uses \file{ar} to collect the resulting
  1871. object fioles in one archive.
  1872. Smartlinking and the creation of shared (or dynamic) libraries are mutually
  1873. exclusive, that is, if you turn on smartlinking, then the creation of shared
  1874. libraries is turned of. The creation of static libraries is still possible.
  1875. The reason for this is that it has little sense in making a smarlinked
  1876. dynamica library. The whole shared library is loaded into memory anyway by
  1877. the dynamic linker (or \windowsnt), so there would be no gain in size by
  1878. making it smartinked.
  1879. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1880. % Objects
  1881. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1882. \chapter{Objects}
  1883. \label{ch:Objects}
  1884. In this short chapter we give some technical things about objects. For
  1885. instructions on how to use and declare objects, see \refref.
  1886. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1887. % Constructor and Destructor calls.
  1888. \section{Constructor and Destructor calls}
  1889. \label{se:ConsDest}
  1890. When using objects that need virtual methods, the compiler uses two help
  1891. procedures that are in the run-time library. They are called
  1892. \var{Help\_Destructor} and \var{Help\_Constructor}, and they are written in
  1893. assembly language. They are used to allocate the necessary memory if needed,
  1894. and to insert the Virtual Method Table (VMT) pointer in the newly allocated
  1895. object.
  1896. When the compiler encounters a call to an object's constructor,
  1897. it sets up the stack frame for the call, and inserts a call to the
  1898. \var{Help\_Constructor}
  1899. procedure before issuing the call to the real constructor.
  1900. The helper procedure allocates the needed memory (if needed) and inserts the
  1901. VMT pointer in the object. After that, the real constructor is called.
  1902. A call to \var{Help\_Destructor} is inserted in every destructor declaration,
  1903. just before the destructor's exit sequence.
  1904. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1905. % memory storage of Objects
  1906. \section{Memory storage of objects}
  1907. \label{se:ObjMemory}
  1908. Objects are stored in memory just as ordinary records with an extra field :
  1909. a pointer to the Virtual Method Table (VMT). This field is stored first, and
  1910. all fields in the object are stored in the order they are declared.
  1911. This field is initialized by the call to the object's \var{Constructor} method.
  1912. If the object you defined has no virtual methods, then a \var{nil} is stored
  1913. in the VMT pointer. This ensures that the size of objects is equal, whether
  1914. they have virtual methods ore not.
  1915. The memory allocated looks as in \seet{ObjMem}.
  1916. \begin{FPCltable}{ll}{Object memory layout}{ObjMem} \hline
  1917. Offset & What \\ \hline
  1918. +0 & Pointer to VMT. \\
  1919. +4 & Data. All fields in the order the've been declared. \\
  1920. ... & \\
  1921. \hline
  1922. \end{FPCltable}
  1923. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1924. % The virtual method table.
  1925. \section{The Virtual Method Table}
  1926. \label{se:VMT}
  1927. The Virtual Method Table (VMT) for each object type consists of 2 check
  1928. fields (containing the size of the data), a pointer to the object's anchestor's
  1929. VMT (\var{Nil} if there is no anchestor), and then the pointers to all virtual
  1930. methods. The VMT layout is illustrated in \seet{VMTMem}.
  1931. The VMT is constructed by the compiler. Every instance of an object receives
  1932. a pointer to its VMT.
  1933. \begin{FPCltable}{ll}{Virtual Method Table memory layout}{VMTMem} \hline
  1934. Offset & What \\ \hline
  1935. +0 & Size of object type data \\
  1936. +4 & Minus the size of object type data. Enables determining of valid VMT
  1937. pointers. \\
  1938. +8 & Pointer to ancestor VMT, \var{Nil} if no ancestor available.\\
  1939. +12 & Pointers to the virtual methods. \\
  1940. ... & \\
  1941. \hline
  1942. \end{FPCltable}
  1943. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1944. % Generated code
  1945. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1946. \chapter{Generated code}
  1947. \label{ch:GenCode}
  1948. The \fpc compiler relies on the assembler to make object files. It generates
  1949. just the assembly language file. In the following two sections, we discuss
  1950. what is generated when you compile a unit or a program.
  1951. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1952. % Units
  1953. \section{Units}
  1954. \label{se:Units}
  1955. When you compile a unit, the \fpc compiler generates 2 files :
  1956. \begin{enumerate}
  1957. \item A unit description file (with extension \file{.ppu}, or \file{.ppw on
  1958. \windowsnt}).
  1959. \item An assembly language file (with extension \file{.s}).
  1960. \end{enumerate}
  1961. The assembly language file contains the actual source code for the
  1962. statements in your unit, and the necessary memory allocations for any
  1963. variables you use in your unit. This file is converted by the assembler to
  1964. an object file (with extension \file{.o}) which can then be linked to other
  1965. units and your program, to form an executable.
  1966. By default (compiler version 0.9.4 and up), the assembly file is removed
  1967. after it has been compiled. Only in the case of the \var{-s} command-line
  1968. option, the assembly file must be left on disk, so the assembler can be
  1969. called later. You can disable the erasing of the assembler file with the
  1970. \var{-a} switch.
  1971. The unit file contains all the information the compiler needs to use the
  1972. unit:
  1973. \begin{enumerate}
  1974. \item Other used units, both in interface and implementation.
  1975. \item Types and variables from the interface section of the unit.
  1976. \item Function declarations from the interface section of the unit.
  1977. \item Some debugging information, when compiled with debugging.
  1978. \item A date and time stamp.
  1979. \end{enumerate}
  1980. Macros, symbols and compiler directives are {\em not} saved to the unit
  1981. description file. Aliases for functions are also not written to this file,
  1982. which is logical, since they cannot appear in the interface section of a
  1983. unit.
  1984. The detailed contents and structure of this file are described in the first
  1985. appendix. You can examine a unit description file using the \file{dumpppu}
  1986. program, which shows the contents of the file.
  1987. If you want to distribute a unit without source code, you must provide both
  1988. the unit description file and the object file.
  1989. You can also provide a C header file to go with the object file. In that
  1990. case, your unit can be used by someone who wishes to write his programs in
  1991. C. However, you must make this header file yourself since the \fpc compiler
  1992. doesn't make one for you.
  1993. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1994. % Programs
  1995. \section{Programs}
  1996. \label{se:Programs}
  1997. When you compile a program, the compiler produces again 2 files :
  1998. \begin{enumerate}
  1999. \item An assembly language file containing the statements of your program,
  2000. and memory allocations for all used variables.
  2001. \item A linker response file. This file contains a list of object files the
  2002. linker must link together.
  2003. \end{enumerate}
  2004. The link response file is, by default, removed from the disk. Only when you
  2005. specify the \var{-s} command-line option or when linking fails, then the ile
  2006. is left on the disk. It is named \file{link.res}.
  2007. The assembly language file is converted to an object file by the assembler,
  2008. and then linked together with the rest of the units and a program header, to
  2009. form your final program.
  2010. The program header file is a small assembly program which provides the entry
  2011. point for the program. This is where the execution of your program starts,
  2012. so it depends on the operating system, because operating systems pass
  2013. parameters to executables in wildly different ways.
  2014. It's name is \file{prt0.o}, and the
  2015. source file resides in \file{prt0.s} or some variant of this name. It
  2016. usually resided where the system unit source for your system resides.
  2017. It's main function is to save the environment and command-line arguments,
  2018. set up the stack. Then it calls the main program.
  2019. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  2020. % MMX Support
  2021. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  2022. \chapter{Intel MMX support}
  2023. \label{ch:MMXSupport}
  2024. \section{What is it about ?}
  2025. \label{se:WhatisMMXabout}
  2026. \fpc supports the new MMX (Multi-Media extensions)
  2027. instructions of Intel processors. The idea of MMX is to
  2028. process multiple data with one instruction, for example the processor
  2029. can add simultaneously 4 words. To implement this efficiently, the
  2030. Pascal language needs to be extended. So Free Pascal allows
  2031. to add for example two \var{array[0..3] of word},
  2032. if MMX support is switched on. The operation is done
  2033. by the \var{MMX} unit and allows people without assembler knowledge to take
  2034. advantage of the MMX extensions.
  2035. Here is an example:
  2036. \begin{verbatim}
  2037. uses
  2038. MMX; { include some predefined data types }
  2039. const
  2040. { tmmxword = array[0..3] of word;, declared by unit MMX }
  2041. w1 : tmmxword = (111,123,432,4356);
  2042. w2 : tmmxword = (4213,63456,756,4);
  2043. var
  2044. w3 : tmmxword;
  2045. l : longint;
  2046. begin
  2047. if is_mmx_cpu then { is_mmx_cpu is exported from unit mmx }
  2048. begin
  2049. {$mmx+} { turn mmx on }
  2050. w3:=w1+w2;
  2051. {$mmx-}
  2052. end
  2053. else
  2054. begin
  2055. for i:=0 to 3 do
  2056. w3[i]:=w1[i]+w2[i];
  2057. end;
  2058. end.
  2059. \end{verbatim}
  2060. \section{Saturation support}
  2061. \label{se:SaturationSupport}
  2062. One important point of MMX is the support of saturated operations.
  2063. If a operation would cause an overflow, the value stays at the
  2064. highest or lowest possible value for the data type:
  2065. If you use byte values you get normally 250+12=6. This is very
  2066. annoying when doing color manipulations or changing audio samples,
  2067. when you have to do a word add and check if the value is greater than
  2068. 255. The solution is saturation: 250+12 gives 255.
  2069. Saturated operations are supported by the \var{MMX} unit. If you
  2070. want to use them, you have simple turn the switch saturation on:
  2071. \var{\$saturation+}
  2072. Here is an example:
  2073. \begin{verbatim}
  2074. Program SaturationDemo;
  2075. {
  2076. example for saturation, scales data (for example audio)
  2077. with 1.5 with rounding to negative infinity
  2078. }
  2079. var
  2080. audio1 : tmmxword;
  2081. const
  2082. helpdata1 : tmmxword = ($c000,$c000,$c000,$c000);
  2083. helpdata2 : tmmxword = ($8000,$8000,$8000,$8000);
  2084. begin
  2085. { audio1 contains four 16 bit audio samples }
  2086. {$mmx+}
  2087. { convert it to $8000 is defined as zero, multiply data with 0.75 }
  2088. audio1:=tmmxfixed16(audio1+helpdata2)*tmmxfixed(helpdata1);
  2089. {$saturation+}
  2090. { avoid overflows (all values>$7fff becomes $ffff) }
  2091. audio1:=(audio1+helpdata2)-helpdata2;
  2092. {$saturation-}
  2093. { now mupltily with 2 and change to integer }
  2094. audio1:=(audio1 shl 1)-helpdata2;
  2095. {$mmx-}
  2096. end.
  2097. \end{verbatim}
  2098. \section{Restrictions of MMX support}
  2099. \label{se:MMXrestrictions}
  2100. In the beginning of 1997 the MMX instructions were introduced in the
  2101. Pentium processors, so multitasking systems wouldn't save the
  2102. newly introduced MMX registers. To work around that problem, Intel
  2103. mapped the MMX registers to the FPU register.
  2104. The consequence is that
  2105. you can't mix MMX and floating point operations. After using
  2106. MMX operations and before using floating point operations, you
  2107. have to call the routine \var{EMMS} of the \var{MMX} unit.
  2108. This routine restores the FPU registers.
  2109. {\em careful:} The compiler doesn't warn, if you mix floating point and
  2110. MMX operations, so be careful.
  2111. The MMX instructions are optimized for multi media (what else?).
  2112. So it isn't possible to perform each operation, some opertions
  2113. give a type mismatch, see section \ref {se:SupportedMMX} for the supported
  2114. MMX operations
  2115. An important restriction is that MMX operations aren't range or overflow
  2116. checked, even when you turn range and overflow checking on. This is due to
  2117. the nature of MMX operations.
  2118. The \var{MMX} unit must be always used when doing MMX operations
  2119. because the exit code of this unit clears the MMX unit. If it wouldn't do
  2120. that, other program will crash. A consequence of this is that you can't use
  2121. MMX operations in the exit code of your units or programs, since they would
  2122. interfere with the exit code of the \var{MMX} unit. The compiler can't
  2123. check this, so you are responsible for this !
  2124. \section{Supported MMX operations}
  2125. \label{se:SupportedMMX}
  2126. \section{Optimizing MMX support}
  2127. \label{se:OptimizingMMX}
  2128. Here are some helpful hints to get optimal performance:
  2129. \begin{itemize}
  2130. \item The \var{EMMS} call takes a lot of time, so try to seperate floating
  2131. point and MMX operations.
  2132. \item Use MMX only in low level routines because the compiler
  2133. saves all used MMX registers when calling a subroutine.
  2134. \item The NOT-operator isn't supported natively by MMX, so the
  2135. compiler has to generate a workaround and this operation
  2136. is inefficient.
  2137. \item Simple assignements of floating point numbers don't access
  2138. floating point registers, so you need no call to the \var{EMMS}
  2139. procedure. Only when doing arithmetic, you need to call the \var{EMMS}
  2140. procedure.
  2141. \end{itemize}
  2142. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  2143. % Memory issues
  2144. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  2145. \chapter{Memory issues}
  2146. \label{ch:Memory}
  2147. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  2148. % The 32-bit model
  2149. \section{The 32-bit model.}
  2150. \label{se:ThirtytwoBit}
  2151. The \fpc Pascal compiler issues 32-bit code. This has several consequences:
  2152. \begin{itemize}
  2153. \item You need a 386 processor to run the generated code. The
  2154. compiler functions on a 286 when you compile it using Turbo Pascal,
  2155. but the generated programs cannot be assembled or executed.
  2156. \item You don't need to bother with segment selectors. Memory can be
  2157. addressed using a single 32-bit pointer.
  2158. The amount of memory is limited only by the available amount of (virtual)
  2159. memory on your machine.
  2160. \item The structures you define are unlimited in size. Arrays can be as long
  2161. as you want. You can request memory blocks from any size.
  2162. \end{itemize}
  2163. The fact that 32-bit code is used, means that some of the older Turbo Pascal
  2164. constructs and functions are obsolete. The following is a list of functions
  2165. which shouldn't be used anymore:
  2166. \begin{description}
  2167. \item [Seg()] : Returned the segment of a memory address. Since segments have
  2168. no more meaning, zero is returned in the \fpc run-time library implementation of
  2169. \var{Seg}.
  2170. \item [Ofs()] : Returned the offset of a memory address. Since segments have
  2171. no more meaning, the complete address is returned in the \fpc implementation
  2172. of this function. This has as a consequence that the return type is
  2173. \var{Longint} instead of \var{Word}.
  2174. \item [Cseg(), Dseg()] : Returned, respectively, the code and data segments
  2175. of your program. This returns zero in the \fpc implementation of the
  2176. system unit, since both code and data are in the same memory space.
  2177. \item [Ptr] accepted a segment and offset from an address, and would return
  2178. a pointer to this address. This has been changed in the run-time library.
  2179. Standard it returns now simply the offset. If you want to retain the old
  2180. functionality, you can recompile the run-time library with the
  2181. \var{DoMapping} symbol defined. This will restore the Turbo Pascal
  2182. behaviour.
  2183. \item [memw and mem] these arrays gave access to the \dos memory. \fpc
  2184. supports them, they are mapped into \dos memory space. You need the
  2185. \var{GO32} unit for this.
  2186. \end{description}
  2187. You shouldn't use these functions, since they are very non-portable, they're
  2188. specific to \dos and the ix86 processor. The \fpc compiler is designed to be
  2189. portable to other platforms, so you should keep your code as portable as
  2190. possible, and not system specific. That is, unless you're writing some driver
  2191. units, of course.
  2192. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  2193. % The stack
  2194. \section{The stack}
  2195. \label{se:Stack}
  2196. The stack is used to pass parameters to procedures or functions,
  2197. to store local variables, and, in some cases, to return function
  2198. results.
  2199. When a function or procedure is called, then the following is done by the
  2200. compiler :
  2201. \begin{enumerate}
  2202. \item If there are any parameters to be passed to the procedure, they are
  2203. pushed from right to left on the stack.
  2204. \item If a function is called that returns a variable of type \var{String},
  2205. \var{Set}, \var{Record}, \var{Object} or \var{Array}, then an address to
  2206. store the function result in, is pushed on the stack.
  2207. \item If the called procedure or function is an object method, then the
  2208. pointer to \var{self} is pushed on the stack.
  2209. \item If the procedure or function is nested in another function or
  2210. procedure, then the frame pointer of the parent procedure is pushed on the
  2211. stack.
  2212. \item The return address is pushed on the stack (This is done automatically
  2213. by the instruction which calls the subroutine).
  2214. \end{enumerate}
  2215. The resulting stack frame upon entering looks as in \seet{StackFrame}.
  2216. \begin{FPCltable}{llc}{Stack frame when calling a procedure}{StackFrame}
  2217. \hline
  2218. Offset & What is stored & Optional ? \\ \hline
  2219. +x & parameters & Yes \\
  2220. +12 & function result & Yes \\
  2221. +8 & self & Yes \\
  2222. +4 & Frame pointer of parent procedure & Yes \\
  2223. +0 & Return address & No\\ \hline
  2224. \end{FPCltable}
  2225. \subsection{ Intel x86 version }
  2226. The stack is cleared with the \var{ret} I386 instruction, meaning that the
  2227. size of all pushed parameters is limited to 64K.
  2228. \subsubsection{ DOS }
  2229. Under the DOS targets , the default stack is set to 256Kb. This value
  2230. cannot be modified for the GO32V1 target. But this can be modified
  2231. with the GO32V2 target using a special DJGPP utility \var{stubedit}.
  2232. It is to note that the stack size may be changed with some compiler
  2233. switches, this stack size, if \emph{greater} then the default stack
  2234. size will be used instead, otherwise the default stack size is used.
  2235. \subsubsection{ Linux }
  2236. Under Linux, stack size is only limited by the available memory by
  2237. the system.
  2238. \subsubsection{ OS/2 }
  2239. Under OS/2, stack size is determined by one of the runtime
  2240. environment variables set for EMX. Therefore, the stack size
  2241. is user defined.
  2242. \subsection{ Motorola 680x0 version }
  2243. All depending on the processor target, the stack can be cleared in two
  2244. manners, if the target processor is a MC68020 or higher, the stack will
  2245. be cleared with a simple \var{rtd} instruction, meaning that the size
  2246. of all pushed parameters is limited to 32K.
  2247. Otherwise on MC68000/68010 processors, the stack clearing mechanism
  2248. is sligthly more complicated, the exit code will look like this:
  2249. \begin{verbatim}
  2250. {
  2251. move.l (sp)+,a0
  2252. add.l paramsize,a0
  2253. move.l a0,-(sp)
  2254. rts
  2255. }
  2256. \end{verbatim}
  2257. \subsubsection{ Amiga }
  2258. Under AmigaOS, stack size is determined by the user, which sets this
  2259. value using the stack program. Typical sizes range from 4K to 40K.
  2260. \subsubsection{ Atari }
  2261. Under Atari TOS, stack size is currently limited to 8K, and it cannot
  2262. be modified. This may change in a future release of the compiler.
  2263. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  2264. % The heap
  2265. \section{The heap}
  2266. \label{se:Heap}
  2267. The heap is used to store all dynamic variables, and to store class
  2268. instances. The interface to the heap is the same as in Turbo Pascal,
  2269. although the effects are maybe not the same. On top of that, the \fpc
  2270. run-time library has some extra possibilities, not available in Turbo
  2271. Pascal. These extra possibilities are explained in the next subsections.
  2272. % The heap grows
  2273. \subsection{The heap grows}
  2274. \fpc supports the \var{HeapEerror} procedural variable. If this variable is
  2275. non-nil, then it is called in case you try to allocate memory, and the heap
  2276. is full. By default, \var{HeapError} points to the \var{GrowHeap} function,
  2277. which tries to increase the heap.
  2278. The growheap function issues a system call to try to increase the size of the
  2279. memory available to your program. It first tries to increase memory in a 1 Mb.
  2280. chunk. If this fails, it tries to increase the heap by the amount you
  2281. requested from the heap.
  2282. If the call to \var{GrowHeap} has failed, then a run-time error is generated,
  2283. or nil is returned, depending on the \var{GrowHeap} result.
  2284. If the call to \var{GrowHeap} was successful, then the needed memory will be
  2285. allocated.
  2286. % Using Blocks
  2287. \subsection{Using Blocks}
  2288. If you need to allocate a lot of small block for a small period, then you
  2289. may want to recompile the run-time library with the \var{USEBLOCKS} symbol
  2290. defined. If it is recompiled, then the heap management is done in a
  2291. different way.
  2292. The run-time library keeps a linked list of allocated blocks with size
  2293. up to 256 bytes\footnote{The size can be set using the \var{max\_size}
  2294. constant in the \file{heap.inc} source file.}. By default, it keeps 32 of
  2295. these lists\footnote{The actual size is \var{max\_size div 8}.}.
  2296. When a piece of memory in a block is deallocated, the heap manager doesn't
  2297. really deallocate the occupied memory. The block is simply put in the linked
  2298. list corresponding to its size.
  2299. When you then again request a block of memory, the manager checks in the
  2300. list if there is a non-allocated block which fits the size you need (rounded
  2301. to 8 bytes). If so, the block is used to allocate the memory you requested.
  2302. This method of allocating works faster if the heap is very fragmented, and
  2303. you allocate a lot of small memory chunks.
  2304. Since it is invisible to the program, this provides an easy way of improving
  2305. the performance of the heap manager.
  2306. % The splitheap
  2307. \subsection{Using the split heap}
  2308. {\em Remark : The split heap is still somewhat buggy. Use at your own risk
  2309. for the moment.}
  2310. The split heap can be used to quickly release a lot of blocks you alloated
  2311. previously.
  2312. Suppose that in a part of your program, you allocate a lot of memory chunks
  2313. on the heap. Suppose that you know that you'll release all this memory when
  2314. this particular part of you program is finished.
  2315. In Turbo Pascal, you could foresee this, and mark the position of the heap
  2316. (using the \var{Mark} function) when entering this particular part of your
  2317. program, and release the occupied memory in one call with the \var{Release}
  2318. call.
  2319. For most purposes, this works very good. But sometimes, you may need to
  2320. allocate something on the heap that you {\em don't} want deallocated when you
  2321. release the allocated memory. That is where the split heap comes in.
  2322. When you split the heap, the heap manager keeps 2 heaps: the base heap (the
  2323. normal heap), and the temporary heap. After the call to split the heap,
  2324. memory is allocated from the temporary heap. When you're finished using all
  2325. this memory, you unsplit the heap. This clears all the memory on the split
  2326. heap with one call. After that, memory will be allocated from the base heap
  2327. again.
  2328. So far, nothing special, nothing that can't be done with calls to \var{mark}
  2329. and \var{release}. Suppose now that you have split the heap, and that you've
  2330. come to a point where you need to allocate memory that is to stay allocated
  2331. after you unsplit the heap again. At this point, mark and release are of no
  2332. use. But when using the split heap, you can tell the heap manager to
  2333. --temporarily-- use the base heap again to allocate memory.
  2334. When you've allocated the needed memory, you can tell the heap manager that
  2335. it should start using the temporary heap again.
  2336. When you're finished using the temporary heap, you release it, and the
  2337. memory you allocated on the base heap will still be allocated.
  2338. To use the split-heap, you must recompile the run-time library with the \var{TempHeap}
  2339. symbol defined.
  2340. This means that the following functions are available :
  2341. \begin{verbatim}
  2342. procedure Split_Heap;
  2343. procedure Switch_To_Base_Heap;
  2344. procedure Switch_To_Temp_Heap;
  2345. procedure Switch_Heap;
  2346. procedure ReleaseTempHeap;
  2347. procedure GetempMem(var p : pointer;size : longint);
  2348. \end{verbatim}
  2349. \var{split\_heap} is used to split the heap. It cannot be called two times
  2350. in a row, without a call to \var{releasetempheap}. \var{Releasetempheap}
  2351. completely releases the memory used by the temporary heap.
  2352. Switching temporarily back to the base heap can be done using the
  2353. \var{switch\_to\_base\_heap} call, and returning to the temporary heap is done
  2354. using the \var{switch\_to\_temp\_heap} call. Switching from one to the other
  2355. without knowing on which one your are right now, can be done using the
  2356. \var{switch\_heap} call, which will split the heap first if needed.
  2357. A call to \var{GetTempMem} will allocate a memory block on the temporary
  2358. heap, whatever the current heap is. The current heap after this call will be
  2359. the temporary heap.
  2360. Typically, what will appear in your code is the following sequence :
  2361. \begin{verbatim}
  2362. Split_Heap
  2363. ...
  2364. { Memory allocation }
  2365. ...
  2366. { !! non-volatile memory needed !!}
  2367. Switch_To_Base_Heap;
  2368. getmem (P,size);
  2369. Switch_To_Temp_Heap;
  2370. ...
  2371. {Memory allocation}
  2372. ...
  2373. ReleaseTempHeap;
  2374. {All allocated memory is now freed, except for the memory pointed to by 'P' }
  2375. ...
  2376. \end{verbatim}
  2377. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  2378. % Accessing DOS memory under the GO32 extender
  2379. \section{using \dos memory under the Go32 extender}
  2380. \label{se:AccessingDosMemory}
  2381. Because \fpc is a 32 bit compiler, and uses a \dos extender, accessing DOS
  2382. memory isn't trivial. What follows is an attempt to an explanation of how to
  2383. access and use \dos or real mode memory\footnote{Thanks to an explanation of
  2384. Thomas schatzl (E-mail:\var{tom\_at\[email protected]}).}.
  2385. In {\em Proteced Mode}, memory is accessed through {\em Selectors} and
  2386. {\em Offsets}. You can think of Selectors as the protected mode
  2387. equivalents of segments.
  2388. In \fpc, a pointer is an offset into the \var{DS} selector, which points to
  2389. the Data of your program.
  2390. To access the (real mode) \dos memory, somehow you need a selector that
  2391. points to the \dos memory.
  2392. The \file{GO32} unit provides you with such a selector: The
  2393. \var{DosMemSelector} variable, as it is conveniently called.
  2394. You can also allocate memory in \dos's memory space, using the
  2395. \var{global\_dos\_alloc} function of the \file{GO32} unit.
  2396. This function will allocate memory in a place where \dos sees it.
  2397. As an example, here is a function that returns memory in real mode \dos and
  2398. returns a selector:offset pair for it.
  2399. \begin{verbatim}
  2400. procedure dosalloc(var selector : word;
  2401. var segment : word;
  2402. size : longint);
  2403. var result : longint;
  2404. begin
  2405. result := global_dos_alloc(size);
  2406. selector := word(result);
  2407. segment := word(result shr 16);
  2408. end;
  2409. \end{verbatim}
  2410. (you need to free this memory using the \var{global\_dos\_free} function.)
  2411. You can access any place in memory using a selector. You can get a selector
  2412. using the \var{allocate\_ldt\_descriptor} function, and then let this selector
  2413. point to the physical memory you want using the
  2414. \var{set\_segment\_base\_address} function, and set its length using
  2415. \var{set\_segment\_limit} function.
  2416. You can manipulate the memory pointed to by the selector using the functions
  2417. of the GO32 unit. For instance with the \var{seg\_fillchar} function.
  2418. After using the selector, you must free it again using the
  2419. \var{free\_ldt\_selector} function.
  2420. More information on all this can be found in the \unitsref, the chapter on
  2421. the \file{GO32} unit.
  2422. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  2423. % Optimizations done in the compiler
  2424. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  2425. \chapter{Optimizations}
  2426. \section{ Non processor specific }
  2427. The following sections describe the general optimizations
  2428. done by the compiler, they are non processor specific. Some
  2429. of these require some compiler switch override while others are done
  2430. automatically (those which require a switch will be noted as such).
  2431. \subsection{ Constant folding }
  2432. In \fpc, if the operand(s) of an operator are constants, they
  2433. will be evaluated at compile time.
  2434. Example
  2435. \begin{verbatim}
  2436. x:=1+2+3+6+5;
  2437. will generate the same code as
  2438. x:=17;
  2439. \end{verbatim}
  2440. Furthermore, if an array index is a constant, the offset will
  2441. be evaluated at compile time. This means that accessing MyData[5]
  2442. is as efficient as accessing a normal variable.
  2443. Finally, calling \var{Chr}, \var{Hi}, \var{Lo}, \var{Ord}, \var{Pred},
  2444. or \var{Succ} functions with constant parameters generates no
  2445. run-time library calls, instead, the values are evaluated at
  2446. compile time.
  2447. \subsection{ Constant merging }
  2448. Using the same constant string two or more times generates only
  2449. one copy of the string constant.
  2450. \subsection{ Short cut evaluation }
  2451. Evaluation of boolean expression stops as soon as the result is
  2452. known, which makes code execute faster then if all boolean operands
  2453. were evaluated.
  2454. \subsection{ Constant set inlining }
  2455. Using the \var{in} operator is always more efficient then using the
  2456. equivalent \verb|<>|, \verb|=|, \verb|<=|, \verb|>=|, \verb|<| and \verb|>|
  2457. operators. This is because range comparisons can be done more easily with
  2458. \var{in} then with normal comparison operators.
  2459. \subsection{ Small sets }
  2460. Sets which contain less then 33 elements can be directly encoded
  2461. using a 32-bit value, therefore no run-time library calls to
  2462. evaluate operands on these sets are required; they are directly encoded
  2463. by the code generator.
  2464. \subsection{ Range checking }
  2465. Assignments of constants to variables are range checked at compile
  2466. time, which removes the need the generation of runtime range checking
  2467. code.
  2468. \emph{Remark:} This feature was not implemented before version
  2469. 0.99.5 of \fpc.
  2470. \subsection{ Shifts instead of multiply or divide }
  2471. When one of the operands in a multiplication is a power of
  2472. two, they are encoded using arithmetic shifts instructions,
  2473. which generates more efficient code.
  2474. Similarly, if the divisor in a \var{div} operation is a power
  2475. of two, it is encoded using arithmetic shifts instructions.
  2476. The same is true when accessing array indexes which are
  2477. powers of two, the address is calculated using arithmetic
  2478. shifts instead of the multiply instruction.
  2479. \subsection{ Automatic alignment }
  2480. By default all variables larger then a byte are guaranteed to be aligned
  2481. at least on a word boundary.
  2482. Furthermore all pointers allocated using the standard runtime
  2483. library (\var{New} and \var{GetMem} among others) are guaranteed
  2484. to return pointers aligned on a quadword boundary (64-bit alignment).
  2485. Alignment of variables on the stack depends on the target processor.
  2486. \emph{ Remark: } Quadword alignment of pointers is not guaranteed
  2487. on systems which don't use an internal heap, such as for the Win32
  2488. target.
  2489. \emph{ Remark: } Alignment is also done \emph{between} fields in
  2490. records, objects and classes, this is \emph{not} the same as
  2491. in Turbo Pascal and may cause problems when using disk I/O with these
  2492. types. To get no alignment between fields use the \var{packed} directive
  2493. or the \var{\{\$PackRecords n\}} switch. For further information, take a
  2494. look at the reference manual under the \var{record} heading.
  2495. \subsection{ Smart linking }
  2496. This feature removes all unreferenced code in the final executable
  2497. file, making the executable file much smaller.
  2498. Smart linking is switched on with the \var{-Cx} command-line switch, or
  2499. using the \var{\{\$SMARTLINK ON\}} global directive.
  2500. \emph{ Remark: } Smart linking was implemented starting with
  2501. version 0.99.6 of \fpc.
  2502. \subsection{ Inline routines }
  2503. The following runtime library routines are coded directly into the
  2504. final executable : \var{Lo}, \var{Hi}, \var{High}, \var{Sizeof},
  2505. \var{TypeOf}, \var{Length}, \var{Pred}, \var{Succ}, \var{Inc},
  2506. \var{Dec} and \var{Assigned}.
  2507. \emph{ Remark: } Inline \var{Inc} and \var{Dec} were not completely
  2508. implemented until version 0.99.6 of \fpc.
  2509. \subsection{ Case optimization }
  2510. When using the \var{-O1} (or higher) switch, case statements will be
  2511. generated using a jump table if appropriate, to make them execute
  2512. faster.
  2513. \subsection{ Stack frame omission }
  2514. Under specific conditions, the stack frame (entry and exit code for
  2515. the routine, see section \ref{se:Calling}) will be omitted, and the
  2516. variable will directly be accessed via the stack pointer.
  2517. Conditions for omission of the stack frame :
  2518. \begin{itemize}
  2519. \item The function has no parameters nor local variables.
  2520. \item Routine does not call other routines.
  2521. \item Routine does not contain assembler statements. However,
  2522. a \var{assembler} routine may omit it's stack frame.
  2523. \item Routine is not declared using the \var{Interrupt} directive.
  2524. \item Routine is not a constructor or destructor.
  2525. \end{itemize}
  2526. \subsection{ Register variables }
  2527. When using the \var{-Or} switch, local variables or parameters
  2528. which are used very often will be moved to registers for faster
  2529. access.
  2530. \emph{ Remark: } Register variable allocation is currently
  2531. an experimental feature, and should be used with caution.
  2532. \subsection{ Intel x86 specific }
  2533. Here follows a listing of the opimizing techniques used in the compiler:
  2534. \begin{enumerate}
  2535. \item When optimizing for a specific Processor (\var{-Op1, -Op2, -Op3},
  2536. the following is done:
  2537. \begin{itemize}
  2538. \item In \var{case} statements, a check is done whether a jump table
  2539. or a sequence of conditional jumps should be used for optimal performance.
  2540. \item Determines a number of strategies when doing peephole optimization, e.g.:
  2541. \var{movzbl (\%ebp), \%eax} will be changed into
  2542. \var{xorl \%eax,\%eax; movb (\%ebp),\%al } for Pentium and PentiumMMX.
  2543. \end{itemize}
  2544. \item When optimizing for speed (\var{-OG}, the default) or size (\var{-Og}), a choice is
  2545. made between using shorter instructions (for size) such as \var{enter \$4},
  2546. or longer instructions \var{subl \$4,\%esp} for speed. When smaller size is
  2547. requested, things aren't aligned on 4-byte boundaries. When speed is
  2548. requested, things are aligned on 4-byte boundaries as much as possible.
  2549. \item Fast optimizations (\var{-O1}): activate the peephole optimizer
  2550. \item Slower optimizations (\var{-O2}): also activate the common subexpression
  2551. elimination (formerly called the "reloading optimizer")
  2552. \item Uncertain optimizations (\var{-Ou}): With this switch, the common subexpression
  2553. elimination algorithm can be forced into making uncertain optimizations.
  2554. Although you can enable uncertain optimizations in most cases, for people who
  2555. do not understand the following technical explanation, it might be the safest to
  2556. leave them off.
  2557. \begin{quote}
  2558. % Jonas's own words..
  2559. \em
  2560. If uncertain optimizations are enabled, the CSE algortihm assumes
  2561. that
  2562. \begin{itemize}
  2563. \item If something is written to a local/global register or a
  2564. procedure/function parameter, this value doesn't overwrite the value to
  2565. which a pointer points.
  2566. \item If something is written to memory pointed to by a pointer variable,
  2567. this value doesn't overwrite the value of a local/global variable or a
  2568. procedure/function parameter.
  2569. \end{itemize}
  2570. % end of quote
  2571. \end{quote}
  2572. The practical upshot of this is that you cannot use the uncertain
  2573. optimizations if you both write and read local or global variables directly and
  2574. through pointers (this includes \var{Var} parameters, as those are pointers too).
  2575. The following example will produce bad code when you switch on
  2576. uncertain optimizations:
  2577. \begin{verbatim}
  2578. Var temp: Longint;
  2579. Procedure Foo(Var Bar: Longint);
  2580. Begin
  2581. If (Bar = temp)
  2582. Then
  2583. Begin
  2584. Inc(Bar);
  2585. If (Bar <> temp) then Writeln('bug!')
  2586. End
  2587. End;
  2588. Begin
  2589. Foo(Temp);
  2590. End.
  2591. \end{verbatim}
  2592. The reason it produces bad code is because you access the global variable
  2593. \var{Temp} both through its name \var{Temp} and through a pointer, in this
  2594. case using the \var{Bar} variable parameter, which is nothing but a pointer
  2595. to \var{Temp} in the above code.
  2596. On the other hand, you can use the uncertain optimizations if
  2597. you access global/local variables or parameters through pointers,
  2598. and {\em only} access them through this pointer\footnote{
  2599. You can use multiple pointers to point to the same variable as well, that
  2600. doesn't matter.}.
  2601. For example:
  2602. \begin{verbatim}
  2603. Type TMyRec = Record
  2604. a, b: Longint;
  2605. End;
  2606. PMyRec = ^TMyRec;
  2607. TMyRecArray = Array [1..100000] of TMyRec;
  2608. PMyRecArray = ^TMyRecArray;
  2609. Var MyRecArrayPtr: PMyRecArray;
  2610. MyRecPtr: PMyRec;
  2611. Counter: Longint;
  2612. Begin
  2613. New(MyRecArrayPtr);
  2614. For Counter := 1 to 100000 Do
  2615. Begin
  2616. MyRecPtr := @MyRecArrayPtr^[Counter];
  2617. MyRecPtr^.a := Counter;
  2618. MyRecPtr^.b := Counter div 2;
  2619. End;
  2620. End.
  2621. \end{verbatim}
  2622. Will produce correct code, because the global variable \var{MyRecArrayPtr}
  2623. is not accessed directly, but only through a pointer (\var{MyRecPtr} in this
  2624. case).
  2625. In conclusion, one could say that you can use uncertain optimizations {\em
  2626. only} when you know what you're doing.
  2627. \end{enumerate}
  2628. \subsection{ Motorola 680x0 specific }
  2629. Using the \var{-O2} switch does several optimizations in the
  2630. code produced, the most notable being:
  2631. \begin{itemize}
  2632. \item Sign extension from byte to long will use \var{EXTB}
  2633. \item Returning of functions will use \var{RTD}
  2634. \item Range checking will generate no run-time calls
  2635. \item Multiplication will use the long \var{MULS} instruction, no
  2636. runtime library call will be generated
  2637. \item Division will use the long \var{DIVS} instruction, no
  2638. runtime library call will be generated
  2639. \end{itemize}
  2640. \section{Optimization switches}
  2641. This is where the various optimizing switches and their actions are
  2642. described, grouped per switch.
  2643. \begin{description}
  2644. \item [-On:\ ] with n = 1..3: these switches activate the optimizer.
  2645. A higher level automatically includes all lower levels.
  2646. \begin{itemize}
  2647. \item Level 1 (\var{-O1}) activates the peephole optimizer
  2648. (common instruction sequences are replaced by faster equivalents).
  2649. \item Level 2 (\var{-O2}) enables the assembler data flow analyzer,
  2650. which allows the common subexpression elimination procedure to
  2651. remove unnecessary reloads of registers with values they already contain.
  2652. \item Level 3 (\var{-O3}) enables uncertain optimizations. For more info, see -Ou.
  2653. \end{itemize}
  2654. \item[-OG:\ ]
  2655. This causes the code generator (and optimizer, IF activated), to favor
  2656. faster, but code-wise larger, instruction sequences (such as
  2657. "\verb|subl $4,%esp|") instead of slower, smaller instructions
  2658. ("\verb|enter $4|"). This is the default setting.
  2659. \item[-Og:\ ] This one is exactly the reverse of -OG, and as such these
  2660. switches are mutually exclusive: enabling one will disable the other.
  2661. \item[-Or:\ ] this setting (once it's fixed) causes the code generator to
  2662. check which variables are used most, so it can keep those in a register.
  2663. \item[-Opn:\ ] with n = 1..3: setting the target processor does NOT
  2664. activate the optimizer. It merely influences the code generator and,
  2665. if activated, the optimizer:
  2666. \begin{itemize}
  2667. \item During the code generation process, this setting is used to
  2668. decide whether a jump table or a sequence of successive jumps provides
  2669. the best performance in a case statement.
  2670. \item The peephole optimizer takes a number of decisions based on this
  2671. setting, for example it translates certain complex instructions, such
  2672. as
  2673. \begin{verbatim}
  2674. movzbl (mem), %eax|
  2675. \end{verbatim}
  2676. to a combination of simpler instructions
  2677. \begin{verbatim}
  2678. xorl %eax, %eax
  2679. movb (mem), %al
  2680. \end{verbatim}
  2681. for the Pentium.
  2682. \end{itemize}
  2683. \item[-Ou:\ ] This enables uncertain optimizations. You cannot use these
  2684. always, however. The previous section explains when they can be used, and
  2685. when they cannot be used.
  2686. \end{description}
  2687. \section{Tips to get faster code}
  2688. Here some general tips for getting better code are presented. They
  2689. mainly concern coding style.
  2690. \begin{itemize}
  2691. \item Find a better algorithm. No matter how much you and the compiler
  2692. tweak the code, a quicksort will (almost) always outperform a bubble
  2693. sort, for example.
  2694. \item Use variables of the native size of the processor you're writing
  2695. for. For the 80x86 and compatibles, this is 32 bit, so you're best of
  2696. using longint and cardinal variables.
  2697. \item Turn on the optimizer.
  2698. \item Write your if/then/else statements so that the code in the "then"-part
  2699. gets executed most of the time (improves the rate of successful jump prediction).
  2700. \item If you are allocating and disposing a lot of small memory blocks,
  2701. check out the heapblocks variable (heapblocks are on by default from
  2702. release 0.99.8 and later)
  2703. \item Profile your code (see the -pg switch) to find out where the
  2704. bottlenecks are. If you want, you can rewrite those parts in assembler.
  2705. You can take the code generated by the compiler as a starting point. When
  2706. given the \var{-a} command-line switch, the compiler will not erase the
  2707. assembler file at the end of the assembly process, so you can study the
  2708. assembler file.
  2709. {\em Note:} code blocks which contain an assembler block, are not processed
  2710. at all by the optimizer at this time.
  2711. \end{itemize}
  2712. \section{ Floating point }
  2713. This is where can be found processor specific information on Floating
  2714. point code generated by the compiler.
  2715. \subsection{ Intel x86 specific }
  2716. All normal floating point types map to their real type, including
  2717. \var{comp} and \var{extended}.
  2718. \subsection{ Motorola 680x0 specific }
  2719. Early generations of the Motorola 680x0 processors did not have integrated
  2720. floating point units, so to circumvent this fact, all floating point
  2721. operations are emulated (when the \var{\$E+} switch ,which is the default)
  2722. using the IEEE \var{Single} floating point type. In other words when
  2723. emulation is on, Real, Single, Double and Extended all map to the
  2724. \var{single} floating point type.
  2725. When the \var{\$E} switch is turned off, normal 68882/68881/68040
  2726. floating point opcodes are emitted. The Real type still maps to
  2727. \var{Single} but the other types map to their true floating point
  2728. types. Only basic FPU opcodes are used, which means that it can
  2729. work on 68040 processors correctly.
  2730. \emph{ Remark: } \var{Double} and \var{Extended} types in true floating
  2731. point mode have not been extensively tested as of version 0.99.5.
  2732. \emph{ Remark: } The \var{comp} data type is currently not supported.
  2733. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  2734. % Appendices
  2735. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  2736. \appendix
  2737. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  2738. % Appendix A
  2739. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  2740. \chapter{Anatomy of a unit file}
  2741. \label{ch:AppA}
  2742. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  2743. % Basics
  2744. \section{Basics}
  2745. The best and most updated documentation about the ppu files can be found
  2746. in \file{ppu.pas} and \file{ppudump.pp} which can be found in
  2747. \file{rtl/utils/}.
  2748. To read or write the ppufile, you can use the ppu unit \file{ppu.pas}
  2749. which has an object called tppufile which holds all routines that deal
  2750. with ppufile handling. Describing the layout of a ppufile, the methods
  2751. which can be used for it are described.
  2752. A unit file consists of basically five or six parts:
  2753. \begin{enumerate}
  2754. \item A unit header.
  2755. \item A file interface part.
  2756. \item A definition part. Contains all type and procedure definitions.
  2757. \item A symbol part. Contains all symbol names and references to their
  2758. definitions.
  2759. \item A browser part. Contains all references from this unit to other
  2760. units and inside this unit. Only available when the \var{uf\_has\_browser} flag is
  2761. set in the unit flags
  2762. \item A file implementation part (currently unused).
  2763. implementation part.
  2764. \end{enumerate}
  2765. \section{reading ppufiles}
  2766. We will first create an object ppufile which will be used below. We are
  2767. opening unit \file{test.ppu} as an example.
  2768. \begin{verbatim}
  2769. var
  2770. ppufile : pppufile;
  2771. begin
  2772. { Initialize object }
  2773. ppufile:=new(pppufile,init('test.ppu');
  2774. { open the unit and read the header, returns false when it fails }
  2775. if not ppufile.open then
  2776. error('error opening unit test.ppu');
  2777. { here we can read the unit }
  2778. { close unit }
  2779. ppufile.close;
  2780. { release object }
  2781. dispose(ppufile,done);
  2782. end;
  2783. \end{verbatim}
  2784. Note: When a function fails (for example not enough bytes left in an
  2785. entry) it sets the \var{ppufile.error} variable.
  2786. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  2787. % The Header
  2788. \section{The Header}
  2789. The header consists of a record containing 24 bytes:
  2790. \begin{verbatim}
  2791. tppuheader=packed record
  2792. id : array[1..3] of char; { = 'PPU' }
  2793. ver : array[1..3] of char;
  2794. compiler : word;
  2795. cpu : word;
  2796. target : word;
  2797. flags : longint;
  2798. size : longint; { size of the ppufile without header }
  2799. checksum : longint; { checksum for this ppufile }
  2800. end;
  2801. \end{verbatim}
  2802. The header is already read by the \var{ppufile.open} command.
  2803. You can access all fields using \var{ppufile.header} which holds
  2804. the current header record.
  2805. \begin{tabular}{lp{10cm}}
  2806. \raggedright
  2807. field & description \\ \hline
  2808. \var{id} &
  2809. this is allways 'PPU', can be checked with
  2810. \mbox{\var{function ppufile.CheckPPUId:boolean;}} \\
  2811. \var{ver} & ppu version, currently '015', can be checked with
  2812. \mbox{\var{function ppufile.GetPPUVersion:longint;}} (returns 15) \\
  2813. \var{compiler}
  2814. & compiler version used to create the unit. Doesn't contain the
  2815. patchlevel. Currently 0.99 where 0 is the high byte and 99 the
  2816. low byte \\
  2817. \var{cpu} & cpu for which this unit is created.
  2818. 0 = i386
  2819. 1 = m68k \\
  2820. \var{target} & target for which this unit is created, this depends also on the
  2821. cpu!
  2822. For i386:
  2823. \begin{tabular}[t]{ll}
  2824. 0 & Go32v1 \\
  2825. 1 & Go32V2 \\
  2826. 2 & Linux-i386 \\
  2827. 3 & OS/2 \\
  2828. 4 & Win32
  2829. \end{tabular}
  2830. For m68k:
  2831. \begin{tabular}[t]{ll}
  2832. 0 & Amiga \\
  2833. 1 & Mac68k \\
  2834. 2 & Atari \\
  2835. 3 & Linux-m68k
  2836. \end{tabular} \\
  2837. \var{flag} &
  2838. the unit flags, contains a combination of the uf\_ constants which
  2839. are definied in \file{ppu.pas} \\
  2840. \var{size} & size of this unit without this header \\
  2841. \var{checksum} &
  2842. checksum of the interface parts of this unit, which determine if
  2843. a unit is changed or not, so other units can see if they need to
  2844. be recompiled
  2845. \\ \hline
  2846. \end{tabular}
  2847. % The sections
  2848. \section{The sections}
  2849. After this header follow the sections. All sections work the same!
  2850. A section contains of entries and is ended with also an entry, but
  2851. containing the specific ibend constant (see \file{ppu.pas} for a list).
  2852. Each entry starts with an entryheader.
  2853. \begin{verbatim}
  2854. tppuentry=packed record
  2855. id : byte;
  2856. nr : byte;
  2857. size : longint;
  2858. end;
  2859. \end{verbatim}
  2860. \begin{tabular}{lp{10cm}}
  2861. field & Description \\ \hline
  2862. id & this is 1 or 2 and can be check if it the entry is correctly
  2863. found. 1 means its a main entry, which says that it is part of the
  2864. basic layout as explained before. 2 toggles that it it a sub entry
  2865. of a record or object \\
  2866. nr & contains the ib constant number which determines what kind of
  2867. entry it is \\
  2868. size & size of this entry without the header, can be used to skip entries
  2869. very easily. \\ \hline
  2870. \end{tabular}
  2871. To read an entry you can simply call \var{ppufile.readentry:byte},
  2872. it returns the
  2873. \var{tppuentry.nr} field, which holds the type of the entry.
  2874. A common way how this works is (example is for the symbols):
  2875. \begin{verbatim}
  2876. repeat
  2877. b:=ppufile.readentry;
  2878. case b of
  2879. ib<etc> : begin
  2880. end;
  2881. ibendsyms : break;
  2882. end;
  2883. until false;
  2884. \end{verbatim}
  2885. Then you can parse each entry type yourself. \var{ppufile.readentry} will take
  2886. care of skipping unread bytes in the entry an read the next entry
  2887. correctly! A special function is \var{skipuntilentry(untilb:byte):boolean;}
  2888. which will read the ppufile until it finds entry \var{untilb} in the main
  2889. entries.
  2890. Parsing an entry can be done with \var{ppufile.getxxx} functions. The
  2891. available functions are:
  2892. \begin{verbatim}
  2893. procedure ppufile.getdata(var b;len:longint);
  2894. function getbyte:byte;
  2895. function getword:word;
  2896. function getlongint:longint;
  2897. function getreal:ppureal;
  2898. function getstring:string;
  2899. \end{verbatim}
  2900. To check if you're at the end of an entry you can use the following
  2901. function:
  2902. \begin{verbatim}
  2903. function EndOfEntry:boolean;
  2904. \end{verbatim}
  2905. {\em notes:}
  2906. \begin{enumerate}
  2907. \item \var{ppureal} is the best real that exists for the cpu where the
  2908. unit is created for. Currently it is \var{extended} for i386 and
  2909. \var{single} for m68k.
  2910. \item the \var{ibobjectdef} and \var{ibrecorddef} have stored a definition
  2911. and symbol section for themselves. So you'll need a recursive call. See
  2912. \file{ppudump.pp} for a correct implementation.
  2913. \end{enumerate}
  2914. A complete list of entries and what their fields contain can be found
  2915. in \file{ppudump.pp}.
  2916. \section{Creating ppufiles}
  2917. Creating a new ppufile works almost the same as writing. First you need
  2918. to init the object and call create:
  2919. \begin{verbatim}
  2920. ppufile:=new(pppufile,'output.ppu');
  2921. ppufile.create;
  2922. \end{verbatim}
  2923. After that you can simply write all needed entries. You'll have to take
  2924. care that you write at least the basic entries for the sections:
  2925. \begin{verbatim}
  2926. ibendinterface
  2927. ibenddefs
  2928. ibendsyms
  2929. ibendbrowser (only when you've set uf_has_browser!)
  2930. ibendimplementation
  2931. ibend
  2932. \end{verbatim}
  2933. Writing an entry is a little different than reading it. You need to first
  2934. put everything in the entry with ppufile.putxxx:
  2935. \begin{verbatim}
  2936. procedure putdata(var b;len:longint);
  2937. procedure putbyte(b:byte);
  2938. procedure putword(w:word);
  2939. procedure putlongint(l:longint);
  2940. procedure putreal(d:ppureal);
  2941. procedure putstring(s:string);
  2942. \end{verbatim}
  2943. After putting all the things in the entry you need to call
  2944. \var{ppufile.writeentry(ibnr:byte)} where \var{ibnr} is the entry number
  2945. you're writing.
  2946. At the end of the file you need to call \var{ppufile.writeheader} to write the
  2947. new header to the file. This takes automatically care of the new size of the
  2948. ppufile. When that is also done you can call \var{ppufile.close} and dispose the
  2949. object.
  2950. Extra functions/variables available for writing are:
  2951. \begin{verbatim}
  2952. ppufile.NewHeader;
  2953. ppufile.NewEntry;
  2954. \end{verbatim}
  2955. This will give you a clean header or entry. Normally called automatically
  2956. in \var{ppufile.writeentry}, so you can't forget it.
  2957. \begin{verbatim}
  2958. ppufile.flush;
  2959. \end{verbatim}
  2960. to flush the current buffers to the disk
  2961. \begin{verbatim}
  2962. ppufile.do_crc:boolean;
  2963. \end{verbatim}
  2964. set to false if you don't want that the crc is updated, this is necessary
  2965. if you write for example the browser data.
  2966. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  2967. % Appendix B
  2968. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  2969. \chapter{Compiler and RTL source tree structure}
  2970. \label{ch:AppB}
  2971. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  2972. % The compiler source tree
  2973. \section{The compiler source tree}
  2974. All compiler source files are in one directory, normally in
  2975. \file{source/compiler}. For more informations
  2976. about the structure of the compiler have a look at the
  2977. Compiler Manual which contains also some informations about
  2978. compiler internals.
  2979. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  2980. % Appendix C
  2981. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  2982. \chapter{Compiler limits}
  2983. \label{ch:AppC}
  2984. Although many of the restrictions imposed by the MS-DOS system are removed
  2985. by use of an extender, or use of another operating system, there still are
  2986. some limitations to the compiler:
  2987. \begin{enumerate}
  2988. \item Procedure or Function definitions can be nested to a level of 32.
  2989. \item Maximally 255 units can be used in a program when using the real-mode
  2990. compiler (i.e. a binary that was compiled by Borland Pascal). When using the 32-bit compiler, the limit is set to 1024. You can
  2991. change this by redefining the \var{maxunits} constant in the
  2992. \file{files.pas} compiler source file.
  2993. \end{enumerate}
  2994. \end{document}