| 1 |
.. role:: switch(samp) |
| 2 |
|
| 3 |
.. |with| replace:: *with* |
| 4 |
.. |withs| replace:: *with*\ s |
| 5 |
.. |withed| replace:: *with*\ ed |
| 6 |
.. |withing| replace:: *with*\ ing |
| 7 |
|
| 8 |
.. -- Example: A |withing| unit has a |with| clause, it |withs| a |withed| unit |
| 9 |
|
| 10 |
|
| 11 |
.. _GNAT_and_Program_Execution: |
| 12 |
|
| 13 |
************************** |
| 14 |
GNAT and Program Execution |
| 15 |
************************** |
| 16 |
|
| 17 |
This chapter covers several topics: |
| 18 |
|
| 19 |
* `Running and Debugging Ada Programs`_ |
| 20 |
* `Profiling`_ |
| 21 |
* `Improving Performance`_ |
| 22 |
* `Overflow Check Handling in GNAT`_ |
| 23 |
* `Performing Dimensionality Analysis in GNAT`_ |
| 24 |
* `Stack Related Facilities`_ |
| 25 |
* `Memory Management Issues`_ |
| 26 |
|
| 27 |
.. _Running_and_Debugging_Ada_Programs: |
| 28 |
|
| 29 |
Running and Debugging Ada Programs |
| 30 |
================================== |
| 31 |
|
| 32 |
.. index:: Debugging |
| 33 |
|
| 34 |
This section discusses how to debug Ada programs. |
| 35 |
|
| 36 |
The GNAT compiler handles an incorrect Ada program in three ways: |
| 37 |
|
| 38 |
* The illegality may be a violation of the static semantics of Ada. In |
| 39 |
that case, GNAT diagnoses the constructs in the program that are illegal. |
| 40 |
It's then a straightforward matter for you to modify those parts of |
| 41 |
the program. |
| 42 |
|
| 43 |
* The illegality may be a violation of the dynamic semantics of Ada. In |
| 44 |
that case the program compiles and executes, but may generate incorrect |
| 45 |
results or may terminate abnormally with some exception. |
| 46 |
|
| 47 |
* When presented with a program that contains convoluted errors, GNAT |
| 48 |
itself may terminate abnormally without providing full diagnostics on |
| 49 |
the incorrect user program. |
| 50 |
|
| 51 |
.. index:: Debugger |
| 52 |
|
| 53 |
.. index:: ! gdb |
| 54 |
|
| 55 |
.. _The_GNAT_Debugger_GDB: |
| 56 |
|
| 57 |
The GNAT Debugger GDB |
| 58 |
--------------------- |
| 59 |
|
| 60 |
``GDB`` is a general purpose, platform-independent debugger that |
| 61 |
you can use to debug mixed-language programs, including compiled with ``gcc``, |
| 62 |
and in particular is capable of debugging Ada programs compiled with |
| 63 |
GNAT. The latest versions of ``GDB`` are Ada-aware and can handle |
| 64 |
complex Ada data structures. |
| 65 |
|
| 66 |
See :title:`Debugging with GDB`, |
| 67 |
for full details on the usage of ``GDB``, including a section on |
| 68 |
its usage on programs. That manual should be consulted for full |
| 69 |
details. The section that follows is a brief introduction to the |
| 70 |
philosophy and use of ``GDB``. |
| 71 |
|
| 72 |
When programs are compiled, the compiler optionally writes debugging |
| 73 |
information into the generated object file, including information on |
| 74 |
line numbers and on declared types and variables. This information is |
| 75 |
separate from the generated code. It makes the object files considerably |
| 76 |
larger, but it does not add to the size of the actual executable that |
| 77 |
is loaded into memory and has no impact on run-time performance. The |
| 78 |
generation of debug information is triggered by the use of the |
| 79 |
:switch:`-g` switch in the ``gcc`` or ``gnatmake`` command |
| 80 |
you used to perform the compilations. It is important to emphasize that |
| 81 |
it's a goal of GCC, and hence GNAT, that the use of this switch does |
| 82 |
not change the generated code. |
| 83 |
|
| 84 |
The compiler writes the debugging information in standard system formats that |
| 85 |
are used by many tools, including debuggers and profilers. The format |
| 86 |
of the information is typically designed to describe C types and |
| 87 |
semantics, but GNAT implements a translation scheme which allows full |
| 88 |
details about Ada types and variables to be encoded into these |
| 89 |
standard C formats. Details of this encoding scheme may be found in |
| 90 |
the file :file:`exp_dbug.ads` in the GNAT source distribution. However, the |
| 91 |
details of this encoding are, in most cases, of no interest to a user, |
| 92 |
since ``GDB`` automatically performs the necessary decoding. |
| 93 |
|
| 94 |
When a program is bound and linked, the debugging information is |
| 95 |
collected from the object files and stored in the executable image of |
| 96 |
the program. Again, this process significantly increases the size of |
| 97 |
the generated executable file, but does not increase the size of |
| 98 |
the executable program in memory. Furthermore, if this program is run in |
| 99 |
the normal manner, it runs exactly as if the debug information were |
| 100 |
not present and takes no more actual memory. |
| 101 |
|
| 102 |
However, if the program is run under control of ``GDB``, the |
| 103 |
debugger is activated. The image of the program is loaded, at which |
| 104 |
point it is ready to run. If you give a run command, the program |
| 105 |
runs exactly as it would have if ``GDB`` were not present. This |
| 106 |
is a crucial part of the ``GDB`` design philosophy: ``GDB`` is |
| 107 |
entirely non-intrusive until a breakpoint is encountered. If no |
| 108 |
breakpoint is ever hit, the program runs exactly as it would if no |
| 109 |
debugger were present. When a breakpoint is hit, ``GDB`` accesses |
| 110 |
the debugging information and can respond to user commands to inspect |
| 111 |
variables and more generally to report on the state of execution. |
| 112 |
|
| 113 |
.. _Running_GDB: |
| 114 |
|
| 115 |
Running GDB |
| 116 |
----------- |
| 117 |
|
| 118 |
This section describes how to initiate the debugger. |
| 119 |
|
| 120 |
You can launch the debugger from a ``GNAT Studio`` menu or |
| 121 |
directly from the command line. The description below covers the latter use. |
| 122 |
You can use all the commands shown in the ``GNAT Studio`` debug console window, |
| 123 |
but there are usually more GUI-based ways to achieve the same effect. |
| 124 |
|
| 125 |
The command to run ``GDB`` is |
| 126 |
|
| 127 |
:: |
| 128 |
|
| 129 |
$ gdb program |
| 130 |
|
| 131 |
where ``program`` is the name of the executable file. This |
| 132 |
activates the debugger and results in a prompt for debugger commands. |
| 133 |
The simplest command is simply ``run``, which causes the program to run |
| 134 |
exactly as if the debugger were not present. The following section |
| 135 |
describes some of the additional commands that you can give to ``GDB``. |
| 136 |
|
| 137 |
|
| 138 |
.. _Introduction_to_GDB_Commands: |
| 139 |
|
| 140 |
Introduction to GDB Commands |
| 141 |
---------------------------- |
| 142 |
|
| 143 |
``GDB`` contains a large repertoire of commands. |
| 144 |
See :title:`Debugging with GDB` for extensive documentation on the use |
| 145 |
of these commands, together with examples of their use. Furthermore, |
| 146 |
the command *help* invoked from within GDB activates a simple help |
| 147 |
facility which summarizes the available commands and their options. |
| 148 |
In this section, we summarize a few of the most commonly |
| 149 |
used commands to give an idea of what ``GDB`` is about. You should create |
| 150 |
a simple program with debugging information and experiment with the use of |
| 151 |
these ``GDB`` commands on that program as you read through the |
| 152 |
following section. |
| 153 |
|
| 154 |
* :samp:`set args {arguments}` |
| 155 |
*arguments* is a list of arguments to be passed to the program on |
| 156 |
a subsequent run command, just as though the arguments had been |
| 157 |
entered on a normal invocation of the program. You do not need the |
| 158 |
``set args`` command if the program does not require arguments. |
| 159 |
|
| 160 |
|
| 161 |
* :samp:`run` |
| 162 |
The ``run`` command causes execution of the program to start from |
| 163 |
the beginning. If the program is already running, that is to say if |
| 164 |
you are currently positioned at a breakpoint, then a prompt will ask |
| 165 |
for confirmation that you want to abandon the current execution and |
| 166 |
restart. You can also specify program arguments on this command and |
| 167 |
if you specify ``run`` with no arguments, the arguments used on |
| 168 |
the previous command will be used again. |
| 169 |
|
| 170 |
|
| 171 |
* :samp:`breakpoint {location}` |
| 172 |
This command sets a breakpoint, that is to say a point at which |
| 173 |
execution will halt and ``GDB`` will await further |
| 174 |
commands. *location* is either a line number within a file, which |
| 175 |
you specify in the format ``file:linenumber``, or the name of a |
| 176 |
subprogram. If you request a breakpoint be set on a subprogram |
| 177 |
that is overloaded, either a prompt will ask you to specify on |
| 178 |
which of those subprograms you want to breakpoint or a breakpoint |
| 179 |
will be set on all of them. If the program is run and execution |
| 180 |
encounters the breakpoint, the program stops and ``GDB`` |
| 181 |
signals that the breakpoint was encountered by printing the line |
| 182 |
of code before which the program is halted. |
| 183 |
|
| 184 |
|
| 185 |
* :samp:`catch exception {name}` |
| 186 |
This command causes the program execution to stop whenever exception |
| 187 |
``name`` is raised. If you omit ``name``, execution is |
| 188 |
suspended when any exception is raised. |
| 189 |
|
| 190 |
|
| 191 |
* :samp:`print {expression}` |
| 192 |
This prints the value of the given expression. Most |
| 193 |
Ada expression formats are properly handled by ``GDB``, so the expression |
| 194 |
can contain function calls, variables, operators, and attribute references. |
| 195 |
|
| 196 |
|
| 197 |
* :samp:`continue` |
| 198 |
Continues execution following a breakpoint until the next breakpoint or the |
| 199 |
termination of the program. |
| 200 |
|
| 201 |
|
| 202 |
* :samp:`step` |
| 203 |
Executes a single line after a breakpoint. If the next statement |
| 204 |
is a subprogram call, execution continues into (the first statement of) |
| 205 |
the called subprogram. |
| 206 |
|
| 207 |
|
| 208 |
* :samp:`next` |
| 209 |
Executes a single line. If this line is a subprogram call, the |
| 210 |
program executes that call and returns. |
| 211 |
|
| 212 |
|
| 213 |
* :samp:`list` |
| 214 |
|
| 215 |
Lists a few lines around the current source location. In practice, |
| 216 |
it is usually more convenient to have a separate edit window open |
| 217 |
with the relevant source file displayed. ``emacs`` has debugging |
| 218 |
modes that display both the relevant source and ``GDB`` commands |
| 219 |
and output. Successive applications of this command print |
| 220 |
subsequent lines. You can give this command an argument which is a |
| 221 |
line number, in which case it displays a few lines around the |
| 222 |
specified line. |
| 223 |
|
| 224 |
|
| 225 |
* :samp:`backtrace` |
| 226 |
Displays a backtrace of the call chain. This command is typically |
| 227 |
used after a breakpoint has occurred to examine the sequence of calls that |
| 228 |
leads to the current breakpoint. The display includes one line for each |
| 229 |
activation record (frame) corresponding to an active subprogram. |
| 230 |
|
| 231 |
|
| 232 |
* :samp:`up` |
| 233 |
At a breakpoint, ``GDB`` can display the values of variables local |
| 234 |
to the current frame. You can use the command ``up`` to |
| 235 |
examine the contents of other active frames by moving the focus up |
| 236 |
the stack, that is to say from callee to caller, one frame at a time. |
| 237 |
|
| 238 |
|
| 239 |
* :samp:`down` |
| 240 |
Moves the focus of ``GDB`` down from the frame currently being |
| 241 |
examined to the frame of its callee (the reverse of the previous command), |
| 242 |
|
| 243 |
|
| 244 |
* :samp:`frame {n}` |
| 245 |
Inspect the frame with the given number. The value 0 denotes the frame |
| 246 |
of the current breakpoint, that is to say the top of the call stack. |
| 247 |
|
| 248 |
|
| 249 |
* :samp:`kill` |
| 250 |
Kills the child process in which the program is running under GDB. |
| 251 |
You may find this useful for several purposes: |
| 252 |
|
| 253 |
* It allows you to recompile and relink your program, since on many systems |
| 254 |
you cannot regenerate an executable file while it is running in a process. |
| 255 |
|
| 256 |
* You can run your program outside the debugger on systems that do not |
| 257 |
permit executing a program outside GDB while breakpoints are set |
| 258 |
within GDB. |
| 259 |
|
| 260 |
* It allows you to debug a core dump rather than a running process. |
| 261 |
|
| 262 |
The above is a very short introduction to the commands that |
| 263 |
``GDB`` provides. Important additional capabilities, including conditional |
| 264 |
breakpoints, the ability to execute command sequences on a breakpoint, |
| 265 |
the ability to debug at the machine instruction level and many other |
| 266 |
features are described in detail in :title:`Debugging with GDB`. |
| 267 |
Note that most commands can be abbreviated |
| 268 |
(for example, "c" for ``continue`` and "bt" for ``backtrace``) and only enough |
| 269 |
characters need be typed to disambiguate the command (e.g., "br" for |
| 270 |
``breakpoint``). |
| 271 |
|
| 272 |
|
| 273 |
.. _Using_Ada_Expressions: |
| 274 |
|
| 275 |
Using Ada Expressions |
| 276 |
--------------------- |
| 277 |
|
| 278 |
.. index:: Ada expressions (in gdb) |
| 279 |
|
| 280 |
``GDB`` supports a very large subset of Ada expression syntax, with some |
| 281 |
extensions. The philosophy behind the design of this subset is |
| 282 |
|
| 283 |
* ``GDB`` should provide basic literals and access to operations for |
| 284 |
arithmetic, dereferencing, field selection, indexing, and subprogram calls, |
| 285 |
leaving more sophisticated computations to subprograms written into the |
| 286 |
program (which therefore may be called from ``GDB``). |
| 287 |
|
| 288 |
* Type safety and strict adherence to Ada language restrictions |
| 289 |
are not particularly relevant in a debugging context. |
| 290 |
|
| 291 |
* Brevity is important to the ``GDB`` user. |
| 292 |
|
| 293 |
Thus, for brevity, the debugger acts as if there were |
| 294 |
implicit ``with`` and ``use`` clauses in effect for all user-written |
| 295 |
packages, thus making it unnecessary to fully qualify most names with |
| 296 |
their packages, regardless of context. Where this causes ambiguity, |
| 297 |
``GDB`` asks the user's intent. |
| 298 |
|
| 299 |
For details on the supported Ada syntax, see :title:`Debugging with GDB`. |
| 300 |
|
| 301 |
|
| 302 |
.. _Calling_User-Defined_Subprograms: |
| 303 |
|
| 304 |
Calling User-Defined Subprograms |
| 305 |
-------------------------------- |
| 306 |
|
| 307 |
An important capability of ``GDB`` is the ability to call user-defined |
| 308 |
subprograms while debugging. You do this by simply entering |
| 309 |
a subprogram call statement in the form: |
| 310 |
|
| 311 |
:: |
| 312 |
|
| 313 |
call subprogram-name (parameters) |
| 314 |
|
| 315 |
You can omit the keyword ``call`` in the normal case where the |
| 316 |
``subprogram-name`` does not coincide with any of the predefined |
| 317 |
``GDB`` commands. |
| 318 |
|
| 319 |
The effect is to invoke the given subprogram, passing it the |
| 320 |
list of parameters that is supplied. The parameters you specify can be expressions and |
| 321 |
can include variables from the program being debugged. The |
| 322 |
subprogram must be defined |
| 323 |
at the library level within your program and ``GDB`` will call the |
| 324 |
subprogram within the environment of your program execution (which |
| 325 |
means that the subprogram is free to access or even modify variables |
| 326 |
within your program). |
| 327 |
|
| 328 |
The most important use of this facility that you can include |
| 329 |
debugging routines that are tailored to particular data structures |
| 330 |
in your program. You can write such debugging routines to provide a suitably |
| 331 |
high-level description of an abstract type, rather than a low-level dump |
| 332 |
of its physical layout. After all, the standard |
| 333 |
``GDB print`` command only knows the physical layout of your |
| 334 |
types, not their abstract meaning. Debugging routines can provide information |
| 335 |
at the desired semantic level and are thus enormously useful. |
| 336 |
|
| 337 |
For example, when debugging GNAT itself, it is crucial to have access to |
| 338 |
the contents of the tree nodes used to represent the program internally. |
| 339 |
But tree nodes are represented simply by an integer value (which in turn |
| 340 |
is an index into a table of nodes). |
| 341 |
Using the ``print`` command on a tree node would simply print this integer |
| 342 |
value, which is not very useful. But the ``PN`` routine (defined in file |
| 343 |
:file:`treepr.adb` in the GNAT sources) takes a tree node as input and displays |
| 344 |
a useful high level representation of the tree node, which includes the |
| 345 |
syntactic category of the node, its position in the source, |
| 346 |
the descendant nodes and parent node, as well as lots of |
| 347 |
semantic information. To study this example in more detail, you might want to |
| 348 |
look at the body of the ``PN`` procedure in the above file. |
| 349 |
|
| 350 |
Another useful application of this capability is to deal with situations where |
| 351 |
complex data which are not handled suitably by GDB. For example, if you specify |
| 352 |
Convention Fortran for a multi-dimensional array, GDB does not know that |
| 353 |
the ordering of array elements has been switched and will not properly |
| 354 |
address the array elements. In such a case, instead of trying to print the |
| 355 |
elements directly from GDB, you can write a callable procedure that prints |
| 356 |
the elements in the format you desire. |
| 357 |
|
| 358 |
|
| 359 |
.. _Using_the_Next_Command_in_a_Function: |
| 360 |
|
| 361 |
Using the *next* Command in a Function |
| 362 |
-------------------------------------- |
| 363 |
|
| 364 |
When you use the ``next`` command in a function, the current source |
| 365 |
location will advance to the next statement as usual. A special case |
| 366 |
arises in the case of a ``return`` statement. |
| 367 |
|
| 368 |
Part of the code for a return statement is the 'epilogue' of the function. |
| 369 |
This is the code that returns to the caller. There is only one copy of |
| 370 |
this epilogue code and it is typically associated with the last return |
| 371 |
statement in the function if there is more than one return. In some |
| 372 |
implementations, this epilogue is associated with the first statement |
| 373 |
of the function. |
| 374 |
|
| 375 |
The result is that if you use the ``next`` command from a return |
| 376 |
statement that is not the last return statement of the function you |
| 377 |
may see a strange apparent jump to the last return statement or to |
| 378 |
the start of the function. You should simply ignore this odd jump. |
| 379 |
The value returned is always that from the first return statement |
| 380 |
that was stepped through. |
| 381 |
|
| 382 |
|
| 383 |
.. _Stopping_When_Ada_Exceptions_Are_Raised: |
| 384 |
|
| 385 |
Stopping When Ada Exceptions Are Raised |
| 386 |
--------------------------------------- |
| 387 |
|
| 388 |
.. index:: Exceptions (in gdb) |
| 389 |
|
| 390 |
You can set catchpoints that stop the program execution when your program |
| 391 |
raises selected exceptions. |
| 392 |
|
| 393 |
|
| 394 |
* :samp:`catch exception` |
| 395 |
Set a catchpoint that stops execution whenever (any task in the) program |
| 396 |
raises any exception. |
| 397 |
|
| 398 |
|
| 399 |
* :samp:`catch exception {name}` |
| 400 |
Set a catchpoint that stops execution whenever (any task in the) program |
| 401 |
raises the exception *name*. |
| 402 |
|
| 403 |
|
| 404 |
* :samp:`catch exception unhandled` |
| 405 |
Set a catchpoint that stops executing whenever (any task in the) program |
| 406 |
raises an exception for which there is no handler. |
| 407 |
|
| 408 |
|
| 409 |
* :samp:`info exceptions`, :samp:`info exceptions {regexp}` |
| 410 |
The ``info exceptions`` command permits the user to examine all defined |
| 411 |
exceptions within Ada programs. With a regular expression, *regexp*, as |
| 412 |
argument, prints out only those exceptions whose name matches *regexp*. |
| 413 |
|
| 414 |
|
| 415 |
.. index:: Tasks (in gdb) |
| 416 |
|
| 417 |
.. _Ada_Tasks: |
| 418 |
|
| 419 |
Ada Tasks |
| 420 |
--------- |
| 421 |
|
| 422 |
``GDB`` allows the following task-related commands: |
| 423 |
|
| 424 |
|
| 425 |
* :samp:`info tasks` |
| 426 |
This command shows a list of current Ada tasks, as in the following example: |
| 427 |
|
| 428 |
:: |
| 429 |
|
| 430 |
(gdb) info tasks |
| 431 |
ID TID P-ID Thread Pri State Name |
| 432 |
1 8088000 0 807e000 15 Child Activation Wait main_task |
| 433 |
2 80a4000 1 80ae000 15 Accept/Select Wait b |
| 434 |
3 809a800 1 80a4800 15 Child Activation Wait a |
| 435 |
* 4 80ae800 3 80b8000 15 Running c |
| 436 |
|
| 437 |
|
| 438 |
In this listing, the asterisk before the first task indicates it's |
| 439 |
currently running task. The first column lists the task ID used |
| 440 |
to refer to tasks in the following commands. |
| 441 |
|
| 442 |
|
| 443 |
.. index:: Breakpoints and tasks |
| 444 |
|
| 445 |
* ``break`` *linespec* ``task`` *taskid*, ``break`` *linespec* ``task`` *taskid* ``if`` ... |
| 446 |
|
| 447 |
These commands are like the ``break ... thread ...``. |
| 448 |
*linespec* specifies source lines. |
| 449 |
|
| 450 |
Use the qualifier :samp:`task {taskid}` with a breakpoint command |
| 451 |
to specify that you only want ``GDB`` to stop the program when that |
| 452 |
particular Ada task reaches this breakpoint. *taskid* is one of the |
| 453 |
numeric task identifiers assigned by ``GDB``, shown in the first |
| 454 |
column of the ``info tasks`` display. |
| 455 |
|
| 456 |
If you don't specify :samp:`task {taskid}` when you set a |
| 457 |
breakpoint, the breakpoint applies to *all* tasks of your |
| 458 |
program. |
| 459 |
|
| 460 |
You can use the ``task`` qualifier on conditional breakpoints as |
| 461 |
well; in this case, place :samp:`task {taskid}` before the |
| 462 |
breakpoint condition (before the ``if``). |
| 463 |
|
| 464 |
.. index:: Task switching (in gdb) |
| 465 |
|
| 466 |
* :samp:`task {taskno}` |
| 467 |
|
| 468 |
This command allows switching to the task referred by *taskno*. In |
| 469 |
particular, it allows browsing the backtrace of the specified |
| 470 |
task. You should switch back to the original task before |
| 471 |
continuing execution; otherwise the scheduling of the program may be |
| 472 |
disturbed. |
| 473 |
|
| 474 |
For more detailed information on tasking support, |
| 475 |
see :title:`Debugging with GDB`. |
| 476 |
|
| 477 |
|
| 478 |
.. index:: Debugging Generic Units |
| 479 |
.. index:: Generics |
| 480 |
|
| 481 |
.. _Debugging_Generic_Units: |
| 482 |
|
| 483 |
Debugging Generic Units |
| 484 |
----------------------- |
| 485 |
|
| 486 |
GNAT always uses the code expansion mechanism for generic |
| 487 |
instantiation. This means that each time an instantiation occurs, the |
| 488 |
compiler makes a complete copy of the original code, with |
| 489 |
appropriate substitutions of formals by actuals. |
| 490 |
|
| 491 |
You can't refer to the original generic entities in ``GDB``, but you |
| 492 |
can debug a particular instance of a generic by using the appropriate |
| 493 |
expanded names. For example, if we have |
| 494 |
|
| 495 |
.. code-block:: ada |
| 496 |
|
| 497 |
procedure g is |
| 498 |
|
| 499 |
generic package k is |
| 500 |
procedure kp (v1 : in out integer); |
| 501 |
end k; |
| 502 |
|
| 503 |
package body k is |
| 504 |
procedure kp (v1 : in out integer) is |
| 505 |
begin |
| 506 |
v1 := v1 + 1; |
| 507 |
end kp; |
| 508 |
end k; |
| 509 |
|
| 510 |
package k1 is new k; |
| 511 |
package k2 is new k; |
| 512 |
|
| 513 |
var : integer := 1; |
| 514 |
|
| 515 |
begin |
| 516 |
k1.kp (var); |
| 517 |
k2.kp (var); |
| 518 |
k1.kp (var); |
| 519 |
k2.kp (var); |
| 520 |
end; |
| 521 |
|
| 522 |
Then to break on a call to procedure kp in the k2 instance, simply |
| 523 |
use the command: |
| 524 |
|
| 525 |
:: |
| 526 |
|
| 527 |
(gdb) break g.k2.kp |
| 528 |
|
| 529 |
When the breakpoint occurs, you can step through the code of the |
| 530 |
instance in the normal manner and examine the values of local |
| 531 |
variables, as you do for other units. |
| 532 |
|
| 533 |
|
| 534 |
.. index:: Remote Debugging with gdbserver |
| 535 |
|
| 536 |
.. _Remote_Debugging_with_gdbserver: |
| 537 |
|
| 538 |
Remote Debugging with gdbserver |
| 539 |
------------------------------- |
| 540 |
|
| 541 |
On platforms that support ``gdbserver``, you can use this tool |
| 542 |
to debug your application remotely. This can be useful in situations |
| 543 |
where the program needs to be run on a target host that is different |
| 544 |
from the host used for development, particularly when the target has |
| 545 |
a limited amount of resources (either CPU and/or memory). |
| 546 |
|
| 547 |
To do so, start your program using ``gdbserver`` on the target machine. |
| 548 |
``gdbserver`` automatically suspends the execution of your program |
| 549 |
at its entry point, waiting for a debugger to connect to it. You use the |
| 550 |
following commands to start an application and tell ``gdbserver`` to |
| 551 |
wait for a connection with the debugger on ``localhost`` port 4444. |
| 552 |
|
| 553 |
|
| 554 |
:: |
| 555 |
|
| 556 |
$ gdbserver localhost:4444 program |
| 557 |
Process program created; pid = 5685 |
| 558 |
Listening on port 4444 |
| 559 |
|
| 560 |
Once ``gdbserver`` has started listening, you can tell the debugger to |
| 561 |
establish a connection with this ``gdbserver``, and then start a |
| 562 |
debugging session as if the program was being debugged on the |
| 563 |
same host, directly under the control of ``GDB``. |
| 564 |
|
| 565 |
:: |
| 566 |
|
| 567 |
$ gdb program |
| 568 |
(gdb) target remote targethost:4444 |
| 569 |
Remote debugging using targethost:4444 |
| 570 |
0x00007f29936d0af0 in ?? () from /lib64/ld-linux-x86-64.so. |
| 571 |
(gdb) b foo.adb:3 |
| 572 |
Breakpoint 1 at 0x401f0c: file foo.adb, line 3. |
| 573 |
(gdb) continue |
| 574 |
Continuing. |
| 575 |
|
| 576 |
Breakpoint 1, foo () at foo.adb:4 |
| 577 |
4 end foo; |
| 578 |
|
| 579 |
You can also use ``gdbserver`` to attach to an already running |
| 580 |
program, in which case the execution of that program is suspended |
| 581 |
until you have established the connection between the debugger and ``gdbserver``. |
| 582 |
|
| 583 |
For more information on how to use ``gdbserver``, see the *Using the |
| 584 |
gdbserver Program* section in :title:`Debugging with GDB`. GNAT |
| 585 |
provides support for ``gdbserver`` on x86-linux, x86-windows and |
| 586 |
x86_64-linux. |
| 587 |
|
| 588 |
|
| 589 |
.. index:: Abnormal Termination or Failure to Terminate |
| 590 |
|
| 591 |
.. _GNAT_Abnormal_Termination_or_Failure_to_Terminate: |
| 592 |
|
| 593 |
GNAT Abnormal Termination or Failure to Terminate |
| 594 |
------------------------------------------------- |
| 595 |
|
| 596 |
When presented with programs that contain serious errors in syntax |
| 597 |
or semantics, |
| 598 |
GNAT may, on rare occasions, experience problems such |
| 599 |
as aborting with a |
| 600 |
segmentation fault or illegal memory access, raising an internal |
| 601 |
exception, terminating abnormally, or failing to terminate at all. |
| 602 |
In such cases, you can activate |
| 603 |
various features of GNAT that can help you pinpoint the construct in your |
| 604 |
program that is the likely source of the problem. |
| 605 |
|
| 606 |
The following strategies for you to use in such cases are presented in |
| 607 |
increasing order of difficulty, corresponding to your experience in |
| 608 |
using GNAT and your familiarity with compiler internals. |
| 609 |
|
| 610 |
* Run ``gcc`` with the :switch:`-gnatf`. This switch causes all errors |
| 611 |
on a given line to be reported. In its absence, GNAT only displays |
| 612 |
the first error on a line. |
| 613 |
|
| 614 |
The :switch:`-gnatdO` switch causes errors to be displayed as soon as they |
| 615 |
are encountered, rather than after compilation is terminated. If GNAT |
| 616 |
terminates prematurely or goes into an infinite loop, the last error |
| 617 |
message displayed may help to pinpoint the culprit. |
| 618 |
|
| 619 |
* Run ``gcc`` with the :switch:`-v` (verbose) switch. In this |
| 620 |
mode, ``gcc`` produces ongoing information about the progress of the |
| 621 |
compilation and provides the name of each procedure as code is |
| 622 |
generated. This switch allows you to find which Ada procedure was being |
| 623 |
compiled when it encountered a problem. |
| 624 |
|
| 625 |
.. index:: -gnatdc switch |
| 626 |
|
| 627 |
* Run ``gcc`` with the :switch:`-gnatdc` switch. This is a GNAT specific |
| 628 |
switch that does for the front-end what :switch:`-v` does |
| 629 |
for the back end. The system prints the name of each unit, |
| 630 |
either a compilation unit or nested unit, as it is being analyzed. |
| 631 |
|
| 632 |
* Finally, you can start |
| 633 |
``gdb`` directly on the ``gnat1`` executable. ``gnat1`` is the |
| 634 |
front-end of GNAT and can be run independently (normally it is just |
| 635 |
called from ``gcc``). You can use ``gdb`` on ``gnat1`` as you |
| 636 |
would on a C program (but :ref:`The_GNAT_Debugger_GDB` for caveats). The |
| 637 |
``where`` command is the first line of attack; the variable |
| 638 |
``lineno`` (seen by ``print lineno``), used by the second phase of |
| 639 |
``gnat1`` and by the ``gcc`` back end, indicates the source line at |
| 640 |
which the execution stopped, and ``input_file name`` indicates the name of |
| 641 |
the source file. |
| 642 |
|
| 643 |
|
| 644 |
.. _Naming_Conventions_for_GNAT_Source_Files: |
| 645 |
|
| 646 |
Naming Conventions for GNAT Source Files |
| 647 |
---------------------------------------- |
| 648 |
|
| 649 |
In order to bettter understand the workings of the GNAT system, the following |
| 650 |
brief description of its organization may be helpful: |
| 651 |
|
| 652 |
* Files with prefix :file:`sc` contain the lexical scanner. |
| 653 |
|
| 654 |
* All files prefixed with :file:`par` are components of the parser. The |
| 655 |
numbers correspond to chapters of the Ada Reference Manual. For example, |
| 656 |
parsing of select statements can be found in :file:`par-ch9.adb`. |
| 657 |
|
| 658 |
* All files prefixed with :file:`sem` perform semantic analysis. The |
| 659 |
numbers correspond to chapters of the Ada standard. For example, all |
| 660 |
issues involving context clauses can be found in |
| 661 |
:file:`sem_ch10.adb`. In addition, some features of the language |
| 662 |
require sufficient special processing to justify their own semantic |
| 663 |
files, such as :file:`sem_aggr.adb` for aggregates and |
| 664 |
:file:`sem_disp.adb` for dynamic dispatching. |
| 665 |
|
| 666 |
* All files prefixed with :file:`exp` perform normalization and |
| 667 |
expansion of the intermediate representation (abstract syntax tree, or AST). |
| 668 |
The expansion has the effect of lowering the semantic level of the AST to |
| 669 |
a level closer to what the back end can handle. For example, it converts |
| 670 |
tasking operations into calls to the appropriate runtime routines. |
| 671 |
These files use the same numbering scheme as the parser and semantics files. |
| 672 |
For example, the construction of record initialization procedures is done in |
| 673 |
:file:`exp_ch3.adb`. |
| 674 |
|
| 675 |
* The files prefixed with :file:`bind` implement the binder, which |
| 676 |
verifies the consistency of the compilation, determines an order of |
| 677 |
elaboration, and generates the bind file. |
| 678 |
|
| 679 |
* The files :file:`atree.ads` and :file:`atree.adb` detail the low-level |
| 680 |
data structures used by the front-end. |
| 681 |
|
| 682 |
* The files :file:`sinfo.ads` and :file:`sinfo.adb` detail the structure of |
| 683 |
the abstract syntax tree as produced by the parser. |
| 684 |
|
| 685 |
* The files :file:`einfo.ads` and :file:`einfo.adb` detail the attributes of |
| 686 |
all entities, computed during semantic analysis. |
| 687 |
|
| 688 |
* The files prefixed with :file:`gen_il` generate most of the functions |
| 689 |
defined in :file:`sinfo.ads` and :file:`einfo.ads`, which set and get |
| 690 |
various fields and flags of the AST. |
| 691 |
|
| 692 |
* Library management issues are dealt with in files with prefix |
| 693 |
:file:`lib`. |
| 694 |
|
| 695 |
.. index:: Annex A (in Ada Reference Manual) |
| 696 |
|
| 697 |
* Ada files with the prefix :file:`a-` are children of ``Ada``, as |
| 698 |
defined in Annex A. |
| 699 |
|
| 700 |
.. index:: Annex B (in Ada reference Manual) |
| 701 |
|
| 702 |
* Files with prefix :file:`i-` are children of ``Interfaces``, as |
| 703 |
defined in Annex B. |
| 704 |
|
| 705 |
.. index:: System (package in Ada Reference Manual) |
| 706 |
|
| 707 |
* Files with prefix :file:`s-` are children of ``System``. This includes |
| 708 |
both language-defined children and GNAT run-time routines. |
| 709 |
|
| 710 |
.. index:: GNAT (package) |
| 711 |
|
| 712 |
* Files with prefix :file:`g-` are children of ``GNAT``. These are useful |
| 713 |
general-purpose packages, fully documented in their specs. All |
| 714 |
the other :file:`.c` files are modifications of common ``gcc`` files. |
| 715 |
|
| 716 |
|
| 717 |
.. _Getting_Internal_Debugging_Information: |
| 718 |
|
| 719 |
Getting Internal Debugging Information |
| 720 |
-------------------------------------- |
| 721 |
|
| 722 |
Most compilers have internal debugging switches and modes. GNAT |
| 723 |
does too, except GNAT internal debugging switches and modes are not |
| 724 |
secret. A summary and full description of all the compiler and binder |
| 725 |
debug flags are in the file :file:`debug.adb`. You must obtain the |
| 726 |
sources of the compiler to see the full detailed effects of these flags. |
| 727 |
|
| 728 |
The switches that print the source of the program (reconstructed from |
| 729 |
the internal tree) are of general interest for user programs, as are the |
| 730 |
options to print |
| 731 |
the full internal tree and the entity table (the symbol table |
| 732 |
information). The reconstructed source provides a readable version of the |
| 733 |
program after the front-end has completed analysis and expansion |
| 734 |
and is useful when studying the performance of specific constructs. |
| 735 |
For example, constraint checks are shown explicitly, complex aggregates |
| 736 |
are replaced with loops and assignments, and tasking primitives |
| 737 |
are replaced with run-time calls. |
| 738 |
|
| 739 |
|
| 740 |
.. index:: traceback |
| 741 |
.. index:: stack traceback |
| 742 |
.. index:: stack unwinding |
| 743 |
|
| 744 |
.. _Stack_Traceback: |
| 745 |
|
| 746 |
Stack Traceback |
| 747 |
--------------- |
| 748 |
|
| 749 |
Traceback is a mechanism to display the sequence of subprogram calls that |
| 750 |
leads to a specified execution point in a program. Often (but not always) |
| 751 |
the execution point is an instruction at which an exception has been raised. |
| 752 |
This mechanism is also known as *stack unwinding* because it obtains |
| 753 |
its information by scanning the run-time stack and recovering the activation |
| 754 |
records of all active subprograms. Stack unwinding is one of the most |
| 755 |
important tools for program debugging. |
| 756 |
|
| 757 |
The first entry stored in traceback corresponds to the deepest calling level, |
| 758 |
that is to say the subprogram currently executing the instruction |
| 759 |
from which we want to obtain the traceback. |
| 760 |
|
| 761 |
Note that there is no runtime performance penalty when stack traceback |
| 762 |
is enabled and no exception is raised during program execution. |
| 763 |
|
| 764 |
.. index:: traceback, non-symbolic |
| 765 |
|
| 766 |
.. _Non-Symbolic_Traceback: |
| 767 |
|
| 768 |
Non-Symbolic Traceback |
| 769 |
^^^^^^^^^^^^^^^^^^^^^^ |
| 770 |
|
| 771 |
Note: this feature is not supported on all platforms. See |
| 772 |
:samp:`GNAT.Traceback` spec in :file:`g-traceb.ads` |
| 773 |
for a complete list of supported platforms. |
| 774 |
|
| 775 |
.. rubric:: Tracebacks From an Unhandled Exception |
| 776 |
|
| 777 |
A runtime non-symbolic traceback is a list of addresses of call |
| 778 |
instructions. To enable this feature you must use the :switch:`-E` |
| 779 |
``gnatbind`` switch. With this switch, a stack traceback is stored at |
| 780 |
runtime as part of exception information. |
| 781 |
|
| 782 |
You can translate this information using the ``addr2line`` tool, provided that |
| 783 |
the program is compiled with debugging options (see :ref:`Switches_for_gcc`) |
| 784 |
and linked at a fixed position with :switch:`-no-pie`. |
| 785 |
|
| 786 |
Here's a simple example with ``gnatmake``: |
| 787 |
|
| 788 |
.. code-block:: ada |
| 789 |
|
| 790 |
procedure STB is |
| 791 |
|
| 792 |
procedure P1 is |
| 793 |
begin |
| 794 |
raise Constraint_Error; |
| 795 |
end P1; |
| 796 |
|
| 797 |
procedure P2 is |
| 798 |
begin |
| 799 |
P1; |
| 800 |
end P2; |
| 801 |
|
| 802 |
begin |
| 803 |
P2; |
| 804 |
end STB; |
| 805 |
|
| 806 |
:: |
| 807 |
|
| 808 |
$ gnatmake stb -g -bargs -E -largs -no-pie |
| 809 |
$ stb |
| 810 |
|
| 811 |
Execution of stb terminated by unhandled exception |
| 812 |
raised CONSTRAINT_ERROR : stb.adb:5 explicit raise |
| 813 |
Load address: 0x400000 |
| 814 |
Call stack traceback locations: |
| 815 |
0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4 |
| 816 |
|
| 817 |
As we can see, the traceback lists a sequence of addresses for the unhandled |
| 818 |
exception ``CONSTRAINT_ERROR`` raised in procedure P1. It's easy to |
| 819 |
see that this exception come from procedure P1. To translate these |
| 820 |
addresses into the source lines where the calls appear, you need to |
| 821 |
invoke the ``addr2line`` tool like this: |
| 822 |
|
| 823 |
:: |
| 824 |
|
| 825 |
$ addr2line -e stb 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 |
| 826 |
0x4011f1 0x77e892a4 |
| 827 |
|
| 828 |
d:/stb/stb.adb:5 |
| 829 |
d:/stb/stb.adb:10 |
| 830 |
d:/stb/stb.adb:14 |
| 831 |
d:/stb/b~stb.adb:197 |
| 832 |
crtexe.c:? |
| 833 |
crtexe.c:? |
| 834 |
??:0 |
| 835 |
|
| 836 |
The ``addr2line`` tool has several other useful options: |
| 837 |
|
| 838 |
========================= ==================================================== |
| 839 |
:samp:`-a --addresses` to show the addresses alongside the line numbers |
| 840 |
:samp:`-f --functions` to get the function name corresponding to a location |
| 841 |
:samp:`-p --pretty-print` to print all the information on a single line |
| 842 |
:samp:`--demangle=gnat` to use the GNAT decoding mode for the function names |
| 843 |
========================= ==================================================== |
| 844 |
|
| 845 |
:: |
| 846 |
|
| 847 |
$ addr2line -e stb -a -f -p --demangle=gnat 0x401373 0x40138b |
| 848 |
0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4 |
| 849 |
|
| 850 |
0x00401373: stb.p1 at d:/stb/stb.adb:5 |
| 851 |
0x0040138B: stb.p2 at d:/stb/stb.adb:10 |
| 852 |
0x0040139C: stb at d:/stb/stb.adb:14 |
| 853 |
0x00401335: main at d:/stb/b~stb.adb:197 |
| 854 |
0x004011c4: ?? at crtexe.c:? |
| 855 |
0x004011f1: ?? at crtexe.c:? |
| 856 |
0x77e892a4: ?? ??:0 |
| 857 |
|
| 858 |
|
| 859 |
From this traceback, we can see that the exception was raised in :file:`stb.adb` |
| 860 |
at line 5, which was reached from a procedure call in :file:`stb.adb` at line |
| 861 |
10, and so on. :file:`b~std.adb` is the binder file, which contains the |
| 862 |
call to the main program; :ref:`Running_gnatbind`. The remaining entries are |
| 863 |
assorted runtime routines. The output will vary from platform to platform. |
| 864 |
|
| 865 |
You can also use ``GDB`` with these traceback addresses to debug |
| 866 |
the program. For example, we can break at a given code location, as reported |
| 867 |
in the stack traceback:: |
| 868 |
|
| 869 |
$ gdb -nw stb |
| 870 |
|
| 871 |
(gdb) break *0x401373 |
| 872 |
Breakpoint 1 at 0x401373: file stb.adb, line 5. |
| 873 |
|
| 874 |
It is important to note that the stack traceback addresses do not change when |
| 875 |
debug information is included. This is particularly useful because it makes it |
| 876 |
possible to release software without debug information (to minimize object |
| 877 |
size), get a field report that includes a stack traceback whenever an internal |
| 878 |
bug occurs, and then be able to retrieve the sequence of calls with the same |
| 879 |
program compiled with debug information. |
| 880 |
|
| 881 |
However the ``addr2line`` tool does not work with Position-Independent Code |
| 882 |
(PIC), the historical example being Linux dynamic libraries and Windows DLLs, |
| 883 |
which nowadays encompasse Position-Independent Executables (PIE) on recent |
| 884 |
Linux and Windows versions. |
| 885 |
|
| 886 |
In order to translate addresses the source lines with Position-Independent |
| 887 |
Executables on recent Linux and Windows versions, in other words without |
| 888 |
using the switch :switch:`-no-pie` during linking, you need to use the |
| 889 |
``gnatsymbolize`` tool with :switch:`--load` instead of the ``addr2line`` |
| 890 |
tool. The main difference is that you need to copy the Load Address output |
| 891 |
in the traceback ahead of the sequence of addresses. The default mode |
| 892 |
of ``gnatsymbolize`` is equivalent to that of ``addr2line`` with the above |
| 893 |
switches, so none of them are needed:: |
| 894 |
|
| 895 |
$ gnatmake stb -g -bargs -E |
| 896 |
$ stb |
| 897 |
|
| 898 |
Execution of stb terminated by unhandled exception |
| 899 |
raised CONSTRAINT_ERROR : stb.adb:5 explicit raise |
| 900 |
Load address: 0x400000 |
| 901 |
Call stack traceback locations: |
| 902 |
0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4 |
| 903 |
|
| 904 |
$ gnatsymbolize --load stb 0x400000 0x401373 0x40138b 0x40139c 0x401335 \ |
| 905 |
0x4011c4 0x4011f1 0x77e892a4 |
| 906 |
|
| 907 |
0x00401373 Stb.P1 at stb.adb:5 |
| 908 |
0x0040138B Stb.P2 at stb.adb:10 |
| 909 |
0x0040139C Stb at stb.adb:14 |
| 910 |
0x00401335 Main at b~stb.adb:197 |
| 911 |
0x004011c4 __tmainCRTStartup at ??? |
| 912 |
0x004011f1 mainCRTStartup at ??? |
| 913 |
0x77e892a4 ??? at ??? |
| 914 |
|
| 915 |
|
| 916 |
.. rubric:: Tracebacks From Exception Occurrences |
| 917 |
|
| 918 |
Non-symbolic tracebacks are obtained by using the :switch:`-E` binder switch. |
| 919 |
The stack traceback is attached to the exception information string and you can |
| 920 |
retrieve it in an exception handler within the Ada program by means of the |
| 921 |
Ada facilities defined in ``Ada.Exceptions``. Here's a simple example: |
| 922 |
|
| 923 |
.. code-block:: ada |
| 924 |
|
| 925 |
with Ada.Text_IO; |
| 926 |
with Ada.Exceptions; |
| 927 |
|
| 928 |
procedure STB is |
| 929 |
|
| 930 |
use Ada; |
| 931 |
use Ada.Exceptions; |
| 932 |
|
| 933 |
procedure P1 is |
| 934 |
K : Positive := 1; |
| 935 |
begin |
| 936 |
K := K - 1; |
| 937 |
exception |
| 938 |
when E : others => |
| 939 |
Text_IO.Put_Line (Exception_Information (E)); |
| 940 |
end P1; |
| 941 |
|
| 942 |
procedure P2 is |
| 943 |
begin |
| 944 |
P1; |
| 945 |
end P2; |
| 946 |
|
| 947 |
begin |
| 948 |
P2; |
| 949 |
end STB; |
| 950 |
|
| 951 |
:: |
| 952 |
|
| 953 |
$ gnatmake stb -g -bargs -E -largs -no-pie |
| 954 |
$ stb |
| 955 |
|
| 956 |
raised CONSTRAINT_ERROR : stb.adb:12 range check failed |
| 957 |
Load address: 0x400000 |
| 958 |
Call stack traceback locations: |
| 959 |
0x4015e4 0x401633 0x401644 0x401461 0x4011c4 0x4011f1 0x77e892a4 |
| 960 |
|
| 961 |
|
| 962 |
.. rubric:: Tracebacks From Anywhere in a Program |
| 963 |
|
| 964 |
You can also retrieve a stack traceback from anywhere in a program. |
| 965 |
For this, you need to use the ``GNAT.Traceback`` API. This package includes a |
| 966 |
procedure called ``Call_Chain`` that computes a complete stack traceback as |
| 967 |
well as useful display procedures described below. You don't have to use |
| 968 |
the :switch:`-E` ``gnatbind`` switch in this case because the stack traceback |
| 969 |
mechanism is invoked explicitly. |
| 970 |
|
| 971 |
In the following example, we compute a traceback at a specific location in the |
| 972 |
program and display it using ``GNAT.Debug_Utilities.Image`` to convert |
| 973 |
addresses to strings: |
| 974 |
|
| 975 |
|
| 976 |
.. code-block:: ada |
| 977 |
|
| 978 |
with Ada.Text_IO; |
| 979 |
with GNAT.Traceback; |
| 980 |
with GNAT.Debug_Utilities; |
| 981 |
with System; |
| 982 |
|
| 983 |
procedure STB is |
| 984 |
|
| 985 |
use Ada; |
| 986 |
use Ada.Text_IO; |
| 987 |
use GNAT; |
| 988 |
use GNAT.Traceback; |
| 989 |
use System; |
| 990 |
|
| 991 |
LA : constant Address := Executable_Load_Address; |
| 992 |
|
| 993 |
procedure P1 is |
| 994 |
TB : Tracebacks_Array (1 .. 10); |
| 995 |
-- We are asking for a maximum of 10 stack frames. |
| 996 |
Len : Natural; |
| 997 |
-- Len will receive the actual number of stack frames returned. |
| 998 |
begin |
| 999 |
Call_Chain (TB, Len); |
| 1000 |
|
| 1001 |
Put ("In STB.P1 : "); |
| 1002 |
|
| 1003 |
for K in 1 .. Len loop |
| 1004 |
Put (Debug_Utilities.Image_C (TB (K))); |
| 1005 |
Put (' '); |
| 1006 |
end loop; |
| 1007 |
|
| 1008 |
New_Line; |
| 1009 |
end P1; |
| 1010 |
|
| 1011 |
procedure P2 is |
| 1012 |
begin |
| 1013 |
P1; |
| 1014 |
end P2; |
| 1015 |
|
| 1016 |
begin |
| 1017 |
if LA /= Null_Address then |
| 1018 |
Put_Line ("Load address: " & Debug_Utilities.Image_C (LA)); |
| 1019 |
end if; |
| 1020 |
|
| 1021 |
P2; |
| 1022 |
end STB; |
| 1023 |
|
| 1024 |
:: |
| 1025 |
|
| 1026 |
$ gnatmake stb -g |
| 1027 |
$ stb |
| 1028 |
|
| 1029 |
Load address: 0x400000 |
| 1030 |
In STB.P1 : 0x40F1E4 0x4014F2 0x40170B 0x40171C 0x401461 0x4011C4 \ |
| 1031 |
0x4011F1 0x77E892A4 |
| 1032 |
|
| 1033 |
|
| 1034 |
You can get even more information by invoking the ``addr2line`` tool or |
| 1035 |
the ``gnatsymbolize`` tool as described earlier (note that the hexadecimal |
| 1036 |
addresses need to be specified in C format, with a leading '0x'). |
| 1037 |
|
| 1038 |
.. index:: traceback, symbolic |
| 1039 |
|
| 1040 |
.. _Symbolic_Traceback: |
| 1041 |
|
| 1042 |
Symbolic Traceback |
| 1043 |
^^^^^^^^^^^^^^^^^^ |
| 1044 |
|
| 1045 |
A symbolic traceback is a stack traceback in which procedure names are |
| 1046 |
associated with each code location. |
| 1047 |
|
| 1048 |
Note that this feature is not supported on all platforms. See |
| 1049 |
:samp:`GNAT.Traceback.Symbolic` spec in :file:`g-trasym.ads` for a complete |
| 1050 |
list of currently supported platforms. |
| 1051 |
|
| 1052 |
Note that the symbolic traceback requires that the program be compiled |
| 1053 |
with debug information. If you do not compile it with debug information, |
| 1054 |
only the non-symbolic information will be valid. |
| 1055 |
|
| 1056 |
|
| 1057 |
.. rubric:: Tracebacks From Exception Occurrences |
| 1058 |
|
| 1059 |
Here is an example: |
| 1060 |
|
| 1061 |
.. code-block:: ada |
| 1062 |
|
| 1063 |
with Ada.Text_IO; |
| 1064 |
with GNAT.Traceback.Symbolic; |
| 1065 |
|
| 1066 |
procedure STB is |
| 1067 |
|
| 1068 |
procedure P1 is |
| 1069 |
begin |
| 1070 |
raise Constraint_Error; |
| 1071 |
end P1; |
| 1072 |
|
| 1073 |
procedure P2 is |
| 1074 |
begin |
| 1075 |
P1; |
| 1076 |
end P2; |
| 1077 |
|
| 1078 |
procedure P3 is |
| 1079 |
begin |
| 1080 |
P2; |
| 1081 |
end P3; |
| 1082 |
|
| 1083 |
begin |
| 1084 |
P3; |
| 1085 |
exception |
| 1086 |
when E : others => |
| 1087 |
Ada.Text_IO.Put_Line (GNAT.Traceback.Symbolic.Symbolic_Traceback (E)); |
| 1088 |
end STB; |
| 1089 |
|
| 1090 |
:: |
| 1091 |
|
| 1092 |
$ gnatmake -g stb -bargs -E |
| 1093 |
$ stb |
| 1094 |
|
| 1095 |
0040149F in stb.p1 at stb.adb:8 |
| 1096 |
004014B7 in stb.p2 at stb.adb:13 |
| 1097 |
004014CF in stb.p3 at stb.adb:18 |
| 1098 |
004015DD in ada.stb at stb.adb:22 |
| 1099 |
00401461 in main at b~stb.adb:168 |
| 1100 |
004011C4 in __mingw_CRTStartup at crt1.c:200 |
| 1101 |
004011F1 in mainCRTStartup at crt1.c:222 |
| 1102 |
77E892A4 in ?? at ??:0 |
| 1103 |
|
| 1104 |
.. rubric:: Tracebacks From Anywhere in a Program |
| 1105 |
|
| 1106 |
You can get a symbolic stack traceback |
| 1107 |
from anywhere in a program, just as you can for non-symbolic tracebacks. |
| 1108 |
The first step is to obtain a non-symbolic |
| 1109 |
traceback. Then call ``Symbolic_Traceback`` to compute the symbolic |
| 1110 |
information. Here is an example: |
| 1111 |
|
| 1112 |
.. code-block:: ada |
| 1113 |
|
| 1114 |
with Ada.Text_IO; |
| 1115 |
with GNAT.Traceback; |
| 1116 |
with GNAT.Traceback.Symbolic; |
| 1117 |
|
| 1118 |
procedure STB is |
| 1119 |
|
| 1120 |
use Ada; |
| 1121 |
use GNAT.Traceback; |
| 1122 |
use GNAT.Traceback.Symbolic; |
| 1123 |
|
| 1124 |
procedure P1 is |
| 1125 |
TB : Tracebacks_Array (1 .. 10); |
| 1126 |
-- We are asking for a maximum of 10 stack frames. |
| 1127 |
Len : Natural; |
| 1128 |
-- Len will receive the actual number of stack frames returned. |
| 1129 |
begin |
| 1130 |
Call_Chain (TB, Len); |
| 1131 |
Text_IO.Put_Line (Symbolic_Traceback (TB (1 .. Len))); |
| 1132 |
end P1; |
| 1133 |
|
| 1134 |
procedure P2 is |
| 1135 |
begin |
| 1136 |
P1; |
| 1137 |
end P2; |
| 1138 |
|
| 1139 |
begin |
| 1140 |
P2; |
| 1141 |
end STB; |
| 1142 |
|
| 1143 |
|
| 1144 |
.. rubric:: Automatic Symbolic Tracebacks |
| 1145 |
|
| 1146 |
You may also enable symbolic tracebacks by using |
| 1147 |
the :switch:`-Es` switch to gnatbind (as in ``gprbuild -g ... -bargs -Es``). |
| 1148 |
This causes the Exception_Information to contain a symbolic |
| 1149 |
traceback, which will also be printed if an unhandled exception |
| 1150 |
terminates the program. |
| 1151 |
|
| 1152 |
|
| 1153 |
.. _Pretty-Printers_For_The_GNAT_Runtime: |
| 1154 |
|
| 1155 |
Pretty-Printers for the GNAT runtime |
| 1156 |
------------------------------------ |
| 1157 |
|
| 1158 |
As discussed in :title:`Calling User-Defined Subprograms`, GDB's |
| 1159 |
``print`` command only knows about the physical layout of program data |
| 1160 |
structures and therefore normally displays only low-level dumps, which |
| 1161 |
are often hard to understand. |
| 1162 |
|
| 1163 |
An example of this is when trying to display the contents of an Ada |
| 1164 |
standard container, such as ``Ada.Containers.Ordered_Maps.Map``: |
| 1165 |
|
| 1166 |
.. code-block:: ada |
| 1167 |
|
| 1168 |
with Ada.Containers.Ordered_Maps; |
| 1169 |
|
| 1170 |
procedure PP is |
| 1171 |
package Int_To_Nat is |
| 1172 |
new Ada.Containers.Ordered_Maps (Integer, Natural); |
| 1173 |
|
| 1174 |
Map : Int_To_Nat.Map; |
| 1175 |
begin |
| 1176 |
Map.Insert (1, 10); |
| 1177 |
Map.Insert (2, 20); |
| 1178 |
Map.Insert (3, 30); |
| 1179 |
|
| 1180 |
Map.Clear; -- BREAK HERE |
| 1181 |
end PP; |
| 1182 |
|
| 1183 |
When this program is built with debugging information and run under |
| 1184 |
``GDB`` up to the ``Map.Clear`` statement, trying to print ``Map`` will |
| 1185 |
yield information that is only relevant to the developers of the standard |
| 1186 |
containers: |
| 1187 |
|
| 1188 |
:: |
| 1189 |
|
| 1190 |
(gdb) print map |
| 1191 |
$1 = ( |
| 1192 |
tree => ( |
| 1193 |
first => 0x64e010, |
| 1194 |
last => 0x64e070, |
| 1195 |
root => 0x64e040, |
| 1196 |
length => 3, |
| 1197 |
tc => ( |
| 1198 |
busy => 0, |
| 1199 |
lock => 0 |
| 1200 |
) |
| 1201 |
) |
| 1202 |
) |
| 1203 |
|
| 1204 |
Fortunately, ``GDB ``has a feature called `pretty-printers |
| 1205 |
<http://docs.adacore.com/gdb-docs/html/gdb.html#Pretty_002dPrinter-Introduction>`_, |
| 1206 |
which allows customizing how ``GDB`` displays data structures. The |
| 1207 |
``GDB`` shipped with GNAT embeds such pretty-printers for the most |
| 1208 |
common containers in the standard library. To enable them, either run |
| 1209 |
the following command manually under ``GDB`` or add it to your |
| 1210 |
:file:`.gdbinit` file: |
| 1211 |
|
| 1212 |
:: |
| 1213 |
|
| 1214 |
python import gnatdbg; gnatdbg.setup() |
| 1215 |
|
| 1216 |
Once you've done this, ``GDB``'s ``print`` command will automatically use |
| 1217 |
these pretty-printers when appropriate. Using the previous example: |
| 1218 |
|
| 1219 |
:: |
| 1220 |
|
| 1221 |
(gdb) print map |
| 1222 |
$1 = pp.int_to_nat.map of length 3 = { |
| 1223 |
[1] = 10, |
| 1224 |
[2] = 20, |
| 1225 |
[3] = 30 |
| 1226 |
} |
| 1227 |
|
| 1228 |
Pretty-printers are invoked each time GDB tries to display a value, |
| 1229 |
including when displaying the arguments of a called subprogram (in |
| 1230 |
GDB's ``backtrace`` command) or when printing the value returned by a |
| 1231 |
function (in GDB's ``finish`` command). |
| 1232 |
|
| 1233 |
To display a value without involving pretty-printers, you can invoke |
| 1234 |
``print`` with its ``/r`` option: |
| 1235 |
|
| 1236 |
:: |
| 1237 |
|
| 1238 |
(gdb) print/r map |
| 1239 |
$1 = ( |
| 1240 |
tree => (... |
| 1241 |
|
| 1242 |
You can also obtain finer control of pretty-printers: see `GDB's online |
| 1243 |
documentation |
| 1244 |
<http://docs.adacore.com/gdb-docs/html/gdb.html#Pretty_002dPrinter-Commands>`_ |
| 1245 |
for more information. |
| 1246 |
|
| 1247 |
|
| 1248 |
.. index:: Profiling |
| 1249 |
|
| 1250 |
|
| 1251 |
.. _Profiling: |
| 1252 |
|
| 1253 |
Profiling |
| 1254 |
========= |
| 1255 |
|
| 1256 |
This section describes how to use the ``gprof`` profiler tool on Ada programs. |
| 1257 |
|
| 1258 |
.. index:: ! gprof |
| 1259 |
.. index:: Profiling |
| 1260 |
|
| 1261 |
.. _Profiling_an_Ada_Program_with_gprof: |
| 1262 |
|
| 1263 |
Profiling an Ada Program with gprof |
| 1264 |
----------------------------------- |
| 1265 |
|
| 1266 |
This section is not meant to be an exhaustive documentation of ``gprof``. |
| 1267 |
You can find full documentation for it in the :title:`GNU Profiler User's Guide` |
| 1268 |
documentation that is part of this GNAT distribution. |
| 1269 |
|
| 1270 |
Profiling a program helps determine the parts of a program that are executed |
| 1271 |
most often and are therefore the most time-consuming. |
| 1272 |
|
| 1273 |
``gprof`` is the standard GNU profiling tool; it has been enhanced to |
| 1274 |
better handle Ada programs and multitasking. |
| 1275 |
It's currently supported on the following platforms |
| 1276 |
|
| 1277 |
* Linux x86/x86_64 |
| 1278 |
* Windows x86/x86_64 (without PIE support) |
| 1279 |
|
| 1280 |
In order to profile a program using ``gprof``, you need to perform the |
| 1281 |
following steps: |
| 1282 |
|
| 1283 |
#. Instrument the code, which requires a full recompilation of the project with the |
| 1284 |
proper switches. |
| 1285 |
|
| 1286 |
#. Execute the program under the analysis conditions, i.e. with the desired |
| 1287 |
input. |
| 1288 |
|
| 1289 |
#. Analyze the results using the ``gprof`` tool. |
| 1290 |
|
| 1291 |
The following sections detail the different steps and indicate how |
| 1292 |
to interpret the results. |
| 1293 |
|
| 1294 |
|
| 1295 |
.. _Compilation_for_profiling: |
| 1296 |
|
| 1297 |
Compilation for profiling |
| 1298 |
^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 1299 |
|
| 1300 |
.. index:: -pg (gcc), for profiling |
| 1301 |
.. index:: -pg (gnatlink), for profiling |
| 1302 |
|
| 1303 |
In order to profile a program, you must first to tell the compiler |
| 1304 |
to generate the necessary profiling information. You do this using the compiler switch :switch:`-pg`, which you must add to other compilation switches. You need |
| 1305 |
to specify this |
| 1306 |
switch during compilation and link stages, and you can |
| 1307 |
specified it only once when using ``gnatmake``: |
| 1308 |
|
| 1309 |
:: |
| 1310 |
|
| 1311 |
$ gnatmake -f -pg -P my_project |
| 1312 |
|
| 1313 |
Note that only the objects that were compiled with the :switch:`-pg` switch will |
| 1314 |
be profiled; if you need to profile your whole project, use the :switch:`-f` |
| 1315 |
``gnatmake`` switch to force full recompilation. |
| 1316 |
|
| 1317 |
Note that on Windows, ``gprof`` does not support PIE. You should add |
| 1318 |
the :switch:`-no-pie` switch to the linker flags to disable PIE. |
| 1319 |
|
| 1320 |
|
| 1321 |
.. _Program_execution: |
| 1322 |
|
| 1323 |
|
| 1324 |
Program execution |
| 1325 |
^^^^^^^^^^^^^^^^^ |
| 1326 |
|
| 1327 |
Once the program has been compiled for profiling, you can run it as usual. |
| 1328 |
|
| 1329 |
The only constraint imposed by profiling is that the program must terminate |
| 1330 |
normally. An interrupted program (via a Ctrl-C, kill, etc.) will not be |
| 1331 |
properly analyzed. |
| 1332 |
|
| 1333 |
Once the program completes execution, a data file called :file:`gmon.out` is |
| 1334 |
generated in the directory where the program was launched from. If this file |
| 1335 |
already exists, it will be overwritten by running the program. |
| 1336 |
|
| 1337 |
|
| 1338 |
.. _Running_gprof: |
| 1339 |
|
| 1340 |
Running gprof |
| 1341 |
^^^^^^^^^^^^^ |
| 1342 |
|
| 1343 |
You can call the ``gprof`` tool as follows: |
| 1344 |
|
| 1345 |
:: |
| 1346 |
|
| 1347 |
$ gprof my_prog gmon.out |
| 1348 |
|
| 1349 |
or simply: |
| 1350 |
|
| 1351 |
:: |
| 1352 |
|
| 1353 |
$ gprof my_prog |
| 1354 |
|
| 1355 |
The complete form of the ``gprof`` command line is the following: |
| 1356 |
|
| 1357 |
:: |
| 1358 |
|
| 1359 |
$ gprof [switches] [executable [data-file]] |
| 1360 |
|
| 1361 |
``gprof`` supports numerous switches, whose order does not matter. You |
| 1362 |
can find the full list of switches in the :title:`GNU Profiler |
| 1363 |
User's Guide`. |
| 1364 |
|
| 1365 |
The following are the most relevant of those switches: |
| 1366 |
|
| 1367 |
.. index:: --demangle (gprof) |
| 1368 |
|
| 1369 |
:switch:`--demangle[={style}]`, :switch:`--no-demangle` |
| 1370 |
These switches control whether symbol names should be demangled when |
| 1371 |
printing output. The default is to demangle C++ symbols. You can use |
| 1372 |
:switch:`--no-demangle` to turn off demangling. Different |
| 1373 |
compilers have different mangling styles. The optional demangling style |
| 1374 |
argument can be used to choose an appropriate demangling style for your |
| 1375 |
compiler, in particular Ada symbols generated by GNAT can be demangled using |
| 1376 |
:switch:`--demangle=gnat`. |
| 1377 |
|
| 1378 |
|
| 1379 |
.. index:: -e (gprof) |
| 1380 |
|
| 1381 |
:switch:`-e {function_name}` |
| 1382 |
The :switch:`-e {function}` option tells ``gprof`` not to print |
| 1383 |
information about the function ``function_name`` and its |
| 1384 |
children in the call graph. The function will still be listed |
| 1385 |
as a child of any functions that call it, but its index number will be |
| 1386 |
shown as ``[not printed]``. You may specify more than one :switch:`-e` switch, |
| 1387 |
but you may only include one ``function_name`` with each :switch:`-e` |
| 1388 |
switch. |
| 1389 |
|
| 1390 |
|
| 1391 |
.. index:: -E (gprof) |
| 1392 |
|
| 1393 |
:switch:`-E {function_name}` |
| 1394 |
The :switch:`-E {function}` switch works like the :switch:`-e` switch, but |
| 1395 |
execution time spent in the function (and children who were not called from |
| 1396 |
anywhere else) will not be used to compute the percentages-of-time for |
| 1397 |
the call graph. You may specify more than one :switch:`-E` switch, but |
| 1398 |
you may only include one ``function_name`` with each :switch:`-E` switch. |
| 1399 |
|
| 1400 |
|
| 1401 |
.. index:: -f (gprof) |
| 1402 |
|
| 1403 |
:switch:`-f {function_name}` |
| 1404 |
The :switch:`-f {function}` switch causes ``gprof`` to limit the |
| 1405 |
call graph to the function ``function_name`` and its children and |
| 1406 |
their children. You may specify more than one :switch:`-f` switch, |
| 1407 |
but you may only include one ``function_name`` with each :switch:`-f` switch. |
| 1408 |
|
| 1409 |
|
| 1410 |
.. index:: -F (gprof) |
| 1411 |
|
| 1412 |
:switch:`-F {function_name}` |
| 1413 |
The :switch:`-F {function}` switch works like the :switch:`-f` switch, but |
| 1414 |
only time spent in the function and its children and their |
| 1415 |
children will be used to determine total-time and |
| 1416 |
percentages-of-time for the call graph. You may specify more than one |
| 1417 |
:switch:`-F` switch, but you may include only one ``function_name`` with each |
| 1418 |
:switch:`-F` switch. The :switch:`-F` switch overrides the :switch:`-E` |
| 1419 |
switch. |
| 1420 |
|
| 1421 |
|
| 1422 |
.. _Interpretation_of_profiling_results: |
| 1423 |
|
| 1424 |
Interpretation of profiling results |
| 1425 |
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 1426 |
|
| 1427 |
The results of the profiling analysis are represented by two arrays: |
| 1428 |
the 'flat profile' and the 'call graph'. You can find full |
| 1429 |
documentation of those outputs in the :title:`GNU Profiler User's Guide`. |
| 1430 |
|
| 1431 |
The flat profile shows the time spent in each function of the program and how |
| 1432 |
many time it has been called. This allows you to easily locate the most |
| 1433 |
time-consuming functions. |
| 1434 |
|
| 1435 |
The call graph shows, for each subprogram, the subprograms that call it, |
| 1436 |
and the subprograms that it calls. It also provides an estimate of the time |
| 1437 |
spent in each of those callers and called subprograms. |
| 1438 |
|
| 1439 |
|
| 1440 |
|
| 1441 |
.. _Improving_Performance: |
| 1442 |
|
| 1443 |
Improving Performance |
| 1444 |
===================== |
| 1445 |
|
| 1446 |
.. index:: Improving performance |
| 1447 |
|
| 1448 |
This section presents several topics related to program performance. |
| 1449 |
It first describes some of the tradeoffs that you need to consider |
| 1450 |
and some of the techniques for making your program run faster. |
| 1451 |
|
| 1452 |
It then documents the unused subprogram/data elimination feature, |
| 1453 |
which can reduce the size of program executables. |
| 1454 |
|
| 1455 |
.. _Performance_Considerations: |
| 1456 |
|
| 1457 |
Performance Considerations |
| 1458 |
-------------------------- |
| 1459 |
|
| 1460 |
The GNAT system provides a number of options that allow a trade-off |
| 1461 |
between: |
| 1462 |
|
| 1463 |
* performance of the generated code |
| 1464 |
|
| 1465 |
* speed of compilation |
| 1466 |
|
| 1467 |
* minimization of dependences and recompilation |
| 1468 |
|
| 1469 |
* the degree of run-time checking. |
| 1470 |
|
| 1471 |
The default (if you don't select any switches) aims at improving the speed |
| 1472 |
of compilation and minimizing dependences, at the expense of performance |
| 1473 |
of the generated code and consists of: |
| 1474 |
|
| 1475 |
* no optimization |
| 1476 |
|
| 1477 |
* no inlining of subprogram calls |
| 1478 |
|
| 1479 |
* all run-time checks enabled except overflow and elaboration checks |
| 1480 |
|
| 1481 |
These options are suitable for most program development purposes. This |
| 1482 |
section describes how you can modify these choices and also provides |
| 1483 |
some guidelines on debugging optimized code. |
| 1484 |
|
| 1485 |
|
| 1486 |
.. _Controlling_Run-Time_Checks: |
| 1487 |
|
| 1488 |
Controlling Run-Time Checks |
| 1489 |
^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 1490 |
|
| 1491 |
By default, GNAT generates all run-time checks, except stack overflow |
| 1492 |
checks and checks for access before elaboration on subprogram |
| 1493 |
calls. The latter are not required in default mode because all |
| 1494 |
necessary checking is done at compile time. |
| 1495 |
|
| 1496 |
.. index:: -gnatp (gcc) |
| 1497 |
.. index:: -gnato (gcc) |
| 1498 |
|
| 1499 |
The GNAT switch, :switch:`-gnatp` allows you to modify this default; see |
| 1500 |
:ref:`Run-Time_Checks`. |
| 1501 |
|
| 1502 |
Our experience is that the default is suitable for most development |
| 1503 |
purposes. |
| 1504 |
|
| 1505 |
Elaboration checks are off by default and also not needed by default |
| 1506 |
since GNAT uses a static elaboration analysis approach that avoids the |
| 1507 |
need for run-time checking. This manual contains a full chapter |
| 1508 |
discussing the issue of elaboration checks and you should read this |
| 1509 |
chapter if the default is not satisfactory for your use, |
| 1510 |
|
| 1511 |
For validity checks, the minimal checks required by the Ada Reference |
| 1512 |
Manual (for case statements and assignments to array elements) are enabled |
| 1513 |
by default. You can suppress these by using the :switch:`-gnatVn` switch. |
| 1514 |
Note that in Ada 83, there were no validity checks, so if the Ada 83 mode |
| 1515 |
is acceptable (or when comparing GNAT performance with an Ada 83 compiler), |
| 1516 |
it may be reasonable to routinely use :switch:`-gnatVn`. Validity checks |
| 1517 |
are also suppressed entirely if you use :switch:`-gnatp`. |
| 1518 |
|
| 1519 |
.. index:: Overflow checks |
| 1520 |
.. index:: Checks, overflow |
| 1521 |
|
| 1522 |
.. index:: Suppress |
| 1523 |
.. index:: Unsuppress |
| 1524 |
.. index:: pragma Suppress |
| 1525 |
.. index:: pragma Unsuppress |
| 1526 |
|
| 1527 |
Note that the setting of the switches controls the default setting of |
| 1528 |
the checks. You may modify them using either ``pragma Suppress`` (to |
| 1529 |
remove checks) or ``pragma Unsuppress`` (to add back suppressed |
| 1530 |
checks) in your program source. |
| 1531 |
|
| 1532 |
|
| 1533 |
.. _Use_of_Restrictions: |
| 1534 |
|
| 1535 |
Use of Restrictions |
| 1536 |
^^^^^^^^^^^^^^^^^^^ |
| 1537 |
|
| 1538 |
You can use pragma Restrictions to control which features are |
| 1539 |
permitted in your program. In most cases, the use of this pragma |
| 1540 |
itself does not affect the generated code (but, of course, if you |
| 1541 |
avoid relatively expensive features like finalization, you'll have |
| 1542 |
more efficient programs and that's enforceable by the use of pragma |
| 1543 |
Restrictions (No_Finalization). |
| 1544 |
|
| 1545 |
One notable exception to this rule is that the possibility of task abort |
| 1546 |
results in some distributed overhead, particularly if finalization or |
| 1547 |
exception handlers are used. This is because certain sections of code |
| 1548 |
must be marked as non-abortable. |
| 1549 |
|
| 1550 |
If you use neither the ``abort`` statement nor asynchronous transfer |
| 1551 |
of control (``select ... then abort``), this distributed overhead can |
| 1552 |
be removed, which may have a general positive effect in improving |
| 1553 |
overall performance, especially in code involving frequent use of |
| 1554 |
tasking constructs and controlled types, which will show much improved |
| 1555 |
performance. The relevant restrictions pragmas are |
| 1556 |
|
| 1557 |
.. code-block:: ada |
| 1558 |
|
| 1559 |
pragma Restrictions (No_Abort_Statements); |
| 1560 |
pragma Restrictions (Max_Asynchronous_Select_Nesting => 0); |
| 1561 |
|
| 1562 |
We recommend that you use these restriction pragmas if possible. If you do |
| 1563 |
this, it also means you can write code without worrying about the |
| 1564 |
possibility of an immediate abort at any point. |
| 1565 |
|
| 1566 |
|
| 1567 |
.. _Optimization_Levels: |
| 1568 |
|
| 1569 |
Optimization Levels |
| 1570 |
^^^^^^^^^^^^^^^^^^^ |
| 1571 |
|
| 1572 |
.. index:: -O (gcc) |
| 1573 |
|
| 1574 |
Without any optimization switch, the compiler's goal is to reduce the |
| 1575 |
cost of compilation and to make debugging produce the expected |
| 1576 |
results. This means that statements are independent: if you stop the |
| 1577 |
program with a breakpoint between statements, you can then assign a |
| 1578 |
new value to any variable or change the program counter to any other |
| 1579 |
statement in the subprogram and get exactly the results you would |
| 1580 |
expect from the source code. However, the generated programs are |
| 1581 |
considerably larger and slower than when optimization is enabled. |
| 1582 |
|
| 1583 |
Turning on optimization makes the compiler attempt to improve the |
| 1584 |
performance and/or code size at the expense of compilation time and |
| 1585 |
possibly the ability to debug the program. |
| 1586 |
|
| 1587 |
You can pass the :switch:`-O` switch, with or without an operand |
| 1588 |
(the permitted forms with an operand are :switch:`-O0`, :switch:`-O1`, |
| 1589 |
:switch:`-O2`, :switch:`-O3`, :switch:`-Os`, :switch:`-Oz`, and |
| 1590 |
:switch:`-Og`) to ``gcc`` to control the optimization level. If you |
| 1591 |
pass multiple :switch:`-O` switches, with or without an operand, |
| 1592 |
the last such switch is the one that's used: |
| 1593 |
|
| 1594 |
|
| 1595 |
* :switch:`-O0` |
| 1596 |
No optimization (the default); generates unoptimized code but has |
| 1597 |
the fastest compilation time. Debugging is easiest with this switch. |
| 1598 |
|
| 1599 |
Note that many other compilers do substantial optimization even if |
| 1600 |
'no optimization' is specified. With GCC, it is very unusual to |
| 1601 |
use :switch:`-O0` for production if execution time is of any |
| 1602 |
concern, since :switch:`-O0` means (almost) no optimization. You |
| 1603 |
should keep this difference between GCC and other compilers in |
| 1604 |
mind when doing performance comparisons. |
| 1605 |
|
| 1606 |
* :switch:`-O1` |
| 1607 |
Moderate optimization (same as :switch:`-O` without an operand); |
| 1608 |
optimizes reasonably well but does not degrade compilation time |
| 1609 |
significantly. You may not be able to see some variables in the |
| 1610 |
debugger, and changing the value of some variables in the debugger |
| 1611 |
may not have the effect you desire. |
| 1612 |
|
| 1613 |
* :switch:`-O2` |
| 1614 |
Extensive optimization; generates highly optimized code but has |
| 1615 |
an increased compilation time. You may see significant impacts on |
| 1616 |
your ability to display and modify variables in the debugger. |
| 1617 |
|
| 1618 |
* :switch:`-O3` |
| 1619 |
Full optimization; attempts more sophisticated transformations, in |
| 1620 |
particular on loops, possibly at the cost of larger generated code. |
| 1621 |
You may be hardly able to use the debugger at this optimization level. |
| 1622 |
|
| 1623 |
* :switch:`-Os` |
| 1624 |
Optimize for size (code and data) of resulting binary rather than |
| 1625 |
speed; based on the :switch:`-O2` optimization level, but disables |
| 1626 |
some of its transformations that often increase code size, as well |
| 1627 |
as performs further optimizations designed to reduce code size. |
| 1628 |
|
| 1629 |
* :switch:`-Oz` |
| 1630 |
Optimize aggressively for size (code and data) of resulting binary |
| 1631 |
rather than speed; may increase the number of instructions executed |
| 1632 |
if these instructions require fewer bytes to be encoded. |
| 1633 |
|
| 1634 |
* :switch:`-Og` |
| 1635 |
Optimize for debugging experience rather than speed; based on the |
| 1636 |
:switch:`-O1` optimization level, but attempts to eliminate all the |
| 1637 |
negative effects of optimization on debugging. |
| 1638 |
|
| 1639 |
|
| 1640 |
Higher optimization levels perform more global transformations on the |
| 1641 |
program and apply more expensive analysis algorithms in order to generate |
| 1642 |
faster and more compact code. The price in compilation time, and the |
| 1643 |
resulting improvement in execution time, both depend on the particular |
| 1644 |
application and the hardware environment. You should experiment to find |
| 1645 |
the best level for your application. |
| 1646 |
|
| 1647 |
Since the precise set of optimizations done at each level will vary from |
| 1648 |
release to release (and sometime from target to target), it is best to think |
| 1649 |
of the optimization settings in general terms. |
| 1650 |
See the *Options That Control Optimization* section in |
| 1651 |
:title:`Using the GNU Compiler Collection (GCC)` |
| 1652 |
for details about |
| 1653 |
the :switch:`-O` settings and a number of :switch:`-f` switches that |
| 1654 |
individually enable or disable specific optimizations. |
| 1655 |
|
| 1656 |
Unlike some other compilation systems, GCC has |
| 1657 |
been tested extensively at all optimization levels. There are some bugs |
| 1658 |
which appear only with optimization turned on, but there have also been |
| 1659 |
bugs which show up only in *unoptimized* code. Selecting a lower |
| 1660 |
level of optimization does not improve the reliability of the code |
| 1661 |
generator, which in practice is highly reliable at all optimization |
| 1662 |
levels. |
| 1663 |
|
| 1664 |
A note regarding the use of :switch:`-O3`: The use of this optimization level |
| 1665 |
ought not to be automatically preferred over that of level :switch:`-O2`, |
| 1666 |
since it often results in larger executables which may run more slowly. |
| 1667 |
See further discussion of this point in :ref:`Inlining_of_Subprograms`. |
| 1668 |
|
| 1669 |
|
| 1670 |
.. _Debugging_Optimized_Code: |
| 1671 |
|
| 1672 |
Debugging Optimized Code |
| 1673 |
^^^^^^^^^^^^^^^^^^^^^^^^ |
| 1674 |
|
| 1675 |
.. index:: Debugging optimized code |
| 1676 |
.. index:: Optimization and debugging |
| 1677 |
|
| 1678 |
Although it is possible to do a reasonable amount of debugging at |
| 1679 |
nonzero optimization levels, |
| 1680 |
the higher the level the more likely that |
| 1681 |
source-level constructs will have been eliminated by optimization. |
| 1682 |
For example, if a loop is strength-reduced, the loop |
| 1683 |
control variable may be completely eliminated and thus cannot be |
| 1684 |
displayed in the debugger. |
| 1685 |
This can only happen at :switch:`-O2` or :switch:`-O3`. |
| 1686 |
Explicit temporary variables that you code might be eliminated at |
| 1687 |
level :switch:`-O1` or higher. |
| 1688 |
|
| 1689 |
.. index:: -g (gcc) |
| 1690 |
|
| 1691 |
The use of the :switch:`-g` switch, |
| 1692 |
which is needed for source-level debugging, |
| 1693 |
affects the size of the program executable on disk, |
| 1694 |
and indeed the debugging information can be quite large. |
| 1695 |
However, it has no effect on the generated code (and thus does not |
| 1696 |
degrade performance) |
| 1697 |
|
| 1698 |
Since the compiler generates debugging tables for a compilation unit before |
| 1699 |
it performs optimizations, the optimizing transformations may invalidate some |
| 1700 |
of the debugging data. You therefore need to anticipate certain |
| 1701 |
anomalous situations that may arise while debugging optimized code. |
| 1702 |
These are the most common cases: |
| 1703 |
|
| 1704 |
* *The 'hopping Program Counter':* Repeated ``step`` or ``next`` |
| 1705 |
commands show |
| 1706 |
the PC bouncing back and forth in the code. This may result from any of |
| 1707 |
the following optimizations: |
| 1708 |
|
| 1709 |
- *Common subexpression elimination:* using a single instance of code for a |
| 1710 |
quantity that the source computes several times. As a result you |
| 1711 |
may not be able to stop on what looks like a statement. |
| 1712 |
|
| 1713 |
- *Invariant code motion:* moving an expression that does not change within a |
| 1714 |
loop to the beginning of the loop. |
| 1715 |
|
| 1716 |
- *Instruction scheduling:* moving instructions so as to |
| 1717 |
overlap loads and stores (typically) with other code or in |
| 1718 |
general to move computations of values closer to their uses. Often |
| 1719 |
this causes you to pass an assignment statement without the assignment |
| 1720 |
happening and then later bounce back to the statement when the |
| 1721 |
value is actually needed. Placing a breakpoint on a line of code |
| 1722 |
and then stepping over it may, therefore, not always cause all the |
| 1723 |
expected side-effects. |
| 1724 |
|
| 1725 |
* *The 'big leap':* More commonly known as *cross-jumping*, in which |
| 1726 |
two identical pieces of code are merged and the program counter suddenly |
| 1727 |
jumps to a statement that is not supposed to be executed, simply because |
| 1728 |
it (and the code following) translates to the same thing as the code |
| 1729 |
that *was* supposed to be executed. This effect is typically seen in |
| 1730 |
sequences that end in a jump, such as a ``goto``, a ``return``, or |
| 1731 |
a ``break`` in a C ``switch`` statement. |
| 1732 |
|
| 1733 |
* *The 'roving variable':* The symptom is an unexpected value in a variable. |
| 1734 |
There are various reasons for this effect: |
| 1735 |
|
| 1736 |
- In a subprogram prologue, a parameter may not yet have been moved to its |
| 1737 |
'home'. |
| 1738 |
|
| 1739 |
- A variable may be dead and its register re-used. This is |
| 1740 |
probably the most common cause. |
| 1741 |
|
| 1742 |
- As mentioned above, the assignment of a value to a variable may |
| 1743 |
have been moved. |
| 1744 |
|
| 1745 |
- A variable may be eliminated entirely by value propagation or |
| 1746 |
other means. In this case, GCC may incorrectly generate debugging |
| 1747 |
information for the variable |
| 1748 |
|
| 1749 |
In general, when an unexpected value appears for a local variable or parameter |
| 1750 |
you should first ascertain if that value was actually computed by |
| 1751 |
your program as opposed to being incorrectly reported by the debugger. |
| 1752 |
Record fields or |
| 1753 |
array elements in an object designated by an access value |
| 1754 |
are generally less of a problem once you have verified that the access |
| 1755 |
value is sensible. |
| 1756 |
Typically, this means checking variables in the preceding code and in the |
| 1757 |
calling subprogram to verify that the value observed is explainable from other |
| 1758 |
values (you must apply the procedure recursively to those |
| 1759 |
other values); or re-running the code and stopping a little earlier |
| 1760 |
(perhaps before the call) and stepping to better see how the variable obtained |
| 1761 |
the value in question; or continuing to step *from* the point of the |
| 1762 |
strange value to see if code motion had simply moved the variable's |
| 1763 |
assignments later. |
| 1764 |
|
| 1765 |
In light of such anomalies, a recommended technique is to use :switch:`-O0` |
| 1766 |
early in the software development cycle, when extensive debugging capabilities |
| 1767 |
are most needed, and then move to :switch:`-O1` and later :switch:`-O2` as |
| 1768 |
the debugger becomes less critical. |
| 1769 |
Whether to use the :switch:`-g` switch in the release version is |
| 1770 |
a release management issue. |
| 1771 |
Note that if you use :switch:`-g` you can then use the ``strip`` program |
| 1772 |
on the resulting executable, |
| 1773 |
which removes both debugging information and global symbols. |
| 1774 |
|
| 1775 |
|
| 1776 |
.. _Inlining_of_Subprograms: |
| 1777 |
|
| 1778 |
Inlining of Subprograms |
| 1779 |
^^^^^^^^^^^^^^^^^^^^^^^ |
| 1780 |
|
| 1781 |
A call to a subprogram in the current unit is inlined if all the |
| 1782 |
following conditions are met: |
| 1783 |
|
| 1784 |
* The optimization level is at least :switch:`-O1`. |
| 1785 |
|
| 1786 |
* The called subprogram is suitable for inlining: it must be small enough |
| 1787 |
and not contain something that the back end cannot support in inlined |
| 1788 |
subprograms. |
| 1789 |
|
| 1790 |
.. index:: pragma Inline |
| 1791 |
.. index:: Inline |
| 1792 |
|
| 1793 |
* Any one of the following applies: ``pragma Inline`` is applied to the |
| 1794 |
subprogram; the subprogram is local to the unit and called once from |
| 1795 |
within it; the subprogram is small and optimization level :switch:`-O2` is |
| 1796 |
specified; optimization level :switch:`-O3` is specified; or the subprogram |
| 1797 |
is an expression function. |
| 1798 |
|
| 1799 |
Calls to subprograms in |withed| units are normally not inlined. |
| 1800 |
To achieve inlining in those case (that is, replacement of the call by the code |
| 1801 |
in the body of the subprogram), the following conditions must all be true: |
| 1802 |
|
| 1803 |
* The optimization level is at least :switch:`-O1`. |
| 1804 |
|
| 1805 |
* The called subprogram is suitable for inlining: It must be small enough |
| 1806 |
and not contain something that the back end cannot support in inlined |
| 1807 |
subprograms. |
| 1808 |
|
| 1809 |
* There is a ``pragma Inline`` for the subprogram. |
| 1810 |
|
| 1811 |
* The :switch:`-gnatn` switch is used on the command line. |
| 1812 |
|
| 1813 |
Even if all these conditions are met, it may not be possible for |
| 1814 |
the compiler to inline the call due to the length of the body, |
| 1815 |
or features in the body that make it impossible for the compiler |
| 1816 |
to do the inlining. |
| 1817 |
|
| 1818 |
Note that specifying the :switch:`-gnatn` switch causes additional |
| 1819 |
compilation dependencies. Consider the following: |
| 1820 |
|
| 1821 |
.. code-block:: ada |
| 1822 |
|
| 1823 |
package R is |
| 1824 |
procedure Q; |
| 1825 |
pragma Inline (Q); |
| 1826 |
end R; |
| 1827 |
package body R is |
| 1828 |
... |
| 1829 |
end R; |
| 1830 |
|
| 1831 |
with R; |
| 1832 |
procedure Main is |
| 1833 |
begin |
| 1834 |
... |
| 1835 |
R.Q; |
| 1836 |
end Main; |
| 1837 |
|
| 1838 |
With the default behavior (no :switch:`-gnatn` switch specified), the |
| 1839 |
compilation of the ``Main`` procedure depends only on its own source, |
| 1840 |
:file:`main.adb`, and the spec of the package in file :file:`r.ads`. This |
| 1841 |
means that editing the body of ``R`` does not require recompiling |
| 1842 |
``Main``. |
| 1843 |
|
| 1844 |
On the other hand, the call ``R.Q`` is not inlined under these |
| 1845 |
circumstances. If the :switch:`-gnatn` switch is present when ``Main`` |
| 1846 |
is compiled, the call will be inlined if the body of ``Q`` is small |
| 1847 |
enough, but now ``Main`` depends on the body of ``R`` in |
| 1848 |
:file:`r.adb` as well as on the spec. This means that if this body is edited, |
| 1849 |
the main program must be recompiled. Note that this extra dependency |
| 1850 |
occurs whether or not the call is in fact inlined by the back end. |
| 1851 |
|
| 1852 |
The use of front end inlining with :switch:`-gnatN` generates similar |
| 1853 |
additional dependencies. |
| 1854 |
|
| 1855 |
.. index:: -fno-inline (gcc) |
| 1856 |
|
| 1857 |
Note: The :switch:`-fno-inline` switch overrides all other conditions |
| 1858 |
and ensures that no inlining occurs, unless requested with pragma |
| 1859 |
Inline_Always for most back ends. The extra dependences resulting from |
| 1860 |
:switch:`-gnatn` will still be active, even if this switch is used to |
| 1861 |
suppress the resulting inlining actions. |
| 1862 |
|
| 1863 |
.. index:: -fno-inline-functions (gcc) |
| 1864 |
|
| 1865 |
For the GCC back end, you can use the |
| 1866 |
:switch:`-fno-inline-functions` switch to prevent automatic inlining |
| 1867 |
of subprograms if you use :switch:`-O3`. |
| 1868 |
|
| 1869 |
.. index:: -fno-inline-small-functions (gcc) |
| 1870 |
|
| 1871 |
For the GCC back end, you can use the |
| 1872 |
:switch:`-fno-inline-small-functions` switch to prevent automatic |
| 1873 |
inlining of small subprograms if you use :switch:`-O2`. |
| 1874 |
|
| 1875 |
.. index:: -fno-inline-functions-called-once (gcc) |
| 1876 |
|
| 1877 |
For the GC back end, you can use the |
| 1878 |
:switch:`-fno-inline-functions-called-once` switch to prevent inlining |
| 1879 |
of subprograms local to the unit and called once from within it if you |
| 1880 |
use :switch:`-O1`. |
| 1881 |
|
| 1882 |
A note regarding the use of :switch:`-O3`: :switch:`-gnatn` is made up of two |
| 1883 |
sub-switches :switch:`-gnatn1` and :switch:`-gnatn2` that you can directly |
| 1884 |
specify. :switch:`-gnatn` is translated into one of them |
| 1885 |
based on the optimization level. With :switch:`-O2` or below, :switch:`-gnatn` |
| 1886 |
is equivalent to :switch:`-gnatn1` which activates pragma ``Inline`` with |
| 1887 |
moderate inlining across modules. With :switch:`-O3`, :switch:`-gnatn` is |
| 1888 |
equivalent to :switch:`-gnatn2` which activates pragma ``Inline`` with |
| 1889 |
full inlining across modules. If you have used pragma ``Inline`` in |
| 1890 |
appropriate cases, it's usually much better to use :switch:`-O2` |
| 1891 |
and :switch:`-gnatn` and avoid the use of :switch:`-O3` which has the additional |
| 1892 |
effect of inlining subprograms you did not think should be inlined. We have |
| 1893 |
found that the use of :switch:`-O3` may slow down the compilation and increase |
| 1894 |
the code size by performing excessive inlining, leading to increased |
| 1895 |
instruction cache pressure from the increased code size and thus minor |
| 1896 |
performance degradations. So the bottom line here is that you should not |
| 1897 |
automatically assume that :switch:`-O3` is better than :switch:`-O2` and |
| 1898 |
indeed you should use :switch:`-O3` only if tests show that it actually |
| 1899 |
improves performance for your program. |
| 1900 |
|
| 1901 |
.. _Floating_Point_Operations: |
| 1902 |
|
| 1903 |
Floating Point Operations |
| 1904 |
^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 1905 |
|
| 1906 |
.. index:: Floating-Point Operations |
| 1907 |
|
| 1908 |
On almost all targets, GNAT maps ``Float`` and ``Long_Float`` to the 32-bit and |
| 1909 |
64-bit standard IEEE floating-point representations and operations will |
| 1910 |
use standard IEEE arithmetic as provided by the processor. On most, but |
| 1911 |
not all, architectures, the attribute ``Machine_Overflows`` is ``False`` for these |
| 1912 |
types, meaning that the semantics of overflow is implementation-defined. |
| 1913 |
In the case of GNAT, these semantics correspond to the normal IEEE |
| 1914 |
treatment of infinities and NaN (not a number) values. For example, |
| 1915 |
1.0 / 0.0 yields plus infinitiy and 0.0 / 0.0 yields a NaN. By |
| 1916 |
avoiding explicit overflow checks, the performance is greatly improved |
| 1917 |
on many targets. However, if required, you can enable floating-point overflow |
| 1918 |
by using the pragma ``Check_Float_Overflow``. |
| 1919 |
|
| 1920 |
Another consideration that applies specifically to x86 32-bit |
| 1921 |
architectures is which form of floating-point arithmetic is used. |
| 1922 |
By default, the operations use the old style x86 floating-point, |
| 1923 |
which implements an 80-bit extended precision form (on these |
| 1924 |
architectures the type ``Long_Long_Float`` corresponds to that form). |
| 1925 |
In addition, generation of efficient code in this mode means that |
| 1926 |
the extended precision form is used for intermediate results. |
| 1927 |
This may be helpful in improving the final precision of a complex |
| 1928 |
expression, but it means that the results obtained on the x86 |
| 1929 |
may be different from those on other architectures and, for some |
| 1930 |
algorithms, the extra intermediate precision can be detrimental. |
| 1931 |
|
| 1932 |
In addition to this old-style floating-point, all modern x86 chips |
| 1933 |
implement an alternative floating-point operation model referred |
| 1934 |
to as SSE2. In this model, there is no extended form and |
| 1935 |
execution performance is significantly enhanced. To force GNAT to use |
| 1936 |
this more modern form, use both of the switches: |
| 1937 |
|
| 1938 |
-msse2 -mfpmath=sse |
| 1939 |
|
| 1940 |
A unit compiled with these switches will automatically use the more |
| 1941 |
efficient SSE2 instruction set for ``Float`` and ``Long_Float`` operations. |
| 1942 |
Note that the ABI has the same form for both floating-point models, |
| 1943 |
so you can mix units compiled with and without these switches. |
| 1944 |
|
| 1945 |
|
| 1946 |
|
| 1947 |
|
| 1948 |
|
| 1949 |
.. _Vectorization_of_loops: |
| 1950 |
|
| 1951 |
Vectorization of loops |
| 1952 |
^^^^^^^^^^^^^^^^^^^^^^ |
| 1953 |
|
| 1954 |
.. index:: Optimization Switches |
| 1955 |
|
| 1956 |
The GCC and LLVM back ends have an auto-vectorizer that's enabled by |
| 1957 |
default at some optimization levels. For the GCC back end, it's |
| 1958 |
enabled by default at :switch:`-O3` and you can request it at other |
| 1959 |
levels with :switch:`-ftree-vectorize`. For the LLVM back end, it's |
| 1960 |
enabled by default at lower levels, but you can explicitly enable or |
| 1961 |
disable it with the :switch:`-fno-vectorize`, :switch:`-fvectorize`, |
| 1962 |
:switch:`-fno-slp-vectorize`, and :switch:`-fslp-vectorize` switches. |
| 1963 |
|
| 1964 |
To get auto-vectorization, you also need to make sure that the target |
| 1965 |
architecture features a supported SIMD instruction set. For example, |
| 1966 |
for the x86 architecture, you should at least specify :switch:`-msse2` |
| 1967 |
to get significant vectorization (but you don't need to specify it for |
| 1968 |
x86-64 as it is part of the base 64-bit architecture). Similarly, for |
| 1969 |
the PowerPC architecture, you should specify :switch:`-maltivec`. |
| 1970 |
|
| 1971 |
The preferred loop form for vectorization is the ``for`` iteration scheme. |
| 1972 |
Loops with a ``while`` iteration scheme can also be vectorized if they are |
| 1973 |
very simple, but the vectorizer will quickly give up otherwise. With either |
| 1974 |
iteration scheme, the flow of control must be straight, in particular no |
| 1975 |
``exit`` statement may appear in the loop body. The loop may however |
| 1976 |
contain a single nested loop, if it can be vectorized when considered alone: |
| 1977 |
|
| 1978 |
.. code-block:: ada |
| 1979 |
|
| 1980 |
A : array (1..4, 1..4) of Long_Float; |
| 1981 |
S : array (1..4) of Long_Float; |
| 1982 |
|
| 1983 |
procedure Sum is |
| 1984 |
begin |
| 1985 |
for I in A'Range(1) loop |
| 1986 |
for J in A'Range(2) loop |
| 1987 |
S (I) := S (I) + A (I, J); |
| 1988 |
end loop; |
| 1989 |
end loop; |
| 1990 |
end Sum; |
| 1991 |
|
| 1992 |
The vectorizable operations depend on the targeted SIMD instruction set, but |
| 1993 |
addition and some multiplication operators are generally supported, as |
| 1994 |
well as the logical operators for modular types. Note that compiling |
| 1995 |
with :switch:`-gnatp` might well reveal cases where some checks do thwart |
| 1996 |
vectorization. |
| 1997 |
|
| 1998 |
Type conversions may also prevent vectorization if they involve semantics that |
| 1999 |
are not directly supported by the code generator or the SIMD instruction set. |
| 2000 |
A typical example is direct conversion from floating-point to integer types. |
| 2001 |
The solution in this case is to use the following idiom: |
| 2002 |
|
| 2003 |
.. code-block:: ada |
| 2004 |
|
| 2005 |
Integer (S'Truncation (F)) |
| 2006 |
|
| 2007 |
if ``S`` is the subtype of floating-point object ``F``. |
| 2008 |
|
| 2009 |
In most cases, the vectorizable loops are loops that iterate over arrays. |
| 2010 |
All kinds of array types are supported, i.e. constrained array types with |
| 2011 |
static bounds: |
| 2012 |
|
| 2013 |
.. code-block:: ada |
| 2014 |
|
| 2015 |
type Array_Type is array (1 .. 4) of Long_Float; |
| 2016 |
|
| 2017 |
constrained array types with dynamic bounds: |
| 2018 |
|
| 2019 |
|
| 2020 |
.. code-block:: ada |
| 2021 |
|
| 2022 |
type Array_Type is array (1 .. Q.N) of Long_Float; |
| 2023 |
|
| 2024 |
type Array_Type is array (Q.K .. 4) of Long_Float; |
| 2025 |
|
| 2026 |
type Array_Type is array (Q.K .. Q.N) of Long_Float; |
| 2027 |
|
| 2028 |
or unconstrained array types: |
| 2029 |
|
| 2030 |
.. code-block:: ada |
| 2031 |
|
| 2032 |
type Array_Type is array (Positive range <>) of Long_Float; |
| 2033 |
|
| 2034 |
The quality of the generated code decreases when the dynamic aspect of the |
| 2035 |
array type increases, the worst code being generated for unconstrained array |
| 2036 |
types. This is because the less information the compiler has about the |
| 2037 |
bounds of the array, the more fallback code it needs to generate in order to |
| 2038 |
fix things up at run time. |
| 2039 |
|
| 2040 |
You can specify that a given loop should be subject to vectorization |
| 2041 |
preferably to other optimizations by means of pragma ``Loop_Optimize``: |
| 2042 |
|
| 2043 |
.. code-block:: ada |
| 2044 |
|
| 2045 |
pragma Loop_Optimize (Vector); |
| 2046 |
|
| 2047 |
placed immediately within the loop will convey the appropriate hint to the |
| 2048 |
compiler for this loop. This is currently only supported for the GCC |
| 2049 |
back end. |
| 2050 |
|
| 2051 |
You can also help the compiler generate better vectorized code |
| 2052 |
for a given loop by asserting that there are no loop-carried dependencies |
| 2053 |
in the loop. Consider for example the procedure: |
| 2054 |
|
| 2055 |
.. code-block:: ada |
| 2056 |
|
| 2057 |
type Arr is array (1 .. 4) of Long_Float; |
| 2058 |
|
| 2059 |
procedure Add (X, Y : not null access Arr; R : not null access Arr) is |
| 2060 |
begin |
| 2061 |
for I in Arr'Range loop |
| 2062 |
R(I) := X(I) + Y(I); |
| 2063 |
end loop; |
| 2064 |
end; |
| 2065 |
|
| 2066 |
By default, the compiler cannot unconditionally vectorize the loop because |
| 2067 |
assigning to a component of the array designated by R in one iteration could |
| 2068 |
change the value read from the components of the array designated by X or Y |
| 2069 |
in a later iteration. As a result, the compiler will generate two versions |
| 2070 |
of the loop in the object code, one vectorized and the other not vectorized, |
| 2071 |
as well as a test to select the appropriate version at run time. This can |
| 2072 |
be overcome by another hint: |
| 2073 |
|
| 2074 |
.. code-block:: ada |
| 2075 |
|
| 2076 |
pragma Loop_Optimize (Ivdep); |
| 2077 |
|
| 2078 |
placed immediately within the loop will tell the compiler that it can safely |
| 2079 |
omit the non-vectorized version of the loop as well as the run-time test. |
| 2080 |
This is also currently only supported by the GCC back end. |
| 2081 |
|
| 2082 |
|
| 2083 |
.. _Other_Optimization_Switches: |
| 2084 |
|
| 2085 |
Other Optimization Switches |
| 2086 |
^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 2087 |
|
| 2088 |
.. index:: Optimization Switches |
| 2089 |
|
| 2090 |
You can also use any specialized optimization switches supported by |
| 2091 |
the back end being used. These switches have not been extensively |
| 2092 |
tested with GNAT but can generally be expected to work. Examples of |
| 2093 |
switches in this category for the GCC back end are |
| 2094 |
:switch:`-funroll-loops` and the various target-specific :switch:`-m` |
| 2095 |
options (in particular, it has been observed that :switch:`-march=xxx` |
| 2096 |
can significantly improve performance on appropriate machines). For |
| 2097 |
full details of these switches, see the *Submodel Options* section in |
| 2098 |
the *Hardware Models and Configurations* chapter of :title:`Using the |
| 2099 |
GNU Compiler Collection (GCC)`. |
| 2100 |
|
| 2101 |
|
| 2102 |
.. _Optimization_and_Strict_Aliasing: |
| 2103 |
|
| 2104 |
Optimization and Strict Aliasing |
| 2105 |
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 2106 |
|
| 2107 |
.. index:: Aliasing |
| 2108 |
.. index:: Strict Aliasing |
| 2109 |
.. index:: No_Strict_Aliasing |
| 2110 |
|
| 2111 |
The strong typing capabilities of Ada allow an optimizer to generate |
| 2112 |
efficient code in situations where other languages would be forced to |
| 2113 |
make worst case assumptions preventing such optimizations. Consider |
| 2114 |
the following example: |
| 2115 |
|
| 2116 |
.. code-block:: ada |
| 2117 |
|
| 2118 |
procedure M is |
| 2119 |
type Int1 is new Integer; |
| 2120 |
I1 : Int1; |
| 2121 |
|
| 2122 |
type Int2 is new Integer; |
| 2123 |
type A2 is access Int2; |
| 2124 |
V2 : A2; |
| 2125 |
... |
| 2126 |
|
| 2127 |
begin |
| 2128 |
... |
| 2129 |
for J in Data'Range loop |
| 2130 |
if Data (J) = I1 then |
| 2131 |
V2.all := V2.all + 1; |
| 2132 |
end if; |
| 2133 |
end loop; |
| 2134 |
... |
| 2135 |
end; |
| 2136 |
|
| 2137 |
Here, since ``V2`` can only access objects of type ``Int2`` |
| 2138 |
and ``I1`` is not one of them, there is no possibility that the assignment |
| 2139 |
to ``V2.all`` affects the value of ``I1``. This means that the compiler |
| 2140 |
optimizer can infer that the value ``I1`` is constant for all iterations |
| 2141 |
of the loop and load it from memory only once, before entering the loop, |
| 2142 |
instead of in every iteration (this is called load hoisting). |
| 2143 |
|
| 2144 |
This kind of optimizations, based on strict type-based aliasing, is |
| 2145 |
triggered by specifying an optimization level of :switch:`-O2` or |
| 2146 |
higher (or :switch:`-Os`) for the GCC back end and :switch:`-O1` or |
| 2147 |
higher for the LLVM back end and allows the compiler to generate more |
| 2148 |
efficient code. |
| 2149 |
|
| 2150 |
However, although this optimization is always correct in terms of the |
| 2151 |
formal semantics of the Ada Reference Manual, you can run into |
| 2152 |
difficulties arise if you use features like ``Unchecked_Conversion`` |
| 2153 |
to break the typing system. Consider the following complete program |
| 2154 |
example: |
| 2155 |
|
| 2156 |
.. code-block:: ada |
| 2157 |
|
| 2158 |
package P1 is |
| 2159 |
type Int1 is new Integer; |
| 2160 |
type A1 is access Int1; |
| 2161 |
|
| 2162 |
type Int2 is new Integer; |
| 2163 |
type A2 is access Int2; |
| 2164 |
end P1; |
| 2165 |
|
| 2166 |
with P1; use P1; |
| 2167 |
package P2 is |
| 2168 |
function To_A2 (Input : A1) return A2; |
| 2169 |
end p2; |
| 2170 |
|
| 2171 |
with Ada.Unchecked_Conversion; |
| 2172 |
package body P2 is |
| 2173 |
function To_A2 (Input : A1) return A2 is |
| 2174 |
function Conv is |
| 2175 |
new Ada.Unchecked_Conversion (A1, A2); |
| 2176 |
begin |
| 2177 |
return Conv (Input); |
| 2178 |
end To_A2; |
| 2179 |
end P2; |
| 2180 |
|
| 2181 |
with P1; use P1; |
| 2182 |
with P2; use P2; |
| 2183 |
with Text_IO; use Text_IO; |
| 2184 |
procedure M is |
| 2185 |
V1 : A1 := new Int1; |
| 2186 |
V2 : A2 := To_A2 (V1); |
| 2187 |
begin |
| 2188 |
V1.all := 1; |
| 2189 |
V2.all := 0; |
| 2190 |
Put_Line (Int1'Image (V1.all)); |
| 2191 |
end; |
| 2192 |
|
| 2193 |
This program prints out ``0`` in :switch:`-O0` mode, |
| 2194 |
but it prints out ``1`` in :switch:`-O2` mode. That's because in strict |
| 2195 |
aliasing mode, the compiler may and does assume that the assignment to |
| 2196 |
``V2.all`` could not affect the value of ``V1.all``, since different |
| 2197 |
types are involved. |
| 2198 |
|
| 2199 |
This behavior is not a case of non-conformance with the standard, since |
| 2200 |
the Ada RM specifies that an unchecked conversion where the resulting |
| 2201 |
bit pattern is not a correct value of the target type can result in an |
| 2202 |
abnormal value and attempting to reference an abnormal value makes the |
| 2203 |
execution of a program erroneous. That's the case here since the result |
| 2204 |
does not point to an object of type ``Int2``. This means that the effect |
| 2205 |
is entirely unpredictable. |
| 2206 |
|
| 2207 |
However, although that explanation may satisfy a language lawyer, in |
| 2208 |
practice, you probably expect an unchecked conversion |
| 2209 |
involving pointers to create true aliases and the behavior of printing |
| 2210 |
``1`` is questionable. In this case, the strict type-based aliasing |
| 2211 |
optimizations are clearly unwelcome. |
| 2212 |
|
| 2213 |
Indeed, the compiler recognizes this possibility and the instantiation of |
| 2214 |
Unchecked_Conversion generates a warning: |
| 2215 |
|
| 2216 |
:: |
| 2217 |
|
| 2218 |
p2.adb:5:07: warning: possible aliasing problem with type "A2" |
| 2219 |
p2.adb:5:07: warning: use -fno-strict-aliasing switch for references |
| 2220 |
p2.adb:5:07: warning: or use "pragma No_Strict_Aliasing (A2);" |
| 2221 |
|
| 2222 |
Unfortunately the problem is only recognized when compiling the body of |
| 2223 |
package ``P2``, but the actual problematic code is generated while |
| 2224 |
compiling the body of ``M`` and this latter compilation does not see |
| 2225 |
the suspicious instance of ``Unchecked_Conversion``. |
| 2226 |
|
| 2227 |
As implied by the warning message, there are approaches you can use to |
| 2228 |
avoid the unwanted strict aliasing optimizations in a case like this. |
| 2229 |
|
| 2230 |
One possibility is to simply avoid the use of higher levels of optimization, |
| 2231 |
but that is quite drastic, since it throws away a number of useful |
| 2232 |
optimizations that don't involve strict aliasing assumptions. |
| 2233 |
|
| 2234 |
A less drastic approach is for you to compile the program using the |
| 2235 |
:switch:`-fno-strict-aliasing` switch. Actually, it is only the |
| 2236 |
unit containing the dereferencing of the suspicious pointer |
| 2237 |
that you need to compile with that switch. So, in this case, if you compile |
| 2238 |
unit ``M`` with this switch, you get the expected |
| 2239 |
value of ``0`` printed. Analyzing which units might need |
| 2240 |
the switch can be painful, so you may find it a more reasonable approach |
| 2241 |
is to compile the entire program with options :switch:`-O2` |
| 2242 |
and :switch:`-fno-strict-aliasing`. If you obtain satisfactory performance |
| 2243 |
with this combination of options, then the |
| 2244 |
advantage is that you have avoided the entire issue of possible problematic |
| 2245 |
optimizations due to strict aliasing. |
| 2246 |
|
| 2247 |
To avoid the use of compiler switches, you may use the configuration |
| 2248 |
pragma ``No_Strict_Aliasing`` with no parameters |
| 2249 |
to specify that for all access types, the strict |
| 2250 |
aliasing optimizations should be suppressed. |
| 2251 |
|
| 2252 |
However, these approaches are still overkill, in that they cause |
| 2253 |
all manipulations of all access values to be deoptimized. A more |
| 2254 |
refined approach is to concentrate attention on the specific |
| 2255 |
access type identified as problematic. |
| 2256 |
|
| 2257 |
The first possibility is to move the instantiation of unchecked |
| 2258 |
conversion to the unit in which the type is declared. In this |
| 2259 |
example, you would move the instantiation of ``Unchecked_Conversion`` |
| 2260 |
from the body of package ``P2`` to the spec of package ``P1``. |
| 2261 |
Now, the warning disappears because any use of the access type |
| 2262 |
knows there is a suspicious unchecked conversion and the strict |
| 2263 |
aliasing optimizations are automatically suppressed for it. |
| 2264 |
|
| 2265 |
If it's not practical to move the unchecked conversion to the same unit |
| 2266 |
in which the destination access type is declared (perhaps because the |
| 2267 |
source type is not visible in that unit), the second possibiliy is for you to |
| 2268 |
use pragma ``No_Strict_Aliasing`` for the type. You must place this pragma |
| 2269 |
in the same declarative part as the declaration of the access type: |
| 2270 |
|
| 2271 |
.. code-block:: ada |
| 2272 |
|
| 2273 |
type A2 is access Int2; |
| 2274 |
pragma No_Strict_Aliasing (A2); |
| 2275 |
|
| 2276 |
Here again, the compiler now knows that strict aliasing optimizations |
| 2277 |
should be suppressed for any dereference made through type ``A2`` and |
| 2278 |
the expected behavior is obtained. |
| 2279 |
|
| 2280 |
The third possibility is to declare that one of the designated types |
| 2281 |
involved, namely ``Int1`` or ``Int2``, is allowed to alias any other |
| 2282 |
type in the universe, by using pragma ``Universal_Aliasing``: |
| 2283 |
|
| 2284 |
.. code-block:: ada |
| 2285 |
|
| 2286 |
type Int2 is new Integer; |
| 2287 |
pragma Universal_Aliasing (Int2); |
| 2288 |
|
| 2289 |
The effect is equivalent to applying pragma ``No_Strict_Aliasing`` to |
| 2290 |
every access type designating ``Int2``, in particular ``A2``, and, more |
| 2291 |
generally, to every reference made to an object of declared type ``Int2``, |
| 2292 |
so it's very powerful and effectively takes ``Int2`` out of the alias |
| 2293 |
analysis performed by the compiler in all circumstances. |
| 2294 |
|
| 2295 |
You can also use this pragma used to deal with aliasing issues that arise |
| 2296 |
from the use of ``Unchecked_Conversion`` in the source code but |
| 2297 |
without the presence of access types. The typical example is code |
| 2298 |
that streams data by means of arrays of storage units (bytes): |
| 2299 |
|
| 2300 |
.. code-block:: ada |
| 2301 |
|
| 2302 |
type Byte is mod 2**System.Storage_Unit; |
| 2303 |
for Byte'Size use System.Storage_Unit; |
| 2304 |
|
| 2305 |
type Chunk_Of_Bytes is array (1 .. 64) of Byte; |
| 2306 |
|
| 2307 |
procedure Send (S : Chunk_Of_Bytes); |
| 2308 |
|
| 2309 |
type Rec is record |
| 2310 |
... |
| 2311 |
end record; |
| 2312 |
|
| 2313 |
procedure Dump (R : Rec) is |
| 2314 |
function To_Stream is |
| 2315 |
new Ada.Unchecked_Conversion (Rec, Chunk_Of_Bytes); |
| 2316 |
begin |
| 2317 |
Send (To_Stream (R)); |
| 2318 |
end; |
| 2319 |
|
| 2320 |
This generates the following warning for the call to ``Send``: |
| 2321 |
|
| 2322 |
:: |
| 2323 |
|
| 2324 |
dump.adb:8:25: warning: unchecked conversion implemented by copy |
| 2325 |
dump.adb:8:25: warning: use pragma Universal_Aliasing on either type |
| 2326 |
dump.adb:8:25: warning: to enable RM 13.9(12) implementation permission |
| 2327 |
|
| 2328 |
This occurs because the formal parameter ``S`` of ``Send`` is passed by |
| 2329 |
reference by the compiler and it's not possible to pass a reference to |
| 2330 |
``R`` directly in the call without violating strict type-based aliasing. |
| 2331 |
That's why the compiler generates a temporary of type ``Chunk_Of_Bytes`` |
| 2332 |
just before the call and passes a reference to this temporary instead. |
| 2333 |
|
| 2334 |
As implied by the warning message, you can avoid the temporary |
| 2335 |
(and the warning) by means of pragma ``Universal_Aliasing``: |
| 2336 |
|
| 2337 |
.. code-block:: ada |
| 2338 |
|
| 2339 |
type Chunk_Of_Bytes is array (1 .. 64) of Byte; |
| 2340 |
pragma Universal_Aliasing (Chunk_Of_Bytes); |
| 2341 |
|
| 2342 |
You can also apply this pragma to the component type instead: |
| 2343 |
|
| 2344 |
.. code-block:: ada |
| 2345 |
|
| 2346 |
type Byte is mod 2**System.Storage_Unit; |
| 2347 |
for Byte'Size use System.Storage_Unit; |
| 2348 |
pragma Universal_Aliasing (Byte); |
| 2349 |
|
| 2350 |
and every array type whose component is ``Byte`` will inherit the pragma. |
| 2351 |
|
| 2352 |
To summarize, the alias analysis performed in strict aliasing mode by |
| 2353 |
the compiler can have significant benefits. We've seen cases of large |
| 2354 |
scale application code where the execution time is increased by up to |
| 2355 |
5% when these optimizations are turned off. However, if you have code |
| 2356 |
that make significant use of unchecked conversion, you might want to |
| 2357 |
just stick with :switch:`-O1` (with the GCC back end) and avoid the |
| 2358 |
entire issue. If you get adequate performance at this level of |
| 2359 |
optimization, that's probably the safest approach. If tests show that |
| 2360 |
you really need higher levels of optimization, then you can experiment |
| 2361 |
with :switch:`-O2` and :switch:`-O2 -fno-strict-aliasing` to see how |
| 2362 |
much effect this has on size and speed of the code. If you really need |
| 2363 |
to use :switch:`-O2` with strict aliasing in effect, then you should |
| 2364 |
review any uses of unchecked conversion, particularly if you are |
| 2365 |
getting the warnings described above. |
| 2366 |
|
| 2367 |
|
| 2368 |
.. _Aliased_Variables_and_Optimization: |
| 2369 |
|
| 2370 |
Aliased Variables and Optimization |
| 2371 |
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 2372 |
|
| 2373 |
.. index:: Aliasing |
| 2374 |
|
| 2375 |
There are scenarios in which your programs may |
| 2376 |
use low level techniques to modify variables |
| 2377 |
that otherwise might be considered to be unassigned. For example, |
| 2378 |
you can pass a variable to a procedure by reference by taking |
| 2379 |
the address of the parameter and using that address to modify the |
| 2380 |
variable's value, even though the address is passed as an ``in`` parameter. |
| 2381 |
Consider the following example: |
| 2382 |
|
| 2383 |
.. code-block:: ada |
| 2384 |
|
| 2385 |
procedure P is |
| 2386 |
Max_Length : constant Natural := 16; |
| 2387 |
type Char_Ptr is access all Character; |
| 2388 |
|
| 2389 |
procedure Get_String(Buffer: Char_Ptr; Size : Integer); |
| 2390 |
pragma Import (C, Get_String, "get_string"); |
| 2391 |
|
| 2392 |
Name : aliased String (1 .. Max_Length) := (others => ' '); |
| 2393 |
Temp : Char_Ptr; |
| 2394 |
|
| 2395 |
function Addr (S : String) return Char_Ptr is |
| 2396 |
function To_Char_Ptr is |
| 2397 |
new Ada.Unchecked_Conversion (System.Address, Char_Ptr); |
| 2398 |
begin |
| 2399 |
return To_Char_Ptr (S (S'First)'Address); |
| 2400 |
end; |
| 2401 |
|
| 2402 |
begin |
| 2403 |
Temp := Addr (Name); |
| 2404 |
Get_String (Temp, Max_Length); |
| 2405 |
end; |
| 2406 |
|
| 2407 |
where Get_String is a C function that uses the address in ``Temp`` to |
| 2408 |
modify the variable ``Name``. This code is dubious, and arguably |
| 2409 |
erroneous, and the compiler is entitled to assume that |
| 2410 |
``Name`` is never modified, and generate code accordingly. |
| 2411 |
|
| 2412 |
However, in practice, this could cause some existing code that |
| 2413 |
seems to work with no optimization to start failing at higher |
| 2414 |
levels of optimization. |
| 2415 |
|
| 2416 |
What the compiler does for such cases, is to assume that marking a |
| 2417 |
variable as aliased indicates that some "funny business" may be going |
| 2418 |
on. The optimizer recognizes the ``aliased`` keyword and inhibits any |
| 2419 |
optimizations that assume the variable cannot be assigned to. This |
| 2420 |
means that the above example will in fact "work" reliably, that is, it |
| 2421 |
will produce the expected results. However, you should nevertheless |
| 2422 |
avoid code such as this if possible because it's not portable and may not |
| 2423 |
functin as you expect with all compilers. |
| 2424 |
|
| 2425 |
|
| 2426 |
.. _Atomic_Variables_and_Optimization: |
| 2427 |
|
| 2428 |
Atomic Variables and Optimization |
| 2429 |
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 2430 |
|
| 2431 |
.. index:: Atomic |
| 2432 |
|
| 2433 |
You need to take two things into consideration with regard to performance when |
| 2434 |
you use atomic variables. |
| 2435 |
|
| 2436 |
First, the RM only guarantees that access to atomic variables |
| 2437 |
be atomic, but has nothing to say about how this is achieved, |
| 2438 |
though there is a strong implication that this should not be |
| 2439 |
achieved by explicit locking code. Indeed, GNAT never |
| 2440 |
generates any locking code for atomic variable access; it will |
| 2441 |
simply reject any attempt to make a variable or type atomic |
| 2442 |
if the atomic access cannot be achieved without such locking code. |
| 2443 |
|
| 2444 |
That being said, it's important to understand that you cannot |
| 2445 |
assume the the program will always access the entire variable. Consider |
| 2446 |
this example: |
| 2447 |
|
| 2448 |
.. code-block:: ada |
| 2449 |
|
| 2450 |
type R is record |
| 2451 |
A,B,C,D : Character; |
| 2452 |
end record; |
| 2453 |
for R'Size use 32; |
| 2454 |
for R'Alignment use 4; |
| 2455 |
|
| 2456 |
RV : R; |
| 2457 |
pragma Atomic (RV); |
| 2458 |
X : Character; |
| 2459 |
... |
| 2460 |
X := RV.B; |
| 2461 |
|
| 2462 |
You cannot assume that the reference to ``RV.B`` |
| 2463 |
will read the entire 32-bit |
| 2464 |
variable with a single load instruction. It is perfectly legitimate, if |
| 2465 |
the hardware allows it, to do a byte read of just the ``B`` field. This read |
| 2466 |
is still atomic, which is all the RM requires. GNAT can and does take |
| 2467 |
advantage of this, depending on the architecture and optimization level. |
| 2468 |
Any assumption to the contrary is non-portable and risky. Even if you |
| 2469 |
examine the assembly language and see a full 32-bit load, this might |
| 2470 |
change in a future version of the compiler. |
| 2471 |
|
| 2472 |
If your application requires that all accesses to ``RV`` in this |
| 2473 |
example be full 32-bit loads, you need to make a copy for the access |
| 2474 |
as in: |
| 2475 |
|
| 2476 |
.. code-block:: ada |
| 2477 |
|
| 2478 |
declare |
| 2479 |
RV_Copy : constant R := RV; |
| 2480 |
begin |
| 2481 |
X := RV_Copy.B; |
| 2482 |
end; |
| 2483 |
|
| 2484 |
Now the reference to ``RV`` must read the whole variable. |
| 2485 |
Actually, one can imagine some compiler which figures |
| 2486 |
out that the whole copy is not required (because only |
| 2487 |
the ``B`` field is actually accessed), but GNAT |
| 2488 |
certainly won't do that, and we don't know of any |
| 2489 |
compiler that would not handle this right, and the |
| 2490 |
above code will in practice work portably across |
| 2491 |
all architectures (that permit the Atomic declaration). |
| 2492 |
|
| 2493 |
The second issue with atomic variables has to do with |
| 2494 |
the possible requirement of generating synchronization |
| 2495 |
code. For more details on this, consult the sections on |
| 2496 |
the pragmas Enable/Disable_Atomic_Synchronization in the |
| 2497 |
:title:``GNAT Reference Manual``. If performance is critical, and |
| 2498 |
such synchronization code is not required, you may find it |
| 2499 |
useful to disable it. |
| 2500 |
|
| 2501 |
|
| 2502 |
.. _Passive_Task_Optimization: |
| 2503 |
|
| 2504 |
Passive Task Optimization |
| 2505 |
^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 2506 |
|
| 2507 |
.. index:: Passive Task |
| 2508 |
|
| 2509 |
A passive task is one which is sufficiently simple that, |
| 2510 |
in theory, a compiler could recognize it and implement it |
| 2511 |
efficiently without creating a new thread. The original design |
| 2512 |
of Ada 83 had in mind this kind of passive task optimization, but |
| 2513 |
only a few Ada 83 compilers attempted it. The reason was that |
| 2514 |
it was difficult to determine the exact conditions under which |
| 2515 |
the optimization was possible. The result is a very fragile |
| 2516 |
optimization where a very minor change in the program can |
| 2517 |
suddenly silently make a task non-optimizable. |
| 2518 |
|
| 2519 |
With the revisiting of this issue in Ada 95, there was general |
| 2520 |
agreement that this approach was fundamentally flawed and the |
| 2521 |
notion of protected types was introduced. When using protected |
| 2522 |
types, the restrictions are well defined, you KNOW that the |
| 2523 |
operations will be optimized, and furthermore this optimized |
| 2524 |
performance is fully portable. |
| 2525 |
|
| 2526 |
Although it would theoretically be possible for GNAT to attempt to |
| 2527 |
do this optimization, it really doesn't make sense in the |
| 2528 |
context of Ada 95 and none of the Ada 95 compilers implement |
| 2529 |
this optimization as far as we know. GNAT never |
| 2530 |
attempts to perform this optimization. |
| 2531 |
|
| 2532 |
In any new Ada 95 code that you write, you should always |
| 2533 |
use protected types in place of tasks that might be able to |
| 2534 |
be optimized in this manner. |
| 2535 |
Of course, this does not help if you have legacy Ada 83 code |
| 2536 |
that depends on this optimization, but it is unusual to encounter |
| 2537 |
a case where the performance gains from this optimization |
| 2538 |
are significant. |
| 2539 |
|
| 2540 |
Your program should work correctly without this optimization. If |
| 2541 |
you have performance problems, the most practical |
| 2542 |
approach is to figure out exactly where these performance problems |
| 2543 |
arise and update those particular tasks to be protected types. Note |
| 2544 |
that typically clients of the tasks who call entries will not have |
| 2545 |
to be modified, only the task definitions themselves. |
| 2546 |
|
| 2547 |
|
| 2548 |
.. _Text_IO_Suggestions: |
| 2549 |
|
| 2550 |
``Text_IO`` Suggestions |
| 2551 |
----------------------- |
| 2552 |
|
| 2553 |
.. index:: Text_IO and performance |
| 2554 |
|
| 2555 |
The ``Ada.Text_IO`` package has fairly high overhead due in part to |
| 2556 |
the requirement of maintaining page and line counts. If performance |
| 2557 |
is critical, one recommendation is to use ``Stream_IO`` instead of |
| 2558 |
``Text_IO`` for large-volume output, since it has less overhead. |
| 2559 |
|
| 2560 |
If you must use ``Text_IO``, note that output to the standard output and |
| 2561 |
standard error files is unbuffered by default (this provides |
| 2562 |
better behavior when output statements are used for debugging or if |
| 2563 |
the progress of a program is observed by tracking the output, e.g. by |
| 2564 |
using the Unix *tail -f* command to watch redirected output). |
| 2565 |
|
| 2566 |
If you're generating large volumes of output with ``Text_IO`` and |
| 2567 |
performance is an important factor, use a designated file instead |
| 2568 |
of the standard output file or change the standard output file to |
| 2569 |
be buffered using ``Interfaces.C_Streams.setvbuf``. |
| 2570 |
|
| 2571 |
|
| 2572 |
.. _Reducing_Size_of_Executables_with_Unused_Subprogram/Data_Elimination: |
| 2573 |
|
| 2574 |
Reducing Size of Executables with Unused Subprogram/Data Elimination |
| 2575 |
-------------------------------------------------------------------- |
| 2576 |
|
| 2577 |
.. index:: Uunused subprogram/data elimination |
| 2578 |
|
| 2579 |
This section describes how you can eliminate unused subprograms and data from |
| 2580 |
your executable just by setting options at compilation time. |
| 2581 |
|
| 2582 |
.. _About_unused_subprogram/data_elimination: |
| 2583 |
|
| 2584 |
About unused subprogram/data elimination |
| 2585 |
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 2586 |
|
| 2587 |
By default, an executable contains all code and data of its objects |
| 2588 |
(directly linked or coming from statically linked libraries), even data or code |
| 2589 |
never used by this executable. This feature eliminates such unused code from your |
| 2590 |
executable, thus making it smaller (in disk and in memory). |
| 2591 |
|
| 2592 |
You can use this functionality on all Linux platforms except for the IA-64 |
| 2593 |
architecture and on all cross platforms using the ELF binary file format. |
| 2594 |
In both cases, GNU binutils version 2.16 or later are required to enable it. |
| 2595 |
|
| 2596 |
.. _Compilation_options: |
| 2597 |
|
| 2598 |
Compilation options |
| 2599 |
^^^^^^^^^^^^^^^^^^^ |
| 2600 |
|
| 2601 |
The operation of eliminating the unused code and data from the final executable |
| 2602 |
is directly performed by the linker. |
| 2603 |
|
| 2604 |
.. index:: -ffunction-sections (gcc) |
| 2605 |
.. index:: -fdata-sections (gcc) |
| 2606 |
|
| 2607 |
In order to do this, it has to work with objects compiled with the |
| 2608 |
following switches passed to the GCC back end: |
| 2609 |
:switch:`-ffunction-sections` :switch:`-fdata-sections`. |
| 2610 |
|
| 2611 |
These options are usable with C and Ada files. |
| 2612 |
They cause the compiler to place each |
| 2613 |
function or data in a separate section in the resulting object file. |
| 2614 |
|
| 2615 |
Once you've created the objects and static libraries with these switches, the |
| 2616 |
linker can perform the dead code elimination. You can do this by specifying |
| 2617 |
the :switch:`-Wl,--gc-sections` switch to your ``gcc`` command or in the |
| 2618 |
:switch:`-largs` section of your invocation of ``gnatmake``. This causes |
| 2619 |
the linker to perform a |
| 2620 |
garbage collection and remove code and data that are never referenced. |
| 2621 |
|
| 2622 |
If the linker performs a partial link (:switch:`-r` linker switch), then you |
| 2623 |
need to provide the entry point using the :switch:`-e` / :switch:`--entry` |
| 2624 |
linker switch. |
| 2625 |
|
| 2626 |
Note that objects compiled without the :switch:`-ffunction-sections` and |
| 2627 |
:switch:`-fdata-sections` options can still be linked with the executable. |
| 2628 |
However, no dead code elimination can be performed on those objects (they will |
| 2629 |
be linked as is). |
| 2630 |
|
| 2631 |
The GNAT static library is compiled with :switch:`-ffunction-sections` |
| 2632 |
and :switch:`-fdata-sections` on some platforms. This allows you to |
| 2633 |
eliminate the unused code and data of the GNAT library from your |
| 2634 |
executable. |
| 2635 |
|
| 2636 |
|
| 2637 |
.. _Example_of_unused_subprogram/data_elimination: |
| 2638 |
|
| 2639 |
Example of unused subprogram/data elimination |
| 2640 |
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 2641 |
|
| 2642 |
Here's a simple example: |
| 2643 |
|
| 2644 |
.. code-block:: ada |
| 2645 |
|
| 2646 |
with Aux; |
| 2647 |
|
| 2648 |
procedure Test is |
| 2649 |
begin |
| 2650 |
Aux.Used (10); |
| 2651 |
end Test; |
| 2652 |
|
| 2653 |
package Aux is |
| 2654 |
Used_Data : Integer; |
| 2655 |
Unused_Data : Integer; |
| 2656 |
|
| 2657 |
procedure Used (Data : Integer); |
| 2658 |
procedure Unused (Data : Integer); |
| 2659 |
end Aux; |
| 2660 |
|
| 2661 |
package body Aux is |
| 2662 |
procedure Used (Data : Integer) is |
| 2663 |
begin |
| 2664 |
Used_Data := Data; |
| 2665 |
end Used; |
| 2666 |
|
| 2667 |
procedure Unused (Data : Integer) is |
| 2668 |
begin |
| 2669 |
Unused_Data := Data; |
| 2670 |
end Unused; |
| 2671 |
end Aux; |
| 2672 |
|
| 2673 |
``Unused`` and ``Unused_Data`` are never referenced in this code |
| 2674 |
excerpt and hence may be safely removed from the final executable. |
| 2675 |
|
| 2676 |
:: |
| 2677 |
|
| 2678 |
$ gnatmake test |
| 2679 |
|
| 2680 |
$ nm test | grep used |
| 2681 |
020015f0 T aux__unused |
| 2682 |
02005d88 B aux__unused_data |
| 2683 |
020015cc T aux__used |
| 2684 |
02005d84 B aux__used_data |
| 2685 |
|
| 2686 |
$ gnatmake test -cargs -fdata-sections -ffunction-sections \\ |
| 2687 |
-largs -Wl,--gc-sections |
| 2688 |
|
| 2689 |
$ nm test | grep used |
| 2690 |
02005350 T aux__used |
| 2691 |
0201ffe0 B aux__used_data |
| 2692 |
|
| 2693 |
You can see that the procedure ``Unused`` and the object |
| 2694 |
``Unused_Data`` are removed by the linker when you've used the |
| 2695 |
appropriate switches. |
| 2696 |
|
| 2697 |
|
| 2698 |
.. index:: Overflow checks |
| 2699 |
.. index:: Checks (overflow) |
| 2700 |
|
| 2701 |
.. _Overflow_Check_Handling_in_GNAT: |
| 2702 |
|
| 2703 |
Overflow Check Handling in GNAT |
| 2704 |
=============================== |
| 2705 |
|
| 2706 |
This section explains how to control the handling of overflow checks. |
| 2707 |
|
| 2708 |
.. _Background: |
| 2709 |
|
| 2710 |
Background |
| 2711 |
---------- |
| 2712 |
|
| 2713 |
Overflow checks are checks that the compiler may make to ensure |
| 2714 |
that intermediate results are not out of range. For example: |
| 2715 |
|
| 2716 |
.. code-block:: ada |
| 2717 |
|
| 2718 |
A : Integer; |
| 2719 |
... |
| 2720 |
A := A + 1; |
| 2721 |
|
| 2722 |
If ``A`` has the value ``Integer'Last``, the addition will cause |
| 2723 |
overflow since the result is out of range of the type ``Integer``. |
| 2724 |
In this case, execution will raise ``Constraint_Error`` if checks are |
| 2725 |
enabled. |
| 2726 |
|
| 2727 |
A trickier situation arises in cases like the following: |
| 2728 |
|
| 2729 |
.. code-block:: ada |
| 2730 |
|
| 2731 |
A, C : Integer; |
| 2732 |
... |
| 2733 |
A := (A + 1) + C; |
| 2734 |
|
| 2735 |
where ``A`` is ``Integer'Last`` and ``C`` is ``-1``. |
| 2736 |
Here, the final result of the expression on the right hand side is |
| 2737 |
``Integer'Last`` which is in range, but the question arises whether the |
| 2738 |
intermediate addition of ``(A + 1)`` raises an overflow error. |
| 2739 |
|
| 2740 |
The (perhaps surprising) answer is that the Ada language |
| 2741 |
definition does not answer this question. Instead, it leaves |
| 2742 |
it up to the implementation to do one of two things if overflow |
| 2743 |
checks are enabled. |
| 2744 |
|
| 2745 |
* raise an exception (``Constraint_Error``), or |
| 2746 |
|
| 2747 |
* yield the correct mathematical result which is then used in |
| 2748 |
subsequent operations. |
| 2749 |
|
| 2750 |
If the compiler chooses the first approach, the execution of this |
| 2751 |
example will indeed raise ``Constraint_Error`` if overflow checking is |
| 2752 |
enabled or result in erroneous execution if overflow checks are suppressed. |
| 2753 |
|
| 2754 |
But if the compiler |
| 2755 |
chooses the second approach, it can perform both additions yielding |
| 2756 |
the correct mathematical result, which is in range, so no exception |
| 2757 |
is raised and the right result is obtained, regardless of whether |
| 2758 |
overflow checks are suppressed. |
| 2759 |
|
| 2760 |
Note that in the first example, an |
| 2761 |
exception will be raised in either case, since if the compiler |
| 2762 |
gives the correct mathematical result for the addition, it will |
| 2763 |
be out of range of the target type of the assignment and thus |
| 2764 |
fails the range check. |
| 2765 |
|
| 2766 |
This lack of specified behavior in the handling of overflow for |
| 2767 |
intermediate results is a source of non-portability and can thus |
| 2768 |
be problematic when you port programs. Most typically, this arises |
| 2769 |
in a situation where the original compiler did not raise an exception |
| 2770 |
and you move the application to a compiler where the check is |
| 2771 |
performed on the intermediate result and an unexpected exception is |
| 2772 |
raised. |
| 2773 |
|
| 2774 |
Furthermore, when using Ada 2012's preconditions and other |
| 2775 |
assertion forms, another issue arises. Consider: |
| 2776 |
|
| 2777 |
.. code-block:: ada |
| 2778 |
|
| 2779 |
procedure P (A, B : Integer) with |
| 2780 |
Pre => A + B <= Integer'Last; |
| 2781 |
|
| 2782 |
We often want to regard arithmetic in a context such as this from a |
| 2783 |
purely mathematical point of view. So, for example, if the two actual |
| 2784 |
parameters for a call to ``P`` are both ``Integer'Last`` then the |
| 2785 |
precondition should be evaluated as ``False``. If we're executing in a |
| 2786 |
mode with run-time checks enabled for preconditions, then we would |
| 2787 |
like this precondition to fail, rather than raising an exception |
| 2788 |
because of the intermediate overflow. |
| 2789 |
|
| 2790 |
However, the language definition leaves the specification of |
| 2791 |
whether the above condition fails (raising ``Assert_Error``) or |
| 2792 |
causes an intermediate overflow (raising ``Constraint_Error``) |
| 2793 |
up to the implementation. |
| 2794 |
|
| 2795 |
The situation is worse in a case such as the following: |
| 2796 |
|
| 2797 |
.. code-block:: ada |
| 2798 |
|
| 2799 |
procedure Q (A, B, C : Integer) with |
| 2800 |
Pre => A + B + C <= Integer'Last; |
| 2801 |
|
| 2802 |
Consider the call |
| 2803 |
|
| 2804 |
.. code-block:: ada |
| 2805 |
|
| 2806 |
Q (A => Integer'Last, B => 1, C => -1); |
| 2807 |
|
| 2808 |
From a mathematical point of view the precondition |
| 2809 |
is ``True``, but at run time we may (but are not guaranteed to) get an |
| 2810 |
exception raised because of the intermediate overflow (and we really |
| 2811 |
would prefer this precondition to be considered ``True`` at run time). |
| 2812 |
|
| 2813 |
|
| 2814 |
.. _Management_of_Overflows_in_GNAT: |
| 2815 |
|
| 2816 |
Management of Overflows in GNAT |
| 2817 |
------------------------------- |
| 2818 |
|
| 2819 |
To deal with the portability issue and with the problem of |
| 2820 |
mathematical versus run-time interpretation of the expressions in |
| 2821 |
assertions, GNAT provides comprehensive control over the handling |
| 2822 |
of intermediate overflows. It can operate in three modes, and |
| 2823 |
in addition, permits separate selection of operating modes for |
| 2824 |
the expressions within assertions (here the term 'assertions' |
| 2825 |
is used in the technical sense, which includes preconditions and so forth) |
| 2826 |
and for expressions appearing outside assertions. |
| 2827 |
|
| 2828 |
The three modes are: |
| 2829 |
|
| 2830 |
* *Use base type for intermediate operations* (``STRICT``) |
| 2831 |
|
| 2832 |
In this mode, all intermediate results for predefined arithmetic |
| 2833 |
operators are computed using the base type, and the result must |
| 2834 |
be in range of the base type. If this is not the |
| 2835 |
case, then either an exception is raised (if overflow checks are |
| 2836 |
enabled) or the execution is erroneous (if overflow checks are suppressed). |
| 2837 |
This is the normal default mode. |
| 2838 |
|
| 2839 |
* *Most intermediate overflows avoided* (``MINIMIZED``) |
| 2840 |
|
| 2841 |
In this mode, the compiler attempts to avoid intermediate overflows by |
| 2842 |
using a larger integer type, typically ``Long_Long_Integer``, |
| 2843 |
as the type in which arithmetic is |
| 2844 |
performed for predefined arithmetic operators. This may be slightly more |
| 2845 |
expensive at |
| 2846 |
run time (compared to suppressing intermediate overflow checks), though |
| 2847 |
the cost is negligible on modern 64-bit machines. For the examples given |
| 2848 |
earlier, no intermediate overflows would have resulted in exceptions, |
| 2849 |
since the intermediate results are all in the range of |
| 2850 |
``Long_Long_Integer`` (typically 64-bits on nearly all implementations |
| 2851 |
of GNAT). In addition, if checks are enabled, this reduces the number of |
| 2852 |
checks that must be made, so this choice may actually result in an |
| 2853 |
improvement in space and time behavior. |
| 2854 |
|
| 2855 |
However, there are cases where ``Long_Long_Integer`` is not large |
| 2856 |
enough. Consider the following example: |
| 2857 |
|
| 2858 |
.. code-block:: ada |
| 2859 |
|
| 2860 |
procedure R (A, B, C, D : Integer) with |
| 2861 |
Pre => (A**2 * B**2) / (C**2 * D**2) <= 10; |
| 2862 |
|
| 2863 |
where ``A`` = ``B`` = ``C`` = ``D`` = ``Integer'Last``. |
| 2864 |
Now the intermediate results are |
| 2865 |
out of the range of ``Long_Long_Integer`` even though the final result |
| 2866 |
is in range and the precondition is ``True`` from a mathematical point |
| 2867 |
of view. In such a case, operating in this mode, an overflow occurs |
| 2868 |
for the intermediate computation (which is why this mode |
| 2869 |
says *most* intermediate overflows are avoided). In this case, |
| 2870 |
an exception is raised if overflow checks are enabled, and the |
| 2871 |
execution is erroneous if overflow checks are suppressed. |
| 2872 |
|
| 2873 |
* *All intermediate overflows avoided* (``ELIMINATED``) |
| 2874 |
|
| 2875 |
In this mode, the compiler avoids all intermediate overflows |
| 2876 |
by using arbitrary precision arithmetic as required. In this |
| 2877 |
mode, the above example with ``A**2 * B**2`` would |
| 2878 |
not cause intermediate overflow, because the intermediate result |
| 2879 |
would be evaluated using sufficient precision, and the result |
| 2880 |
of evaluating the precondition would be ``True``. |
| 2881 |
|
| 2882 |
This mode has the advantage of avoiding any intermediate |
| 2883 |
overflows, but at the expense of significant run-time overhead, |
| 2884 |
including the use of a library (included automatically in this |
| 2885 |
mode) for multiple-precision arithmetic. |
| 2886 |
|
| 2887 |
This mode provides cleaner semantics for assertions, since now |
| 2888 |
the run-time behavior emulates true arithmetic behavior for the |
| 2889 |
predefined arithmetic operators, meaning that there is never a |
| 2890 |
conflict between the mathematical view of the assertion and its |
| 2891 |
run-time behavior. |
| 2892 |
|
| 2893 |
Note that in this mode, the behavior is unaffected by whether or |
| 2894 |
not overflow checks are suppressed, since overflow does not occur. |
| 2895 |
Gigantic intermediate expressions can still raise |
| 2896 |
``Storage_Error`` as a result of attempting to compute the |
| 2897 |
results of such expressions (e.g. ``Integer'Last ** Integer'Last``) |
| 2898 |
but overflow is impossible. |
| 2899 |
|
| 2900 |
|
| 2901 |
Note that these modes apply only to the evaluation of predefined |
| 2902 |
arithmetic, membership, and comparison operators for signed integer |
| 2903 |
arithmetic. |
| 2904 |
|
| 2905 |
For fixed-point arithmetic, you suppress checks. But if checks |
| 2906 |
are enabled, |
| 2907 |
fixed-point values are always checked for overflow against the |
| 2908 |
base type for intermediate expressions (i.e., such checks always |
| 2909 |
operate in the equivalent of ``STRICT`` mode). |
| 2910 |
|
| 2911 |
For floating-point, on nearly all architectures, ``Machine_Overflows`` |
| 2912 |
is ``False``, and IEEE infinities are generated, so overflow exceptions |
| 2913 |
are never raised. If you want to avoid infinities and check that |
| 2914 |
final results of expressions are in range, you can declare a |
| 2915 |
constrained floating-point type and range checks are carried |
| 2916 |
out in the normal manner (with infinite values always failing all |
| 2917 |
range checks). |
| 2918 |
|
| 2919 |
|
| 2920 |
.. _Specifying_the_Desired_Mode: |
| 2921 |
|
| 2922 |
Specifying the Desired Mode |
| 2923 |
--------------------------- |
| 2924 |
|
| 2925 |
.. index:: pragma Overflow_Mode |
| 2926 |
|
| 2927 |
You can specify |
| 2928 |
the desired mode of for handling intermediate overflow using |
| 2929 |
either the ``Overflow_Mode`` pragma or an equivalent compiler switch. |
| 2930 |
The pragma has the form: |
| 2931 |
|
| 2932 |
.. code-block:: ada |
| 2933 |
|
| 2934 |
pragma Overflow_Mode ([General =>] MODE [, [Assertions =>] MODE]); |
| 2935 |
|
| 2936 |
where ``MODE`` is one of |
| 2937 |
|
| 2938 |
* ``STRICT``: intermediate overflows checked (using base type) |
| 2939 |
* ``MINIMIZED``: minimize intermediate overflows |
| 2940 |
* ``ELIMINATED``: eliminate intermediate overflows |
| 2941 |
|
| 2942 |
The case is ignored, so ``MINIMIZED``, ``Minimized`` and |
| 2943 |
``minimized`` all have the same effect. |
| 2944 |
|
| 2945 |
If you only specify the ``General`` parameter, the given ``MODE`` applies |
| 2946 |
to expressions both within and outside assertions. If you specify both arguments, |
| 2947 |
the value of ``General`` applies to expressions outside assertions, |
| 2948 |
and ``Assertions`` applies to expressions within assertions. For example: |
| 2949 |
|
| 2950 |
.. code-block:: ada |
| 2951 |
|
| 2952 |
pragma Overflow_Mode |
| 2953 |
(General => Minimized, Assertions => Eliminated); |
| 2954 |
|
| 2955 |
specifies that expressions outside assertions be evaluated |
| 2956 |
in 'minimize intermediate overflows' mode and expressions within |
| 2957 |
assertions be evaluated in 'eliminate intermediate overflows' mode. |
| 2958 |
This is often a reasonable choice, avoiding excessive overhead |
| 2959 |
outside assertions, but assuring a high degree of portability |
| 2960 |
when importing code from another compiler while incurring |
| 2961 |
the extra overhead for assertion expressions to ensure that |
| 2962 |
the behavior at run time matches the expected mathematical |
| 2963 |
behavior. |
| 2964 |
|
| 2965 |
The ``Overflow_Mode`` pragma has the same scoping and placement |
| 2966 |
rules as pragma ``Suppress``, so you can use it either as a |
| 2967 |
configuration pragma, specifying a default for the whole |
| 2968 |
program, or in a declarative scope, where it applies to the |
| 2969 |
remaining declarations and statements in that scope. |
| 2970 |
|
| 2971 |
Note that pragma ``Overflow_Mode`` does not affect whether |
| 2972 |
overflow checks are enabled or suppressed. It only controls the |
| 2973 |
method used to compute intermediate values. To control whether |
| 2974 |
overflow checking is enabled or suppressed, use pragma ``Suppress`` |
| 2975 |
or ``Unsuppress`` in the usual manner. |
| 2976 |
|
| 2977 |
|
| 2978 |
.. index:: -gnato? (gcc) |
| 2979 |
.. index:: -gnato?? (gcc) |
| 2980 |
|
| 2981 |
Additionally, you can use the compiler switch :switch:`-gnato?` or |
| 2982 |
:switch:`-gnato??` to control the checking mode default (which you can |
| 2983 |
subsequently override using the above pragmas). |
| 2984 |
|
| 2985 |
Here ``?`` is one of the digits ``1`` through ``3``: |
| 2986 |
|
| 2987 |
====== ====================================================== |
| 2988 |
``1`` use base type for intermediate operations (``STRICT``) |
| 2989 |
``2`` minimize intermediate overflows (``MINIMIZED``) |
| 2990 |
``3`` eliminate intermediate overflows (``ELIMINATED``) |
| 2991 |
====== ====================================================== |
| 2992 |
|
| 2993 |
As with the pragma, if only one digit appears, it applies to all |
| 2994 |
cases; if two digits are given, the first applies to expressions outside |
| 2995 |
assertions and the second within assertions. Thus the equivalent |
| 2996 |
of the example pragma above would be |
| 2997 |
:switch:`-gnato23`. |
| 2998 |
|
| 2999 |
If you don't provide any digits following the :switch:`-gnato`, it's |
| 3000 |
equivalent to :switch:`-gnato11`, causing all intermediate operations |
| 3001 |
to be computed using the base type (``STRICT`` mode). |
| 3002 |
|
| 3003 |
|
| 3004 |
.. _Default_Settings: |
| 3005 |
|
| 3006 |
Default Settings |
| 3007 |
---------------- |
| 3008 |
|
| 3009 |
The default mode for overflow checks is |
| 3010 |
|
| 3011 |
:: |
| 3012 |
|
| 3013 |
General => Strict |
| 3014 |
|
| 3015 |
which causes all computations both inside and outside assertions to use the |
| 3016 |
base type, and is equivalent to :switch:`-gnato` (with no digits following). |
| 3017 |
|
| 3018 |
The pragma ``Suppress (Overflow_Check)`` disables overflow |
| 3019 |
checking but has no effect on the method used for computing |
| 3020 |
intermediate results. |
| 3021 |
The pragma ``Unsuppress (Overflow_Check)`` enables overflow |
| 3022 |
checking but has no effect on the method used for computing |
| 3023 |
intermediate results. |
| 3024 |
|
| 3025 |
|
| 3026 |
.. _Implementation_Notes: |
| 3027 |
|
| 3028 |
Implementation Notes |
| 3029 |
-------------------- |
| 3030 |
|
| 3031 |
In practice, on typical 64-bit machines, the ``MINIMIZED`` mode is |
| 3032 |
reasonably efficient and you can generally use it. It also helps |
| 3033 |
to ensure compatibility with code imported from other |
| 3034 |
compilers to GNAT. |
| 3035 |
|
| 3036 |
Setting all intermediate overflows checking (``STRICT`` mode) |
| 3037 |
makes sense if you want to |
| 3038 |
make sure your code is compatible with any other |
| 3039 |
Ada implementations. You may find this useful in ensuring portability |
| 3040 |
for code that is to be exported to some other compiler than GNAT. |
| 3041 |
|
| 3042 |
The Ada standard allows the reassociation of expressions at |
| 3043 |
the same precedence level if no parentheses are present. For |
| 3044 |
example, ``A+B+C`` parses as though it were ``(A+B)+C``, but |
| 3045 |
the compiler can reintepret this as ``A+(B+C)``, possibly |
| 3046 |
introducing or eliminating an overflow exception. The GNAT |
| 3047 |
compiler never takes advantage of this freedom, and the |
| 3048 |
expression ``A+B+C`` will be evaluated as ``(A+B)+C``. |
| 3049 |
If you need the other order, you can write the parentheses |
| 3050 |
explicitly ``A+(B+C)`` and GNAT will respect this order. |
| 3051 |
|
| 3052 |
The use of ``ELIMINATED`` mode will cause the compiler to |
| 3053 |
automatically include an appropriate arbitrary precision |
| 3054 |
integer arithmetic package. The compiler will make calls |
| 3055 |
to this package, though only in cases where it cannot be |
| 3056 |
sure that ``Long_Long_Integer`` is sufficient to guard against |
| 3057 |
intermediate overflows. This package does not use dynamic |
| 3058 |
allocation, but it does use the secondary stack, so an |
| 3059 |
appropriate secondary stack package must be present (this |
| 3060 |
is always true for standard full Ada, but may require |
| 3061 |
specific steps for restricted run times such as ZFP). |
| 3062 |
|
| 3063 |
Although ``ELIMINATED`` mode causes expressions to use arbitrary |
| 3064 |
precision arithmetic, avoiding overflow, the final result |
| 3065 |
must be in an appropriate range. This is true even if the |
| 3066 |
final result is of type ``[Long_[Long_]]Integer'Base``, which |
| 3067 |
still has the same bounds as its associated constrained |
| 3068 |
type at run-time. |
| 3069 |
|
| 3070 |
Currently, the ``ELIMINATED`` mode is only available on target |
| 3071 |
platforms for which ``Long_Long_Integer`` is at least 64-bits (nearly all GNAT |
| 3072 |
platforms). |
| 3073 |
|
| 3074 |
|
| 3075 |
|
| 3076 |
.. _Performing_Dimensionality_Analysis_in_GNAT: |
| 3077 |
|
| 3078 |
Performing Dimensionality Analysis in GNAT |
| 3079 |
========================================== |
| 3080 |
|
| 3081 |
.. index:: Dimensionality analysis |
| 3082 |
|
| 3083 |
The GNAT compiler supports dimensionality checking. You can |
| 3084 |
specify physical units for objects and the compiler verifies that uses |
| 3085 |
of these objects are compatible with their dimension, in a fashion that is |
| 3086 |
familiar to engineering practice. The dimensions of algebraic expressions |
| 3087 |
(including powers with static exponents) are computed from their constituents. |
| 3088 |
|
| 3089 |
.. index:: Dimension_System aspect |
| 3090 |
.. index:: Dimension aspect |
| 3091 |
|
| 3092 |
This feature depends on Ada 2012 aspect specifications and is available for |
| 3093 |
versions 7.0.1 and later of GNAT. |
| 3094 |
The GNAT-specific aspect ``Dimension_System`` |
| 3095 |
allows you to define a system of units; the aspect ``Dimension`` |
| 3096 |
allows you to declare dimensioned quantities within a given system. |
| 3097 |
(These aspects are described in the *Implementation Defined Aspects* |
| 3098 |
chapter of the :title:`GNAT Reference Manual`). |
| 3099 |
|
| 3100 |
The major advantage of this model is that it does not require the declaration of |
| 3101 |
multiple operators for all possible combinations of types: you is only need |
| 3102 |
to use the proper subtypes in object declarations. |
| 3103 |
|
| 3104 |
.. index:: System.Dim.Mks package (GNAT library) |
| 3105 |
.. index:: MKS_Type type |
| 3106 |
|
| 3107 |
The simplest way to impose dimensionality checking on a computation is to make |
| 3108 |
use of one of the instantiations of the package ``System.Dim.Generic_Mks``, which |
| 3109 |
is part of the GNAT library. This generic package defines a floating-point |
| 3110 |
type ``MKS_Type``, for which a sequence of dimension names are specified, |
| 3111 |
together with their conventional abbreviations. You should read the following |
| 3112 |
together with the full specification of the package, in file |
| 3113 |
:file:`s-digemk.ads`. |
| 3114 |
|
| 3115 |
.. index:: s-digemk.ads file |
| 3116 |
|
| 3117 |
.. code-block:: ada |
| 3118 |
|
| 3119 |
type Mks_Type is new Float_Type |
| 3120 |
with |
| 3121 |
Dimension_System => ( |
| 3122 |
(Unit_Name => Meter, Unit_Symbol => 'm', Dim_Symbol => 'L'), |
| 3123 |
(Unit_Name => Kilogram, Unit_Symbol => "kg", Dim_Symbol => 'M'), |
| 3124 |
(Unit_Name => Second, Unit_Symbol => 's', Dim_Symbol => 'T'), |
| 3125 |
(Unit_Name => Ampere, Unit_Symbol => 'A', Dim_Symbol => 'I'), |
| 3126 |
(Unit_Name => Kelvin, Unit_Symbol => 'K', Dim_Symbol => "Theta"), |
| 3127 |
(Unit_Name => Mole, Unit_Symbol => "mol", Dim_Symbol => 'N'), |
| 3128 |
(Unit_Name => Candela, Unit_Symbol => "cd", Dim_Symbol => 'J')); |
| 3129 |
|
| 3130 |
The package then defines a series of subtypes that correspond to these |
| 3131 |
conventional units. For example: |
| 3132 |
|
| 3133 |
.. code-block:: ada |
| 3134 |
|
| 3135 |
subtype Length is Mks_Type |
| 3136 |
with |
| 3137 |
Dimension => (Symbol => 'm', Meter => 1, others => 0); |
| 3138 |
|
| 3139 |
and similarly for ``Mass``, ``Time``, ``Electric_Current``, |
| 3140 |
``Thermodynamic_Temperature``, ``Amount_Of_Substance``, and |
| 3141 |
``Luminous_Intensity`` (the standard set of units of the SI system). |
| 3142 |
|
| 3143 |
The package also defines conventional names for values of each unit, for |
| 3144 |
example: |
| 3145 |
|
| 3146 |
.. code-block:: ada |
| 3147 |
|
| 3148 |
m : constant Length := 1.0; |
| 3149 |
kg : constant Mass := 1.0; |
| 3150 |
s : constant Time := 1.0; |
| 3151 |
A : constant Electric_Current := 1.0; |
| 3152 |
|
| 3153 |
as well as useful multiples of these units: |
| 3154 |
|
| 3155 |
.. code-block:: ada |
| 3156 |
|
| 3157 |
cm : constant Length := 1.0E-02; |
| 3158 |
g : constant Mass := 1.0E-03; |
| 3159 |
min : constant Time := 60.0; |
| 3160 |
day : constant Time := 60.0 * 24.0 * min; |
| 3161 |
... |
| 3162 |
|
| 3163 |
There are three instantiations of ``System.Dim.Generic_Mks`` defined in the |
| 3164 |
GNAT library: |
| 3165 |
|
| 3166 |
* ``System.Dim.Float_Mks`` based on ``Float`` defined in :file:`s-diflmk.ads`. |
| 3167 |
* ``System.Dim.Long_Mks`` based on ``Long_Float`` defined in :file:`s-dilomk.ads`. |
| 3168 |
* ``System.Dim.Mks`` based on ``Long_Long_Float`` defined in :file:`s-dimmks.ads`. |
| 3169 |
|
| 3170 |
Using one of these packages, you can then define a derived unit by providing |
| 3171 |
the aspect that specifies its dimensions within the MKS system as well as the |
| 3172 |
string to be used for output of a value of that unit: |
| 3173 |
|
| 3174 |
.. code-block:: ada |
| 3175 |
|
| 3176 |
subtype Acceleration is Mks_Type |
| 3177 |
with Dimension => ("m/sec^2", |
| 3178 |
Meter => 1, |
| 3179 |
Second => -2, |
| 3180 |
others => 0); |
| 3181 |
|
| 3182 |
Here's a complete example: |
| 3183 |
|
| 3184 |
.. code-block:: ada |
| 3185 |
|
| 3186 |
with System.Dim.MKS; use System.Dim.Mks; |
| 3187 |
with System.Dim.Mks_IO; use System.Dim.Mks_IO; |
| 3188 |
with Text_IO; use Text_IO; |
| 3189 |
procedure Free_Fall is |
| 3190 |
subtype Acceleration is Mks_Type |
| 3191 |
with Dimension => ("m/sec^2", 1, 0, -2, others => 0); |
| 3192 |
G : constant acceleration := 9.81 * m / (s ** 2); |
| 3193 |
T : Time := 10.0*s; |
| 3194 |
Distance : Length; |
| 3195 |
|
| 3196 |
begin |
| 3197 |
Put ("Gravitational constant: "); |
| 3198 |
Put (G, Aft => 2, Exp => 0); Put_Line (""); |
| 3199 |
Distance := 0.5 * G * T ** 2; |
| 3200 |
Put ("distance travelled in 10 seconds of free fall "); |
| 3201 |
Put (Distance, Aft => 2, Exp => 0); |
| 3202 |
Put_Line (""); |
| 3203 |
end Free_Fall; |
| 3204 |
|
| 3205 |
Execution of this program yields: |
| 3206 |
|
| 3207 |
:: |
| 3208 |
|
| 3209 |
Gravitational constant: 9.81 m/sec^2 |
| 3210 |
distance travelled in 10 seconds of free fall 490.50 m |
| 3211 |
|
| 3212 |
However, incorrect assignments such as: |
| 3213 |
|
| 3214 |
.. code-block:: ada |
| 3215 |
|
| 3216 |
Distance := 5.0; |
| 3217 |
Distance := 5.0 * kg; |
| 3218 |
|
| 3219 |
are rejected with the following diagnoses: |
| 3220 |
|
| 3221 |
:: |
| 3222 |
|
| 3223 |
Distance := 5.0; |
| 3224 |
>>> dimensions mismatch in assignment |
| 3225 |
>>> left-hand side has dimension [L] |
| 3226 |
>>> right-hand side is dimensionless |
| 3227 |
|
| 3228 |
Distance := 5.0 * kg: |
| 3229 |
>>> dimensions mismatch in assignment |
| 3230 |
>>> left-hand side has dimension [L] |
| 3231 |
>>> right-hand side has dimension [M] |
| 3232 |
|
| 3233 |
The dimensions of an expression are properly displayed even if there is |
| 3234 |
no explicit subtype for it. If we add to the program: |
| 3235 |
|
| 3236 |
.. code-block:: ada |
| 3237 |
|
| 3238 |
Put ("Final velocity: "); |
| 3239 |
Put (G * T, Aft =>2, Exp =>0); |
| 3240 |
Put_Line (""); |
| 3241 |
|
| 3242 |
the output includes: |
| 3243 |
|
| 3244 |
:: |
| 3245 |
|
| 3246 |
Final velocity: 98.10 m.s**(-1) |
| 3247 |
|
| 3248 |
|
| 3249 |
.. index:: Dimensionable type |
| 3250 |
.. index:: Dimensioned subtype |
| 3251 |
|
| 3252 |
The type ``Mks_Type`` is said to be a *dimensionable type* since it has a |
| 3253 |
``Dimension_System`` aspect, and the subtypes ``Length``, ``Mass``, etc., |
| 3254 |
are said to be *dimensioned subtypes* since each one has a ``Dimension`` |
| 3255 |
aspect. |
| 3256 |
|
| 3257 |
.. index:: Dimension Vector (for a dimensioned subtype) |
| 3258 |
.. index:: Dimension aspect |
| 3259 |
.. index:: Dimension_System aspect |
| 3260 |
|
| 3261 |
The ``Dimension`` aspect of a dimensioned subtype ``S`` defines a mapping |
| 3262 |
from the base type's Unit_Names to integer (or, more generally, rational) |
| 3263 |
values. This mapping is the *dimension vector* (also referred to as the |
| 3264 |
*dimensionality*) for that subtype, denoted by ``DV(S)``, and thus for each |
| 3265 |
object of that subtype. Intuitively, the value specified for each |
| 3266 |
``Unit_Name`` is the exponent associated with that unit; a zero value |
| 3267 |
means that the unit is not used. For example: |
| 3268 |
|
| 3269 |
.. code-block:: ada |
| 3270 |
|
| 3271 |
declare |
| 3272 |
Acc : Acceleration; |
| 3273 |
... |
| 3274 |
begin |
| 3275 |
... |
| 3276 |
end; |
| 3277 |
|
| 3278 |
Here ``DV(Acc)`` = ``DV(Acceleration)`` = |
| 3279 |
``(Meter=>1, Kilogram=>0, Second=>-2, Ampere=>0, Kelvin=>0, Mole=>0, Candela=>0)``. |
| 3280 |
Symbolically, we can express this as ``Meter / Second**2``. |
| 3281 |
|
| 3282 |
The dimension vector of an arithmetic expression is synthesized from the |
| 3283 |
dimension vectors of its components, with compile-time dimensionality checks |
| 3284 |
that help prevent mismatches such as using an ``Acceleration`` where a |
| 3285 |
``Length`` is required. |
| 3286 |
|
| 3287 |
The dimension vector of the result of an arithmetic expression *expr*, or |
| 3288 |
:samp:`DV({expr})`, is defined as follows, assuming conventional |
| 3289 |
mathematical definitions for the vector operations that are used: |
| 3290 |
|
| 3291 |
* If *expr* is of the type *universal_real*, or is not of a dimensioned subtype, |
| 3292 |
then *expr* is dimensionless; :samp:`DV({expr})` is the empty vector. |
| 3293 |
|
| 3294 |
* :samp:`DV({op expr})`, where *op* is a unary operator, is :samp:`DV({expr})` |
| 3295 |
|
| 3296 |
* :samp:`DV({expr1 op expr2})`, where *op* is "+" or "-", is :samp:`DV({expr1})` |
| 3297 |
provided that :samp:`DV({expr1})` = :samp:`DV({expr2})`. |
| 3298 |
If this condition is not met then the construct is illegal. |
| 3299 |
|
| 3300 |
* :samp:`DV({expr1} * {expr2})` is :samp:`DV({expr1})` + :samp:`DV({expr2})`, |
| 3301 |
and :samp:`DV({expr1} / {expr2})` = :samp:`DV({expr1})` - :samp:`DV({expr2})`. |
| 3302 |
In this context if one of the *expr*\ s is dimensionless then its empty |
| 3303 |
dimension vector is treated as ``(others => 0)``. |
| 3304 |
|
| 3305 |
* :samp:`DV({expr} ** {power})` is *power* * :samp:`DV({expr})`, |
| 3306 |
provided that *power* is a static rational value. If this condition is not |
| 3307 |
met then the construct is illegal. |
| 3308 |
|
| 3309 |
Note that, by the above rules, it is illegal to use binary "+" or "-" to |
| 3310 |
combine a dimensioned and dimensionless value. Thus an expression such as |
| 3311 |
``acc-10.0`` is illegal, where ``acc`` is an object of subtype |
| 3312 |
``Acceleration``. |
| 3313 |
|
| 3314 |
The dimensionality checks for relationals use the same rules as |
| 3315 |
for "+" and "-" except when comparing to a literal; thus |
| 3316 |
|
| 3317 |
.. code-block:: ada |
| 3318 |
|
| 3319 |
acc > len |
| 3320 |
|
| 3321 |
is equivalent to |
| 3322 |
|
| 3323 |
.. code-block:: ada |
| 3324 |
|
| 3325 |
acc-len > 0.0 |
| 3326 |
|
| 3327 |
and is thus illegal, but |
| 3328 |
|
| 3329 |
.. code-block:: ada |
| 3330 |
|
| 3331 |
acc > 10.0 |
| 3332 |
|
| 3333 |
is accepted with a warning. Analogously, a conditional expression requires the |
| 3334 |
same dimension vector for each branch (with no exception for literals). |
| 3335 |
|
| 3336 |
The dimension vector of a type conversion :samp:`T({expr})` is defined |
| 3337 |
as follows, based on the nature of ``T``: |
| 3338 |
|
| 3339 |
* If ``T`` is a dimensioned subtype, then :samp:`DV(T({expr}))` is ``DV(T)`` |
| 3340 |
provided that either *expr* is dimensionless or |
| 3341 |
:samp:`DV(T)` = :samp:`DV({expr})`. The conversion is illegal |
| 3342 |
if *expr* is dimensioned and :samp:`DV({expr})` /= ``DV(T)``. |
| 3343 |
Note that vector equality does not require that the corresponding |
| 3344 |
Unit_Names be the same. |
| 3345 |
|
| 3346 |
As a consequence of the above rule, you can convert between |
| 3347 |
different dimension systems that follow the same international |
| 3348 |
system of units, with the seven physical components given in the |
| 3349 |
standard order (length, mass, time, etc.). Thus, you can convert a |
| 3350 |
length in meters to a length in inches (with a suitable conversion |
| 3351 |
factor) but not, for example, to a mass in pounds. |
| 3352 |
|
| 3353 |
* If ``T`` is the base type for *expr* (and the dimensionless root type of |
| 3354 |
the dimension system), then :samp:`DV(T({expr}))` is ``DV(expr)``. |
| 3355 |
Thus, if *expr* is of a dimensioned subtype of ``T``, the conversion may |
| 3356 |
be regarded as a "view conversion" that preserves dimensionality. |
| 3357 |
|
| 3358 |
This rule means you can write generic code that can be instantiated |
| 3359 |
with compatible dimensioned subtypes. You include in the generic unit |
| 3360 |
conversions that will consequently be present in instantiations, but |
| 3361 |
conversions to the base type will preserve dimensionality and make it |
| 3362 |
possible to write generic code that is correct with respect to |
| 3363 |
dimensionality. |
| 3364 |
|
| 3365 |
* Otherwise (i.e., ``T`` is neither a dimensioned subtype nor a dimensionable |
| 3366 |
base type), :samp:`DV(T({expr}))` is the empty vector. Thus, a dimensioned |
| 3367 |
value can be explicitly converted to a non-dimensioned subtype, which |
| 3368 |
of course then escapes dimensionality analysis. |
| 3369 |
|
| 3370 |
The dimension vector for a type qualification :samp:`T'({expr})` is the same |
| 3371 |
as for the type conversion :samp:`T({expr})`. |
| 3372 |
|
| 3373 |
An assignment statement |
| 3374 |
|
| 3375 |
.. code-block:: ada |
| 3376 |
|
| 3377 |
Source := Target; |
| 3378 |
|
| 3379 |
requires ``DV(Source)`` = ``DV(Target)`` and analogously for parameter |
| 3380 |
passing (the dimension vector for the actual parameter must be equal to the |
| 3381 |
dimension vector for the formal parameter). |
| 3382 |
|
| 3383 |
When using dimensioned types with elementary functions, you need not |
| 3384 |
instantiate the ``Ada.Numerics.Generic_Elementary_Functions`` package using |
| 3385 |
the ``Mks_Type`` nor for any of the derived subtypes such as ``Distance``. |
| 3386 |
For functions such as ``Sqrt``, the dimensional analysis will fail when using |
| 3387 |
the subtypes because both the parameter and return are of the same type. |
| 3388 |
|
| 3389 |
An example instantiation |
| 3390 |
|
| 3391 |
.. code-block:: ada |
| 3392 |
|
| 3393 |
package Mks_Numerics is new |
| 3394 |
Ada.Numerics.Generic_Elementary_Functions (System.Dim.Mks.Mks_Type); |
| 3395 |
|
| 3396 |
.. _Stack_Related_Facilities: |
| 3397 |
|
| 3398 |
Stack Related Facilities |
| 3399 |
======================== |
| 3400 |
|
| 3401 |
This section describes some useful tools associated with stack |
| 3402 |
checking and analysis. In |
| 3403 |
particular, it deals with dynamic and static stack usage measurements. |
| 3404 |
|
| 3405 |
.. _Stack_Overflow_Checking: |
| 3406 |
|
| 3407 |
Stack Overflow Checking |
| 3408 |
----------------------- |
| 3409 |
|
| 3410 |
.. index:: Stack Overflow Checking |
| 3411 |
|
| 3412 |
.. index:: -fstack-check (gcc) |
| 3413 |
|
| 3414 |
For most operating systems, ``gcc`` does not perform stack overflow |
| 3415 |
checking by default. This means that if the main environment task or |
| 3416 |
some other task exceeds the available stack space, unpredictable |
| 3417 |
behavior will occur. Most native systems offer some level of protection by |
| 3418 |
adding a guard page at the end of each task stack. This mechanism is usually |
| 3419 |
not enough for dealing properly with stack overflow situations because |
| 3420 |
a large local variable could "jump" above the guard page. |
| 3421 |
Furthermore, when the |
| 3422 |
guard page is hit, there may not be any space left on the stack for executing |
| 3423 |
the exception propagation code. Enabling stack checking avoids |
| 3424 |
such situations. |
| 3425 |
|
| 3426 |
To activate stack checking, compile all units with the ``gcc`` switch |
| 3427 |
:switch:`-fstack-check`. For example: |
| 3428 |
|
| 3429 |
:: |
| 3430 |
|
| 3431 |
$ gcc -c -fstack-check package1.adb |
| 3432 |
|
| 3433 |
Units compiled with this option will generate extra instructions to check |
| 3434 |
that any use of the stack (for procedure calls or for declaring local |
| 3435 |
variables in declare blocks) does not exceed the available stack space. |
| 3436 |
If the space is exceeded, a ``Storage_Error`` exception is raised. |
| 3437 |
|
| 3438 |
For declared tasks, the default stack size is defined by the GNAT runtime, |
| 3439 |
whose size may be modified at bind time through the ``-d`` bind switch |
| 3440 |
(:ref:`Switches_for_gnatbind`). You can set task specific stack sizes using the |
| 3441 |
``Storage_Size`` pragma. |
| 3442 |
|
| 3443 |
For the environment task, the stack size is determined by the operating system. |
| 3444 |
Consequently, to modify the size of the environment task please refer to your |
| 3445 |
operating system documentation. |
| 3446 |
|
| 3447 |
When using the LLVM back end, this switch doesn't perform full stack overflow |
| 3448 |
checking, but just checks for very large local dynamic allocations. |
| 3449 |
|
| 3450 |
.. _Static_Stack_Usage_Analysis: |
| 3451 |
|
| 3452 |
Static Stack Usage Analysis |
| 3453 |
--------------------------- |
| 3454 |
|
| 3455 |
.. index:: Static Stack Usage Analysis |
| 3456 |
|
| 3457 |
.. index:: -fstack-usage |
| 3458 |
|
| 3459 |
A unit compiled with the :switch:`-fstack-usage` switch generate an extra file |
| 3460 |
that specifies |
| 3461 |
the maximum amount of stack used on a per-function basis. |
| 3462 |
The file has the same |
| 3463 |
basename as the target object file with a :file:`.su` extension. |
| 3464 |
Each line of this file is made up of three fields: |
| 3465 |
|
| 3466 |
* The name of the function. |
| 3467 |
* A number of bytes. |
| 3468 |
* One or more qualifiers: ``static``, ``dynamic``, ``bounded``. |
| 3469 |
|
| 3470 |
The second field corresponds to the size of the known part of the function |
| 3471 |
frame. |
| 3472 |
|
| 3473 |
The qualifier ``static`` means that the function frame size |
| 3474 |
is purely static. |
| 3475 |
It usually means that all local variables have a static size. |
| 3476 |
In this case, the second field is a reliable measure of the function stack |
| 3477 |
utilization. |
| 3478 |
|
| 3479 |
The qualifier ``dynamic`` means that the function frame size is not static. |
| 3480 |
It happens mainly when some local variables have a dynamic size. When this |
| 3481 |
qualifier appears alone, the second field is not a reliable measure |
| 3482 |
of the function stack analysis. When it is qualified with ``bounded``, it |
| 3483 |
means that the second field is a reliable maximum of the function stack |
| 3484 |
utilization. |
| 3485 |
|
| 3486 |
Compilation of a unit with the :switch:`-Wstack-usage` switch will |
| 3487 |
issue a warning for each subprogram whose stack usage might be larger |
| 3488 |
than the specified amount of bytes. The wording of that warning is |
| 3489 |
consistent with that in the file documented above. |
| 3490 |
|
| 3491 |
This is not supported by the LLVM back end. |
| 3492 |
|
| 3493 |
|
| 3494 |
.. _Dynamic_Stack_Usage_Analysis: |
| 3495 |
|
| 3496 |
Dynamic Stack Usage Analysis |
| 3497 |
---------------------------- |
| 3498 |
|
| 3499 |
You can measure the maximum amount of stack used by a task by |
| 3500 |
adding a switch to ``gnatbind``, as: |
| 3501 |
|
| 3502 |
:: |
| 3503 |
|
| 3504 |
$ gnatbind -u0 file |
| 3505 |
|
| 3506 |
With this option, at each task termination, its stack usage is output on |
| 3507 |
:file:`stderr`. |
| 3508 |
Note that this switch is not compatible with tools like |
| 3509 |
Valgrind and DrMemory; they will report errors. |
| 3510 |
|
| 3511 |
It is not always convenient to output the stack usage when the program |
| 3512 |
is still running. Hence, you can delay this output until the |
| 3513 |
termination of the number of tasks specified as the argument of the |
| 3514 |
:switch:`-u` switch. For example: |
| 3515 |
|
| 3516 |
:: |
| 3517 |
|
| 3518 |
$ gnatbind -u100 file |
| 3519 |
|
| 3520 |
buffers the stack usage information of the first 100 tasks to terminate and |
| 3521 |
outputs it when the program terminates. Results are displayed in four |
| 3522 |
columns: |
| 3523 |
|
| 3524 |
:: |
| 3525 |
|
| 3526 |
Index | Task Name | Stack Size | Stack Usage |
| 3527 |
|
| 3528 |
where: |
| 3529 |
|
| 3530 |
* *Index* is a number associated with each task. |
| 3531 |
|
| 3532 |
* *Task Name* is the name of the task analyzed. |
| 3533 |
|
| 3534 |
* *Stack Size* is the maximum size for the stack. |
| 3535 |
|
| 3536 |
* *Stack Usage* is the measure done by the stack analyzer. |
| 3537 |
In order to prevent overflow, the stack |
| 3538 |
is not entirely analyzed, and it's not possible to know exactly how |
| 3539 |
much has actually been used. |
| 3540 |
|
| 3541 |
By default, ``gnatbind`` does not process the environment task stack, |
| 3542 |
the stack that contains the main unit. To enable processing of the |
| 3543 |
environment task stack, set the environment variable GNAT_STACK_LIMIT |
| 3544 |
to the maximum size of the environment task stack. This amount is |
| 3545 |
given in kilobytes. For example: |
| 3546 |
|
| 3547 |
:: |
| 3548 |
|
| 3549 |
$ set GNAT_STACK_LIMIT 1600 |
| 3550 |
|
| 3551 |
would specify to the analyzer that the environment task stack has a limit |
| 3552 |
of 1.6 megabytes. Any stack usage beyond this will be ignored by the analysis. |
| 3553 |
|
| 3554 |
This is not suppored by the LLVM back end. |
| 3555 |
|
| 3556 |
The package ``GNAT.Task_Stack_Usage`` provides facilities to get |
| 3557 |
stack-usage reports at run time. See its body for the details. |
| 3558 |
|
| 3559 |
|
| 3560 |
|
| 3561 |
.. _Memory_Management_Issues: |
| 3562 |
|
| 3563 |
Memory Management Issues |
| 3564 |
======================== |
| 3565 |
|
| 3566 |
This section describes some useful memory pools provided in the GNAT library, |
| 3567 |
and in particular the GNAT Debug Pool facility, which can be used to detect |
| 3568 |
incorrect uses of access values (including 'dangling references'). |
| 3569 |
|
| 3570 |
.. only:: PRO or GPL |
| 3571 |
|
| 3572 |
It also describes the ``gnatmem`` tool, which can be used to track down |
| 3573 |
"memory leaks". |
| 3574 |
|
| 3575 |
.. _Some_Useful_Memory_Pools: |
| 3576 |
|
| 3577 |
Some Useful Memory Pools |
| 3578 |
------------------------ |
| 3579 |
|
| 3580 |
.. index:: Memory Pool |
| 3581 |
.. index:: storage, pool |
| 3582 |
|
| 3583 |
The ``System.Pool_Global`` package provides the ``Unbounded_No_Reclaim_Pool`` |
| 3584 |
storage pool. Allocations use the standard system call ``malloc`` while |
| 3585 |
deallocations use the standard system call ``free``. No reclamation is |
| 3586 |
performed when the pool goes out of scope. For performance reasons, the |
| 3587 |
standard default Ada allocators/deallocators do not use any explicit storage |
| 3588 |
pools but if they did, they could use this storage pool without any change in |
| 3589 |
behavior. That is why this storage pool is used when the user |
| 3590 |
makes the default implicit allocator explicit as in this example: |
| 3591 |
|
| 3592 |
.. code-block:: ada |
| 3593 |
|
| 3594 |
type T1 is access Something; |
| 3595 |
-- no Storage pool is defined for T2 |
| 3596 |
|
| 3597 |
type T2 is access Something_Else; |
| 3598 |
for T2'Storage_Pool use T1'Storage_Pool; |
| 3599 |
-- the above is equivalent to |
| 3600 |
for T2'Storage_Pool use System.Pool_Global.Global_Pool_Object; |
| 3601 |
|
| 3602 |
The ``System.Pool_Local`` package provides the ``Unbounded_Reclaim_Pool`` storage |
| 3603 |
pool. Its allocation strategy is similar to ``Pool_Local`` |
| 3604 |
except that the all |
| 3605 |
storage allocated with this pool is reclaimed when the pool object goes out of |
| 3606 |
scope. This pool provides a explicit mechanism similar to the implicit one |
| 3607 |
provided by several Ada 83 compilers for allocations performed through a local |
| 3608 |
access type and whose purpose was to reclaim memory when exiting the |
| 3609 |
scope of a given local access. As an example, the following program does not |
| 3610 |
leak memory even though it does not perform explicit deallocation: |
| 3611 |
|
| 3612 |
.. code-block:: ada |
| 3613 |
|
| 3614 |
with System.Pool_Local; |
| 3615 |
procedure Pooloc1 is |
| 3616 |
procedure Internal is |
| 3617 |
type A is access Integer; |
| 3618 |
X : System.Pool_Local.Unbounded_Reclaim_Pool; |
| 3619 |
for A'Storage_Pool use X; |
| 3620 |
v : A; |
| 3621 |
begin |
| 3622 |
for I in 1 .. 50 loop |
| 3623 |
v := new Integer; |
| 3624 |
end loop; |
| 3625 |
end Internal; |
| 3626 |
begin |
| 3627 |
for I in 1 .. 100 loop |
| 3628 |
Internal; |
| 3629 |
end loop; |
| 3630 |
end Pooloc1; |
| 3631 |
|
| 3632 |
The ``System.Pool_Size`` package implements the ``Stack_Bounded_Pool`` used when |
| 3633 |
``Storage_Size`` is specified for an access type. |
| 3634 |
The whole storage for the pool is |
| 3635 |
allocated at once, usually on the stack at the point where the access type is |
| 3636 |
elaborated. It is automatically reclaimed when exiting the scope where the |
| 3637 |
access type is defined. This package is not intended to be used directly by the |
| 3638 |
user; it is implicitly used for each declaration with a specified |
| 3639 |
``Storage_Size``: |
| 3640 |
|
| 3641 |
.. code-block:: ada |
| 3642 |
|
| 3643 |
type T1 is access Something; |
| 3644 |
for T1'Storage_Size use 10_000; |
| 3645 |
|
| 3646 |
|
| 3647 |
.. _The_GNAT_Debug_Pool_Facility: |
| 3648 |
|
| 3649 |
The GNAT Debug Pool Facility |
| 3650 |
---------------------------- |
| 3651 |
|
| 3652 |
.. index:: Debug Pool |
| 3653 |
.. index:: storage, pool, memory corruption |
| 3654 |
|
| 3655 |
Using unchecked deallocation and unchecked conversion can easily |
| 3656 |
lead to incorrect memory references. The problems generated by such |
| 3657 |
references are usually difficult to find because the symptoms can be |
| 3658 |
very remote from the origin of the problem. In such cases, it is |
| 3659 |
very helpful to detect the problem as early as possible. This is the |
| 3660 |
purpose of the Storage Pool provided by ``GNAT.Debug_Pools``. |
| 3661 |
|
| 3662 |
In order to use the GNAT specific debugging pool, you must |
| 3663 |
associate a debug pool object with each of the access types that may be |
| 3664 |
related to suspected memory problems. See Ada Reference Manual 13.11. |
| 3665 |
|
| 3666 |
.. code-block:: ada |
| 3667 |
|
| 3668 |
type Ptr is access Some_Type; |
| 3669 |
Pool : GNAT.Debug_Pools.Debug_Pool; |
| 3670 |
for Ptr'Storage_Pool use Pool; |
| 3671 |
|
| 3672 |
``GNAT.Debug_Pools`` is derived from a GNAT-specific kind of |
| 3673 |
pool: the ``Checked_Pool``. Such pools, like standard Ada storage pools, |
| 3674 |
allow you to redefine allocation and deallocation strategies. They |
| 3675 |
also provide a checkpoint for each dereference through the use of |
| 3676 |
the primitive operation ``Dereference`` which is implicitly called at |
| 3677 |
each dereference of an access value. |
| 3678 |
|
| 3679 |
Once you have associated an access type with a debug pool, operations on |
| 3680 |
values of the type may raise four distinct exceptions, |
| 3681 |
which correspond to four potential kinds of memory corruption: |
| 3682 |
|
| 3683 |
* ``GNAT.Debug_Pools.Accessing_Not_Allocated_Storage`` |
| 3684 |
* ``GNAT.Debug_Pools.Accessing_Deallocated_Storage`` |
| 3685 |
* ``GNAT.Debug_Pools.Freeing_Not_Allocated_Storage`` |
| 3686 |
* ``GNAT.Debug_Pools.Freeing_Deallocated_Storage`` |
| 3687 |
|
| 3688 |
For types associated with a Debug_Pool, dynamic allocation is performed using |
| 3689 |
the standard GNAT allocation routine. References to all allocated chunks of |
| 3690 |
memory are kept in an internal dictionary. Several deallocation strategies are |
| 3691 |
provided, allowing you to choose to release the memory to the system, |
| 3692 |
keep it allocated for further invalid access checks, or fill it with an easily |
| 3693 |
recognizable pattern for debug sessions. The memory pattern is the old IBM |
| 3694 |
hexadecimal convention: ``16#DEADBEEF#``. |
| 3695 |
|
| 3696 |
See the documentation in the file :file:`g-debpoo.ads` for more |
| 3697 |
information on the various strategies. |
| 3698 |
|
| 3699 |
Upon each dereference, a check is made that the access value denotes a |
| 3700 |
properly allocated memory location. Here's a complete example of use of |
| 3701 |
``Debug_Pools``, which includes typical instances of memory corruption: |
| 3702 |
|
| 3703 |
.. code-block:: ada |
| 3704 |
|
| 3705 |
with GNAT.IO; use GNAT.IO; |
| 3706 |
with Ada.Unchecked_Deallocation; |
| 3707 |
with Ada.Unchecked_Conversion; |
| 3708 |
with GNAT.Debug_Pools; |
| 3709 |
with System.Storage_Elements; |
| 3710 |
with Ada.Exceptions; use Ada.Exceptions; |
| 3711 |
procedure Debug_Pool_Test is |
| 3712 |
|
| 3713 |
type T is access Integer; |
| 3714 |
type U is access all T; |
| 3715 |
|
| 3716 |
P : GNAT.Debug_Pools.Debug_Pool; |
| 3717 |
for T'Storage_Pool use P; |
| 3718 |
|
| 3719 |
procedure Free is new Ada.Unchecked_Deallocation (Integer, T); |
| 3720 |
function UC is new Ada.Unchecked_Conversion (U, T); |
| 3721 |
A, B : aliased T; |
| 3722 |
|
| 3723 |
procedure Info is new GNAT.Debug_Pools.Print_Info(Put_Line); |
| 3724 |
|
| 3725 |
begin |
| 3726 |
Info (P); |
| 3727 |
A := new Integer; |
| 3728 |
B := new Integer; |
| 3729 |
B := A; |
| 3730 |
Info (P); |
| 3731 |
Free (A); |
| 3732 |
begin |
| 3733 |
Put_Line (Integer'Image(B.all)); |
| 3734 |
exception |
| 3735 |
when E : others => Put_Line ("raised: " & Exception_Name (E)); |
| 3736 |
end; |
| 3737 |
begin |
| 3738 |
Free (B); |
| 3739 |
exception |
| 3740 |
when E : others => Put_Line ("raised: " & Exception_Name (E)); |
| 3741 |
end; |
| 3742 |
B := UC(A'Access); |
| 3743 |
begin |
| 3744 |
Put_Line (Integer'Image(B.all)); |
| 3745 |
exception |
| 3746 |
when E : others => Put_Line ("raised: " & Exception_Name (E)); |
| 3747 |
end; |
| 3748 |
begin |
| 3749 |
Free (B); |
| 3750 |
exception |
| 3751 |
when E : others => Put_Line ("raised: " & Exception_Name (E)); |
| 3752 |
end; |
| 3753 |
Info (P); |
| 3754 |
end Debug_Pool_Test; |
| 3755 |
|
| 3756 |
The debug pool mechanism provides the following precise diagnostics on the |
| 3757 |
execution of this erroneous program: |
| 3758 |
|
| 3759 |
:: |
| 3760 |
|
| 3761 |
Debug Pool info: |
| 3762 |
Total allocated bytes : 0 |
| 3763 |
Total deallocated bytes : 0 |
| 3764 |
Current Water Mark: 0 |
| 3765 |
High Water Mark: 0 |
| 3766 |
|
| 3767 |
Debug Pool info: |
| 3768 |
Total allocated bytes : 8 |
| 3769 |
Total deallocated bytes : 0 |
| 3770 |
Current Water Mark: 8 |
| 3771 |
High Water Mark: 8 |
| 3772 |
|
| 3773 |
raised: GNAT.DEBUG_POOLS.ACCESSING_DEALLOCATED_STORAGE |
| 3774 |
raised: GNAT.DEBUG_POOLS.FREEING_DEALLOCATED_STORAGE |
| 3775 |
raised: GNAT.DEBUG_POOLS.ACCESSING_NOT_ALLOCATED_STORAGE |
| 3776 |
raised: GNAT.DEBUG_POOLS.FREEING_NOT_ALLOCATED_STORAGE |
| 3777 |
Debug Pool info: |
| 3778 |
Total allocated bytes : 8 |
| 3779 |
Total deallocated bytes : 4 |
| 3780 |
Current Water Mark: 4 |
| 3781 |
High Water Mark: 8 |
| 3782 |
|
| 3783 |
.. only:: PRO or GPL |
| 3784 |
|
| 3785 |
.. _The_gnatmem_Tool: |
| 3786 |
|
| 3787 |
The ``gnatmem`` Tool |
| 3788 |
-------------------- |
| 3789 |
|
| 3790 |
.. index:: ! gnatmem |
| 3791 |
|
| 3792 |
The ``gnatmem`` utility monitors dynamic allocation and |
| 3793 |
deallocation activity in a program, and displays information about |
| 3794 |
incorrect deallocations and possible sources of memory leaks. |
| 3795 |
It is designed to work for fixed-position executables that use |
| 3796 |
a static runtime library and, in this context, provides three |
| 3797 |
types of information: |
| 3798 |
|
| 3799 |
* General information concerning memory management, such as the total |
| 3800 |
number of allocations and deallocations, the amount of allocated |
| 3801 |
memory and the high water mark, i.e., the largest amount of allocated |
| 3802 |
memory in the course of program execution. |
| 3803 |
|
| 3804 |
* Backtraces for all incorrect deallocations, which are deallocations |
| 3805 |
that do not correspond to a valid allocation. |
| 3806 |
|
| 3807 |
* Information on each allocation that is potentially the origin of a memory |
| 3808 |
leak. |
| 3809 |
|
| 3810 |
.. _Running_gnatmem: |
| 3811 |
|
| 3812 |
Running ``gnatmem`` |
| 3813 |
^^^^^^^^^^^^^^^^^^^ |
| 3814 |
|
| 3815 |
``gnatmem`` makes use of the output created by the special version of |
| 3816 |
allocation and deallocation routines that record call information. This allows |
| 3817 |
it to obtain accurate dynamic memory usage history at a minimal cost to the |
| 3818 |
execution speed. Note however, that ``gnatmem`` is only supported on |
| 3819 |
GNU/Linux and Windows. |
| 3820 |
|
| 3821 |
The ``gnatmem`` command has the form |
| 3822 |
|
| 3823 |
:: |
| 3824 |
|
| 3825 |
$ gnatmem [ switches ] [ DEPTH ] user_program |
| 3826 |
|
| 3827 |
You must link your program with the instrumented version of the |
| 3828 |
allocation and deallocation routines. You do this by linking with the |
| 3829 |
:file:`libgmem.a` library. For correct symbolic backtrace information, |
| 3830 |
you should also compile your program with debugging options |
| 3831 |
(see :ref:`Switches_for_gcc`) and be linked at a fixed position (with |
| 3832 |
:switch:`-no-pie`). For example to build :file:`my_program` with |
| 3833 |
``gnatmake``: |
| 3834 |
|
| 3835 |
:: |
| 3836 |
|
| 3837 |
$ gnatmake my_program -g -largs -lgmem -no-pie |
| 3838 |
|
| 3839 |
Because library :file:`libgmem.a` contains an alternate body for package |
| 3840 |
``System.Memory``, you should not compile and link :file:`s-memory.adb` |
| 3841 |
when you link an executable with library :file:`libgmem.a`. In that case, |
| 3842 |
we don't recommended specifying switch :switch:`-a` to ``gnatmake``. |
| 3843 |
|
| 3844 |
When :file:`my_program` is executed, the file :file:`gmem.out` is produced. |
| 3845 |
This file contains information about all allocations and deallocations |
| 3846 |
performed by the program. It is produced by the instrumented allocations and |
| 3847 |
deallocations routines and will be used by ``gnatmem``. |
| 3848 |
|
| 3849 |
To produce symbolic backtrace information for allocations and |
| 3850 |
deallocations performed by the GNAT run-time library, you need to use a |
| 3851 |
version of that library that has been compiled with the :switch:`-g` switch |
| 3852 |
(see :ref:`Rebuilding_the_GNAT_Run-Time_Library`). |
| 3853 |
|
| 3854 |
You must supply ``gnatmem`` with the :file:`gmem.out` file and the executable to |
| 3855 |
examine. If the location of :file:`gmem.out` file was not explicitly supplied by |
| 3856 |
:switch:`-i` switch, ``gnatmem`` assumes that this file can be found in the |
| 3857 |
current directory. For example, after you have executed :file:`my_program`, |
| 3858 |
:file:`gmem.out` can be analyzed by ``gnatmem`` using the command: |
| 3859 |
|
| 3860 |
:: |
| 3861 |
|
| 3862 |
$ gnatmem my_program |
| 3863 |
|
| 3864 |
This will produce the output with the following format: |
| 3865 |
|
| 3866 |
:: |
| 3867 |
|
| 3868 |
$ gnatmem my_program |
| 3869 |
|
| 3870 |
Global information |
| 3871 |
------------------ |
| 3872 |
Total number of allocations : 45 |
| 3873 |
Total number of deallocations : 6 |
| 3874 |
Final Water Mark (non freed mem) : 11.29 Kilobytes |
| 3875 |
High Water Mark : 11.40 Kilobytes |
| 3876 |
|
| 3877 |
. |
| 3878 |
. |
| 3879 |
. |
| 3880 |
Allocation Root # 2 |
| 3881 |
------------------- |
| 3882 |
Number of non freed allocations : 11 |
| 3883 |
Final Water Mark (non freed mem) : 1.16 Kilobytes |
| 3884 |
High Water Mark : 1.27 Kilobytes |
| 3885 |
Backtrace : |
| 3886 |
my_program.adb:23 my_program.alloc |
| 3887 |
. |
| 3888 |
. |
| 3889 |
. |
| 3890 |
|
| 3891 |
The first block of output gives general information. In this case, the |
| 3892 |
Ada construct ``new`` was executed 45 times and only 6 calls to an |
| 3893 |
``Unchecked_Deallocation`` routine occurred. |
| 3894 |
|
| 3895 |
Subsequent paragraphs display information on all allocation roots. |
| 3896 |
An *allocation root* is a specific point in the execution of the program |
| 3897 |
that generates some dynamic allocation, such as a ``new`` |
| 3898 |
construct. This root is represented by an execution backtrace (or subprogram |
| 3899 |
call stack). By default, the backtrace depth for allocations roots is 1, so |
| 3900 |
that a root corresponds exactly to a source location. The backtrace can |
| 3901 |
be made deeper, to make the root more specific. |
| 3902 |
|
| 3903 |
.. _Switches_for_gnatmem: |
| 3904 |
|
| 3905 |
Switches for ``gnatmem`` |
| 3906 |
^^^^^^^^^^^^^^^^^^^^^^^^ |
| 3907 |
|
| 3908 |
``gnatmem`` recognizes the following switches: |
| 3909 |
|
| 3910 |
.. index:: -q (gnatmem) |
| 3911 |
|
| 3912 |
:switch:`-q` |
| 3913 |
Quiet. Gives the minimum output needed to identify the origin of the |
| 3914 |
memory leaks. Omits statistical information. |
| 3915 |
|
| 3916 |
|
| 3917 |
.. index:: DEPTH switch (gnatmem) |
| 3918 |
|
| 3919 |
:switch:`{DEPTH}` |
| 3920 |
``DEPTH`` is an integer literal (usually between 1 and 10) which controls |
| 3921 |
the depth of the backtraces defining allocation root. The default value for |
| 3922 |
DEPTH is 1. The deeper the backtrace, the more precise the localization of |
| 3923 |
the root. Note that the total number of roots can depend on this |
| 3924 |
parameter; in other words there may be more roots when the requested |
| 3925 |
backtrace depth is higher. You must specify this parameter *before* the |
| 3926 |
name of the executable to be analyzed, to avoid ambiguity. |
| 3927 |
|
| 3928 |
|
| 3929 |
.. index:: -b (gnatmem) |
| 3930 |
|
| 3931 |
:switch:`-b {N}` |
| 3932 |
This switch has the same effect as just a depth parameter ``N``. |
| 3933 |
|
| 3934 |
|
| 3935 |
.. index:: -i (gnatmem) |
| 3936 |
|
| 3937 |
:switch:`-i {file}` |
| 3938 |
Do the ``gnatmem`` processing starting from :file:`file`, rather than |
| 3939 |
:file:`gmem.out` in the current directory. |
| 3940 |
|
| 3941 |
|
| 3942 |
.. index:: -m (gnatmem) |
| 3943 |
|
| 3944 |
:switch:`-m {n}` |
| 3945 |
This switch causes ``gnatmem`` to mask the allocation roots that have less |
| 3946 |
than ``n`` leaks. The default value is 1. Specifying the value of 0 will allow |
| 3947 |
examination of even the roots that did not result in leaks. |
| 3948 |
|
| 3949 |
|
| 3950 |
.. index:: -s (gnatmem) |
| 3951 |
|
| 3952 |
:switch:`-s {order}` |
| 3953 |
This switch causes ``gnatmem`` to sort the allocation roots |
| 3954 |
according to the specified sort criteria, each identified by a |
| 3955 |
single letter. The currently supported criteria are ``n``, ``h``, |
| 3956 |
and ``w`` representing, respectively, the number of unfreed |
| 3957 |
allocations, the high watermark, and the final watermark corresponding to |
| 3958 |
a specific root. The default order is ``nwh``. |
| 3959 |
|
| 3960 |
|
| 3961 |
.. index:: -t (gnatmem) |
| 3962 |
|
| 3963 |
:switch:`-t` |
| 3964 |
This switch causes memory allocated size to be always output in bytes. |
| 3965 |
The default ``gnatmem`` behavior is to show memory sizes less then 1 kilobyte |
| 3966 |
in bytes, from 1 kilobyte till 1 megabyte in kilobytes and the rest in |
| 3967 |
megabytes. |
| 3968 |
|
| 3969 |
|
| 3970 |
.. _Example_of_gnatmem_Usage: |
| 3971 |
|
| 3972 |
Example of ``gnatmem`` Usage |
| 3973 |
^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 3974 |
|
| 3975 |
The following example shows the use of ``gnatmem`` |
| 3976 |
on a simple memory-leaking program. |
| 3977 |
Suppose that we have the following Ada program: |
| 3978 |
|
| 3979 |
.. code-block:: ada |
| 3980 |
|
| 3981 |
with Ada.Unchecked_Deallocation; |
| 3982 |
procedure Test_Gm is |
| 3983 |
|
| 3984 |
type T is array (1..1000) of Integer; |
| 3985 |
type Ptr is access T; |
| 3986 |
procedure Free is new Ada.Unchecked_Deallocation (T, Ptr); |
| 3987 |
A : Ptr; |
| 3988 |
|
| 3989 |
procedure My_Alloc is |
| 3990 |
begin |
| 3991 |
A := new T; |
| 3992 |
end My_Alloc; |
| 3993 |
|
| 3994 |
procedure My_DeAlloc is |
| 3995 |
B : Ptr := A; |
| 3996 |
begin |
| 3997 |
Free (B); |
| 3998 |
end My_DeAlloc; |
| 3999 |
|
| 4000 |
begin |
| 4001 |
My_Alloc; |
| 4002 |
for I in 1 .. 5 loop |
| 4003 |
for J in I .. 5 loop |
| 4004 |
My_Alloc; |
| 4005 |
end loop; |
| 4006 |
My_Dealloc; |
| 4007 |
end loop; |
| 4008 |
end; |
| 4009 |
|
| 4010 |
The program needs to be compiled with the debugging option and linked with |
| 4011 |
the ``gmem`` library: |
| 4012 |
|
| 4013 |
:: |
| 4014 |
|
| 4015 |
$ gnatmake -g test_gm -largs -lgmem |
| 4016 |
|
| 4017 |
We execute the program as usual: |
| 4018 |
|
| 4019 |
:: |
| 4020 |
|
| 4021 |
$ test_gm |
| 4022 |
|
| 4023 |
``gnatmem`` is invoked simply with |
| 4024 |
|
| 4025 |
:: |
| 4026 |
|
| 4027 |
$ gnatmem test_gm |
| 4028 |
|
| 4029 |
which produces the following output (the details may vary on |
| 4030 |
different platforms): |
| 4031 |
|
| 4032 |
:: |
| 4033 |
|
| 4034 |
Global information |
| 4035 |
------------------ |
| 4036 |
Total number of allocations : 18 |
| 4037 |
Total number of deallocations : 5 |
| 4038 |
Final Water Mark (non freed mem) : 53.00 Kilobytes |
| 4039 |
High Water Mark : 56.90 Kilobytes |
| 4040 |
|
| 4041 |
Allocation Root # 1 |
| 4042 |
------------------- |
| 4043 |
Number of non freed allocations : 11 |
| 4044 |
Final Water Mark (non freed mem) : 42.97 Kilobytes |
| 4045 |
High Water Mark : 46.88 Kilobytes |
| 4046 |
Backtrace : |
| 4047 |
test_gm.adb:11 test_gm.my_alloc |
| 4048 |
|
| 4049 |
Allocation Root # 2 |
| 4050 |
------------------- |
| 4051 |
Number of non freed allocations : 1 |
| 4052 |
Final Water Mark (non freed mem) : 10.02 Kilobytes |
| 4053 |
High Water Mark : 10.02 Kilobytes |
| 4054 |
Backtrace : |
| 4055 |
s-secsta.adb:81 system.secondary_stack.ss_init |
| 4056 |
|
| 4057 |
Allocation Root # 3 |
| 4058 |
------------------- |
| 4059 |
Number of non freed allocations : 1 |
| 4060 |
Final Water Mark (non freed mem) : 12 Bytes |
| 4061 |
High Water Mark : 12 Bytes |
| 4062 |
Backtrace : |
| 4063 |
s-secsta.adb:181 system.secondary_stack.ss_init |
| 4064 |
|
| 4065 |
|
| 4066 |
Note that the GNAT runtime itself contains a certain number of |
| 4067 |
allocations that have no corresponding deallocations, |
| 4068 |
as shown here for root #2 and root #3. |
| 4069 |
This is a normal behavior when the number of non-freed allocations |
| 4070 |
is one: it allocates dynamic data structures that the run time needs for |
| 4071 |
the complete lifetime of the program. Note also that there is only one |
| 4072 |
allocation root in the user program, with a single line back trace: |
| 4073 |
``test_gm.adb:11 test_gm.my_alloc``, whereas a careful analysis of the |
| 4074 |
program shows that ``My_Alloc`` is called at 2 different points in the |
| 4075 |
source (line 21 and line 24). If those two allocation roots need to be |
| 4076 |
distinguished, you can use the backtrace depth parameter: |
| 4077 |
|
| 4078 |
:: |
| 4079 |
|
| 4080 |
$ gnatmem 3 test_gm |
| 4081 |
|
| 4082 |
which produces the following output: |
| 4083 |
|
| 4084 |
|
| 4085 |
:: |
| 4086 |
|
| 4087 |
Global information |
| 4088 |
------------------ |
| 4089 |
Total number of allocations : 18 |
| 4090 |
Total number of deallocations : 5 |
| 4091 |
Final Water Mark (non freed mem) : 53.00 Kilobytes |
| 4092 |
High Water Mark : 56.90 Kilobytes |
| 4093 |
|
| 4094 |
Allocation Root # 1 |
| 4095 |
------------------- |
| 4096 |
Number of non freed allocations : 10 |
| 4097 |
Final Water Mark (non freed mem) : 39.06 Kilobytes |
| 4098 |
High Water Mark : 42.97 Kilobytes |
| 4099 |
Backtrace : |
| 4100 |
test_gm.adb:11 test_gm.my_alloc |
| 4101 |
test_gm.adb:24 test_gm |
| 4102 |
b_test_gm.c:52 main |
| 4103 |
|
| 4104 |
Allocation Root # 2 |
| 4105 |
------------------- |
| 4106 |
Number of non freed allocations : 1 |
| 4107 |
Final Water Mark (non freed mem) : 10.02 Kilobytes |
| 4108 |
High Water Mark : 10.02 Kilobytes |
| 4109 |
Backtrace : |
| 4110 |
s-secsta.adb:81 system.secondary_stack.ss_init |
| 4111 |
s-secsta.adb:283 <system__secondary_stack___elabb> |
| 4112 |
b_test_gm.c:33 adainit |
| 4113 |
|
| 4114 |
Allocation Root # 3 |
| 4115 |
------------------- |
| 4116 |
Number of non freed allocations : 1 |
| 4117 |
Final Water Mark (non freed mem) : 3.91 Kilobytes |
| 4118 |
High Water Mark : 3.91 Kilobytes |
| 4119 |
Backtrace : |
| 4120 |
test_gm.adb:11 test_gm.my_alloc |
| 4121 |
test_gm.adb:21 test_gm |
| 4122 |
b_test_gm.c:52 main |
| 4123 |
|
| 4124 |
Allocation Root # 4 |
| 4125 |
------------------- |
| 4126 |
Number of non freed allocations : 1 |
| 4127 |
Final Water Mark (non freed mem) : 12 Bytes |
| 4128 |
High Water Mark : 12 Bytes |
| 4129 |
Backtrace : |
| 4130 |
s-secsta.adb:181 system.secondary_stack.ss_init |
| 4131 |
s-secsta.adb:283 <system__secondary_stack___elabb> |
| 4132 |
b_test_gm.c:33 adainit |
| 4133 |
|
| 4134 |
The allocation root #1 of the first example has been split in 2 roots #1 |
| 4135 |
and #3, thanks to the more precise associated backtrace. |