prog.tex 91 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410
  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. \html{\input{fpc-html.tex}}
  27. % define the version number here, and not in the fpc.sty !!!
  28. \newcommand{\remark}[1]{\par$\rightarrow$\textbf{#1}\par}
  29. \newcommand{\olabel}[1]{\label{option:#1}}
  30. % We should change this to something better. See \seef etc.
  31. \begin{document}
  32. \title{Free Pascal \\ Programmers' manual}
  33. \docdescription{Programmers' manual for \fpc, version \fpcversion}
  34. \docversion{1.3}
  35. \date{March 1998}
  36. \author{Micha\"el Van Canneyt}
  37. \maketitle
  38. \tableofcontents
  39. \newpage
  40. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  41. % Introduction
  42. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  43. \section*{About this document}
  44. This is the programmer's manual for \fpc.
  45. It describes some of the peculiarities of the \fpc compiler, and provides a
  46. glimp of how the compiler generates its code, and how you can change the
  47. generated code. It will not, however, provide you with a detailed account of
  48. the inner workings of the compiler, nor will it tell you how to use the
  49. compiler (described in the \userref). It also will not describe the inner
  50. workings of the Run-Time Library (RTL). The best way to learn about the way
  51. the RTL is implemented is from the sources themselves.
  52. The things described here are useful if you want to do things which need
  53. greater flexibility than the standard Pascal language constructs.
  54. (described in the \refref)
  55. Since the compiler is continuously under development, this document may get
  56. out of date. Wherever possible, the information in this manual will be
  57. updated. If you find something which isn't correct, or you think something
  58. is missing, feel free to contact me\footnote{at
  59. \var{[email protected]}}.
  60. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  61. % Compiler switches
  62. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  63. \chapter{Compiler directives}
  64. \label{ch:CompSwitch}
  65. \fpc supports compiler directives in your source file. They are not the same
  66. as Turbo Pascal directives, although some are supported for compatibility.
  67. There is a distinction between local and global directives; local directives
  68. take effect from the moment they are encountered, global directives have an
  69. effect on all of the compiled code.
  70. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  71. % Local switches
  72. \section{Local directives}
  73. \label{se:LocalSwitch}
  74. Local directives have no command-line counterpart. They influence the
  75. compiler's behaviour from the moment they're encountered until the moment
  76. another switch annihilates their behaviour, or the end of the unit or
  77. program is reached.
  78. \subsection{\var{\$F} : Far or near functions}
  79. This directive is recognized for compatibility with Turbo Pascal. Under the
  80. 32-bit programming model, the concept of near and far calls have no meaning,
  81. hence the directive is ignored. A warning is printed to the screen, telling
  82. you so.
  83. As an example, : the following piece of code :
  84. \begin{verbatim}
  85. {$F+}
  86. Procedure TestProc;
  87. begin
  88. Writeln ('Hello From TestProc');
  89. end;
  90. begin
  91. testProc
  92. end.
  93. \end{verbatim}
  94. Generates the following compiler output:
  95. \begin{verbatim}
  96. malpertuus: >pp -vw testf
  97. Compiler: ppc386
  98. Units are searched in: /home/michael;/usr/bin/;/usr/lib/ppc/0.9.1/linuxunits
  99. Target OS: Linux
  100. Compiling testf.pp
  101. testf.pp(1) Warning: illegal compiler switch
  102. 7739 kB free
  103. Calling assembler...
  104. Assembled...
  105. Calling linker...
  106. 12 lines compiled,
  107. 1.00000000000000E+0000
  108. \end{verbatim}
  109. You can see that the verbosity level was set to display warnings.
  110. If you declare a function as \var{Far} (this has the same effect as setting it
  111. between \var{\{\$F+\}...\{\$F-\}} directives), the compiler also generates a
  112. warning :
  113. \begin{verbatim}
  114. testf.pp(3) Warning: FAR ignored
  115. \end{verbatim}
  116. The same story is true for procedures declared as \var{Near}. The warning
  117. displayed in that case is:
  118. \begin{verbatim}
  119. testf.pp(3) Warning: NEAR ignored
  120. \end{verbatim}
  121. \subsection{\var{\$I} : Input/Output checking}
  122. The \var{\{\$I-\}} directive tells the compiler not to generate input/output
  123. checking code in your program. If you compile using the \var{-Ci} compiler
  124. switch, the \fpc compiler inserts input/output
  125. checking code after every input/output call in your program. If an error
  126. occurred during input or output, then a run-time error will be generated.
  127. Use this switch if you wish to avoid this behavior.
  128. If you still want to check if something went wrong, you can use the
  129. \var{IOResult} function to see if everything went without problems.
  130. Conversely, \var{\{\$I+\}} will turn error-checking back on, until another
  131. directive is encountered which turns it off again.
  132. The most common use for this switch is to check if the opening of a file
  133. went without problems, as in the following piece of code:
  134. \begin{verbatim}
  135. ...
  136. assign (f,'file.txt');
  137. {$I-}
  138. rewrite (f);
  139. {$I+}
  140. if IOResult<>0 then
  141. begin
  142. Writeln ('Error opening file : "file.txt"');
  143. exit
  144. end;
  145. ...
  146. \end{verbatim}
  147. \subsection{\var{\$I} : Include file }
  148. The \var{\{\$I filename\}} directive tells the compiler to read further
  149. statements from the file \var{filename}. The statements read there will be
  150. inserted as if they occurred in the current file.
  151. The compiler will append the \file{.pp} extension to the file if you don't
  152. specify an extension yourself. Do not put the filename between quotes, as
  153. they will be regarded as part of the file's name.
  154. You can nest included files, but not infinitely deep. The number of files is
  155. restricted to the number of file descriptors available to the \fpc compiler.
  156. Contrary to Turbo Pascal, include files can cross blocks. I.e. you can start
  157. a block in one file (with a \var{Begin} keyword) and end it in another (with
  158. a \var{End} keyword). The smallest entity in an include file must be a token,
  159. i.e. an identifier, keyword or operator.
  160. \subsection{\var{\$L} : Link object file}
  161. The \var{\{\$L filename\}} directive tells the compiler that the file \file{filename}
  162. should be linked to your program. You can only use this directive in a
  163. program. If you do use it in a unit, the compiler will not complain, but
  164. simply ignores the directive.
  165. The compiler will {\em not} look for the file in the unit path.
  166. The name will be passed to the linker {\em exactly} as you've typed it.
  167. Since the files name is passed directly to the linker, this means that on
  168. \linux systems, the name is case sensitive, and must be typed exactly as it
  169. appears on your system.
  170. {\em Remark :} Take care that the object file you're linking is in a
  171. format the linker understands. Which format this is, depends on the platform
  172. you're on. Typing \var{ld} on th command line gives a list of formats
  173. \var{ld} knows about.
  174. You can pass other files and options to the linker using the \var{-k}
  175. command-line option. You can specify more than one of these options, and
  176. they
  177. will be passed to the linker, in the order that you specified them on the
  178. command line, just before the names of the object files that must be linked.
  179. % Assembler type
  180. \subsection{\var{\$I386\_XXX} : Specify assembler format}
  181. This switch informs the compiler what kind of assembler it can expect in an
  182. \var{asm} block. The \var{XXX} should be replaced by one of the following:
  183. \begin{description}
  184. \item [att\ ] Indicates that \var{asm} blocks contain AT\&T syntax assembler.
  185. \item [intel\ ] Indicates that \var{asm} blocks contain Intel syntax
  186. assembler.
  187. \item [direct\ ] Tells the compiler that asm blocks should be copied
  188. directly to the assembler file.
  189. \end{description}
  190. These switches are local, and retain their value to the end of the unit that
  191. is compiled, unless they are replaced by another directive of the same type.
  192. The command-line switch that corresponds to this switch is \var{-R}.
  193. \subsection{\var{\$MMX} : MMX support}
  194. As of version 0.9.8, \fpc supports optimization for the \textbf{MMX} Intel
  195. processor (see also \ref{ch:MMXSupport}). This optimizes certain code parts for the \textbf{MMX} Intel
  196. processor, thus greatly improving speed. The speed is noticed mostly when
  197. moving large amounts of data. Things that change are
  198. \begin{itemize}
  199. \item Data with a size that is a multiple of 8 bytes is moved using the
  200. \var{movq} assembler instruction, which moves 8 bytes at a time
  201. \end{itemize}
  202. When \textbf{MMX} support is on, you aren't allowed to do floating point
  203. arithmetic. You are allowed to move floating point data, but no arithmetic
  204. can be done. If you wish to do floating point math anyway, you must first
  205. switch of \textbf{MMX} support and clear the FPU using the \var{emms}
  206. function of the \file{cpu} unit.
  207. The following example will make this more clear:
  208. \begin{verbatim}
  209. Program MMXDemo;
  210. uses cpu;
  211. var
  212. d1 : double;
  213. a : array[0..10000] of double;
  214. i : longint;
  215. begin
  216. d1:=1.0;
  217. {$mmx+}
  218. { floating point data is used, but we do _no_ arithmetic }
  219. for i:=0 to 10000 do
  220. a[i]:=d2; { this is done with 64 bit moves }
  221. {$mmx-}
  222. emms; { clear fpu }
  223. { now we can do floating point arithmetic }
  224. ....
  225. end.
  226. \end{verbatim}
  227. See, however, the chapter on MMX (\ref{ch:MMXSupport}) for more information
  228. on this topic.
  229. \subsection{\var{\$OUTPUT\_FORMAT} : Specify the output format}
  230. \var{\{\$OUTPUT\_FORMAT format\}} has the same functionality as the \var{-A}
  231. command-line option : It tells the compiler what kind of object file must be
  232. generated. You can specify this switch \textbf{only} befor the \var{Program}
  233. or \var{Unit} clause in your source file. The different kinds of formats are
  234. shown in \seet{Formats}.
  235. \begin{FPCltable}{ll}{Formats generated by the compiler}{Formats} \hline
  236. Switch value & Generated format \\ \hline
  237. att & AT\&T assembler file. \\
  238. o & Unix object file.\\
  239. obj & OMF file.\\
  240. wasm & assembler for the Watcom assembler. \\ \hline
  241. \end{FPCltable}
  242. \subsection{\var{\$V} : Var-string checking}
  243. When in the \var{+} state, the compiler checks that strings passed as
  244. parameters are of the same, identical, string type as the declared
  245. parameters of the procedure.
  246. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  247. % Global switches
  248. \section{Global directives}
  249. \label{se:GlobalSwitch}
  250. Global directives affect the whole of the compilation process. That is why
  251. they also have a command - line counterpart. The command-line counterpart is
  252. given for each of the directives.
  253. \subsection{\var{\$A} : Align Data}
  254. This switch is recognized for Turbo Pascal Compatibility, but is not
  255. yet implemented. The alignment of data will be different in any case, since
  256. \fpc is a 32-bit compiler.
  257. \subsection{\var{\$B} : Complete boolean evaluation}
  258. This switch is understood by the \fpc compiler, but is ignored. The compiler
  259. always uses shortcut evaluation, i.e. the evaluation of a boolean expression
  260. is stopped once the result of the total exression is known with certainty.
  261. So, in the following example, the function \var{Bofu}, which has a boolean
  262. result, will never get called.
  263. \begin{verbatim}
  264. If False and Bofu then
  265. ...
  266. \end{verbatim}
  267. \subsection{\var{\$D} : Debugging symbols}
  268. When this switch is on, the compiler inserts GNU debugging information in
  269. the executable. The effect of this switch is the same as the command-line
  270. switch \var{-g}. By default, insertion of debugging information is off.
  271. \subsection{\var{\$E} : Emulation of coprocessor}
  272. This directive controls the emulation of the coprocessor. On the i386
  273. processor, it is supported for
  274. compatibility with Turbo Pascal. The compiler itself doesn't do the emulation
  275. of the coprocessor. Under \dos, the \dos extender does this, and under
  276. \linux, the kernel takes care of the coprocessor support.
  277. If you use the Motorola 680x0 version, then the switch is recognized, as
  278. there is no extender to emulate the coprocessor, so the compiler must do
  279. that by itself.
  280. There is no command-line counterpart for this directive.
  281. \subsection{\var{\$G} : Generate 80286 code}
  282. This option is recognised for Turbo Pascal cmpatibility, but is ignored,
  283. because the compiler needs at least a 386 or higher class processor.
  284. \subsection{\var{\$L} : Local symbol information}
  285. This switch (not to be confused with the \var{\{\$L file\}} file linking
  286. directive) is recognised for Turbo Pascal compatibility, but is ignored.
  287. generation of symbol information is controlled by the \var{\$D} switch.
  288. \subsection{\var{\$N} : Numeric processing }
  289. This switch is recognised for Turbo Pascal compatibility, but is otherwise
  290. ignored, since the compiler always uses the coprocessor for floating point
  291. mathematics.
  292. \subsection{\var{\$O} : Overlay code generation }
  293. This switch is recognised for Turbo Pascal compatibility, but is otherwise
  294. ignored, since the compiler requires a 386 or higher computer, with at
  295. least 4 Mb. of ram.
  296. \subsection{\var{\$Q} : Overflow checking}
  297. The \var{\{\$Q+\}} directive turns on integer overflow checking.
  298. This means that the compiler inserts code to check for overflow when doing
  299. computations with an integer.
  300. When an overflow occurs, the run-time library will print a message
  301. \var{Overflow at xxx}, and exit the program with exit code 1.
  302. Using the \var{\{\$Q-\}} switch switches off the overflow checking code
  303. generation.
  304. The generation of overflow checking code can also be controlled
  305. using the \var{-Co} command line compiler option (see \userref).
  306. \subsection{\var{\$R} : Range checking}
  307. By default, the computer doesn't generate code to check the ranges of array
  308. indices, enumeration types, subrange types, etc. Specifying the
  309. \var{\{\$R+\}} switch tells the computer to generate code to check these
  310. indices. If, at run-time, an index or enumeration type is specified that is
  311. out of the declared range of the compiler, then a run-time error is
  312. generated, and the program exits with exit code 1.
  313. The \var{\{\$R-\}} switch tells the compiler not to generate range checking
  314. code. This may result in faulty program behaviour, but no run-time errors
  315. will be generated.
  316. {\em Remark: } this has not been implemented completely yet.
  317. \subsection{\var{\$S} : Stack checking}
  318. The \var{\{\$S+\}} directive tells the compiler to generate stack checking
  319. code. This generates code to check if a stack overflow occurred, i.e. to see
  320. whether the stack has grown beyond its maximally allowed size. If the stack
  321. grows beyond the maximum size, then a run-time error is generated, and the
  322. program will exit with exit code 1.
  323. Specifying \var{\{\$S-\}} will turn generation of stack-checking code off.
  324. There is no command-line switch which is equivalent to this directive.
  325. {\em Remark: } In principle, the stack is almost unlimited,
  326. i.e. limited to the total free amount of memory on the computer.
  327. \subsection{\var{\$X} : Extended syntax}
  328. Extended syntax allows you to drop the result of a function. This means that
  329. you can use a function call as if it were a procedure. Standard this feature
  330. is on. You can switch it off using the \var{\{\$X-\}} directive.
  331. The following, for instance, will not compile :
  332. \begin{verbatim}
  333. function Func (var Arg : sometype) : longint;
  334. begin
  335. ... { declaration of Func }
  336. end;
  337. ...
  338. {$X-}
  339. Func (A);
  340. \end{verbatim}
  341. The reason this construct is supported is that
  342. you may wish to call a function for certain side-effects it has, but you
  343. don't need the function result. In this case you don't need to assign the
  344. function result, saving you an extra variable.
  345. The command-line compiler switch \var{-Sa1} has the same effect as the
  346. \var{\{\$X+\}} directive.
  347. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  348. % Using conditionals and macros
  349. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  350. \chapter{Using conditionals, Messages and macros}
  351. \label{ch:CondMessageMacro}
  352. The \fpc compiler supports conditionals as in normal Turbo Pascal. It does,
  353. however, more than that. It allows you to make macros which can be used in
  354. your code, and it allows you to define messages or errors which will be
  355. displayed when compiling.
  356. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  357. % Conditionals
  358. \section{Conditionals}
  359. \label{se:Conditionals}
  360. The rules for using conditional symbols are the same as under Turbo Pascal.
  361. Defining a symbol goes as follows:
  362. \begin{verbatim}
  363. {$Define Symbol }
  364. \end{verbatim}
  365. From this point on in your code, the compiler know the symbol \var{Symbol}
  366. Symbols are, like the Pascal language, case insensitive.
  367. You can also define a symbol on the command line. the \var{-dSymbol} option
  368. defines the symbol \var{Symbol}. You can specify as many symbols on the
  369. command line as you want.
  370. Undefining an existing symbol is done in a similar way:
  371. \begin{verbatim}
  372. {$Undef Symbol }
  373. \end{verbatim}
  374. If the symbol didn't exist yet, this doesn't do anything. If the symbol
  375. existed previously, the symbol will be erased, and will not be recognized
  376. any more in the code following the \verb|{$Undef ...}| statement.
  377. You can also undefine symbols from the command line with the \var{-u}
  378. command-line switch..
  379. To compile code conditionally, depending on whether a symbol is defined or
  380. not, you can enclose the code in a \verb|{$ifdef Symbol}| .. \verb|{$endif}|
  381. pair. For instance the following code will never be compiled :
  382. \begin{verbatim}
  383. {$Undef MySymbol}
  384. {$ifdef Mysymbol}
  385. DoSomething;
  386. ...
  387. {$endif}
  388. \end{verbatim}
  389. Similarly, you can enclose your code in a \verb|{$Ifndef Symbol}| .. \verb|{$endif}|
  390. pair. Then the code between the pair will only be compiled when the used
  391. symbol doesn't exist. For example, in the following example, the call to the
  392. \var{DoSomething} will always be compiled:
  393. \begin{verbatim}
  394. {$Undef MySymbol}
  395. {$ifndef Mysymbol}
  396. DoSomething;
  397. ...
  398. {$endif}
  399. \end{verbatim}
  400. You can combine the two alternatives in one structure, namely as follows
  401. \begin{verbatim}
  402. {$ifdef Mysymbol}
  403. DoSomething;
  404. {$else}
  405. DoSomethingElse
  406. {$endif}
  407. \end{verbatim}
  408. In this example, if \var{MySymbol} exists, then the call to \var{DoSomething}
  409. will be compiled. If it doesn't exist, the call to \var{DoSomethingElse} is
  410. compiled.
  411. The \fpc compiler defines some symbols before starting to compile your
  412. program or unit. You can use these symbols to differentiate between
  413. different versions of the compiler, and between different compilers.
  414. In \seet{Symbols}, a list of pre-defined symbols is given\footnote{Remark:
  415. The \var{FPK} symbol is still defined for compatibility with older versions.}. In that table,
  416. you should change \var{v} with the version number of the compiler
  417. you're using, \var{r} with the release number and \var{p}
  418. with the patch-number of the compiler. 'OS' needs to be changed by the type
  419. of operating system. Currently this can be one of \var{DOS}, \var{GO32V2},
  420. \var{LINUX}, \var{OS2} or \var{WIN32}. This symbol is undefined if you
  421. specify a target that is different from the platform you're compiling on.
  422. the \var{-TSomeOS} option on the command line will define the \var{SomeOS} symbol,
  423. and will undefined the existing platform symbol\footnote{In versions prior to
  424. 0.9.4, this didn't happen, thus making Cross-compiling impossible.}.
  425. \begin{FPCltable}{c}{Symbols defined by the compiler.}{Symbols} \hline
  426. Free \\
  427. VER\var{v} \\
  428. VER\var{v}\_\var{r} \\
  429. VER\var{v}\_\var{r}\_\var{p} \\
  430. OS \\ \hline
  431. \end{FPCltable}
  432. As an example : Version 0.9.1 of the compiler, running on a Linux system,
  433. defines the following symbols before reading the command line arguments:
  434. \var{FPC}, \var{VER0}, \var{VER0\_9}, \var{VER0\_9\_1} and \var{LINUX}.
  435. Specifying \var{-TOS2} on the command-line will undefine the \var{LINUX}
  436. symbol, and will define the \var{OS2} symbol.
  437. {\em Remark: } Symbols, even when they're defined in the interface part of
  438. a unit, are not available outside that unit.
  439. \fpc supports the \var{\{\$IFOPT \}} directive for Turbo Pascal
  440. compatibility, but doesn't act on it. It always rejects the condition, so
  441. code between \var{\{\$IFOPT \}} and \var{\{\$Endif\}} is never compiled.
  442. Except for the Turbo Pascal constructs, from version 0.9.8 and higher,
  443. the \fpc compiler also supports a stronger conditional compile mechanism:
  444. The \var{\{\$If \}} construct.
  445. The prototype of this construct is as follows :
  446. \begin{verbatim}
  447. {$If expr}
  448. CompileTheseLines;
  449. {$else}
  450. BetterCompileTheseLines;
  451. {$endif}
  452. \end{verbatim}
  453. In this directive \var{expr} is a Pascal expression which is evaluated using
  454. strings, unless both parts of a comparision can be evaluated as numbers,
  455. in which case they are evaluated using numbers\footnote{Otherwise
  456. \var{\{\$If 8>54} would evaluate to \var{True}}.
  457. If the complemete expression evaluates to \var{'0'}, then it is considered
  458. false and rejected. Otherwise it is considered true and accepted. This may
  459. have unsexpected consequences :
  460. \begin{verbatim}
  461. {$If 0}
  462. \end{verbatim}
  463. Will evaluate to \var{False} and be rejected, while
  464. \begin{verbatim}
  465. {$If 00}
  466. \end{verbatim}
  467. Will evaluate to \var{True}.
  468. You can use any Pascal operator to construct your expression : \var{=, <>,
  469. >, <, >=, <=, AND, NOT, OR} and you can use round brackets to change the
  470. precedence of the operators.
  471. The following example shows you many of the possibilities:
  472. \begin{verbatim}
  473. {$ifdef fpc}
  474. var
  475. y : longint;
  476. {$else fpc}
  477. var
  478. z : longint;
  479. {$endif fpc}
  480. var
  481. x : longint;
  482. begin
  483. {$if (fpc_version=0) and (fpc_release>6) and (fpc_patch>4)}
  484. {$info At least this is version 0.9.5}
  485. {$else}
  486. {$fatalerror Problem with version check}
  487. {$endif}
  488. {$define x:=1234}
  489. {$if x=1234}
  490. {$info x=1234}
  491. {$else}
  492. {$fatalerror x should be 1234}
  493. {$endif}
  494. {$if 12asdf and 12asdf}
  495. {$info $if 12asdf and 12asdf is ok}
  496. {$else}
  497. {$fatalerror $if 12asdf and 12asdf rejected}
  498. {$endif}
  499. {$if 0 or 1}
  500. {$info $if 0 or 1 is ok}
  501. {$else}
  502. {$fatalerror $if 0 or 1 rejected}
  503. {$endif}
  504. {$if 0}
  505. {$fatalerror $if 0 accepted}
  506. {$else}
  507. {$info $if 0 is ok}
  508. {$endif}
  509. {$if 12=12}
  510. {$info $if 12=12 is ok}
  511. {$else}
  512. {$fatalerror $if 12=12 rejected}
  513. {$endif}
  514. {$if 12<>312}
  515. {$info $if 12<>312 is ok}
  516. {$else}
  517. {$fatalerror $if 12<>312 rejected}
  518. {$endif}
  519. {$if 12<=312}
  520. {$info $if 12<=312 is ok}
  521. {$else}
  522. {$fatalerror $if 12<=312 rejected}
  523. {$endif}
  524. {$if 12<312}
  525. {$info $if 12<312 is ok}
  526. {$else}
  527. {$fatalerror $if 12<312 rejected}
  528. {$endif}
  529. {$if a12=a12}
  530. {$info $if a12=a12 is ok}
  531. {$else}
  532. {$fatalerror $if a12=a12 rejected}
  533. {$endif}
  534. {$if a12<=z312}
  535. {$info $if a12<=z312 is ok}
  536. {$else}
  537. {$fatalerror $if a12<=z312 rejected}
  538. {$endif}
  539. {$if a12<z312}
  540. {$info $if a12<z312 is ok}
  541. {$else}
  542. {$fatalerror $if a12<z312 rejected}
  543. {$endif}
  544. {$if not(0)}
  545. {$info $if not(0) is OK}
  546. {$else}
  547. {$fatalerror $if not(0) rejected}
  548. {$endif}
  549. {$info *************************************************}
  550. {$info * Now have to follow at least 2 error messages: *}
  551. {$info *************************************************}
  552. {$if not(0}
  553. {$endif}
  554. {$if not(<}
  555. {$endif}
  556. end.
  557. \end{verbatim}
  558. As you can see from the example, this construct isn't useful when used
  559. with normal symbols, but it is if you use macros, which are explained in
  560. \sees{Macros}, they can be very useful. When trying this example, you must
  561. switch on macro support, with the \var{-Sm} command-line switch.
  562. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  563. % Macros
  564. \section{Messages}
  565. \label{se:Messages}
  566. \fpc lets you define normal, warning and error messages in your code.
  567. Messages can be used to display useful information, such as copyright
  568. notices, a list of symbols that your code reacts on etc.
  569. Warnings can be used if you think some part of your code is still buggy, or
  570. if you think that a certain combination of symbols isn't useful. In general
  571. anything which may cause problems when compiling.
  572. Error messages can be useful if you need a certain symbol to be defined
  573. to warn that a certain variable isn't defined or so, or when the compiler
  574. version isn't suitable for your code.
  575. The compiler treats these messages as if they were generated by the
  576. compiler. This means that if you haven't turned on warning messages, the
  577. warning will not e displayed. Errors are always displayed, and the compiler
  578. stops as if an error had occurred.
  579. For messages, the syntax is as follows :
  580. \begin{verbatim}
  581. {$Message Message text }
  582. \end{verbatim}
  583. Or
  584. \begin{verbatim}
  585. {$Info Message text }
  586. \end{verbatim}
  587. For notes:
  588. \begin{verbatim}
  589. {$Note Message text }
  590. \end{verbatim}
  591. For warnings:
  592. \begin{verbatim}
  593. {$Warning Warning Message text }
  594. \end{verbatim}
  595. For errors :
  596. \begin{verbatim}
  597. {$Error Error Message text }
  598. \end{verbatim}
  599. Lastly, for fatal errors :
  600. \begin{verbatim}
  601. {$FatalError Error Message text }
  602. \end{verbatim}
  603. or
  604. \begin{verbatim}
  605. {$Stop Error Message text }
  606. \end{verbatim}
  607. The difference between \var{\$Error} and \var{\$FatalError} or \var{\$Stop}
  608. messages is that when the compiler encounters an error, it still continues
  609. to compile. With a fatal error, the compiler stops.
  610. {\em Remark :} You cannot use the '\var{\}}' character in your message, since
  611. this will be treated as the closing brace of the message.
  612. As an example, the following piece of code will generate an error when
  613. the symbol \var{RequiredVar} isn't defined:
  614. \begin{verbatim}
  615. {$ifndef RequiredVar}
  616. {$Error Requiredvar isn't defined !}
  617. {$endif}
  618. \end{verbatim}
  619. But the compiler will continue to compile. It will not, however, generate a
  620. unit file or a program (since an error occurred).
  621. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  622. % Macros
  623. \section{Macros}
  624. \label{se:Macros}
  625. Macros are very much like symbols in their syntax, the difference is that
  626. macros have a value whereas a symbol simply is defined or is not defined.
  627. If you want macro support, you need to specify the \var{-Sm} command-line
  628. switch, otherwise your macro will be regarded as a symbol.
  629. Defining a macro in your program is done in the same way as defining a symbol;
  630. in a \var{\{\$define \}} preprocessor statement\footnote{In compiler
  631. versions older than 0.9.8, the assignment operator for a macros wasn't
  632. \var{:=}, but \var{=}}:
  633. \begin{verbatim}
  634. {$define ident:=expr}
  635. \end{verbatim}
  636. If the compiler encounters \var{ident} in the rest of the source file, it
  637. will be replaced immediately by \var{expr}. This replacement works
  638. recursive, meaning that when the compiler expanded one of your macros, it
  639. will look at the resulting expression again to see if another replacement
  640. can be made. You need to be careful with this, because an infinite loop can
  641. occur in this manner.
  642. Here are two examples which illustrate the use of macros:
  643. \begin{verbatim}
  644. {$define sum:=a:=a+b;}
  645. ...
  646. sum { will be expanded to 'a:=a+b;'
  647. remark the absence of the semicolon}
  648. ...
  649. {$define b:=100}
  650. sum { Will be expanded recursively to a:=a+100; }
  651. ...
  652. \end{verbatim}
  653. The previous example could go wrong :
  654. \begin{verbatim}
  655. {$define sum:=a:=a+b;}
  656. ...
  657. sum { will be expanded to 'a:=a+b;'
  658. remark the absence of the semicolon}
  659. ...
  660. {$define b=sum} { DON'T do this !!!}
  661. sum { Will be infinitely recursively expanded... }
  662. ...
  663. \end{verbatim}
  664. On my system, the last example results in a heap error, causing the compiler
  665. to exit with a run-time error 203.
  666. {\em Remark: } Macros defined in the interface part of a unit are not
  667. available outside that unit ! They can just be used as a notational
  668. convenience, or in conditional compiles.
  669. By default, from version 0.9.8 of the compiler on, the compiler predefines three
  670. macros, containing the version number, the release number and the patch
  671. number. They are listed in \seet{DefMacros}.
  672. \begin{FPCltable}{ll}{Predefined macros}{DefMacros} \hline
  673. Symbol & Contains \\ \hline
  674. \var{FPC\_VERSION} & The version number of the compiler. \\
  675. \var{FPC\_RELEASE} & The release number of the compiler. \\
  676. \var{FPC\_PATCH} & The patch number of the compiler. \\
  677. \hline
  678. \end{FPCltable}
  679. {\em Remark: } Don't forget that macros support isn't on by default. You
  680. need to compile with the \var{-Sm} command-line switch.
  681. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  682. % Using assembly language
  683. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  684. \chapter{Using assembly language}
  685. \label{ch:AsmLang}
  686. \fpc supports inserting of assembler instructions in your code. The
  687. mechanism for this is the same as under Turbo Pascal. There are, however
  688. some substantial differences, as will be explained in the following.
  689. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  690. % Intel syntax
  691. \section{Intel syntax}
  692. \label{se:Intel}
  693. As of version 0.9.7, \fpc supports Intel syntax in it's \var{asm} blocks.
  694. The Intel syntax in your \var{asm} block is converted to AT\&T syntax by the
  695. compiler, after which it is inserted in the compiled source.
  696. The supported assembler constructs are a subset of the normal assembly
  697. syntax. In what follows we specify what constructs are not supported in
  698. \fpc, but which exist in Turbo Pascal:
  699. \begin{itemize}
  700. \item The \var{TBYTE} qualifier is not supported.
  701. \item The \var{\&} identifier override is not supported.
  702. \item The \var{HIGH} operator is not supported.
  703. \item The \var{LOW} operator is not supported.
  704. \item The \var{OFFSET} and \var{SEG} operators are not supported.
  705. use \var{LEA} and the various \var{Lxx} instructions instead.
  706. \item Expressions with constant strings are not allowed.
  707. \item Access to record fields via parenthesis is not allowed
  708. \item Typecasts with normal pascal types are not allowed, only
  709. recognized assembler typecasts are allowed.\\ Example:
  710. \begin{verbatim}
  711. mov al, byte ptr MyWord -- allowed,
  712. mov al, byte(MyWord) -- allowed,
  713. mov al, shortint(MyWord) -- not allowed.
  714. \end{verbatim}
  715. \item Pascal type typecasts on constants are not allowed. \\
  716. Example:
  717. \begin{verbatim}
  718. const s= 10; const t = 32767;
  719. \end{verbatim}
  720. in Turbo Pascal:
  721. \begin{verbatim}
  722. mov al, byte(s) -- useless typecast.
  723. mov al, byte(t) -- syntax error!
  724. \end{verbatim}
  725. In this parser, either of those cases will give out a syntax error.
  726. \item Constant references expressions with constants only are not
  727. allowed (in all cases they do not work in protected mode,
  728. under linux i386). \\ Examples:
  729. \begin{verbatim}
  730. mov al,byte ptr ['c'] -- not allowed.
  731. mov al,byte ptr [100h] -- not allowed.
  732. \end{verbatim}
  733. (This is due to the limitation of Turbo Assembler).
  734. \item Brackets within brackets are not allowed
  735. \item Expressions with segment overrides fully in brackets are
  736. presently not supported, but they can easily be implemented
  737. in BuildReference if requested. \\ Example:
  738. \begin{verbatim}
  739. mov al,[ds:bx] -- not allowed
  740. \end{verbatim}
  741. use instead:
  742. \begin{verbatim}
  743. mov al,ds:[bx]
  744. \end{verbatim}
  745. \item Possible allowed indexing are as follows:
  746. \begin{itemize}
  747. \item \var{Sreg:[REG+REG*SCALING+/-disp]}
  748. \item \var{SReg:[REG+/-disp]}
  749. \item \var{SReg:[REG]}
  750. \item \var{SReg:[REG+REG+/-disp]}
  751. \item \var{SReg:[REG+REG*SCALING]}
  752. \end{itemize}
  753. Where \var{Sreg} is optional and specifies the segment override.
  754. {\em Notes:}
  755. \begin{enumerate}
  756. \item The order of terms is important contrary to Turbo Pascal.
  757. \item The Scaling value must be a value, and not an identifier
  758. to a symbol.\\ Examples:
  759. \begin{verbatim}
  760. const myscale = 1;
  761. ...
  762. mov al,byte ptr [esi+ebx*myscale] -- not allowed.
  763. \end{verbatim}
  764. use:
  765. \begin{verbatim}
  766. mov al, byte ptr [esi+ebx*1]
  767. \end{verbatim}
  768. \end{enumerate}
  769. \item Possible variable identifier syntax is as follows:
  770. (Id = Variable or typed constant identifier.)
  771. \begin{enumerate}
  772. \item \var{ID}
  773. \item \var{[ID]}
  774. \item \var{[ID+expr]}
  775. \item \var{ID[expr]}
  776. \end{enumerate}
  777. Possible fields are as follow:
  778. \begin{enumerate}
  779. \item \var{ID.subfield.subfield ...}
  780. \item \var{[ref].ID.subfield.subfield ...}
  781. \item \var{[ref].typename.subfield ...}
  782. \end{enumerate}
  783. \item Local Labels: Contrary to Turbo Pascal, local labels, must
  784. at least contain one character after the local symbol indicator.\\
  785. Example:
  786. \begin{verbatim}
  787. @: -- not allowed
  788. \end{verbatim}
  789. use instead, for example:
  790. \begin{verbatim}
  791. @1: -- allowed
  792. \end{verbatim}
  793. \item Contrary to Turbo Pascal local references cannot be used as references,
  794. only as displacements. \\ example:
  795. \begin{verbatim}
  796. lds si,@mylabel -- not allowed
  797. \end{verbatim}
  798. \item Contrary to Turbo Pascal, \var{SEGCS}, \var{SEGDS}, \var{SEGES} and
  799. \var{SEGSS} segment overrides are presently not supported.
  800. (This is a planned addition though).
  801. \item Contrary to Turbo Pascal where memory sizes specifiers can
  802. be practically anywhere, the \fpc Intel inline assembler requires
  803. memory size specifiers to be outside the brackets. \\
  804. example:
  805. \begin{verbatim}
  806. mov al,[byte ptr myvar] -- not allowed.
  807. \end{verbatim}
  808. use:
  809. \begin{verbatim}
  810. mov al,byte ptr [myvar] -- allowed.
  811. \end{verbatim}
  812. \item Base and Index registers must be 32-bit registers.
  813. (limitation of the GNU Assembler).
  814. \item \var{XLAT} is equivalent to \var{XLATB}.
  815. \item Only Single and Double FPU opcodes are supported.
  816. \item Floating point opcodes are currently not supported
  817. (except those which involve only floating point registers).
  818. \end{itemize}
  819. The Intel inline assembler supports the following macros :
  820. \begin{description}
  821. \item [@Result] represents the function result return value.
  822. \item [Self] represents the object method pointer in methods.
  823. \end{description}
  824. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  825. % AT&T syntax
  826. \section{AT\&T Syntax}
  827. \label{se:AttSyntax}
  828. \fpc uses the \gnu \var{as} assembler to generate its object files. Since
  829. the \gnu assembler uses AT\&T assembly syntax, the code you write should
  830. use the same syntax. The differences between AT\&T and Intel syntax as used
  831. in Turbo Pascal are summarized in the following:
  832. \begin{itemize}
  833. \item The opcode names include the size of the operand. In general, one can
  834. say that the AT\&T opcode name is the Intel opcode name, suffixed with a
  835. '\var{l}', '\var{w}' or '\var{b}' for, respectively, longint (32 bit),
  836. word (16 bit) and byte (8 bit) memory or register references. As an example,
  837. the Intel construct \mbox{'\var{mov al bl}} is equivalent to the AT\&T style '\var{movb
  838. \%bl,\%al}' instruction.
  839. \item AT\&T immediate operands are designated with '\$', while Intel syntax
  840. doesn't use a prefix for immediate operands. Thus the Intel construct
  841. '\var{mov ax, 2}' becomes '\var{movb \$2, \%al}' in AT\&T syntax.
  842. \item AT\&T register names are preceded by a '\var{\%}' sign.
  843. They are undelimited in Intel syntax.
  844. \item AT\&T indicates absolute jump/call operands with '\var{*}', Intel
  845. syntax doesn't delimit these addresses.
  846. \item The order of the source and destination operands are switched. AT\&T
  847. syntax uses '\var{Source, Dest}', while Intel syntax features '\var{Dest,
  848. Source}'. Thus the Intel construct '\var{add eax, 4}' transforms to
  849. '\var{addl \$4, \%eax}' in the AT\&T dialect.
  850. \item Immediate long jumps are prefixed with the '\var{l}' prefix. Thus the
  851. Intel '\var{call/jmp section:offset'} is transformed to '\var{lcall/ljmp
  852. \$section,\$offset}'. Similarly the far return is '\var{lret}', instead of the
  853. Intel '\var{ret far}'.
  854. \item Memory references are specified differently in AT\&T and Intel
  855. assembly. The Intel indirect memory reference
  856. \begin{quote}
  857. \var{Section:[Base + Index*Scale + Offs]}
  858. \end{quote}
  859. is written in AT\&T syntax as :
  860. \begin{quote}
  861. \var{Section:Offs(Base,Index,Scale)}
  862. \end{quote}
  863. Where \var{Base} and \var{Index} are optional 32-bit base and index
  864. registers, and \var{Scale} is used to multiply \var{Index}. It can take the
  865. values 1,2,4 and 8. The \var{Section} is used to specify an optional section
  866. register for the memory operand.
  867. \end{itemize}
  868. More information about the AT\&T syntax can be found in the \var{as} manual,
  869. although the following differences with normal AT\&T assembly must be taken
  870. into account :
  871. \begin{itemize}
  872. \item Only the following directives are presently supported:
  873. \begin{description}
  874. \item[.byte]
  875. \item[.word]
  876. \item[.long]
  877. \item[.ascii]
  878. \item[.asciz]
  879. \item[.globl]
  880. \end{description}
  881. \item The following directives are recognized but are not
  882. supported:
  883. \begin{description}
  884. \item[.align]
  885. \item[.lcomm]
  886. \end{description}
  887. Eventually they will be supported.
  888. \item Directives are case sensitive, other identifiers are not case sensitive.
  889. \item Contrary to GAS local labels/symbols {\em must} start with \var{.L}
  890. \item The nor operator \var{'!'} is not supported.
  891. \item String expressions in operands are not supported.
  892. \item Constant expressions which represent memory references are not
  893. allowed even though constant immediate value expressions are supported. \\
  894. examples:
  895. \begin{verbatim}
  896. const myid = 10;
  897. ...
  898. movl $myid,%eax -- allowed
  899. movl myid(%esi),%eax -- not allowed.
  900. \end{verbatim}
  901. \item When the \var{.globl} directive is found, the symbol following
  902. it is made public and is immediately emitted.
  903. Therefore label names with this name will be ignored.
  904. \item Only Single and Double FPU opcodes are supported.
  905. \end{itemize}
  906. The AT\&T inline assembler supports the following macros :
  907. \begin{description}
  908. \item [\_\_RESULT] represents the function result return value.
  909. \item [\_\_SELF] represents the object method pointer in methods.
  910. \item [\_\_OLDEBP] represents the old base pointer in recusrive routines.
  911. \end{description}
  912. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  913. % Calling mechanism
  914. \section{Calling mechanism}
  915. \label{se:Calling}
  916. Procedures and Functions are called with their parameters on the stack.
  917. Contrary to Turbo Pascal, {\em all} parameters are pushed on the stack, and
  918. they are pushed {\em right} to {\em left}, instead of left to right for
  919. Turbo Pascal. This is especially important if you have some assembly
  920. subroutines in Turbo Pascal which you would like to translate to \fpc.
  921. Function results are returned in the first register, if they fit in the
  922. register. For more information on this, see \sees{Stack}
  923. The registers are {\em not} saved when calling a function or procedure. If
  924. you want to call a procedure or function from assembly language, you must
  925. save any registers you wish to preserve.
  926. The first thing a procedure does is saving the base pointer, and setting the
  927. base (\var{\%ebp}) pointer equal to the stack pointer (\var{\%esp}).
  928. References to the pushed parameters and local variables are constructed
  929. using the base pointer.
  930. In practice this amounts to the following assembly code as the procedure or
  931. function header :
  932. \begin{verbatim}
  933. pushl %ebp
  934. movl %esp,%ebp
  935. \end{verbatim}
  936. When the procedure or function exits, it clears the stack by means of the
  937. \var{RET xx} call, where \var{xx} is the total size of the pushed parameters
  938. on the stack. Thus, in case parameters with a total size of \var{xx} have
  939. been passed to a function, the generated exit sequence looks as follows:
  940. \begin{verbatim}
  941. leave
  942. ret $xx
  943. \end{verbatim}
  944. When you want your code to be called by a C library or used in a C
  945. program, you will run into trouble because of this calling mechanism. In C,
  946. the calling procedure is expected to clear the stack, not the called
  947. procedure. To avoid this problem, \fpc supports the \var{export} modifier.
  948. Procedures that are defined using the export modifier, use a C-compatible
  949. calling mechanism. This means that they can be called from a C program or
  950. library, or that you can use them as a callback function.
  951. This also means that you cannot call this procedure or function from your
  952. own program, since your program uses the Pascal calling convention.
  953. However, in the exported function, you can of course call other Pascal
  954. routines.
  955. Technically, the C calling mechanism is implemented by generating the
  956. following exit sequence at the end of your function or procedure:
  957. \begin{verbatim}
  958. leave {Copies EBP to ESP, pops EBP from the stack.}
  959. ret
  960. \end{verbatim}
  961. Comparing this exit sequence with the previous one makes it clear why you
  962. cannot call this procedure from within Pascal: The arguments still are on
  963. the stack when the procedure exits.
  964. As of version 0.9.8, the \fpc compiler supports also the \var{cdecl} and
  965. \var{stdcall} modifiers, as found in Delphi. The \var{cdecl} modifier does
  966. the same as the \var{export} modifier, and \var{stdcall} does nothing, since
  967. \fpc pushes the paramaters from right to left by default.
  968. In addition to the Delphi \var{cdecl} construct, \fpc also supports the
  969. \var{popstack} directive; it is nearly the same a the \var{cdecl} directive,
  970. only it still mangles the name, i.e. makes it into a name such as the
  971. compiler uses internally.
  972. All this is summarized in \seet{Calling}. The first column lists the
  973. modifier you specify for a procedure declaration. The second one lists the
  974. order the paramaters are pushed on the stack. The third column specifies who
  975. is responsible for cleaning the stack: the caller or the called function.
  976. Finally, the last column specifies if registers are used to pass parameters
  977. to the function.
  978. \begin{FPCltable}{llll}{Calling mechanisms in \fpc}{Calling}\hline
  979. Modifier & Pushing order & Stack cleaned by & Parameters in registers \\
  980. \hline
  981. (none) & Right-to-left & Function & No \\
  982. cdecl & Right-to-left & Caller & No \\
  983. export & Right-to-left & Caller & No \\
  984. stdcall & Right-to-left & Function & No \\
  985. popstack & Right-to-left & Caller & No \\ \hline
  986. \end{FPCltable}
  987. More about this can be found in \seec{Linking} on linking.
  988. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  989. % Telling the compiler what registers have changed
  990. \section{Telling the compiler what registers have changed}
  991. \label{se:RegChanges}
  992. When the compiler uses variables, it sometimes stores them, or the result of
  993. some calculations, in the processor registers. If you insert assembler code
  994. in your program that modifies the processor registers, then this may
  995. interfere with the compiler's idea about the registers. To avoid this
  996. problem, \fpc allows you to tell the compiler which registers have changed.
  997. The compiler will then avoid using these registers. Telling the compiler
  998. which registers have changed, is done by specifying a set of register names
  999. behind an assembly block, as follows:
  1000. \begin{verbatim}
  1001. asm
  1002. ...
  1003. end ['R1',...,'Rn'];
  1004. \end{verbatim}
  1005. Here \var{R1} to \var{Rn} are the names of the (extended) registers you
  1006. modify in your assembly code. They can be one of \var{'EAX', 'EBX', 'ECX',
  1007. 'EDX', 'EDI', 'ESI'} for the Intel processor.
  1008. As an example :
  1009. \begin{verbatim}
  1010. asm
  1011. movl BP,%eax
  1012. movl 4(%eax),%eax
  1013. movl %eax,__RESULT
  1014. end ['EAX'];
  1015. \end{verbatim}
  1016. This example tells the compiler that the \var{EAX} register was modified.
  1017. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1018. % Linking issues
  1019. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1020. \chapter{Linking issues}
  1021. \label{ch:Linking}
  1022. When you only use Pascal code, and Pascal units, then you will not see much
  1023. of the part that the linker plays in creating your executable.
  1024. The linker is only called when you compile a program. When compiling units,
  1025. the linker isn't invoked.
  1026. However, there are times that you want to C libraries, or to external
  1027. object files that are generated using a C compiler (or even another pascal
  1028. compiler). The \fpc compiler can generate calls to a C function,
  1029. and can generate functions that can be called from C (exported functions).
  1030. However, these exported functions cannot be called from
  1031. inside Pascal anymore. More on these calling conventions can be found in
  1032. \sees{Calling}.
  1033. In general, there are 2 things you must do to use a function that resides in
  1034. an external library or object file:
  1035. \begin{enumerate}
  1036. \item You must make a pascal declaration of the function or procedure you
  1037. want to use.
  1038. \item You must tell the compiler where the function resides, i.e. in what
  1039. object file or what library, so the compiler can link the necessary code in.
  1040. \end{enumerate}
  1041. The following sections attempt to explain how to do this.
  1042. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1043. % Declaring an external function or procedure
  1044. \section{Declaring an external function or procedure}
  1045. \label{se:ExternalDeclaration}
  1046. The first step in using external code blocks is declaring the function you
  1047. want to use. \fpc supports Delphi syntax, i.e. you must use the
  1048. \var{external} directive.
  1049. There exist four variants of the external direcive :
  1050. \begin{enumerate}
  1051. \item A simple external declaration:
  1052. \begin{verbatim}
  1053. Procedure ProcName (Args : TPRocArgs); external;
  1054. \end{verbatim}
  1055. The \var{external} directive tells the compiler that the function resides in
  1056. an external block of code. You can use this together with the \var{\{\$L \}}
  1057. or \var{\{\$LinkLib \}} directives to link to a function or procedure in a
  1058. library or external object file.
  1059. \item You can give the \var{external} directive a library name as an
  1060. argument:
  1061. \begin{verbatim}
  1062. Procedure ProcName (Args : TPRocArgs); external 'Name';
  1063. \end{verbatim}
  1064. This tells the compiler that the procedure resides in a library with name
  1065. \var{'Name'}. This method is equivalent to the following:
  1066. \begin{verbatim}
  1067. Procedure ProcName (Args : TPRocArgs);external;
  1068. {$LinkLib 'Name'}
  1069. \end{verbatim}
  1070. \item The \var{external} can also be used with two arguments:
  1071. \begin{verbatim}
  1072. Procedure ProcName (Args : TPRocArgs); external 'Name'
  1073. name 'OtherProcName';
  1074. \end{verbatim}
  1075. This has the same meaning as the previous declaration, only the compiler
  1076. will use the name \var{'OtherProcName'} when linking to the library. This
  1077. can be used to give different names to procedures and functions in an
  1078. external library.
  1079. This method is equivalent to the following code:
  1080. \begin{verbatim}
  1081. Procedure OtherProcName (Args : TProcArgs); external;
  1082. {$LinkLib 'Name'}
  1083. Procedure ProcName (Args : TPRocArgs);
  1084. begin
  1085. OtherProcName (Args);
  1086. end;
  1087. \end{verbatim}
  1088. \item Lastly, onder \windows and \ostwo, there is a fourth possibility
  1089. to specify an external function: In \file{.DLL} files, functionas also have
  1090. a unique number (their index). It is possible to refer to these fuctions
  1091. using their index:
  1092. \begin{verbatim}
  1093. Procedure ProcName (Args : TPRocArgs); external 'Name' Index SomeIndex;
  1094. \end{verbatim}
  1095. This tells the compiler that the procedure \var{ProcName} resides in a
  1096. dynamic link library, with index {SomeIndex}.
  1097. \em{Remark:} Note that this is ONLY available under \windows and \ostwo.
  1098. \end{enumerate}
  1099. In earlier versions of the \fpc compiler, the following construct was
  1100. also possible :
  1101. \begin{verbatim}
  1102. Procedure ProcName (Args : TPRocArgs); [ C ];
  1103. \end{verbatim}
  1104. This method is equivalent to the following statement:
  1105. \begin{verbatim}
  1106. Procedure ProcName (Args : TPRocArgs); cdecl; external;
  1107. \end{verbatim}
  1108. However, the \var{[ C ]} directive is no longer supoerted as of version
  1109. 0.99.5 of \fpc, therefore you should use the
  1110. \var{external} directive, with the \var{cdecl} directive, if needed.
  1111. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1112. % Linking an object file in your program
  1113. \section{Explicitly linking an object file in your program}
  1114. \label{se:LinkIn}
  1115. Having declared the external function that resides in an object file,
  1116. you can use it as if it was defined in your own program or unit.
  1117. To produce an executable, you must still link the object file in.
  1118. This can be done with the \var{\{\$L 'file.o'\}} directive.
  1119. This will cause the linker to link in the object file \file{file.o}. On
  1120. \linux systems, this filename is case sensitive. Under \dos, case isn't
  1121. important. Note that \var{file.o} must be in the current directory if you
  1122. don't specify a path. The linker will not search for \file{file.o} if it
  1123. isn't found.
  1124. You cannot specify libraries in this way, it is for object files only.
  1125. Here we present an example. Consider that you have some assembly routine that
  1126. calculates the nth Fibonacci number :
  1127. \begin{verbatim}
  1128. .text
  1129. .align 4
  1130. .globl Fibonacci
  1131. .type Fibonacci,@function
  1132. Fibonacci:
  1133. pushl %ebp
  1134. movl %esp,%ebp
  1135. movl 8(%ebp),%edx
  1136. xorl %ecx,%ecx
  1137. xorl %eax,%eax
  1138. movl $1,%ebx
  1139. incl %edx
  1140. loop:
  1141. decl %edx
  1142. je endloop
  1143. movl %ecx,%eax
  1144. addl %ebx,%eax
  1145. movl %ebx,%ecx
  1146. movl %eax,%ebx
  1147. jmp loop
  1148. endloop:
  1149. movl %ebp,%esp
  1150. popl %ebp
  1151. ret
  1152. \end{verbatim}
  1153. Then you can call this function with the following Pascal Program:
  1154. \begin{verbatim}
  1155. Program FibonacciDemo;
  1156. var i : longint;
  1157. Function Fibonacci (L : longint):longint;cdecl;external;
  1158. {$L fib.o}
  1159. begin
  1160. For I:=1 to 40 do
  1161. writeln ('Fib(',i,') : ',Fibonacci (i));
  1162. end.
  1163. \end{verbatim}
  1164. With just two commands, this can be made into a program :
  1165. \begin{verbatim}
  1166. as -o fib.o fib.s
  1167. pp fibo.pp
  1168. \end{verbatim}
  1169. This example supposes that you have your assembler routine in \file{fib.s},
  1170. and your Pascal program in \file{fibo.pp}.
  1171. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1172. % Linking your program to a library
  1173. \section{Linking your program to a library}
  1174. \label{se:LinkOut}
  1175. To link your program to a library, the procedure depends on how you declared
  1176. the external procedure. If you used thediffers a little from the
  1177. procedure when you link in an object file. although the declaration step
  1178. remains the same (see \ref{se:ExternalDeclaration} on how to do that).
  1179. In case you used the follwing syntax to declare your procedure:
  1180. \begin{verbatim}
  1181. Procedure ProcName (Args : TPRocArgs); external 'Name';
  1182. \end{verbatim}
  1183. You don't need to take additional steps to link your file in, the compiler
  1184. will do all that is needed for you.
  1185. In case you used
  1186. \begin{verbatim}
  1187. Procedure ProcName (Args : TPRocArgs); external;
  1188. \end{verbatim}
  1189. You still need to explicity link to the library. This can be done in 2 ways:
  1190. \begin{enumerate}
  1191. \item You can tell the compiler in the source file what library to link to
  1192. using the \var{\{\$LinkLib 'Name'\}} directive:
  1193. \begin{verbatim}
  1194. {$LinkLib 'gpm'}
  1195. \end{verbatim}
  1196. This will link to the \file{gpm} library. On \linux systems, you needn't
  1197. specify the extension or 'lib' prefix of the library. The compiler takes
  1198. care of that. On \dos or \windows systems, you need to specify the full
  1199. name.
  1200. \item You can also tell the compiler on the command-line to link in a
  1201. library: The \var{-k} option can be used for that. For example
  1202. \begin{verbatim}
  1203. ppc386 -k'-lgpm' myprog.pp
  1204. \end{verbatim}
  1205. Is equivalent to the above method, and tells the linker to link to the
  1206. \file{gpm} library.
  1207. \end{enumerate}
  1208. As an example; consider the following program :
  1209. \begin{verbatim}
  1210. program printlength;
  1211. {$linklib c} { Case sensitive }
  1212. { Declaration for the standard C function strlen }
  1213. Function strlen (P : pchar) : longint; cdecl;external;
  1214. begin
  1215. Writeln (strlen('Programming is easy !'));
  1216. end.
  1217. \end{verbatim}
  1218. This program can be compiled with :
  1219. \begin{verbatim}
  1220. pp prlen.pp
  1221. \end{verbatim}
  1222. Supposing, of course, that the program source resides in \file{prlen.pp}.
  1223. You cannot use procedures or functions that have a variable number of
  1224. arguments in C. Pascal doesn't support this feature of C.
  1225. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1226. % Making a shared library
  1227. \section{Making a shared library}
  1228. \label{se:SharedLib}
  1229. \fpc supports making shared libraries in a straightforward and easy manner.
  1230. If you want to make libraries for other \fpc programmers, you just need to
  1231. provide a command line switch. If you want C programmers to be able to use
  1232. your code as well, you will need to adapt your code a little. This process
  1233. is described first.
  1234. % Adapting your code
  1235. \subsection{Adapting your code}
  1236. If you want to make your procedures and functions available to C
  1237. programmers, you can do this very easily. All you need to do is declare the
  1238. functions and procedures that you want to make available as \var{Export}, as
  1239. follows:
  1240. \begin{verbatim}
  1241. Procedure ExportedProcedure ; export;
  1242. \end{verbatim}
  1243. This tells the compiler that it shouldn't clear the stack upon exiting the
  1244. procedure (see \sees{Calling}), thus enabling a C program to call your
  1245. function. It also means that your Pascal program can't call this function,
  1246. since it will be using the C calling mechanism.
  1247. {\em Remark :} You can only declare a function as exported in the
  1248. \var{Implementation} section of a unit. This function may {\em not} appear
  1249. in the interface part of a unit. This is logical, since a Pascal routine
  1250. cannot call an exported function, anyway.
  1251. However, the generated object file will not contain the name of the function
  1252. as you declared it. The \fpc compiler ''mangles'' the name you give your
  1253. function. It makes the name all-uppercase, and adds the types of all
  1254. parameters to it. For \fpc units, this doesn't matter, since the \file{.ppu}
  1255. unit file contains all information to map your function declaration onto the
  1256. mangled name in the object file. For a C programmer, who has no access to
  1257. the \var{.ppu} file, this is not very convenient. That is why \fpc
  1258. has the \var{Alias} modifier. The \var{Alias} modifier allows you to specify
  1259. another name (a nickname) for your function or procedure.
  1260. The prototype for an aliased function or procedure is as follows :
  1261. \begin{verbatim}
  1262. Procedure AliasedProc; [ Alias : 'AliasName'];
  1263. \end{verbatim}
  1264. The procedure \var{AliasedProc} will also be known as \var{AliasName}. Take
  1265. care, the name you specify is case sensitive (as C is).
  1266. Of course, you want to combine these two features of \fpc, to export a
  1267. function under a reasonable name; If you want to do that, you must first
  1268. specify that the function is to be exported, and then only declare an alias:
  1269. \begin{verbatim}
  1270. Procedure ExportToCProc; Export; [Alias : 'procname'];
  1271. \end{verbatim}
  1272. After that, any C program will be able to use your procedure or function.
  1273. {\em Remark: }
  1274. If you use in your unit functions that are in other units, or
  1275. system functions, then the C program will need to link in the object files
  1276. from the units too.
  1277. % Compiling libraries
  1278. \subsection {Compiling libraries}
  1279. Once you have your (adapted) code, with exported and other functions,
  1280. you can compile your unit, and tell the compiler to make it into a library.
  1281. The compiler will simply compile your unit, and perform the necessary steps
  1282. to transform it into a \var{static} or \var{shared} (\var{dynamical}) library.
  1283. You can do this as follows, for a dynamical library:
  1284. \begin{verbatim}
  1285. ppc386 -Uld myunit
  1286. \end{verbatim}
  1287. On \linux this will leave you with a file \file{libmyunit.so}. On \windows
  1288. and \ostwo, this will leave you with \file{myunit.dll}.
  1289. If you want a static library, you can do
  1290. \begin{verbatim}
  1291. ppc386 -Uls myunit
  1292. \end{verbatim}
  1293. This will leave you with \file{libmyunit.a} and a file \file{myunit.ppl}.
  1294. The \file{myunit.ppl} is the unit file needed by the \fpc compiler.
  1295. The extension \file{.ppl} means that the file describes a unit that resides
  1296. in a library.
  1297. The resulting files are then libraries. To make static libraries, you need
  1298. the \file{ranlib} or \var{ar} program on your system. It is standard on any
  1299. \linux system, and is provided with the \file{GCC} compiler under \dos.
  1300. {\em BEWARE:} This command doesn't include anything but the current unit in
  1301. thelibrary. Other units are left out, so if you use code from other units,
  1302. you must dpley them together with your library.
  1303. % Moving units
  1304. \subsection{Moving units into a library}
  1305. You can put multiple units into a library with the \var{ppumove} command, as
  1306. follows:
  1307. \begin{verbatim}
  1308. ppumove unit1 unit2 unit3 name
  1309. \end{verbatim}
  1310. This will move 3 units in 1 library (called \file{libname.so} on linux,
  1311. \file{name.dll} on \windows) and it will create 3 files \file{unit1.ppl},
  1312. \file{unit2.ppl} and \file{file3.ppl}, which are unit files, but which tell
  1313. the compiler to look in library \var{name} when linking your executable.
  1314. The \var{ppumove} program has options to create statical or dynammical
  1315. libraries. It is provided with the compiler.
  1316. % unit searching
  1317. \subsection{Unit searching strategy}
  1318. When you compile a program or unit, the compiler will by
  1319. default always look for \file{.ppl} files. If it doesn't find one, it will
  1320. look for a \file{.ppu} file. You can disable this behaviour by
  1321. specifying the \var{-Cs} switch. This tells the compiler to make a static
  1322. binary, and refrains it from looking for units which reside in a library.
  1323. You can tell the compiler only to use dynamic libraries by specifying
  1324. the \var{-Cd} switch; the compiler will then only look for \var{.ppl} files,
  1325. and will give an error if it doesn't find one.
  1326. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1327. % Objects
  1328. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1329. \chapter{Objects}
  1330. \label{ch:Objects}
  1331. In this short chapter we give some technical things about objects. For
  1332. instructions on how to use and declare objects, see \refref.
  1333. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1334. % Constructor and Destructor calls.
  1335. \section{Constructor and Destructor calls}
  1336. \label{se:ConsDest}
  1337. When using objects that need virtual methods, the compiler uses two help
  1338. procedures that are in the run-time library. They are called
  1339. \var{Help\_Destructor} and \var{Help\_Constructor}, and they are written in
  1340. assebly language. They are used to allocate the necessary memory if needed,
  1341. and to insert the Virtual Method Table (VMT) pointer in the newly allocated
  1342. object.
  1343. When the compiler encounters a call to an object's constructor,
  1344. it sets up the stack frame for the call, and inserts a call to the
  1345. \var{Help\_Constructor}
  1346. procedure before issuing the call to the real constuctor.
  1347. The helper procedure allocates the needed memory (if needed) and inserts the
  1348. VMT pointer in the object. After that, the real constructor is called.
  1349. A call to \var{Help\_Destructor} is inserted in every destructor declaration,
  1350. just before the destructor's exit sequence.
  1351. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1352. % memory storage of Objects
  1353. \section{Memory storage of objects}
  1354. \label{se:ObjMemory}
  1355. Objects are stored in memory just as ordinary records with an extra field :
  1356. a pointer to the Virtual Method Table (VMT). This field is stored first, and
  1357. all fields in the object are stored in the order they are declared.
  1358. This field is initialized by the call to the object's \var{Constructor} method.
  1359. If the object you defined has no virtual methods, then a \var{nil} is stored
  1360. in the VMT pointer. This ensures that the size of objects is equal, whether
  1361. they have virtual methods ore not.
  1362. The memory allocated looks as in \seet{ObjMem}.
  1363. \begin{FPCltable}{ll}{Object memory layout}{ObjMem} \hline
  1364. Offset & What \\ \hline
  1365. +0 & Pointer to VMT. \\
  1366. +4 & Data. All fields in the order the've been declared. \\
  1367. ... & \\
  1368. \hline
  1369. \end{FPCltable}
  1370. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1371. % The virtual method table.
  1372. \section{The Virtual Method Table}
  1373. \label{se:VMT}
  1374. The Virtual Method Table (VMT) for each object type consists of 2 check
  1375. fields (containing the size of the data), a pointer to the object's anchestor's
  1376. VMT (\var{Nil} if there is no anchestor), and then the pointers to all virtual
  1377. methods. The VMT layout is illustrated in \seet{VMTMem}.
  1378. The VMT is constructed by the compiler. Every instance of an object receives
  1379. a pointer to its VMT.
  1380. \begin{FPCltable}{ll}{Virtual Method Table memory layout}{VMTMem} \hline
  1381. Offset & What \\ \hline
  1382. +0 & Size of object type data \\
  1383. +4 & Minus the size of object type data. Enables determining of valid VMT
  1384. pointers. \\
  1385. +8 & Pointer to ancestor VMT, \var{Nil} if no ancestor available.\\
  1386. +12 & Pointers to the virtual methods. \\
  1387. ... & \\
  1388. \hline
  1389. \end{FPCltable}
  1390. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1391. % Generated code
  1392. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1393. \chapter{Generated code}
  1394. \label{ch:GenCode}
  1395. The \fpc compiler relies on the assembler to make object files. It generates
  1396. just the assembly language file. In the following two sections, we discuss
  1397. what is generated when you compile a unit or a program.
  1398. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1399. % Units
  1400. \section{Units}
  1401. \label{se:Units}
  1402. When you compile a unit, the \fpc compiler generates 2 files :
  1403. \begin{enumerate}
  1404. \item A unit description file (with extension \file{.ppu}).
  1405. \item An assembly language file (with extension \file{.s}).
  1406. \end{enumerate}
  1407. The assembly language file contains the actual source code for the
  1408. statements in your unit, and the necessary memory allocations for any
  1409. variables you use in your unit. This file is converted by the assembler to
  1410. an object file (with extension \file{.o}) which can then be linked to other
  1411. units and your program, to form an executable.
  1412. By default (compiler version 0.9.4 and up), the assembly file is removed
  1413. after it has been compiled. Only in the case of the \var{-s} command-line
  1414. option, the assembly file must be left on disk, so the assembler can be
  1415. called later.
  1416. The unit file contains all the information the compiler needs to use the
  1417. unit:
  1418. \begin{enumerate}
  1419. \item Other used units, both in interface and implementation.
  1420. \item Types and variables from the interface section of the unit.
  1421. \item Function declarations from the interface section of the unit.
  1422. \item Some debugging information, when compiled with debugging.
  1423. \item A date and time stamp.
  1424. \end{enumerate}
  1425. Macros, symbols and compiler directives are {\em not} saved to the unit
  1426. description file. Aliases for functions are also not written to this file,
  1427. which is logical, since they cannot appear in the interface section of a
  1428. unit.
  1429. The detailed contents and structure of this file are described in the first
  1430. appendix. You can examine a unit description file using the \file{dumpppu}
  1431. program, which shows the contents of the file.
  1432. If you want to distribute a unit without source code, you must provide both
  1433. the unit description file and the object file.
  1434. You can also provide a C header file to go with the object file. In that
  1435. case, your unit can be used by someone who wishes to write his programs in
  1436. C. However, you must make this header file yourself since the \fpc compiler
  1437. doesn't make one for you.
  1438. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1439. % Programs
  1440. \section{Programs}
  1441. \label{se:Programs}
  1442. When you compile a program, the compiler produces again 2 files :
  1443. \begin{enumerate}
  1444. \item An assembly language file containing the statements of your program,
  1445. and memory allocations for all used variables.
  1446. \item A linker response file. This file contains a list of object files the
  1447. linker must link together.
  1448. \end{enumerate}
  1449. The link response file is, by default, removed from the disk. Only when you
  1450. specify the \var{-s} command-line option or when linking fails, then the ile
  1451. is left on the disk. It is named \file{link.res}.
  1452. The assembly language file is converted to an object file by the assembler,
  1453. and then linked together with the rest of the units and a program header, to
  1454. form your final program.
  1455. The program header file is a small assembly program which provides the entry
  1456. point for the program. This is where the execution of your program starts,
  1457. so it depends on the operating system, because operating systems pass
  1458. parameters to executables in wildly different ways.
  1459. It's name is \file{prt0.o}, and the
  1460. source file resides in \file{prt0.s} or some variant of this name. It
  1461. usually resided where the system unit source for your system resides.
  1462. It's main function is to save the environment and command-line arguments,
  1463. set up the stack. Then it calls the main program.
  1464. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1465. % MMX Support
  1466. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1467. \chapter{MMX support}
  1468. \label{ch:MMXSupport}
  1469. \section{What is it about ?}
  1470. \label{se:WhatisMMXabout}
  1471. \fpc supports the new MMX (Multi-Media extensions)
  1472. instructions of Intel processors. The idea of MMX is to
  1473. process multiple data with one instruction, for example the processor
  1474. can add simultaneously 4 words. To implement this efficiently, the
  1475. Pascal language needs to be extended. So Free Pascal allows
  1476. to add for example two \var{array[0..3] of word},
  1477. if MMX support is switched on. The operation is done
  1478. by the \var{MMX} unit and allows people without assembler knowledge to take
  1479. advantage of the MMX extensions.
  1480. Here is an example:
  1481. \begin{verbatim}
  1482. uses
  1483. MMX; { include some predefined data types }
  1484. const
  1485. { tmmxword = array[0..3] of word;, declared by unit MMX }
  1486. w1 : tmmxword = (111,123,432,4356);
  1487. w2 : tmmxword = (4213,63456,756,4);
  1488. var
  1489. w3 : tmmxword;
  1490. l : longint;
  1491. begin
  1492. if is_mmx_cpu then { is_mmx_cpu is exported from unit mmx }
  1493. begin
  1494. {$mmx+} { turn mmx on }
  1495. w3:=w1+w2;
  1496. {$mmx-}
  1497. end
  1498. else
  1499. begin
  1500. for i:=0 to 3 do
  1501. w3[i]:=w1[i]+w2[i];
  1502. end;
  1503. end.
  1504. \end{verbatim}
  1505. \section{Saturation support}
  1506. \label{se:SaturationSupport}
  1507. One important point of MMX is the support of saturated operations.
  1508. If a operation would cause an overflow, the value stays at the
  1509. highest or lowest possible value for the data type:
  1510. If you use byte values you get normally 250+12=6. This is very
  1511. annoying when doing color manipulations or changing audio samples,
  1512. when you have to do a word add and check if the value is greater than
  1513. 255. The solution is saturation: 250+12 gives 255.
  1514. Saturated operations are supported by the \var{MMX} unit. If you
  1515. want to use them, you have simple turn the switch saturation on:
  1516. \var{\$saturation+}
  1517. Here is an example:
  1518. \begin{verbatim}
  1519. Program SaturationDemo;
  1520. {
  1521. example for saturation, scales data (for example audio)
  1522. with 1.5 with rounding to negative infinity
  1523. }
  1524. var
  1525. audio1 : tmmxword;
  1526. const
  1527. helpdata1 : tmmxword = ($c000,$c000,$c000,$c000);
  1528. helpdata2 : tmmxword = ($8000,$8000,$8000,$8000);
  1529. begin
  1530. { audio1 contains four 16 bit audio samples }
  1531. {$mmx+}
  1532. { convert it to $8000 is defined as zero, multiply data with 0.75 }
  1533. audio1:=tmmxfixed16(audio1+helpdata2)*tmmxfixed(helpdata1);
  1534. {$saturation+}
  1535. { avoid overflows (all values>$7fff becomes $ffff) }
  1536. audio1:=(audio1+helpdata2)-helpdata2;
  1537. {$saturation-}
  1538. { now mupltily with 2 and change to integer }
  1539. audio1:=(audio1 shl 1)-helpdata2;
  1540. {$mmx-}
  1541. end.
  1542. \end{verbatim}
  1543. \section{Restrictions of MMX support}
  1544. \label{se:MMXrestrictions}
  1545. In the beginning of 1997 the MMX instructions were introduced in the
  1546. Pentium processors, so multitasking systems wouldn't save the
  1547. newly introduced MMX registers. To work around that problem, Intel
  1548. mapped the MMX registers to the FPU register.
  1549. The consequence is that
  1550. you can't mix MMX and floating point operations. After using
  1551. MMX operations and before using floating point operations, you
  1552. have to call the routine \var{EMMS} of the \var{MMX} unit.
  1553. This routine restores the FPU registers.
  1554. {\em careful:} The compiler doesn't warn, if you mix floating point and
  1555. MMX operations, so be careful.
  1556. The MMX instructions are optimized for multi media (what else?).
  1557. So it isn't possible to perform each operation, some opertions
  1558. give a type mismatch, see section \ref {se:SupportedMMX} for the supported
  1559. MMX operations
  1560. An important restriction is that MMX operations aren't range or overflow
  1561. checked, even when you turn range and overflow checking on. This is due to
  1562. the nature of MMX operations.
  1563. The \var{MMX} unit must be always used when doing MMX operations
  1564. because the exit code of this unit clears the MMX unit. If it wouldn't do
  1565. that, other program will crash. A consequence of this is that you can't use
  1566. MMX operations in the exit code of your units or programs, since they would
  1567. interfere with the exit code of the \var{MMX} unit. The compiler can't
  1568. check this, so you are responsible for this !
  1569. \section{Supported MMX operations}
  1570. \label{se:SupportedMMX}
  1571. \section{Optimizing MMX support}
  1572. \label{se:OptimizingMMX}
  1573. Here are some helpful hints to get optimal performance:
  1574. \begin{itemize}
  1575. \item The \var{EMMS} call takes a lot of time, so try to seperate floating
  1576. point and MMX operations.
  1577. \item Use MMX only in low level routines because the compiler
  1578. saves all used MMX registers when calling a subroutine.
  1579. \item The NOT-operator isn't supported natively by MMX, so the
  1580. compiler has to generate a workaround and this operation
  1581. is inefficient.
  1582. \item Simple assignements of floating point numbers don't access
  1583. floating point registers, so you need no call to the \var{EMMS}
  1584. procedure. Only when doing arithmetic, you need to call the \var{EMMS}
  1585. procedure.
  1586. \end{itemize}
  1587. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1588. % Memory issues
  1589. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1590. \chapter{Memory issues}
  1591. \label{ch:Memory}
  1592. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1593. % The 32-bit model
  1594. \section{The 32-bit model.}
  1595. \label{se:ThirtytwoBit}
  1596. The \fpc Pascal compiler issues 32-bit code. This has several consequences:
  1597. \begin{itemize}
  1598. \item You need a i386 or higher processor to run the generated code. The
  1599. compiler functions on a 286 when you compile it using Turbo Pascal,
  1600. but the generated programs cannot be assembled or executed.
  1601. \item You don't need to bother with segment selectors. Memory can be
  1602. addressed using a single 32-bit pointer.
  1603. The amount of memory is limited only by the available amount of (virtual)
  1604. memory on your machine.
  1605. \item The structures you define are unlimited in size. Arrays can be as long
  1606. as you want. You can request memory blocks from any size.
  1607. \end{itemize}
  1608. The fact that 32-bit code is used, means that some of the older Turbo Pascal
  1609. constructs and functions are obsolete. The following is a list of functions
  1610. which shouldn't be used anymore:
  1611. \begin{description}
  1612. \item [Seg()] : Returned the segment of a memory address. Since segments have
  1613. no more meaning, zero is returned in the \fpc run-time library implementation of
  1614. \var{Seg}.
  1615. \item [Ofs()] : Returned the offset of a memory address. Since segments have
  1616. no more meaning, the complete address is returned in the \fpc implementation
  1617. of this function. This has as a consequence that the return type is
  1618. \var{Longint} instead of \var{Word}.
  1619. \item [Cseg(), Dseg()] : Returned, respectively, the code and data segments
  1620. of your program. This returns zero in the \fpc implementation of the
  1621. system unit, since both code and data are in the same memory space.
  1622. \item [Ptr] accepted a segment and offset from an address, and would return
  1623. a pointer to this address. This has been changed in the run-time library.
  1624. Standard it returns now simply the offset. If you want to retain the old
  1625. functionality, you can recompile the run-time library with the
  1626. \var{DoMapping} symbol defined. This will restore the Turbo Pascal
  1627. behaviour.
  1628. \item [memw and mem] these arrays gave access to the \dos memory. \fpc
  1629. supports them, they are mapped into \dos memory space. You need the
  1630. \var{GO32} unit for this.
  1631. \end{description}
  1632. You shouldn't use these functions, since they are very non-portable, they're
  1633. specific to \dos and the ix86 processor. The \fpc compiler is designed to be
  1634. portable to other platforms, so you should keep your code as portable as
  1635. possible, and not system specific. That is, unless you're writing some driver
  1636. units, of course.
  1637. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1638. % The stack
  1639. \section{The stack}
  1640. \label{se:Stack}
  1641. The stack is used to pass parameters to procedures or functions,
  1642. to store local variables, and, in some cases, to return function
  1643. results.
  1644. When a function or procedure is called, then the following is done by the
  1645. compiler :
  1646. \begin{enumerate}
  1647. \item If there are any parameters to be passed to the procedure, they are
  1648. pushed from right to left on the stack.
  1649. \item If a function is called that returns a variable of type \var{String},
  1650. \var{Set}, \var{Record}, \var{Object} or \var{Array}, then an address to
  1651. store the function result in, is pushed on the stack.
  1652. \item If the called procedure or function is an object method, then the
  1653. pointer to \var{self} is pushed on the stack.
  1654. \item If the procedure or function is nested in another function or
  1655. procedure, then the frame pointer of the parent procedure is pushed on the
  1656. stack.
  1657. \item The return address is pushed on the stack (by the \var{Call}
  1658. instruction).
  1659. \end{enumerate}
  1660. The resulting stack frame upon entering looks as in \seet{StackFrame}.
  1661. \begin{FPCltable}{llc}{Stack frame when calling a procedure}{StackFrame}
  1662. \hline
  1663. Offset & What is stored & Optional ? \\ \hline
  1664. +x & parameters & Yes \\
  1665. +12 & function result & Yes \\
  1666. +8 & self & Yes \\
  1667. +4 & Frame pointer of parent procedure & Yes \\
  1668. +0 & Return address & No\\ \hline
  1669. \end{FPCltable}
  1670. The stack is cleared with the \var{ret} I386 instruction, meaning that the
  1671. size of all pushed parameters is limited to 64K.
  1672. The stack size is unlimited for all supported platforms. On the \var{GO32V2}
  1673. platform, the minimum guaranteed stack is 128Kb, but this can be set with
  1674. the \var{-Ctxxx} compiler switch.
  1675. The heap is used to store all dynamic variables, and to store class
  1676. instances. The interface to the heap is the same as in Turbo Pascal,
  1677. although the effects are maybe not the same. On top of that, the \fpc
  1678. run-time library has some extra possibilities, not available in Turbo
  1679. Pascal. These extra possibilities are explained in the next subsections.
  1680. % The heap grows
  1681. \subsection{The heap grows}
  1682. \fpc supports the \var{HeapEerror} procedural variable. If this variable is
  1683. non-nil, then it is called in case you try to allocate memory, and the heap
  1684. is full. By default, \var{HeapError} points to the \var{GrowHeap} function,
  1685. which tries to increase the heap.
  1686. The growheap function issues a system call to try to increase the size of the
  1687. memory available to your program. It first tries to increase memory in a 1 Mb.
  1688. chunk. If this fails, it tries to increase the heap by the amount you
  1689. requested from the heap.
  1690. If the call to \var{GrowHeap} has failed, then a run-time error is generated,
  1691. or nil is returned, depending on the \var{GrowHeap} result.
  1692. If the call to \var{GrowHeap} was successful, then the needed memory will be
  1693. allocated.
  1694. % Using Blocks
  1695. \subsection{Using Blocks}
  1696. If you need to allocate a lot of small block for a small period, then you
  1697. may want to recompile the run-time library with the \var{USEBLOCKS} symbol
  1698. defined. If it is recompiled, then the heap management is done in a
  1699. different way.
  1700. The run-time library keeps a linked list of allocated blocks with size
  1701. up to 256 bytes\footnote{The size can be set using the \var{max\_size}
  1702. constant in the \file{heap.inc} source file.}. By default, it keeps 32 of
  1703. these lists\footnote{The actual size is \var{max\_size div 8}.}.
  1704. When a piece of memory in a block is deallocated, the heap manager doesn't
  1705. really deallocate the occupied memory. The block is simply put in the linked
  1706. list corresponding to its size.
  1707. When you then again request a block of memory, the manager checks in the
  1708. list if there is a non-allocated block which fits the size you need (rounded
  1709. to 8 bytes). If so, the block is used to allocate the memory you requested.
  1710. This method of allocating works faster if the heap is very fragmented, and
  1711. you allocate a lot of small memory chunks.
  1712. Since it is invisible to the program, this provides an easy way of improving
  1713. the performance of the heap manager.
  1714. % The splitheap
  1715. \subsection{Using the split heap}
  1716. {\em Remark : The split heap is still somewhat buggy. Use at your own risk
  1717. for the moment.}
  1718. The split heap can be used to quickly release a lot of blocks you alloated
  1719. previously.
  1720. Suppose that in a part of your program, you allocate a lot of memory chunks
  1721. on the heap. Suppose that you know that you'll release all this memory when
  1722. this particular part of you program is finished.
  1723. In Turbo Pascal, you could foresee this, and mark the position of the heap
  1724. (using the \var{Mark} function) when entering this particular part of your
  1725. program, and release the occupied memory in one call with the \var{Release}
  1726. call.
  1727. For most purposes, this works very good. But sometimes, you may need to
  1728. allocate something on the heap that you {\em don't} want deallocated when you
  1729. release the allocated memory. That is where the split heap comes in.
  1730. When you split the heap, the heap manager keeps 2 heaps: the base heap (the
  1731. normal heap), and the temporary heap. After the call to split the heap,
  1732. memory is allocated from the temporary heap. When you're finished using all
  1733. this memory, you unsplit the heap. This clears all the memory on the split
  1734. heap with one call. After that, memory will be allocated from the base heap
  1735. again.
  1736. So far, nothing special, nothing that can't be done with calls to \var{mark}
  1737. and \var{release}. Suppose now that you have split the heap, and that you've
  1738. come to a point where you need to allocate memory that is to stay allocated
  1739. after you unsplit the heap again. At this point, mark and release are of no
  1740. use. But when using the split heap, you can tell the heap manager to
  1741. --temporarily-- use the base heap again to allocate memory.
  1742. When you've allocated the needed memory, you can tell the heap manager that
  1743. it should start using the temporary heap again.
  1744. When you're finished using the temporary heap, you release it, and the
  1745. memory you allocated on the base heap will still be allocated.
  1746. To use the split-heap, you must recompile the run-time library with the \var{TempHeap}
  1747. symbol defined.
  1748. This means that the following functions are available :
  1749. \begin{verbatim}
  1750. procedure Split_Heap;
  1751. procedure Switch_To_Base_Heap;
  1752. procedure Switch_To_Temp_Heap;
  1753. procedure Switch_Heap;
  1754. procedure ReleaseTempHeap;
  1755. procedure GetempMem(var p : pointer;size : longint);
  1756. \end{verbatim}
  1757. \var{split\_heap} is used to split the heap. It cannot be called two times
  1758. in a row, without a call to \var{releasetempheap}. \var{Releasetempheap}
  1759. completely releases the memory used by the temporary heap.
  1760. Switching temporarily back to the base heap can be done using the
  1761. \var{switch\_to\_base\_heap} call, and returning to the temporary heap is done
  1762. using the \var{switch\_to\_temp\_heap} call. Switching from one to the other
  1763. without knowing on which one your are right now, can be done using the
  1764. \var{switch\_heap} call, which will split the heap first if needed.
  1765. A call to \var{GetTempMem} will allocate a memory block on the temporary
  1766. heap, whatever the current heap is. The current heap after this call will be
  1767. the temporary heap.
  1768. Typically, what will appear in your code is the following sequence :
  1769. \begin{verbatim}
  1770. Split_Heap
  1771. ...
  1772. { Memory allocation }
  1773. ...
  1774. { !! non-volatile memory needed !!}
  1775. Switch_To_Base_Heap;
  1776. getmem (P,size);
  1777. Switch_To_Temp_Heap;
  1778. ...
  1779. {Memory allocation}
  1780. ...
  1781. ReleaseTempHeap;
  1782. {All allocated memory is now freed, except for the memory pointed to by 'P' }
  1783. ...
  1784. \end{verbatim}
  1785. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1786. % Accessing DOS memory under the GO32 extender
  1787. \section{Accessing \dos memory under the Go32 extender}
  1788. \label{se:AccessingDosMemory}
  1789. Because \fpc is a 32 bit compiler, and uses a \dos extender, accessing DOS
  1790. memory isn't trivial. What follows is an attempt to an explanation of how to
  1791. access and use \dos or real mode memory\footnote{Thanks to an explanation of
  1792. Thomas schatzl (E-mail:\var{tom\_at\[email protected]}).}.
  1793. In {\em Proteced Mode}, memory is accessed through {\em Selectors} and
  1794. {\em Offsets}. You can think of Selectors as the protected mode
  1795. equivalents of segments.
  1796. In \fpc, a pointer is an offset into the \var{DS} selector, which points to
  1797. the Data of your program.
  1798. To access the (real mode) \dos memory, somehow you need a selector that
  1799. points to the \dos memory.
  1800. The \file{GO32} unit provides you with such a selector: The
  1801. \var{DosMemSelector} variable, as it is conveniently called.
  1802. You can also allocate memory in \dos's memory space, using the
  1803. \var{global\_dos\_alloc} function of the \file{GO32} unit.
  1804. This function will allocate memory in a place where \dos sees it.
  1805. As an example, here is a function that returns memory in real mode \dos and
  1806. returns a selector:offset pair for it.
  1807. \begin{verbatim}
  1808. procedure dosalloc(var selector : word;
  1809. var segment : word;
  1810. size : longint);
  1811. var result : longint;
  1812. begin
  1813. result := global_dos_alloc(size);
  1814. selector := word(result);
  1815. segment := word(result shr 16);
  1816. end;
  1817. \end{verbatim}
  1818. (you need to free this memory using the \var{global\_dos\_free} function.)
  1819. You can access any place in memory using a selector. You can get a selector
  1820. using the \var{allocate\_ldt\_descriptor} function, and then let this selector
  1821. point to the physical memory you want using the
  1822. \var{set\_segment\_base\_address} function, and set its length using
  1823. \var{set\_segment\_limit} function.
  1824. You can manipulate the memory pointed to by the selector using the functions
  1825. of the GO32 unit. For instance with the \var{seg\_fillchar} function.
  1826. After using the selector, you must free it again using the
  1827. \var{free\_ldt\_selector} function.
  1828. More information on all this can be found in the \unitsref, the chapter on
  1829. the \file{GO32} unit.
  1830. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1831. % Appendices
  1832. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1833. \appendix
  1834. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1835. % Appendix A
  1836. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1837. \chapter{Anatomy of a unit file}
  1838. \label{ch:AppA}
  1839. A unit file consists of basically five parts:
  1840. \begin{enumerate}
  1841. \item A unit header.
  1842. \item A file references part. This contains the references to used units
  1843. and sources with name, checksum and time stamps.
  1844. \item A definition part. Contains all type and procedure definitions.
  1845. \item A Symbol part. Contains all symbol names and references to their
  1846. definitions.
  1847. \item A list of units that are in the implementation part.
  1848. \end{enumerate}
  1849. The header consists of a sequence of 20 bytes, together they give some
  1850. information about the unit file, the compiler version that was used to
  1851. generate the unit file, etc. The complete layout can be found in
  1852. \seet{UnitHeader}. The header is generated by the compiler, and changes only
  1853. when the compiler changes. The current and up-to-date header definition can
  1854. be found in the \file{files.pas} source file of the compiler. Look in this
  1855. file for the \var{unitheader} constant declaration.
  1856. \begin{FPCltable}{ll}{Unit header structure.}{UnitHeader} \hline
  1857. Byte & What is stored \\ \hline
  1858. 0..3 & The letters 'PPU' in upper case. This acts as a check. \\
  1859. 4..6 & The unit format as a 3 letter sequence : e.g. '0','1,'2' for format
  1860. 12. \\
  1861. 7,8 & The compiler version and release numbers as bytes. \\
  1862. 9 & The target OS number. \\
  1863. 10 & Unit flags.\\
  1864. 11..14 & Checksum (as a longint). \\
  1865. 15,16 & unused (equal to 255). \\
  1866. 17..20 & Marks start of unit file. \\ \hline
  1867. \end{FPCltable}
  1868. After the header, in the second part, first the list of all source files for
  1869. the unit is written. Each name is written as a direct copy of the string in
  1870. memory, i.e. a length bytes, and then all characters of the string. This
  1871. list includes any file that was included in the unit source with the
  1872. \var{\{\$i file\}} directive. The list is terminated with a \var{\$ff} byte
  1873. marker.
  1874. After this, the list of units in the \var{uses} clause is written,
  1875. together with their checksums. The file is written as a string, the checksum
  1876. as a longint (i.e. four bytes). Again this list is terminated with a
  1877. \var{\$ff} byte marker.
  1878. After that, in the third part, the definitions of all types, variables,
  1879. constants, procedures and functions are written to the unit file.
  1880. They are written in the following manner: First a byte is written, which
  1881. determines the kind of definition that follows. then follows, as a series of
  1882. bytes, a type-dependent description of the definition. The exact byte order
  1883. for each type can be found in \seet{DefDef}
  1884. \begin{FPCltable}{lccl}{Description of definition fields}{DefDef} \\hline
  1885. Type & Start byte & Size & Stored fields \\ \hline\hline
  1886. Pointer & 3 & 4 & Reference to the type pointer points to. \\ \hline
  1887. Base type & 2 & 9 &
  1888. \begin{tabular}[t]{l}
  1889. 1 byte to indicate base type. \\
  1890. 4-byte start range \\
  1891. 4-byte end range \\
  1892. \end{tabular}\\ \hline
  1893. Array type &5 & 16 &
  1894. \begin{tabular}[t]{l}
  1895. 4-byte reference to element type. \\
  1896. 4-byte reference to range type.\\
  1897. 4-byte start range (longint) \\
  1898. 4-byte end range (longint)\\
  1899. \end{tabular} \\ \hline
  1900. Procedure & 6 & ? &
  1901. \begin{tabular}[t]{l}
  1902. 4-byte reference to the return type definition. \\
  1903. 2 byte Word containing modifiers. \\
  1904. 2 byte Word containing number of parameters. \\
  1905. 5 bytes per parameter.\\
  1906. 1 byte : used registers. \\
  1907. String containing the mangled name. \\
  1908. 8 bytes.
  1909. \end{tabular}
  1910. \\ \hline
  1911. Procedural type & 21 & ? &
  1912. \begin{tabular}[t]{l}
  1913. 4-byte reference to the return type definition. \\
  1914. 2 byte Word containing modifiers. \\
  1915. 2 byte Word containing number of parameters. \\
  1916. 5 bytes per parameter. \\
  1917. \end{tabular}
  1918. \\ \hline
  1919. String & 9 & 1 & 1 byte containing the length of the string. \\
  1920. Record & 15 & variable &
  1921. \begin{tabular}[t]{l}
  1922. Longint indicating record length \\
  1923. list of fields, to be read as unit in itself. \\
  1924. \var{\$ff} end marker.
  1925. \end{tabular} \\ \hline
  1926. Class & 18 & variable &
  1927. \begin{tabular}[t]{l}
  1928. Longint indicating data length \\
  1929. String with mangled name of class.\\
  1930. 4 byte reference to ancestor class.\\
  1931. list of fields, to be read as unit in itself. \\
  1932. \var{\$ff} end marker.
  1933. \end{tabular} \\ \hline
  1934. file & 16 & 1(+4) &
  1935. \begin{tabular}[t]{l}
  1936. 1 byte for type of file. \\
  1937. 4-byte reference to type of typed file.
  1938. \end{tabular}\\ \hline
  1939. Enumeration & 19 & 4 & Biggest element. \\ \hline
  1940. set & 20 & 5 &
  1941. \begin{tabular}[t]{l}
  1942. 4-byte reference to set element type. \\
  1943. 1 byte flag.
  1944. \end{tabular} \\ \hline \hline
  1945. \end{FPCltable}
  1946. This list of definitions is again terminated with a \var{\$ff} byte marker.
  1947. After that, a list of symbols is given, together with a reference to a
  1948. definition. This represents the names of the declarations, and the
  1949. definition they refer to.
  1950. A reference consists of 2 words : the first word indicates the unit number
  1951. (as it appears in the uses clause), and the second word is the number of the
  1952. definition in that unit. A \var{nil} reference is stored as \var{\$ffffffff}.
  1953. After this follows again a \var{\$ff} byte terminated list of filenames: The
  1954. names of the units in the \var{uses} clause of the implementation section.
  1955. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1956. % Appendix B
  1957. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1958. %\chapter{Compiler and RTL source tree structure}
  1959. %\label{ch:AppB}
  1960. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1961. % Appendix C
  1962. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1963. \chapter{Compiler limits}
  1964. \label{ch:AppC}
  1965. Although many of the restrictions imposed by the MS-DOS system are removed
  1966. by use of an extender, or use of another operating system, there still are
  1967. some limitations to the compiler:
  1968. \begin{enumerate}
  1969. \item String constants are limited to 128 characters. All other characters
  1970. are simply dropped from the definition.
  1971. \item The length of generated unit files is limited to 65K for the
  1972. real-mode compiler, and to 1Mb for the 32-bit compiler. This limit can be
  1973. changed by changing the \var{bytearray1} type in \file{cobjects.pas}
  1974. \item Procedure or Function definitions can be nested to a level of 32.
  1975. \item Maximally 255 units can be used in a program when using the real-mode
  1976. compiler. When using the 32-bit compiler, the limit is set to 1024. You can
  1977. change this by redefining the \var{maxunits} constant in the
  1978. \file{files.pas} compiler source file.
  1979. \item Procedures or functions accept parameters with a total size up to
  1980. \var{\$ffff} bytes. This limit is due to the \var{RET} instruction of the I386
  1981. processor. If the calls were made using the C convention this limit would
  1982. disappear.
  1983. \end{enumerate}
  1984. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1985. % Appendix D
  1986. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1987. \chapter{Optimizing techniques used in the compiler.}
  1988. Here follows a listing of the opimizing techniques used in the compiler:
  1989. \begin{enumerate}
  1990. \item When optimizing for a specific Processor (\var{-O3, -O4, -O5 -O6},
  1991. the following is done:
  1992. \begin{itemize}
  1993. \item In \var{case} statements, a check is done whether a jump table
  1994. or a sequence of conditional jumps should be used for optimal performance.
  1995. \item Determines a number of strategies when doing peephole optimization:
  1996. \var{movzbl (\%ebp), \%eax} on PentiumPro and PII systems will be changed
  1997. into \var{xorl \%eax,\%eax; movb (\%ebp),\%al } for lesser systems.
  1998. \end{itemize}
  1999. Cyrix \var{6x86} processor owners should optimize with \var{-O4} instead of
  2000. \var{-O5}, because \var{-O5} leads to larger code, and thus to smaller
  2001. speed, according to the Cyrix developers FAQ.
  2002. \item When optimizing for speed (\var{-OG}) or size (\var{-Og}), a choice is
  2003. made between using shorter instructions (for size) such as \var{enter \$4},
  2004. or longer instructions \var{subl \$4,\%esp} for speed. When smaller size is
  2005. requested, things aren't aligned on 4-byte boundaries. When speed is
  2006. requested, things are aligned on 4-byte boundaries as much as possible.
  2007. \item Simple optimization (\var{-Oa}) makes sure the peephole optimizer is
  2008. used, as well as the reloading optimizer.
  2009. \item Maximum optimization (\var{-Ox}) avoids creation of stack frames if
  2010. they aren't required, and unnecessary loading of registers is avoided as
  2011. much as possible. (buggy at the moment (version 0.99.0).
  2012. \item Uncertain optimizations (\var{-Oz}): With this switch, the reloading
  2013. optimizer (enabled with \var{-Oa}) can be forced into making uncertain
  2014. optimizations.
  2015. You can enable uncertain optimizations only in certain cases,
  2016. otherwise you will produce a bug; the following technical description
  2017. tells you when to use them:
  2018. \begin{quote}
  2019. % Jonas's own words..
  2020. \em
  2021. If uncertain optimizations are enabled, the reloading optimizer assumes
  2022. that
  2023. \begin{itemize}
  2024. \item If something is written to a local/global register or a
  2025. procedure/function parameter, this value doesn't overwrite the value to
  2026. which a pointer points.
  2027. \item If something is written to memory pointed to by a pointer variable,
  2028. this value doesn't overwrite the value of a local/global variable or a
  2029. procedure/function parameter.
  2030. \end{itemize}
  2031. % end of quote
  2032. \end{quote}
  2033. The practical upshot of this is that you cannot use the uncertain
  2034. optimizations if you access any local or global variables through pointers. In
  2035. theory, this includes \var{Var} parameters, but it is all right
  2036. if you don't both read the variable once through its \var{Var} reference
  2037. and then read it using it's name.
  2038. The following example will produce bad code when you switch on
  2039. uncertain optimizations:
  2040. \begin{verbatim}
  2041. Var temp: Longint;
  2042. Procedure Foo(Var Bar: Longint);
  2043. Begin
  2044. If (Bar = temp)
  2045. Then
  2046. Begin
  2047. Inc(Bar);
  2048. If (Bar <> temp) then Writeln('bug!')
  2049. End
  2050. End;
  2051. Begin
  2052. Foo(Temp);
  2053. End.
  2054. \end{verbatim}
  2055. The reason it produces bad code is because you access the global variable
  2056. \var{Temp} both through its name \var{Temp} and through a pointer, in this
  2057. case using the \var{Bar} variable parameter, which is nothing but a pointer
  2058. to \var{Temp} in the above code.
  2059. On the other hand, you can use the uncertain optimizations if
  2060. you access global/local variables or parameters through pointers,
  2061. and {\em only} access them through this pointer\footnote{
  2062. You can use multiple pointers to point to the same variable as well, that
  2063. doesn't matter.}.
  2064. For example:
  2065. \begin{verbatim}
  2066. Type TMyRec = Record
  2067. a, b: Longint;
  2068. End;
  2069. PMyRec = ^TMyRec;
  2070. TMyRecArray = Array [1..100000] of TMyRec;
  2071. PMyRecArray = ^TMyRecArray;
  2072. Var MyRecArrayPtr: PMyRecArray;
  2073. MyRecPtr: PMyRec;
  2074. Counter: Longint;
  2075. Begin
  2076. New(MyRecArrayPtr);
  2077. For Counter := 1 to 100000 Do
  2078. Begin
  2079. MyRecPtr := @MyRecArrayPtr^[Counter];
  2080. MyRecPtr^.a := Counter;
  2081. MyRecPtr^.b := Counter div 2;
  2082. End;
  2083. End.
  2084. \end{verbatim}
  2085. Will produce correct code, because the global variable \var{MyRecArrayPtr}
  2086. is not accessed directly, but through a pointer (\var{MyRecPtr} in this
  2087. case).
  2088. In conclusion, one could say that you can use uncertain optimizations {\em
  2089. only} when you know what you're doing.
  2090. \end{enumerate}
  2091. \end{document}