Unconditionally use MAX_EXPR/MIN_EXPR for MAX/MIN intrinsics
[official-gcc.git] / gcc / fortran / gfortran.texi
blob0f3f454ff83692a9c0008817d697cf55fbed33f2
1 \input texinfo  @c -*-texinfo-*-
2 @c %**start of header
3 @setfilename gfortran.info
4 @set copyrights-gfortran 1999-2018
6 @include gcc-common.texi
8 @settitle The GNU Fortran Compiler
10 @c Create a separate index for command line options
11 @defcodeindex op
12 @c Merge the standard indexes into a single one.
13 @syncodeindex fn cp
14 @syncodeindex vr cp
15 @syncodeindex ky cp
16 @syncodeindex pg cp
17 @syncodeindex tp cp
19 @c TODO: The following "Part" definitions are included here temporarily
20 @c until they are incorporated into the official Texinfo distribution.
21 @c They borrow heavily from Texinfo's \unnchapentry definitions.
23 @tex
24 \gdef\part#1#2{%
25   \pchapsepmacro
26   \gdef\thischapter{}
27   \begingroup
28     \vglue\titlepagetopglue
29     \titlefonts \rm
30     \leftline{Part #1:@* #2}
31     \vskip4pt \hrule height 4pt width \hsize \vskip4pt
32   \endgroup
33   \writetocentry{part}{#2}{#1}
35 \gdef\blankpart{%
36   \writetocentry{blankpart}{}{}
38 % Part TOC-entry definition for summary contents.
39 \gdef\dosmallpartentry#1#2#3#4{%
40   \vskip .5\baselineskip plus.2\baselineskip
41   \begingroup
42     \let\rm=\bf \rm
43     \tocentry{Part #2: #1}{\doshortpageno\bgroup#4\egroup}
44   \endgroup
46 \gdef\dosmallblankpartentry#1#2#3#4{%
47   \vskip .5\baselineskip plus.2\baselineskip
49 % Part TOC-entry definition for regular contents.  This has to be
50 % equated to an existing entry to not cause problems when the PDF
51 % outline is created.
52 \gdef\dopartentry#1#2#3#4{%
53   \unnchapentry{Part #2: #1}{}{#3}{#4}
55 \gdef\doblankpartentry#1#2#3#4{}
56 @end tex
58 @c %**end of header
60 @c Use with @@smallbook.
62 @c %** start of document
64 @c Cause even numbered pages to be printed on the left hand side of
65 @c the page and odd numbered pages to be printed on the right hand
66 @c side of the page.  Using this, you can print on both sides of a
67 @c sheet of paper and have the text on the same part of the sheet.
69 @c The text on right hand pages is pushed towards the right hand
70 @c margin and the text on left hand pages is pushed toward the left
71 @c hand margin.
72 @c (To provide the reverse effect, set bindingoffset to -0.75in.)
74 @c @tex
75 @c \global\bindingoffset=0.75in
76 @c \global\normaloffset =0.75in
77 @c @end tex
79 @copying
80 Copyright @copyright{} @value{copyrights-gfortran} Free Software Foundation, Inc.
82 Permission is granted to copy, distribute and/or modify this document
83 under the terms of the GNU Free Documentation License, Version 1.3 or
84 any later version published by the Free Software Foundation; with the
85 Invariant Sections being ``Funding Free Software'', the Front-Cover
86 Texts being (a) (see below), and with the Back-Cover Texts being (b)
87 (see below).  A copy of the license is included in the section entitled
88 ``GNU Free Documentation License''.
90 (a) The FSF's Front-Cover Text is:
92      A GNU Manual
94 (b) The FSF's Back-Cover Text is:
96      You have freedom to copy and modify this GNU Manual, like GNU
97      software.  Copies published by the Free Software Foundation raise
98      funds for GNU development.
99 @end copying
101 @ifinfo
102 @dircategory Software development
103 @direntry
104 * gfortran: (gfortran).                  The GNU Fortran Compiler.
105 @end direntry
106 This file documents the use and the internals of
107 the GNU Fortran compiler, (@command{gfortran}).
109 Published by the Free Software Foundation
110 51 Franklin Street, Fifth Floor
111 Boston, MA 02110-1301 USA
113 @insertcopying
114 @end ifinfo
117 @setchapternewpage odd
118 @titlepage
119 @title Using GNU Fortran
120 @versionsubtitle
121 @author The @t{gfortran} team
122 @page
123 @vskip 0pt plus 1filll
124 Published by the Free Software Foundation@*
125 51 Franklin Street, Fifth Floor@*
126 Boston, MA 02110-1301, USA@*
127 @c Last printed ??ber, 19??.@*
128 @c Printed copies are available for $? each.@*
129 @c ISBN ???
130 @sp 1
131 @insertcopying
132 @end titlepage
134 @c TODO: The following "Part" definitions are included here temporarily
135 @c until they are incorporated into the official Texinfo distribution.
137 @tex
138 \global\let\partentry=\dosmallpartentry
139 \global\let\blankpartentry=\dosmallblankpartentry
140 @end tex
141 @summarycontents
143 @tex
144 \global\let\partentry=\dopartentry
145 \global\let\blankpartentry=\doblankpartentry
146 @end tex
147 @contents
149 @page
151 @c ---------------------------------------------------------------------
152 @c TexInfo table of contents.
153 @c ---------------------------------------------------------------------
155 @ifnottex
156 @node Top
157 @top Introduction
158 @cindex Introduction
160 This manual documents the use of @command{gfortran},
161 the GNU Fortran compiler.  You can find in this manual how to invoke
162 @command{gfortran}, as well as its features and incompatibilities.
164 @ifset DEVELOPMENT
165 @emph{Warning:} This document, and the compiler it describes, are still
166 under development.  While efforts are made to keep it up-to-date, it might
167 not accurately reflect the status of the most recent GNU Fortran compiler.
168 @end ifset
170 @comment
171 @comment  When you add a new menu item, please keep the right hand
172 @comment  aligned to the same column.  Do not use tabs.  This provides
173 @comment  better formatting.
174 @comment
175 @menu
176 * Introduction::
178 Part I: Invoking GNU Fortran
179 * Invoking GNU Fortran:: Command options supported by @command{gfortran}.
180 * Runtime::              Influencing runtime behavior with environment variables.
182 Part II: Language Reference
183 * Fortran standards status::      Fortran 2003, 2008 and 2018 features supported by GNU Fortran.
184 * Compiler Characteristics::      User-visible implementation details.
185 * Extensions::                    Language extensions implemented by GNU Fortran.
186 * Mixed-Language Programming::    Interoperability with C
187 * Coarray Programming::
188 * Intrinsic Procedures:: Intrinsic procedures supported by GNU Fortran.
189 * Intrinsic Modules::    Intrinsic modules supported by GNU Fortran.
191 * Contributing::         How you can help.
192 * Copying::              GNU General Public License says
193                          how you can copy and share GNU Fortran.
194 * GNU Free Documentation License::
195                          How you can copy and share this manual.
196 * Funding::              How to help assure continued work for free software.
197 * Option Index::         Index of command line options
198 * Keyword Index::        Index of concepts
199 @end menu
200 @end ifnottex
202 @c ---------------------------------------------------------------------
203 @c Introduction
204 @c ---------------------------------------------------------------------
206 @node Introduction
207 @chapter Introduction
209 @c The following duplicates the text on the TexInfo table of contents.
210 @iftex
211 This manual documents the use of @command{gfortran}, the GNU Fortran
212 compiler.  You can find in this manual how to invoke @command{gfortran},
213 as well as its features and incompatibilities.
215 @ifset DEVELOPMENT
216 @emph{Warning:} This document, and the compiler it describes, are still
217 under development.  While efforts are made to keep it up-to-date, it
218 might not accurately reflect the status of the most recent GNU Fortran
219 compiler.
220 @end ifset
221 @end iftex
223 The GNU Fortran compiler front end was
224 designed initially as a free replacement for,
225 or alternative to, the Unix @command{f95} command;
226 @command{gfortran} is the command you will use to invoke the compiler.
228 @menu
229 * About GNU Fortran::    What you should know about the GNU Fortran compiler.
230 * GNU Fortran and GCC::  You can compile Fortran, C, or other programs.
231 * Preprocessing and conditional compilation:: The Fortran preprocessor
232 * GNU Fortran and G77::  Why we chose to start from scratch.
233 * Project Status::       Status of GNU Fortran, roadmap, proposed extensions.
234 * Standards::            Standards supported by GNU Fortran.
235 @end menu
238 @c ---------------------------------------------------------------------
239 @c About GNU Fortran
240 @c ---------------------------------------------------------------------
242 @node About GNU Fortran
243 @section About GNU Fortran
245 The GNU Fortran compiler supports the Fortran 77, 90 and 95 standards
246 completely, parts of the Fortran 2003, 2008 and 2018 standards, and
247 several vendor extensions.  The development goal is to provide the
248 following features:
250 @itemize @bullet
251 @item
252 Read a user's program, stored in a file and containing instructions
253 written in Fortran 77, Fortran 90, Fortran 95, Fortran 2003, Fortran
254 2008 or Fortran 2018.  This file contains @dfn{source code}.
256 @item
257 Translate the user's program into instructions a computer
258 can carry out more quickly than it takes to translate the
259 instructions in the first
260 place.  The result after compilation of a program is
261 @dfn{machine code},
262 code designed to be efficiently translated and processed
263 by a machine such as your computer.
264 Humans usually are not as good writing machine code
265 as they are at writing Fortran (or C++, Ada, or Java),
266 because it is easy to make tiny mistakes writing machine code.
268 @item
269 Provide the user with information about the reasons why
270 the compiler is unable to create a binary from the source code.
271 Usually this will be the case if the source code is flawed.
272 The Fortran 90 standard requires that the compiler can point out
273 mistakes to the user.
274 An incorrect usage of the language causes an @dfn{error message}.
276 The compiler will also attempt to diagnose cases where the
277 user's program contains a correct usage of the language,
278 but instructs the computer to do something questionable.
279 This kind of diagnostics message is called a @dfn{warning message}.
281 @item
282 Provide optional information about the translation passes
283 from the source code to machine code.
284 This can help a user of the compiler to find the cause of
285 certain bugs which may not be obvious in the source code,
286 but may be more easily found at a lower level compiler output.
287 It also helps developers to find bugs in the compiler itself.
289 @item
290 Provide information in the generated machine code that can
291 make it easier to find bugs in the program (using a debugging tool,
292 called a @dfn{debugger}, such as the GNU Debugger @command{gdb}).
294 @item
295 Locate and gather machine code already generated to
296 perform actions requested by statements in the user's program.
297 This machine code is organized into @dfn{modules} and is located
298 and @dfn{linked} to the user program.
299 @end itemize
301 The GNU Fortran compiler consists of several components:
303 @itemize @bullet
304 @item
305 A version of the @command{gcc} command
306 (which also might be installed as the system's @command{cc} command)
307 that also understands and accepts Fortran source code.
308 The @command{gcc} command is the @dfn{driver} program for
309 all the languages in the GNU Compiler Collection (GCC);
310 With @command{gcc},
311 you can compile the source code of any language for
312 which a front end is available in GCC.
314 @item
315 The @command{gfortran} command itself,
316 which also might be installed as the
317 system's @command{f95} command.
318 @command{gfortran} is just another driver program,
319 but specifically for the Fortran compiler only.
320 The difference with @command{gcc} is that @command{gfortran}
321 will automatically link the correct libraries to your program.
323 @item
324 A collection of run-time libraries.
325 These libraries contain the machine code needed to support
326 capabilities of the Fortran language that are not directly
327 provided by the machine code generated by the
328 @command{gfortran} compilation phase,
329 such as intrinsic functions and subroutines,
330 and routines for interaction with files and the operating system.
331 @c and mechanisms to spawn,
332 @c unleash and pause threads in parallelized code.
334 @item
335 The Fortran compiler itself, (@command{f951}).
336 This is the GNU Fortran parser and code generator,
337 linked to and interfaced with the GCC backend library.
338 @command{f951} ``translates'' the source code to
339 assembler code.  You would typically not use this
340 program directly;
341 instead, the @command{gcc} or @command{gfortran} driver
342 programs will call it for you.
343 @end itemize
346 @c ---------------------------------------------------------------------
347 @c GNU Fortran and GCC
348 @c ---------------------------------------------------------------------
350 @node GNU Fortran and GCC
351 @section GNU Fortran and GCC
352 @cindex GNU Compiler Collection
353 @cindex GCC
355 GNU Fortran is a part of GCC, the @dfn{GNU Compiler Collection}.  GCC
356 consists of a collection of front ends for various languages, which
357 translate the source code into a language-independent form called
358 @dfn{GENERIC}.  This is then processed by a common middle end which
359 provides optimization, and then passed to one of a collection of back
360 ends which generate code for different computer architectures and
361 operating systems.
363 Functionally, this is implemented with a driver program (@command{gcc})
364 which provides the command-line interface for the compiler.  It calls
365 the relevant compiler front-end program (e.g., @command{f951} for
366 Fortran) for each file in the source code, and then calls the assembler
367 and linker as appropriate to produce the compiled output.  In a copy of
368 GCC which has been compiled with Fortran language support enabled,
369 @command{gcc} will recognize files with @file{.f}, @file{.for}, @file{.ftn},
370 @file{.f90}, @file{.f95}, @file{.f03} and @file{.f08} extensions as
371 Fortran source code, and compile it accordingly.  A @command{gfortran}
372 driver program is also provided, which is identical to @command{gcc}
373 except that it automatically links the Fortran runtime libraries into the
374 compiled program.
376 Source files with @file{.f}, @file{.for}, @file{.fpp}, @file{.ftn}, @file{.F},
377 @file{.FOR}, @file{.FPP}, and @file{.FTN} extensions are treated as fixed form.
378 Source files with @file{.f90}, @file{.f95}, @file{.f03}, @file{.f08},
379 @file{.F90}, @file{.F95}, @file{.F03} and @file{.F08} extensions are
380 treated as free form.  The capitalized versions of either form are run
381 through preprocessing.  Source files with the lower case @file{.fpp}
382 extension are also run through preprocessing.
384 This manual specifically documents the Fortran front end, which handles
385 the programming language's syntax and semantics.  The aspects of GCC
386 which relate to the optimization passes and the back-end code generation
387 are documented in the GCC manual; see 
388 @ref{Top,,Introduction,gcc,Using the GNU Compiler Collection (GCC)}.
389 The two manuals together provide a complete reference for the GNU
390 Fortran compiler.
393 @c ---------------------------------------------------------------------
394 @c Preprocessing and conditional compilation
395 @c ---------------------------------------------------------------------
397 @node Preprocessing and conditional compilation
398 @section Preprocessing and conditional compilation
399 @cindex CPP
400 @cindex FPP
401 @cindex Conditional compilation
402 @cindex Preprocessing
403 @cindex preprocessor, include file handling
405 Many Fortran compilers including GNU Fortran allow passing the source code
406 through a C preprocessor (CPP; sometimes also called the Fortran preprocessor,
407 FPP) to allow for conditional compilation.  In the case of GNU Fortran,
408 this is the GNU C Preprocessor in the traditional mode.  On systems with
409 case-preserving file names, the preprocessor is automatically invoked if the
410 filename extension is @file{.F}, @file{.FOR}, @file{.FTN}, @file{.fpp},
411 @file{.FPP}, @file{.F90}, @file{.F95}, @file{.F03} or @file{.F08}.  To manually
412 invoke the preprocessor on any file, use @option{-cpp}, to disable
413 preprocessing on files where the preprocessor is run automatically, use
414 @option{-nocpp}.
416 If a preprocessed file includes another file with the Fortran @code{INCLUDE}
417 statement, the included file is not preprocessed.  To preprocess included
418 files, use the equivalent preprocessor statement @code{#include}.
420 If GNU Fortran invokes the preprocessor, @code{__GFORTRAN__}
421 is defined and @code{__GNUC__}, @code{__GNUC_MINOR__} and
422 @code{__GNUC_PATCHLEVEL__} can be used to determine the version of the
423 compiler.  See @ref{Top,,Overview,cpp,The C Preprocessor} for details.
425 While CPP is the de-facto standard for preprocessing Fortran code,
426 Part 3 of the Fortran 95 standard (ISO/IEC 1539-3:1998) defines
427 Conditional Compilation, which is not widely used and not directly
428 supported by the GNU Fortran compiler.  You can use the program coco
429 to preprocess such files (@uref{http://www.daniellnagle.com/coco.html}).
432 @c ---------------------------------------------------------------------
433 @c GNU Fortran and G77
434 @c ---------------------------------------------------------------------
436 @node GNU Fortran and G77
437 @section GNU Fortran and G77
438 @cindex Fortran 77
439 @cindex @command{g77}
441 The GNU Fortran compiler is the successor to @command{g77}, the Fortran 
442 77 front end included in GCC prior to version 4.  It is an entirely new 
443 program that has been designed to provide Fortran 95 support and 
444 extensibility for future Fortran language standards, as well as providing 
445 backwards compatibility for Fortran 77 and nearly all of the GNU language 
446 extensions supported by @command{g77}.
449 @c ---------------------------------------------------------------------
450 @c Project Status
451 @c ---------------------------------------------------------------------
453 @node Project Status
454 @section Project Status
456 @quotation
457 As soon as @command{gfortran} can parse all of the statements correctly,
458 it will be in the ``larva'' state.
459 When we generate code, the ``puppa'' state.
460 When @command{gfortran} is done,
461 we'll see if it will be a beautiful butterfly,
462 or just a big bug....
464 --Andy Vaught, April 2000
465 @end quotation
467 The start of the GNU Fortran 95 project was announced on
468 the GCC homepage in March 18, 2000
469 (even though Andy had already been working on it for a while,
470 of course).
472 The GNU Fortran compiler is able to compile nearly all
473 standard-compliant Fortran 95, Fortran 90, and Fortran 77 programs,
474 including a number of standard and non-standard extensions, and can be
475 used on real-world programs.  In particular, the supported extensions
476 include OpenMP, Cray-style pointers, some old vendor extensions, and several
477 Fortran 2003 and Fortran 2008 features, including TR 15581.  However, it is
478 still under development and has a few remaining rough edges.
479 There also is initial support for OpenACC.
480 Note that this is an experimental feature, incomplete, and subject to
481 change in future versions of GCC.  See
482 @uref{https://gcc.gnu.org/wiki/OpenACC} for more information.
484 At present, the GNU Fortran compiler passes the
485 @uref{http://www.fortran-2000.com/ArnaudRecipes/fcvs21_f95.html, 
486 NIST Fortran 77 Test Suite}, and produces acceptable results on the
487 @uref{http://www.netlib.org/lapack/faq.html#1.21, LAPACK Test Suite}.
488 It also provides respectable performance on 
489 the @uref{http://www.polyhedron.com/fortran-compiler-comparisons/polyhedron-benchmark-suite,
490 Polyhedron Fortran
491 compiler benchmarks} and the
492 @uref{http://www.netlib.org/benchmark/livermore,
493 Livermore Fortran Kernels test}.  It has been used to compile a number of
494 large real-world programs, including
495 @uref{http://hirlam.org/, the HARMONIE and HIRLAM weather forecasting code} and
496 @uref{http://physical-chemistry.scb.uwa.edu.au/tonto/wiki/index.php/Main_Page,
497 the Tonto quantum chemistry package}; see
498 @url{https://gcc.gnu.org/@/wiki/@/GfortranApps} for an extended list.
500 Among other things, the GNU Fortran compiler is intended as a replacement
501 for G77.  At this point, nearly all programs that could be compiled with
502 G77 can be compiled with GNU Fortran, although there are a few minor known
503 regressions.
505 The primary work remaining to be done on GNU Fortran falls into three
506 categories: bug fixing (primarily regarding the treatment of invalid
507 code and providing useful error messages), improving the compiler
508 optimizations and the performance of compiled code, and extending the
509 compiler to support future standards---in particular, Fortran 2003,
510 Fortran 2008 and Fortran 2018.
513 @c ---------------------------------------------------------------------
514 @c Standards
515 @c ---------------------------------------------------------------------
517 @node Standards
518 @section Standards
519 @cindex Standards
521 @menu
522 * Varying Length Character Strings::
523 @end menu
525 The GNU Fortran compiler implements
526 ISO/IEC 1539:1997 (Fortran 95).  As such, it can also compile essentially all
527 standard-compliant Fortran 90 and Fortran 77 programs.   It also supports
528 the ISO/IEC TR-15581 enhancements to allocatable arrays.
530 GNU Fortran also have a partial support for ISO/IEC 1539-1:2004
531 (Fortran 2003), ISO/IEC 1539-1:2010 (Fortran 2008), the Technical
532 Specification @code{Further Interoperability of Fortran with C}
533 (ISO/IEC TS 29113:2012).  Full support of those standards and future
534 Fortran standards is planned.  The current status of the support is
535 can be found in the @ref{Fortran 2003 status}, @ref{Fortran 2008
536 status} and @ref{Fortran 2018 status} sections of the documentation.
538 Additionally, the GNU Fortran compilers supports the OpenMP specification
539 (version 4.0 and most of the features of the 4.5 version,
540 @url{http://openmp.org/@/wp/@/openmp-specifications/}).
541 There also is initial support for the OpenACC specification (targeting
542 version 2.0, @uref{http://www.openacc.org/}).
543 Note that this is an experimental feature, incomplete, and subject to
544 change in future versions of GCC.  See
545 @uref{https://gcc.gnu.org/wiki/OpenACC} for more information.
547 @node Varying Length Character Strings
548 @subsection Varying Length Character Strings
549 @cindex Varying length character strings
550 @cindex Varying length strings
551 @cindex strings, varying length
553 The Fortran 95 standard specifies in Part 2 (ISO/IEC 1539-2:2000)
554 varying length character strings.  While GNU Fortran currently does not
555 support such strings directly, there exist two Fortran implementations
556 for them, which work with GNU Fortran.  They can be found at
557 @uref{http://www.fortran.com/@/iso_varying_string.f95} and at
558 @uref{ftp://ftp.nag.co.uk/@/sc22wg5/@/ISO_VARYING_STRING/}.
560 Deferred-length character strings of Fortran 2003 supports part of
561 the features of @code{ISO_VARYING_STRING} and should be considered as
562 replacement. (Namely, allocatable or pointers of the type
563 @code{character(len=:)}.)
566 @c =====================================================================
567 @c PART I: INVOCATION REFERENCE
568 @c =====================================================================
570 @tex
571 \part{I}{Invoking GNU Fortran}
572 @end tex
574 @c ---------------------------------------------------------------------
575 @c Compiler Options
576 @c ---------------------------------------------------------------------
578 @include invoke.texi
581 @c ---------------------------------------------------------------------
582 @c Runtime
583 @c ---------------------------------------------------------------------
585 @node Runtime
586 @chapter Runtime:  Influencing runtime behavior with environment variables
587 @cindex environment variable
589 The behavior of the @command{gfortran} can be influenced by
590 environment variables.
592 Malformed environment variables are silently ignored.
594 @menu
595 * TMPDIR:: Directory for scratch files
596 * GFORTRAN_STDIN_UNIT:: Unit number for standard input
597 * GFORTRAN_STDOUT_UNIT:: Unit number for standard output
598 * GFORTRAN_STDERR_UNIT:: Unit number for standard error
599 * GFORTRAN_UNBUFFERED_ALL:: Do not buffer I/O for all units.
600 * GFORTRAN_UNBUFFERED_PRECONNECTED:: Do not buffer I/O for preconnected units.
601 * GFORTRAN_SHOW_LOCUS::  Show location for runtime errors
602 * GFORTRAN_OPTIONAL_PLUS:: Print leading + where permitted
603 * GFORTRAN_LIST_SEPARATOR::  Separator for list output
604 * GFORTRAN_CONVERT_UNIT::  Set endianness for unformatted I/O
605 * GFORTRAN_ERROR_BACKTRACE:: Show backtrace on run-time errors
606 @end menu
608 @node TMPDIR
609 @section @env{TMPDIR}---Directory for scratch files
611 When opening a file with @code{STATUS='SCRATCH'}, GNU Fortran tries to
612 create the file in one of the potential directories by testing each
613 directory in the order below.
615 @enumerate
616 @item
617 The environment variable @env{TMPDIR}, if it exists.
619 @item
620 On the MinGW target, the directory returned by the @code{GetTempPath}
621 function. Alternatively, on the Cygwin target, the @env{TMP} and
622 @env{TEMP} environment variables, if they exist, in that order.
624 @item
625 The @code{P_tmpdir} macro if it is defined, otherwise the directory
626 @file{/tmp}.
627 @end enumerate
629 @node GFORTRAN_STDIN_UNIT
630 @section @env{GFORTRAN_STDIN_UNIT}---Unit number for standard input
632 This environment variable can be used to select the unit number
633 preconnected to standard input.  This must be a positive integer.
634 The default value is 5.
636 @node GFORTRAN_STDOUT_UNIT
637 @section @env{GFORTRAN_STDOUT_UNIT}---Unit number for standard output
639 This environment variable can be used to select the unit number
640 preconnected to standard output.  This must be a positive integer.
641 The default value is 6.
643 @node GFORTRAN_STDERR_UNIT
644 @section @env{GFORTRAN_STDERR_UNIT}---Unit number for standard error
646 This environment variable can be used to select the unit number
647 preconnected to standard error.  This must be a positive integer.
648 The default value is 0.
650 @node GFORTRAN_UNBUFFERED_ALL
651 @section @env{GFORTRAN_UNBUFFERED_ALL}---Do not buffer I/O on all units
653 This environment variable controls whether all I/O is unbuffered.  If
654 the first letter is @samp{y}, @samp{Y} or @samp{1}, all I/O is
655 unbuffered.  This will slow down small sequential reads and writes.  If
656 the first letter is @samp{n}, @samp{N} or @samp{0}, I/O is buffered.
657 This is the default.
659 @node GFORTRAN_UNBUFFERED_PRECONNECTED
660 @section @env{GFORTRAN_UNBUFFERED_PRECONNECTED}---Do not buffer I/O on preconnected units
662 The environment variable named @env{GFORTRAN_UNBUFFERED_PRECONNECTED} controls
663 whether I/O on a preconnected unit (i.e.@: STDOUT or STDERR) is unbuffered.  If 
664 the first letter is @samp{y}, @samp{Y} or @samp{1}, I/O is unbuffered.  This
665 will slow down small sequential reads and writes.  If the first letter
666 is @samp{n}, @samp{N} or @samp{0}, I/O is buffered.  This is the default.
668 @node GFORTRAN_SHOW_LOCUS
669 @section @env{GFORTRAN_SHOW_LOCUS}---Show location for runtime errors
671 If the first letter is @samp{y}, @samp{Y} or @samp{1}, filename and
672 line numbers for runtime errors are printed.  If the first letter is
673 @samp{n}, @samp{N} or @samp{0}, do not print filename and line numbers
674 for runtime errors.  The default is to print the location.
676 @node GFORTRAN_OPTIONAL_PLUS
677 @section @env{GFORTRAN_OPTIONAL_PLUS}---Print leading + where permitted
679 If the first letter is @samp{y}, @samp{Y} or @samp{1},
680 a plus sign is printed
681 where permitted by the Fortran standard.  If the first letter
682 is @samp{n}, @samp{N} or @samp{0}, a plus sign is not printed
683 in most cases.  Default is not to print plus signs.
685 @node GFORTRAN_LIST_SEPARATOR
686 @section @env{GFORTRAN_LIST_SEPARATOR}---Separator for list output
688 This environment variable specifies the separator when writing
689 list-directed output.  It may contain any number of spaces and
690 at most one comma.  If you specify this on the command line,
691 be sure to quote spaces, as in
692 @smallexample
693 $ GFORTRAN_LIST_SEPARATOR='  ,  ' ./a.out
694 @end smallexample
695 when @command{a.out} is the compiled Fortran program that you want to run.
696 Default is a single space.
698 @node GFORTRAN_CONVERT_UNIT
699 @section @env{GFORTRAN_CONVERT_UNIT}---Set endianness for unformatted I/O
701 By setting the @env{GFORTRAN_CONVERT_UNIT} variable, it is possible
702 to change the representation of data for unformatted files.
703 The syntax for the @env{GFORTRAN_CONVERT_UNIT} variable is:
704 @smallexample
705 GFORTRAN_CONVERT_UNIT: mode | mode ';' exception | exception ;
706 mode: 'native' | 'swap' | 'big_endian' | 'little_endian' ;
707 exception: mode ':' unit_list | unit_list ;
708 unit_list: unit_spec | unit_list unit_spec ;
709 unit_spec: INTEGER | INTEGER '-' INTEGER ;
710 @end smallexample
711 The variable consists of an optional default mode, followed by
712 a list of optional exceptions, which are separated by semicolons
713 from the preceding default and each other.  Each exception consists
714 of a format and a comma-separated list of units.  Valid values for
715 the modes are the same as for the @code{CONVERT} specifier:
717 @itemize @w{}
718 @item @code{NATIVE} Use the native format.  This is the default.
719 @item @code{SWAP} Swap between little- and big-endian.
720 @item @code{LITTLE_ENDIAN} Use the little-endian format
721 for unformatted files.
722 @item @code{BIG_ENDIAN} Use the big-endian format for unformatted files.
723 @end itemize
724 A missing mode for an exception is taken to mean @code{BIG_ENDIAN}.
725 Examples of values for @env{GFORTRAN_CONVERT_UNIT} are:
726 @itemize @w{}
727 @item @code{'big_endian'}  Do all unformatted I/O in big_endian mode.
728 @item @code{'little_endian;native:10-20,25'}  Do all unformatted I/O 
729 in little_endian mode, except for units 10 to 20 and 25, which are in
730 native format.
731 @item @code{'10-20'}  Units 10 to 20 are big-endian, the rest is native.
732 @end itemize
734 Setting the environment variables should be done on the command
735 line or via the @command{export}
736 command for @command{sh}-compatible shells and via @command{setenv}
737 for @command{csh}-compatible shells.
739 Example for @command{sh}:
740 @smallexample
741 $ gfortran foo.f90
742 $ GFORTRAN_CONVERT_UNIT='big_endian;native:10-20' ./a.out
743 @end smallexample
745 Example code for @command{csh}:
746 @smallexample
747 % gfortran foo.f90
748 % setenv GFORTRAN_CONVERT_UNIT 'big_endian;native:10-20'
749 % ./a.out
750 @end smallexample
752 Using anything but the native representation for unformatted data
753 carries a significant speed overhead.  If speed in this area matters
754 to you, it is best if you use this only for data that needs to be
755 portable.
757 @xref{CONVERT specifier}, for an alternative way to specify the
758 data representation for unformatted files.  @xref{Runtime Options}, for
759 setting a default data representation for the whole program.  The
760 @code{CONVERT} specifier overrides the @option{-fconvert} compile options.
762 @emph{Note that the values specified via the GFORTRAN_CONVERT_UNIT
763 environment variable will override the CONVERT specifier in the
764 open statement}.  This is to give control over data formats to
765 users who do not have the source code of their program available.
767 @node GFORTRAN_ERROR_BACKTRACE
768 @section @env{GFORTRAN_ERROR_BACKTRACE}---Show backtrace on run-time errors
770 If the @env{GFORTRAN_ERROR_BACKTRACE} variable is set to @samp{y},
771 @samp{Y} or @samp{1} (only the first letter is relevant) then a
772 backtrace is printed when a serious run-time error occurs.  To disable
773 the backtracing, set the variable to @samp{n}, @samp{N}, @samp{0}.
774 Default is to print a backtrace unless the @option{-fno-backtrace}
775 compile option was used.
777 @c =====================================================================
778 @c PART II: LANGUAGE REFERENCE
779 @c =====================================================================
781 @tex
782 \part{II}{Language Reference}
783 @end tex
785 @c ---------------------------------------------------------------------
786 @c Fortran standards status
787 @c ---------------------------------------------------------------------
789 @node Fortran standards status
790 @chapter Fortran standards status
792 @menu
793 * Fortran 2003 status::
794 * Fortran 2008 status::
795 * Fortran 2018 status::
796 @end menu
798 @node Fortran 2003 status
799 @section Fortran 2003 status
801 GNU Fortran supports several Fortran 2003 features; an incomplete
802 list can be found below.  See also the
803 @uref{https://gcc.gnu.org/wiki/Fortran2003, wiki page} about Fortran 2003.
805 @itemize
806 @item Procedure pointers including procedure-pointer components with
807 @code{PASS} attribute.
809 @item Procedures which are bound to a derived type (type-bound procedures)
810 including @code{PASS}, @code{PROCEDURE} and @code{GENERIC}, and
811 operators bound to a type.
813 @item Abstract interfaces and type extension with the possibility to
814 override type-bound procedures or to have deferred binding.
816 @item Polymorphic entities (``@code{CLASS}'') for derived types and unlimited
817 polymorphism (``@code{CLASS(*)}'') -- including @code{SAME_TYPE_AS},
818 @code{EXTENDS_TYPE_OF} and @code{SELECT TYPE} for scalars and arrays and
819 finalization.
821 @item Generic interface names, which have the same name as derived types,
822 are now supported. This allows one to write constructor functions.  Note
823 that Fortran does not support static constructor functions.  For static
824 variables, only default initialization or structure-constructor
825 initialization are available.
827 @item The @code{ASSOCIATE} construct.
829 @item Interoperability with C including enumerations, 
831 @item In structure constructors the components with default values may be
832 omitted.
834 @item Extensions to the @code{ALLOCATE} statement, allowing for a
835 type-specification with type parameter and for allocation and initialization
836 from a @code{SOURCE=} expression; @code{ALLOCATE} and @code{DEALLOCATE}
837 optionally return an error message string via @code{ERRMSG=}.
839 @item Reallocation on assignment: If an intrinsic assignment is
840 used, an allocatable variable on the left-hand side is automatically allocated
841 (if unallocated) or reallocated (if the shape is different). Currently, scalar
842 deferred character length left-hand sides are correctly handled but arrays
843 are not yet fully implemented.
845 @item Deferred-length character variables and scalar deferred-length character
846 components of derived types are supported. (Note that array-valued compoents
847 are not yet implemented.)
849 @item Transferring of allocations via @code{MOVE_ALLOC}.
851 @item The @code{PRIVATE} and @code{PUBLIC} attributes may be given individually
852 to derived-type components.
854 @item In pointer assignments, the lower bound may be specified and
855 the remapping of elements is supported.
857 @item For pointers an @code{INTENT} may be specified which affect the
858 association status not the value of the pointer target.
860 @item Intrinsics @code{command_argument_count}, @code{get_command},
861 @code{get_command_argument}, and @code{get_environment_variable}.
863 @item Support for Unicode characters (ISO 10646) and UTF-8, including
864 the @code{SELECTED_CHAR_KIND} and @code{NEW_LINE} intrinsic functions.
866 @item Support for binary, octal and hexadecimal (BOZ) constants in the
867 intrinsic functions @code{INT}, @code{REAL}, @code{CMPLX} and @code{DBLE}.
869 @item Support for namelist variables with allocatable and pointer
870 attribute and nonconstant length type parameter.
872 @item
873 @cindex array, constructors
874 @cindex @code{[...]}
875 Array constructors using square brackets.  That is, @code{[...]} rather
876 than @code{(/.../)}.  Type-specification for array constructors like
877 @code{(/ some-type :: ... /)}.
879 @item Extensions to the specification and initialization expressions,
880 including the support for intrinsics with real and complex arguments.
882 @item Support for the asynchronous input/output.
884 @item
885 @cindex @code{FLUSH} statement
886 @cindex statement, @code{FLUSH}
887 @code{FLUSH} statement.
889 @item
890 @cindex @code{IOMSG=} specifier
891 @code{IOMSG=} specifier for I/O statements.
893 @item
894 @cindex @code{ENUM} statement
895 @cindex @code{ENUMERATOR} statement
896 @cindex statement, @code{ENUM}
897 @cindex statement, @code{ENUMERATOR}
898 @opindex @code{fshort-enums}
899 Support for the declaration of enumeration constants via the
900 @code{ENUM} and @code{ENUMERATOR} statements.  Interoperability with
901 @command{gcc} is guaranteed also for the case where the
902 @command{-fshort-enums} command line option is given.
904 @item
905 @cindex TR 15581
906 TR 15581:
907 @itemize
908 @item
909 @cindex @code{ALLOCATABLE} dummy arguments
910 @code{ALLOCATABLE} dummy arguments.
911 @item
912 @cindex @code{ALLOCATABLE} function results
913 @code{ALLOCATABLE} function results
914 @item
915 @cindex @code{ALLOCATABLE} components of derived types
916 @code{ALLOCATABLE} components of derived types
917 @end itemize
919 @item
920 @cindex @code{STREAM} I/O
921 @cindex @code{ACCESS='STREAM'} I/O
922 The @code{OPEN} statement supports the @code{ACCESS='STREAM'} specifier,
923 allowing I/O without any record structure.
925 @item
926 Namelist input/output for internal files.
928 @item Minor I/O features: Rounding during formatted output, using of
929 a decimal comma instead of a decimal point, setting whether a plus sign
930 should appear for positive numbers. On systems where @code{strtod} honours
931 the rounding mode, the rounding mode is also supported for input.
933 @item
934 @cindex @code{PROTECTED} statement
935 @cindex statement, @code{PROTECTED}
936 The @code{PROTECTED} statement and attribute.
938 @item
939 @cindex @code{VALUE} statement
940 @cindex statement, @code{VALUE}
941 The @code{VALUE} statement and attribute.
943 @item
944 @cindex @code{VOLATILE} statement
945 @cindex statement, @code{VOLATILE}
946 The @code{VOLATILE} statement and attribute.
948 @item
949 @cindex @code{IMPORT} statement
950 @cindex statement, @code{IMPORT}
951 The @code{IMPORT} statement, allowing to import
952 host-associated derived types.
954 @item The intrinsic modules @code{ISO_FORTRAN_ENVIRONMENT} is supported,
955 which contains parameters of the I/O units, storage sizes. Additionally,
956 procedures for C interoperability are available in the @code{ISO_C_BINDING}
957 module.
959 @item
960 @cindex @code{USE, INTRINSIC} statement
961 @cindex statement, @code{USE, INTRINSIC}
962 @cindex @code{ISO_FORTRAN_ENV} statement
963 @cindex statement, @code{ISO_FORTRAN_ENV}
964 @code{USE} statement with @code{INTRINSIC} and @code{NON_INTRINSIC}
965 attribute; supported intrinsic modules: @code{ISO_FORTRAN_ENV},
966 @code{ISO_C_BINDING}, @code{OMP_LIB} and @code{OMP_LIB_KINDS},
967 and @code{OPENACC}.
969 @item
970 Renaming of operators in the @code{USE} statement.
972 @end itemize
975 @node Fortran 2008 status
976 @section Fortran 2008 status
978 The latest version of the Fortran standard is ISO/IEC 1539-1:2010, informally
979 known as Fortran 2008.  The official version is available from International
980 Organization for Standardization (ISO) or its national member organizations.
981 The the final draft (FDIS) can be downloaded free of charge from
982 @url{http://www.nag.co.uk/@/sc22wg5/@/links.html}.  Fortran is developed by the
983 Working Group 5 of Sub-Committee 22 of the Joint Technical Committee 1 of the
984 International Organization for Standardization and the International
985 Electrotechnical Commission (IEC).  This group is known as
986 @uref{http://www.nag.co.uk/sc22wg5/, WG5}.
988 The GNU Fortran compiler supports several of the new features of Fortran 2008;
989 the @uref{https://gcc.gnu.org/wiki/Fortran2008Status, wiki} has some information
990 about the current Fortran 2008 implementation status.  In particular, the
991 following is implemented.
993 @itemize
994 @item The @option{-std=f2008} option and support for the file extensions 
995 @file{.f08} and @file{.F08}.
997 @item The @code{OPEN} statement now supports the @code{NEWUNIT=} option,
998 which returns a unique file unit, thus preventing inadvertent use of the
999 same unit in different parts of the program.
1001 @item The @code{g0} format descriptor and unlimited format items.
1003 @item The mathematical intrinsics @code{ASINH}, @code{ACOSH}, @code{ATANH},
1004 @code{ERF}, @code{ERFC}, @code{GAMMA}, @code{LOG_GAMMA}, @code{BESSEL_J0},
1005 @code{BESSEL_J1}, @code{BESSEL_JN}, @code{BESSEL_Y0}, @code{BESSEL_Y1},
1006 @code{BESSEL_YN}, @code{HYPOT}, @code{NORM2}, and @code{ERFC_SCALED}.
1008 @item Using complex arguments with @code{TAN}, @code{SINH}, @code{COSH},
1009 @code{TANH}, @code{ASIN}, @code{ACOS}, and @code{ATAN} is now possible;
1010 @code{ATAN}(@var{Y},@var{X}) is now an alias for @code{ATAN2}(@var{Y},@var{X}).
1012 @item Support of the @code{PARITY} intrinsic functions.
1014 @item The following bit intrinsics: @code{LEADZ} and @code{TRAILZ} for
1015 counting the number of leading and trailing zero bits, @code{POPCNT} and
1016 @code{POPPAR} for counting the number of one bits and returning the parity;
1017 @code{BGE}, @code{BGT}, @code{BLE}, and @code{BLT} for bitwise comparisons;
1018 @code{DSHIFTL} and @code{DSHIFTR} for combined left and right shifts,
1019 @code{MASKL} and @code{MASKR} for simple left and right justified masks,
1020 @code{MERGE_BITS} for a bitwise merge using a mask, @code{SHIFTA},
1021 @code{SHIFTL} and @code{SHIFTR} for shift operations, and the
1022 transformational bit intrinsics @code{IALL}, @code{IANY} and @code{IPARITY}.
1024 @item Support of the @code{EXECUTE_COMMAND_LINE} intrinsic subroutine.
1026 @item Support for the @code{STORAGE_SIZE} intrinsic inquiry function.
1028 @item The @code{INT@{8,16,32@}} and @code{REAL@{32,64,128@}} kind type
1029 parameters and the array-valued named constants @code{INTEGER_KINDS},
1030 @code{LOGICAL_KINDS}, @code{REAL_KINDS} and @code{CHARACTER_KINDS} of
1031 the intrinsic module @code{ISO_FORTRAN_ENV}.
1033 @item The module procedures @code{C_SIZEOF} of the intrinsic module
1034 @code{ISO_C_BINDINGS} and @code{COMPILER_VERSION} and @code{COMPILER_OPTIONS}
1035 of @code{ISO_FORTRAN_ENV}.
1037 @item Coarray support for serial programs with @option{-fcoarray=single} flag
1038 and experimental support for multiple images with the @option{-fcoarray=lib}
1039 flag.
1041 @item Submodules are supported. It should noted that @code{MODULEs} do not
1042 produce the smod file needed by the descendent @code{SUBMODULEs} unless they
1043 contain at least one @code{MODULE PROCEDURE} interface. The reason for this is
1044 that @code{SUBMODULEs} are useless without @code{MODULE PROCEDUREs}. See
1045 http://j3-fortran.org/doc/meeting/207/15-209.txt for a discussion and a draft
1046 interpretation. Adopting this interpretation has the advantage that code that
1047 does not use submodules does not generate smod files.
1049 @item The @code{DO CONCURRENT} construct is supported.
1051 @item The @code{BLOCK} construct is supported.
1053 @item The @code{STOP} and the new @code{ERROR STOP} statements now
1054 support all constant expressions. Both show the signals which were signaling
1055 at termination.
1057 @item Support for the @code{CONTIGUOUS} attribute.
1059 @item Support for @code{ALLOCATE} with @code{MOLD}.
1061 @item Support for the @code{IMPURE} attribute for procedures, which
1062 allows for @code{ELEMENTAL} procedures without the restrictions of
1063 @code{PURE}.
1065 @item Null pointers (including @code{NULL()}) and not-allocated variables
1066 can be used as actual argument to optional non-pointer, non-allocatable
1067 dummy arguments, denoting an absent argument.
1069 @item Non-pointer variables with @code{TARGET} attribute can be used as
1070 actual argument to @code{POINTER} dummies with @code{INTENT(IN)}.
1072 @item Pointers including procedure pointers and those in a derived
1073 type (pointer components) can now be initialized by a target instead
1074 of only by @code{NULL}.
1076 @item The @code{EXIT} statement (with construct-name) can be now be
1077 used to leave not only the @code{DO} but also the @code{ASSOCIATE},
1078 @code{BLOCK}, @code{IF}, @code{SELECT CASE} and @code{SELECT TYPE}
1079 constructs.
1081 @item Internal procedures can now be used as actual argument.
1083 @item Minor features: obsolesce diagnostics for @code{ENTRY} with
1084 @option{-std=f2008}; a line may start with a semicolon; for internal
1085 and module procedures @code{END} can be used instead of
1086 @code{END SUBROUTINE} and @code{END FUNCTION}; @code{SELECTED_REAL_KIND}
1087 now also takes a @code{RADIX} argument; intrinsic types are supported
1088 for @code{TYPE}(@var{intrinsic-type-spec}); multiple type-bound procedures
1089 can be declared in a single @code{PROCEDURE} statement; implied-shape
1090 arrays are supported for named constants (@code{PARAMETER}).
1091 @end itemize
1095 @node Fortran 2018 status
1096 @section Status of Fortran 2018 support
1098 So far very little work has been done to support Fortran 2018.
1100 @itemize
1101 @item ERROR STOP in a PURE procedure
1102 An @code{ERROR STOP} statement is permitted in a @code{PURE}
1103 procedure.
1105 @item IMPLICIT NONE with a spec-list
1106 Support the @code{IMPLICIT NONE} statement with an
1107 @code{implicit-none-spec-list}.
1109 @item Behavior of INQUIRE with the RECL= specifier
1111 The behavior of the @code{INQUIRE} statement with the @code{RECL=}
1112 specifier now conforms to Fortran 2018.
1114 @end itemize
1117 @subsection TS 29113 Status (Further Interoperability with C)
1119 GNU Fortran supports some of the new features of the Technical
1120 Specification (TS) 29113 on Further Interoperability of Fortran with C.
1121 The @uref{https://gcc.gnu.org/wiki/TS29113Status, wiki} has some information
1122 about the current TS 29113 implementation status.  In particular, the
1123 following is implemented.
1125 See also @ref{Further Interoperability of Fortran with C}.
1127 @itemize
1128 @item The @code{OPTIONAL} attribute is allowed for dummy arguments
1129 of @code{BIND(C) procedures.}
1131 @item The @code{RANK} intrinsic is supported.
1133 @item GNU Fortran's implementation for variables with @code{ASYNCHRONOUS}
1134 attribute is compatible with TS 29113.
1136 @item Assumed types (@code{TYPE(*)}).
1138 @item Assumed-rank (@code{DIMENSION(..)}). However, the array descriptor
1139 of the TS is not yet supported.
1140 @end itemize
1144 @subsection TS 18508 Status (Additional Parallel Features)
1146 GNU Fortran supports the following new features of the Technical
1147 Specification 18508 on Additional Parallel Features in Fortran:
1149 @itemize
1150 @item The new atomic ADD, CAS, FETCH and ADD/OR/XOR, OR and XOR intrinsics.
1152 @item The @code{CO_MIN} and @code{CO_MAX} and @code{SUM} reduction intrinsics.
1153 And the @code{CO_BROADCAST} and @code{CO_REDUCE} intrinsic, except that those
1154 do not support polymorphic types or types with allocatable, pointer or
1155 polymorphic components.
1157 @item Events (@code{EVENT POST}, @code{EVENT WAIT}, @code{EVENT_QUERY})
1159 @item Failed images (@code{FAIL IMAGE}, @code{IMAGE_STATUS},
1160 @code{FAILED_IMAGES}, @code{STOPPED_IMAGES})
1162 @end itemize
1165 @c ---------------------------------------------------------------------
1166 @c Compiler Characteristics
1167 @c ---------------------------------------------------------------------
1169 @node Compiler Characteristics
1170 @chapter Compiler Characteristics
1172 This chapter describes certain characteristics of the GNU Fortran
1173 compiler, that are not specified by the Fortran standard, but which
1174 might in some way or another become visible to the programmer.
1176 @menu
1177 * KIND Type Parameters::
1178 * Internal representation of LOGICAL variables::
1179 * Evaluation of logical expressions::
1180 * MAX and MIN intrinsics with REAL NaN arguments::
1181 * Thread-safety of the runtime library::
1182 * Data consistency and durability::
1183 * Files opened without an explicit ACTION= specifier::
1184 * File operations on symbolic links::
1185 * File format of unformatted sequential files::
1186 * Asynchronous I/O::
1187 @end menu
1190 @node KIND Type Parameters
1191 @section KIND Type Parameters
1192 @cindex kind
1194 The @code{KIND} type parameters supported by GNU Fortran for the primitive
1195 data types are:
1197 @table @code
1199 @item INTEGER
1200 1, 2, 4, 8*, 16*, default: 4**
1202 @item LOGICAL
1203 1, 2, 4, 8*, 16*, default: 4**
1205 @item REAL
1206 4, 8, 10*, 16*, default: 4***
1208 @item COMPLEX
1209 4, 8, 10*, 16*, default: 4***
1211 @item DOUBLE PRECISION
1212 4, 8, 10*, 16*, default: 8***
1214 @item CHARACTER
1215 1, 4, default: 1
1217 @end table
1219 @noindent
1220 * not available on all systems @*
1221 ** unless @option{-fdefault-integer-8} is used @*
1222 *** unless @option{-fdefault-real-8} is used (see @ref{Fortran Dialect Options})
1224 @noindent
1225 The @code{KIND} value matches the storage size in bytes, except for
1226 @code{COMPLEX} where the storage size is twice as much (or both real and
1227 imaginary part are a real value of the given size).  It is recommended to use
1228 the @ref{SELECTED_CHAR_KIND}, @ref{SELECTED_INT_KIND} and
1229 @ref{SELECTED_REAL_KIND} intrinsics or the @code{INT8}, @code{INT16},
1230 @code{INT32}, @code{INT64}, @code{REAL32}, @code{REAL64}, and @code{REAL128}
1231 parameters of the @code{ISO_FORTRAN_ENV} module instead of the concrete values.
1232 The available kind parameters can be found in the constant arrays
1233 @code{CHARACTER_KINDS}, @code{INTEGER_KINDS}, @code{LOGICAL_KINDS} and
1234 @code{REAL_KINDS} in the @ref{ISO_FORTRAN_ENV} module.  For C interoperability,
1235 the kind parameters of the @ref{ISO_C_BINDING} module should be used.
1238 @node Internal representation of LOGICAL variables
1239 @section Internal representation of LOGICAL variables
1240 @cindex logical, variable representation
1242 The Fortran standard does not specify how variables of @code{LOGICAL}
1243 type are represented, beyond requiring that @code{LOGICAL} variables
1244 of default kind have the same storage size as default @code{INTEGER}
1245 and @code{REAL} variables.  The GNU Fortran internal representation is
1246 as follows.
1248 A @code{LOGICAL(KIND=N)} variable is represented as an
1249 @code{INTEGER(KIND=N)} variable, however, with only two permissible
1250 values: @code{1} for @code{.TRUE.} and @code{0} for
1251 @code{.FALSE.}.  Any other integer value results in undefined behavior.
1253 See also @ref{Argument passing conventions} and @ref{Interoperability with C}.
1256 @node Evaluation of logical expressions
1257 @section Evaluation of logical expressions
1259 The Fortran standard does not require the compiler to evaluate all parts of an
1260 expression, if they do not contribute to the final result.  For logical
1261 expressions with @code{.AND.} or @code{.OR.} operators, in particular, GNU
1262 Fortran will optimize out function calls (even to impure functions) if the
1263 result of the expression can be established without them.  However, since not
1264 all compilers do that, and such an optimization can potentially modify the
1265 program flow and subsequent results, GNU Fortran throws warnings for such
1266 situations with the @option{-Wfunction-elimination} flag.
1269 @node MAX and MIN intrinsics with REAL NaN arguments
1270 @section MAX and MIN intrinsics with REAL NaN arguments
1271 @cindex MAX, MIN, NaN
1273 The Fortran standard does not specify what the result of the
1274 @code{MAX} and @code{MIN} intrinsics are if one of the arguments is a
1275 @code{NaN}.  Accordingly, the GNU Fortran compiler does not specify
1276 that either, as this allows for faster and more compact code to be
1277 generated.  If the programmer wishes to take some specific action in
1278 case one of the arguments is a @code{NaN}, it is necessary to
1279 explicitly test the arguments before calling @code{MAX} or @code{MIN},
1280 e.g. with the @code{IEEE_IS_NAN} function from the intrinsic module
1281 @code{IEEE_ARITHMETIC}.
1284 @node Thread-safety of the runtime library
1285 @section Thread-safety of the runtime library
1286 @cindex thread-safety, threads
1288 GNU Fortran can be used in programs with multiple threads, e.g.@: by
1289 using OpenMP, by calling OS thread handling functions via the
1290 @code{ISO_C_BINDING} facility, or by GNU Fortran compiled library code
1291 being called from a multi-threaded program.
1293 The GNU Fortran runtime library, (@code{libgfortran}), supports being
1294 called concurrently from multiple threads with the following
1295 exceptions. 
1297 During library initialization, the C @code{getenv} function is used,
1298 which need not be thread-safe.  Similarly, the @code{getenv}
1299 function is used to implement the @code{GET_ENVIRONMENT_VARIABLE} and
1300 @code{GETENV} intrinsics.  It is the responsibility of the user to
1301 ensure that the environment is not being updated concurrently when any
1302 of these actions are taking place.
1304 The @code{EXECUTE_COMMAND_LINE} and @code{SYSTEM} intrinsics are
1305 implemented with the @code{system} function, which need not be
1306 thread-safe.  It is the responsibility of the user to ensure that
1307 @code{system} is not called concurrently.
1309 For platforms not supporting thread-safe POSIX functions, further
1310 functionality might not be thread-safe.  For details, please consult
1311 the documentation for your operating system.
1313 The GNU Fortran runtime library uses various C library functions that
1314 depend on the locale, such as @code{strtod} and @code{snprintf}.  In
1315 order to work correctly in locale-aware programs that set the locale
1316 using @code{setlocale}, the locale is reset to the default ``C''
1317 locale while executing a formatted @code{READ} or @code{WRITE}
1318 statement.  On targets supporting the POSIX 2008 per-thread locale
1319 functions (e.g. @code{newlocale}, @code{uselocale},
1320 @code{freelocale}), these are used and thus the global locale set
1321 using @code{setlocale} or the per-thread locales in other threads are
1322 not affected.  However, on targets lacking this functionality, the
1323 global LC_NUMERIC locale is set to ``C'' during the formatted I/O.
1324 Thus, on such targets it's not safe to call @code{setlocale}
1325 concurrently from another thread while a Fortran formatted I/O
1326 operation is in progress.  Also, other threads doing something
1327 dependent on the LC_NUMERIC locale might not work correctly if a
1328 formatted I/O operation is in progress in another thread.
1330 @node Data consistency and durability
1331 @section Data consistency and durability
1332 @cindex consistency, durability
1334 This section contains a brief overview of data and metadata
1335 consistency and durability issues when doing I/O.
1337 With respect to durability, GNU Fortran makes no effort to ensure that
1338 data is committed to stable storage. If this is required, the GNU
1339 Fortran programmer can use the intrinsic @code{FNUM} to retrieve the
1340 low level file descriptor corresponding to an open Fortran unit. Then,
1341 using e.g. the @code{ISO_C_BINDING} feature, one can call the
1342 underlying system call to flush dirty data to stable storage, such as
1343 @code{fsync} on POSIX, @code{_commit} on MingW, or @code{fcntl(fd,
1344 F_FULLSYNC, 0)} on Mac OS X. The following example shows how to call
1345 fsync:
1347 @smallexample
1348   ! Declare the interface for POSIX fsync function
1349   interface
1350     function fsync (fd) bind(c,name="fsync")
1351     use iso_c_binding, only: c_int
1352       integer(c_int), value :: fd
1353       integer(c_int) :: fsync
1354     end function fsync
1355   end interface
1357   ! Variable declaration
1358   integer :: ret
1360   ! Opening unit 10
1361   open (10,file="foo")
1363   ! ...
1364   ! Perform I/O on unit 10
1365   ! ...
1367   ! Flush and sync
1368   flush(10)
1369   ret = fsync(fnum(10))
1371   ! Handle possible error
1372   if (ret /= 0) stop "Error calling FSYNC"
1373 @end smallexample
1375 With respect to consistency, for regular files GNU Fortran uses
1376 buffered I/O in order to improve performance. This buffer is flushed
1377 automatically when full and in some other situations, e.g. when
1378 closing a unit. It can also be explicitly flushed with the
1379 @code{FLUSH} statement. Also, the buffering can be turned off with the
1380 @code{GFORTRAN_UNBUFFERED_ALL} and
1381 @code{GFORTRAN_UNBUFFERED_PRECONNECTED} environment variables. Special
1382 files, such as terminals and pipes, are always unbuffered. Sometimes,
1383 however, further things may need to be done in order to allow other
1384 processes to see data that GNU Fortran has written, as follows.
1386 The Windows platform supports a relaxed metadata consistency model,
1387 where file metadata is written to the directory lazily. This means
1388 that, for instance, the @code{dir} command can show a stale size for a
1389 file. One can force a directory metadata update by closing the unit,
1390 or by calling @code{_commit} on the file descriptor. Note, though,
1391 that @code{_commit} will force all dirty data to stable storage, which
1392 is often a very slow operation.
1394 The Network File System (NFS) implements a relaxed consistency model
1395 called open-to-close consistency. Closing a file forces dirty data and
1396 metadata to be flushed to the server, and opening a file forces the
1397 client to contact the server in order to revalidate cached
1398 data. @code{fsync} will also force a flush of dirty data and metadata
1399 to the server. Similar to @code{open} and @code{close}, acquiring and
1400 releasing @code{fcntl} file locks, if the server supports them, will
1401 also force cache validation and flushing dirty data and metadata.
1404 @node Files opened without an explicit ACTION= specifier
1405 @section Files opened without an explicit ACTION= specifier
1406 @cindex open, action
1408 The Fortran standard says that if an @code{OPEN} statement is executed
1409 without an explicit @code{ACTION=} specifier, the default value is
1410 processor dependent.  GNU Fortran behaves as follows:
1412 @enumerate
1413 @item Attempt to open the file with @code{ACTION='READWRITE'}
1414 @item If that fails, try to open with @code{ACTION='READ'}
1415 @item If that fails, try to open with @code{ACTION='WRITE'}
1416 @item If that fails, generate an error
1417 @end enumerate
1420 @node File operations on symbolic links
1421 @section File operations on symbolic links
1422 @cindex file, symbolic link
1424 This section documents the behavior of GNU Fortran for file operations on
1425 symbolic links, on systems that support them. 
1427 @itemize
1429 @item Results of INQUIRE statements of the ``inquire by file'' form will
1430 relate to the target of the symbolic link. For example,
1431 @code{INQUIRE(FILE="foo",EXIST=ex)} will set @var{ex} to @var{.true.} if
1432 @var{foo} is a symbolic link pointing to an existing file, and @var{.false.}
1433 if @var{foo} points to an non-existing file (``dangling'' symbolic link).
1435 @item Using the @code{OPEN} statement with a @code{STATUS="NEW"} specifier
1436 on a symbolic link will result in an error condition, whether the symbolic
1437 link points to an existing target or is dangling.
1439 @item If a symbolic link was connected, using the @code{CLOSE} statement
1440 with a @code{STATUS="DELETE"} specifier will cause the symbolic link itself
1441 to be deleted, not its target.
1443 @end itemize
1445 @node File format of unformatted sequential files
1446 @section File format of unformatted sequential files
1447 @cindex file, unformatted sequential
1448 @cindex unformatted sequential
1449 @cindex sequential, unformatted
1450 @cindex record marker
1451 @cindex subrecord
1453 Unformatted sequential files are stored as logical records using
1454 record markers.  Each logical record consists of one of more
1455 subrecords.
1457 Each subrecord consists of a leading record marker, the data written
1458 by the user program, and a trailing record marker.  The record markers
1459 are four-byte integers by default, and eight-byte integers if the
1460 @option{-fmax-subrecord-length=8} option (which exists for backwards
1461 compability only) is in effect.
1463 The representation of the record markers is that of unformatted files
1464 given with the @option{-fconvert} option, the @xref{CONVERT specifier}
1465 on the open statement or the @xref{GFORTRAN_CONVERT_UNIT} environment
1466 variable.
1468 The maximum number of bytes of user data in a subrecord is 2147483639
1469 (2 GiB - 9) for a four-byte record marker.  This limit can be lowered
1470 with the @option{-fmax-subrecord-length} option, altough this is
1471 rarely useful. If the length of a logical record exceeds this limit,
1472 the data is distributed among several subrecords.
1474 The absolute of the number stored in the record markers is the number
1475 of bytes of user data in the corresponding subrecord.  If the leading
1476 record marker of a subrecord contains a negative number, another
1477 subrecord follows the current one.  If the trailing record marker
1478 contains a negative number, then there is a preceding subrecord.
1480 In the most simple case, with only one subrecord per logical record,
1481 both record markers contain the number of bytes of user data in the
1482 record,
1484 The format for unformatted sequential data can be duplicated using
1485 unformatted stream, as shown in the example program for an unformatted
1486 record containing a single subrecord:
1488 @smallexample
1489 program main
1490   use iso_fortran_env, only: int32
1491   implicit none
1492   integer(int32) :: i 
1493   real, dimension(10) :: a, b
1494   call random_number(a)
1495   open (10,file='test.dat',form='unformatted',access='stream')
1496   inquire (iolength=i) a
1497   write (10) i, a, i
1498   close (10)
1499   open (10,file='test.dat',form='unformatted')
1500   read (10) b
1501   if (all (a == b)) print *,'success!'
1502 end program main
1503 @end smallexample
1505 @node Asynchronous I/O
1506 @section Asynchronous I/O
1507 @cindex input/output, asynchronous
1508 @cindex asynchronous I/O
1510 Asynchronous I/O is supported if the program is linked against the
1511 POSIX thread library. If that is not the case, all I/O is performed
1512 as synchronous.
1514 On some systems, such as Darwin or Solaris, the POSIX thread library
1515 is always linked in, so asynchronous I/O is always performed. On other
1516 sytems, such as Linux, it is necessary to specify @option{-pthread},
1517 @option{-lpthread} or @option{-fopenmp} during the linking step.
1519 @c ---------------------------------------------------------------------
1520 @c Extensions
1521 @c ---------------------------------------------------------------------
1523 @c Maybe this chapter should be merged with the 'Standards' section,
1524 @c whenever that is written :-)
1526 @node Extensions
1527 @chapter Extensions
1528 @cindex extensions
1530 The two sections below detail the extensions to standard Fortran that are
1531 implemented in GNU Fortran, as well as some of the popular or
1532 historically important extensions that are not (or not yet) implemented.
1533 For the latter case, we explain the alternatives available to GNU Fortran
1534 users, including replacement by standard-conforming code or GNU
1535 extensions.
1537 @menu
1538 * Extensions implemented in GNU Fortran::
1539 * Extensions not implemented in GNU Fortran::
1540 @end menu
1543 @node Extensions implemented in GNU Fortran
1544 @section Extensions implemented in GNU Fortran
1545 @cindex extensions, implemented
1547 GNU Fortran implements a number of extensions over standard Fortran.
1548 This chapter contains information on their syntax and meaning.  There
1549 are currently two categories of GNU Fortran extensions, those that
1550 provide functionality beyond that provided by any standard, and those
1551 that are supported by GNU Fortran purely for backward compatibility
1552 with legacy compilers.  By default, @option{-std=gnu} allows the
1553 compiler to accept both types of extensions, but to warn about the use
1554 of the latter.  Specifying either @option{-std=f95},
1555 @option{-std=f2003}, @option{-std=f2008}, or @option{-std=f2018}
1556 disables both types of extensions, and @option{-std=legacy} allows
1557 both without warning.  The special compile flag @option{-fdec} enables
1558 additional compatibility extensions along with those enabled by
1559 @option{-std=legacy}.
1561 @menu
1562 * Old-style kind specifications::
1563 * Old-style variable initialization::
1564 * Extensions to namelist::
1565 * X format descriptor without count field::
1566 * Commas in FORMAT specifications::
1567 * Missing period in FORMAT specifications::
1568 * I/O item lists::
1569 * @code{Q} exponent-letter::
1570 * BOZ literal constants::
1571 * Real array indices::
1572 * Unary operators::
1573 * Implicitly convert LOGICAL and INTEGER values::
1574 * Hollerith constants support::
1575 * Cray pointers::
1576 * CONVERT specifier::
1577 * OpenMP::
1578 * OpenACC::
1579 * Argument list functions::
1580 * Read/Write after EOF marker::
1581 * STRUCTURE and RECORD::
1582 * UNION and MAP::
1583 * Type variants for integer intrinsics::
1584 * AUTOMATIC and STATIC attributes::
1585 * Extended math intrinsics::
1586 * Form feed as whitespace::
1587 * TYPE as an alias for PRINT::
1588 * %LOC as an rvalue::
1589 * .XOR. operator::
1590 * Bitwise logical operators::
1591 * Extended I/O specifiers::
1592 * Legacy PARAMETER statements::
1593 * Default exponents::
1594 @end menu
1596 @node Old-style kind specifications
1597 @subsection Old-style kind specifications
1598 @cindex kind, old-style
1600 GNU Fortran allows old-style kind specifications in declarations.  These
1601 look like:
1602 @smallexample
1603       TYPESPEC*size x,y,z
1604 @end smallexample
1605 @noindent
1606 where @code{TYPESPEC} is a basic type (@code{INTEGER}, @code{REAL},
1607 etc.), and where @code{size} is a byte count corresponding to the
1608 storage size of a valid kind for that type.  (For @code{COMPLEX}
1609 variables, @code{size} is the total size of the real and imaginary
1610 parts.)  The statement then declares @code{x}, @code{y} and @code{z} to
1611 be of type @code{TYPESPEC} with the appropriate kind.  This is
1612 equivalent to the standard-conforming declaration
1613 @smallexample
1614       TYPESPEC(k) x,y,z
1615 @end smallexample
1616 @noindent
1617 where @code{k} is the kind parameter suitable for the intended precision.  As
1618 kind parameters are implementation-dependent, use the @code{KIND},
1619 @code{SELECTED_INT_KIND} and @code{SELECTED_REAL_KIND} intrinsics to retrieve
1620 the correct value, for instance @code{REAL*8 x} can be replaced by:
1621 @smallexample
1622 INTEGER, PARAMETER :: dbl = KIND(1.0d0)
1623 REAL(KIND=dbl) :: x
1624 @end smallexample
1626 @node Old-style variable initialization
1627 @subsection Old-style variable initialization
1629 GNU Fortran allows old-style initialization of variables of the
1630 form:
1631 @smallexample
1632       INTEGER i/1/,j/2/
1633       REAL x(2,2) /3*0.,1./
1634 @end smallexample
1635 The syntax for the initializers is as for the @code{DATA} statement, but
1636 unlike in a @code{DATA} statement, an initializer only applies to the
1637 variable immediately preceding the initialization.  In other words,
1638 something like @code{INTEGER I,J/2,3/} is not valid.  This style of
1639 initialization is only allowed in declarations without double colons
1640 (@code{::}); the double colons were introduced in Fortran 90, which also
1641 introduced a standard syntax for initializing variables in type
1642 declarations.
1644 Examples of standard-conforming code equivalent to the above example
1645 are:
1646 @smallexample
1647 ! Fortran 90
1648       INTEGER :: i = 1, j = 2
1649       REAL :: x(2,2) = RESHAPE((/0.,0.,0.,1./),SHAPE(x))
1650 ! Fortran 77
1651       INTEGER i, j
1652       REAL x(2,2)
1653       DATA i/1/, j/2/, x/3*0.,1./
1654 @end smallexample
1656 Note that variables which are explicitly initialized in declarations
1657 or in @code{DATA} statements automatically acquire the @code{SAVE}
1658 attribute.
1660 @node Extensions to namelist
1661 @subsection Extensions to namelist
1662 @cindex Namelist
1664 GNU Fortran fully supports the Fortran 95 standard for namelist I/O
1665 including array qualifiers, substrings and fully qualified derived types.
1666 The output from a namelist write is compatible with namelist read.  The
1667 output has all names in upper case and indentation to column 1 after the
1668 namelist name.  Two extensions are permitted:
1670 Old-style use of @samp{$} instead of @samp{&}
1671 @smallexample
1672 $MYNML
1673  X(:)%Y(2) = 1.0 2.0 3.0
1674  CH(1:4) = "abcd"
1675 $END
1676 @end smallexample
1678 It should be noted that the default terminator is @samp{/} rather than
1679 @samp{&END}.
1681 Querying of the namelist when inputting from stdin.  After at least
1682 one space, entering @samp{?} sends to stdout the namelist name and the names of
1683 the variables in the namelist:
1684 @smallexample
1687 &mynml
1689  x%y
1690  ch
1691 &end
1692 @end smallexample
1694 Entering @samp{=?} outputs the namelist to stdout, as if
1695 @code{WRITE(*,NML = mynml)} had been called:
1696 @smallexample
1699 &MYNML
1700  X(1)%Y=  0.000000    ,  1.000000    ,  0.000000    ,
1701  X(2)%Y=  0.000000    ,  2.000000    ,  0.000000    ,
1702  X(3)%Y=  0.000000    ,  3.000000    ,  0.000000    ,
1703  CH=abcd,  /
1704 @end smallexample
1706 To aid this dialog, when input is from stdin, errors send their
1707 messages to stderr and execution continues, even if @code{IOSTAT} is set.
1709 @code{PRINT} namelist is permitted.  This causes an error if
1710 @option{-std=f95} is used.
1711 @smallexample
1712 PROGRAM test_print
1713   REAL, dimension (4)  ::  x = (/1.0, 2.0, 3.0, 4.0/)
1714   NAMELIST /mynml/ x
1715   PRINT mynml
1716 END PROGRAM test_print
1717 @end smallexample
1719 Expanded namelist reads are permitted.  This causes an error if 
1720 @option{-std=f95} is used.  In the following example, the first element
1721 of the array will be given the value 0.00 and the two succeeding
1722 elements will be given the values 1.00 and 2.00.
1723 @smallexample
1724 &MYNML
1725   X(1,1) = 0.00 , 1.00 , 2.00
1727 @end smallexample
1729 When writing a namelist, if no @code{DELIM=} is specified, by default a
1730 double quote is used to delimit character strings. If -std=F95, F2003,
1731 or F2008, etc, the delim status is set to 'none'.  Defaulting to
1732 quotes ensures that namelists with character strings can be subsequently
1733 read back in accurately.
1735 @node X format descriptor without count field
1736 @subsection @code{X} format descriptor without count field
1738 To support legacy codes, GNU Fortran permits the count field of the
1739 @code{X} edit descriptor in @code{FORMAT} statements to be omitted.
1740 When omitted, the count is implicitly assumed to be one.
1742 @smallexample
1743        PRINT 10, 2, 3
1744 10     FORMAT (I1, X, I1)
1745 @end smallexample
1747 @node Commas in FORMAT specifications
1748 @subsection Commas in @code{FORMAT} specifications
1750 To support legacy codes, GNU Fortran allows the comma separator
1751 to be omitted immediately before and after character string edit
1752 descriptors in @code{FORMAT} statements.
1754 @smallexample
1755        PRINT 10, 2, 3
1756 10     FORMAT ('FOO='I1' BAR='I2)
1757 @end smallexample
1760 @node Missing period in FORMAT specifications
1761 @subsection Missing period in @code{FORMAT} specifications
1763 To support legacy codes, GNU Fortran allows missing periods in format
1764 specifications if and only if @option{-std=legacy} is given on the
1765 command line.  This is considered non-conforming code and is
1766 discouraged.
1768 @smallexample
1769        REAL :: value
1770        READ(*,10) value
1771 10     FORMAT ('F4')
1772 @end smallexample
1774 @node I/O item lists
1775 @subsection I/O item lists
1776 @cindex I/O item lists
1778 To support legacy codes, GNU Fortran allows the input item list
1779 of the @code{READ} statement, and the output item lists of the
1780 @code{WRITE} and @code{PRINT} statements, to start with a comma.
1782 @node @code{Q} exponent-letter
1783 @subsection @code{Q} exponent-letter
1784 @cindex @code{Q} exponent-letter
1786 GNU Fortran accepts real literal constants with an exponent-letter
1787 of @code{Q}, for example, @code{1.23Q45}.  The constant is interpreted
1788 as a @code{REAL(16)} entity on targets that support this type.  If
1789 the target does not support @code{REAL(16)} but has a @code{REAL(10)}
1790 type, then the real-literal-constant will be interpreted as a
1791 @code{REAL(10)} entity.  In the absence of @code{REAL(16)} and
1792 @code{REAL(10)}, an error will occur.
1794 @node BOZ literal constants
1795 @subsection BOZ literal constants
1796 @cindex BOZ literal constants
1798 Besides decimal constants, Fortran also supports binary (@code{b}),
1799 octal (@code{o}) and hexadecimal (@code{z}) integer constants.  The
1800 syntax is: @samp{prefix quote digits quote}, were the prefix is
1801 either @code{b}, @code{o} or @code{z}, quote is either @code{'} or
1802 @code{"} and the digits are for binary @code{0} or @code{1}, for
1803 octal between @code{0} and @code{7}, and for hexadecimal between
1804 @code{0} and @code{F}.  (Example: @code{b'01011101'}.)
1806 Up to Fortran 95, BOZ literals were only allowed to initialize
1807 integer variables in DATA statements.  Since Fortran 2003 BOZ literals
1808 are also allowed as argument of @code{REAL}, @code{DBLE}, @code{INT}
1809 and @code{CMPLX}; the result is the same as if the integer BOZ
1810 literal had been converted by @code{TRANSFER} to, respectively,
1811 @code{real}, @code{double precision}, @code{integer} or @code{complex}.
1812 As GNU Fortran extension the intrinsic procedures @code{FLOAT},
1813 @code{DFLOAT}, @code{COMPLEX} and @code{DCMPLX} are treated alike.
1815 As an extension, GNU Fortran allows hexadecimal BOZ literal constants to
1816 be specified using the @code{X} prefix, in addition to the standard
1817 @code{Z} prefix.  The BOZ literal can also be specified by adding a
1818 suffix to the string, for example, @code{Z'ABC'} and @code{'ABC'Z} are
1819 equivalent.
1821 Furthermore, GNU Fortran allows using BOZ literal constants outside
1822 DATA statements and the four intrinsic functions allowed by Fortran 2003.
1823 In DATA statements, in direct assignments, where the right-hand side
1824 only contains a BOZ literal constant, and for old-style initializers of
1825 the form @code{integer i /o'0173'/}, the constant is transferred
1826 as if @code{TRANSFER} had been used; for @code{COMPLEX} numbers, only
1827 the real part is initialized unless @code{CMPLX} is used.  In all other
1828 cases, the BOZ literal constant is converted to an @code{INTEGER} value with
1829 the largest decimal representation.  This value is then converted
1830 numerically to the type and kind of the variable in question.
1831 (For instance, @code{real :: r = b'0000001' + 1} initializes @code{r}
1832 with @code{2.0}.) As different compilers implement the extension
1833 differently, one should be careful when doing bitwise initialization
1834 of non-integer variables.
1836 Note that initializing an @code{INTEGER} variable with a statement such
1837 as @code{DATA i/Z'FFFFFFFF'/} will give an integer overflow error rather
1838 than the desired result of @math{-1} when @code{i} is a 32-bit integer
1839 on a system that supports 64-bit integers.  The @samp{-fno-range-check}
1840 option can be used as a workaround for legacy code that initializes
1841 integers in this manner.
1843 @node Real array indices
1844 @subsection Real array indices
1845 @cindex array, indices of type real
1847 As an extension, GNU Fortran allows the use of @code{REAL} expressions
1848 or variables as array indices.
1850 @node Unary operators
1851 @subsection Unary operators
1852 @cindex operators, unary
1854 As an extension, GNU Fortran allows unary plus and unary minus operators
1855 to appear as the second operand of binary arithmetic operators without
1856 the need for parenthesis.
1858 @smallexample
1859        X = Y * -Z
1860 @end smallexample
1862 @node Implicitly convert LOGICAL and INTEGER values
1863 @subsection Implicitly convert @code{LOGICAL} and @code{INTEGER} values
1864 @cindex conversion, to integer
1865 @cindex conversion, to logical
1867 As an extension for backwards compatibility with other compilers, GNU
1868 Fortran allows the implicit conversion of @code{LOGICAL} values to
1869 @code{INTEGER} values and vice versa.  When converting from a
1870 @code{LOGICAL} to an @code{INTEGER}, @code{.FALSE.} is interpreted as
1871 zero, and @code{.TRUE.} is interpreted as one.  When converting from
1872 @code{INTEGER} to @code{LOGICAL}, the value zero is interpreted as
1873 @code{.FALSE.} and any nonzero value is interpreted as @code{.TRUE.}.
1875 @smallexample
1876         LOGICAL :: l
1877         l = 1
1878 @end smallexample
1879 @smallexample
1880         INTEGER :: i
1881         i = .TRUE.
1882 @end smallexample
1884 However, there is no implicit conversion of @code{INTEGER} values in
1885 @code{if}-statements, nor of @code{LOGICAL} or @code{INTEGER} values
1886 in I/O operations.
1888 @node Hollerith constants support
1889 @subsection Hollerith constants support
1890 @cindex Hollerith constants
1892 GNU Fortran supports Hollerith constants in assignments, function
1893 arguments, and @code{DATA} and @code{ASSIGN} statements.  A Hollerith
1894 constant is written as a string of characters preceded by an integer
1895 constant indicating the character count, and the letter @code{H} or
1896 @code{h}, and stored in bytewise fashion in a numeric (@code{INTEGER},
1897 @code{REAL}, or @code{complex}) or @code{LOGICAL} variable.  The
1898 constant will be padded or truncated to fit the size of the variable in
1899 which it is stored.
1901 Examples of valid uses of Hollerith constants:
1902 @smallexample
1903       complex*16 x(2)
1904       data x /16Habcdefghijklmnop, 16Hqrstuvwxyz012345/
1905       x(1) = 16HABCDEFGHIJKLMNOP
1906       call foo (4h abc)
1907 @end smallexample
1909 Invalid Hollerith constants examples:
1910 @smallexample
1911       integer*4 a
1912       a = 8H12345678 ! Valid, but the Hollerith constant will be truncated.
1913       a = 0H         ! At least one character is needed.
1914 @end smallexample
1916 In general, Hollerith constants were used to provide a rudimentary
1917 facility for handling character strings in early Fortran compilers,
1918 prior to the introduction of @code{CHARACTER} variables in Fortran 77;
1919 in those cases, the standard-compliant equivalent is to convert the
1920 program to use proper character strings.  On occasion, there may be a
1921 case where the intent is specifically to initialize a numeric variable
1922 with a given byte sequence.  In these cases, the same result can be
1923 obtained by using the @code{TRANSFER} statement, as in this example.
1924 @smallexample
1925       INTEGER(KIND=4) :: a
1926       a = TRANSFER ("abcd", a)     ! equivalent to: a = 4Habcd
1927 @end smallexample
1930 @node Cray pointers
1931 @subsection Cray pointers
1932 @cindex pointer, Cray
1934 Cray pointers are part of a non-standard extension that provides a
1935 C-like pointer in Fortran.  This is accomplished through a pair of
1936 variables: an integer "pointer" that holds a memory address, and a
1937 "pointee" that is used to dereference the pointer.
1939 Pointer/pointee pairs are declared in statements of the form:
1940 @smallexample
1941         pointer ( <pointer> , <pointee> )
1942 @end smallexample
1944 @smallexample
1945         pointer ( <pointer1> , <pointee1> ), ( <pointer2> , <pointee2> ), ...
1946 @end smallexample
1947 The pointer is an integer that is intended to hold a memory address.
1948 The pointee may be an array or scalar.
1949 If an assumed-size array is permitted within the scoping unit, a
1950 pointee can be an assumed-size array.
1951 That is, the last dimension may be left unspecified by using a @code{*}
1952 in place of a value. A pointee cannot be an assumed shape array.
1953 No space is allocated for the pointee.
1955 The pointee may have its type declared before or after the pointer
1956 statement, and its array specification (if any) may be declared
1957 before, during, or after the pointer statement.  The pointer may be
1958 declared as an integer prior to the pointer statement.  However, some
1959 machines have default integer sizes that are different than the size
1960 of a pointer, and so the following code is not portable:
1961 @smallexample
1962         integer ipt
1963         pointer (ipt, iarr)
1964 @end smallexample
1965 If a pointer is declared with a kind that is too small, the compiler
1966 will issue a warning; the resulting binary will probably not work
1967 correctly, because the memory addresses stored in the pointers may be
1968 truncated.  It is safer to omit the first line of the above example;
1969 if explicit declaration of ipt's type is omitted, then the compiler
1970 will ensure that ipt is an integer variable large enough to hold a
1971 pointer.
1973 Pointer arithmetic is valid with Cray pointers, but it is not the same
1974 as C pointer arithmetic.  Cray pointers are just ordinary integers, so
1975 the user is responsible for determining how many bytes to add to a
1976 pointer in order to increment it.  Consider the following example:
1977 @smallexample
1978         real target(10)
1979         real pointee(10)
1980         pointer (ipt, pointee)
1981         ipt = loc (target)
1982         ipt = ipt + 1       
1983 @end smallexample
1984 The last statement does not set @code{ipt} to the address of
1985 @code{target(1)}, as it would in C pointer arithmetic.  Adding @code{1}
1986 to @code{ipt} just adds one byte to the address stored in @code{ipt}.
1988 Any expression involving the pointee will be translated to use the
1989 value stored in the pointer as the base address.
1991 To get the address of elements, this extension provides an intrinsic
1992 function @code{LOC()}.  The @code{LOC()} function is equivalent to the
1993 @code{&} operator in C, except the address is cast to an integer type:
1994 @smallexample
1995         real ar(10)
1996         pointer(ipt, arpte(10))
1997         real arpte
1998         ipt = loc(ar)  ! Makes arpte is an alias for ar
1999         arpte(1) = 1.0 ! Sets ar(1) to 1.0
2000 @end smallexample
2001 The pointer can also be set by a call to the @code{MALLOC} intrinsic
2002 (see @ref{MALLOC}).
2004 Cray pointees often are used to alias an existing variable.  For
2005 example:
2006 @smallexample
2007         integer target(10)
2008         integer iarr(10)
2009         pointer (ipt, iarr)
2010         ipt = loc(target)
2011 @end smallexample
2012 As long as @code{ipt} remains unchanged, @code{iarr} is now an alias for
2013 @code{target}.  The optimizer, however, will not detect this aliasing, so
2014 it is unsafe to use @code{iarr} and @code{target} simultaneously.  Using
2015 a pointee in any way that violates the Fortran aliasing rules or
2016 assumptions is illegal.  It is the user's responsibility to avoid doing
2017 this; the compiler works under the assumption that no such aliasing
2018 occurs.
2020 Cray pointers will work correctly when there is no aliasing (i.e., when
2021 they are used to access a dynamically allocated block of memory), and
2022 also in any routine where a pointee is used, but any variable with which
2023 it shares storage is not used.  Code that violates these rules may not
2024 run as the user intends.  This is not a bug in the optimizer; any code
2025 that violates the aliasing rules is illegal.  (Note that this is not
2026 unique to GNU Fortran; any Fortran compiler that supports Cray pointers
2027 will ``incorrectly'' optimize code with illegal aliasing.)
2029 There are a number of restrictions on the attributes that can be applied
2030 to Cray pointers and pointees.  Pointees may not have the
2031 @code{ALLOCATABLE}, @code{INTENT}, @code{OPTIONAL}, @code{DUMMY},
2032 @code{TARGET}, @code{INTRINSIC}, or @code{POINTER} attributes.  Pointers
2033 may not have the @code{DIMENSION}, @code{POINTER}, @code{TARGET},
2034 @code{ALLOCATABLE}, @code{EXTERNAL}, or @code{INTRINSIC} attributes, nor
2035 may they be function results.  Pointees may not occur in more than one
2036 pointer statement.  A pointee cannot be a pointer.  Pointees cannot occur
2037 in equivalence, common, or data statements.
2039 A Cray pointer may also point to a function or a subroutine.  For
2040 example, the following excerpt is valid:
2041 @smallexample
2042   implicit none
2043   external sub
2044   pointer (subptr,subpte)
2045   external subpte
2046   subptr = loc(sub)
2047   call subpte()
2048   [...]
2049   subroutine sub
2050   [...]
2051   end subroutine sub
2052 @end smallexample
2054 A pointer may be modified during the course of a program, and this
2055 will change the location to which the pointee refers.  However, when
2056 pointees are passed as arguments, they are treated as ordinary
2057 variables in the invoked function.  Subsequent changes to the pointer
2058 will not change the base address of the array that was passed.
2060 @node CONVERT specifier
2061 @subsection @code{CONVERT} specifier
2062 @cindex @code{CONVERT} specifier
2064 GNU Fortran allows the conversion of unformatted data between little-
2065 and big-endian representation to facilitate moving of data
2066 between different systems.  The conversion can be indicated with
2067 the @code{CONVERT} specifier on the @code{OPEN} statement.
2068 @xref{GFORTRAN_CONVERT_UNIT}, for an alternative way of specifying
2069 the data format via an environment variable.
2071 Valid values for @code{CONVERT} are:
2072 @itemize @w{}
2073 @item @code{CONVERT='NATIVE'} Use the native format.  This is the default.
2074 @item @code{CONVERT='SWAP'} Swap between little- and big-endian.
2075 @item @code{CONVERT='LITTLE_ENDIAN'} Use the little-endian representation
2076 for unformatted files.
2077 @item @code{CONVERT='BIG_ENDIAN'} Use the big-endian representation for
2078 unformatted files.
2079 @end itemize
2081 Using the option could look like this:
2082 @smallexample
2083   open(file='big.dat',form='unformatted',access='sequential', &
2084        convert='big_endian')
2085 @end smallexample
2087 The value of the conversion can be queried by using
2088 @code{INQUIRE(CONVERT=ch)}.  The values returned are
2089 @code{'BIG_ENDIAN'} and @code{'LITTLE_ENDIAN'}.
2091 @code{CONVERT} works between big- and little-endian for
2092 @code{INTEGER} values of all supported kinds and for @code{REAL}
2093 on IEEE systems of kinds 4 and 8.  Conversion between different
2094 ``extended double'' types on different architectures such as
2095 m68k and x86_64, which GNU Fortran
2096 supports as @code{REAL(KIND=10)} and @code{REAL(KIND=16)}, will
2097 probably not work.
2099 @emph{Note that the values specified via the GFORTRAN_CONVERT_UNIT
2100 environment variable will override the CONVERT specifier in the
2101 open statement}.  This is to give control over data formats to
2102 users who do not have the source code of their program available.
2104 Using anything but the native representation for unformatted data
2105 carries a significant speed overhead.  If speed in this area matters
2106 to you, it is best if you use this only for data that needs to be
2107 portable.
2109 @node OpenMP
2110 @subsection OpenMP
2111 @cindex OpenMP
2113 OpenMP (Open Multi-Processing) is an application programming
2114 interface (API) that supports multi-platform shared memory 
2115 multiprocessing programming in C/C++ and Fortran on many 
2116 architectures, including Unix and Microsoft Windows platforms.
2117 It consists of a set of compiler directives, library routines,
2118 and environment variables that influence run-time behavior.
2120 GNU Fortran strives to be compatible to the 
2121 @uref{http://openmp.org/wp/openmp-specifications/,
2122 OpenMP Application Program Interface v4.5}.
2124 To enable the processing of the OpenMP directive @code{!$omp} in
2125 free-form source code; the @code{c$omp}, @code{*$omp} and @code{!$omp}
2126 directives in fixed form; the @code{!$} conditional compilation sentinels
2127 in free form; and the @code{c$}, @code{*$} and @code{!$} sentinels
2128 in fixed form, @command{gfortran} needs to be invoked with the
2129 @option{-fopenmp}.  This also arranges for automatic linking of the
2130 GNU Offloading and Multi Processing Runtime Library
2131 @ref{Top,,libgomp,libgomp,GNU Offloading and Multi Processing Runtime
2132 Library}.
2134 The OpenMP Fortran runtime library routines are provided both in a
2135 form of a Fortran 90 module named @code{omp_lib} and in a form of
2136 a Fortran @code{include} file named @file{omp_lib.h}.
2138 An example of a parallelized loop taken from Appendix A.1 of
2139 the OpenMP Application Program Interface v2.5:
2140 @smallexample
2141 SUBROUTINE A1(N, A, B)
2142   INTEGER I, N
2143   REAL B(N), A(N)
2144 !$OMP PARALLEL DO !I is private by default
2145   DO I=2,N
2146     B(I) = (A(I) + A(I-1)) / 2.0
2147   ENDDO
2148 !$OMP END PARALLEL DO
2149 END SUBROUTINE A1
2150 @end smallexample
2152 Please note:
2153 @itemize
2154 @item
2155 @option{-fopenmp} implies @option{-frecursive}, i.e., all local arrays
2156 will be allocated on the stack.  When porting existing code to OpenMP,
2157 this may lead to surprising results, especially to segmentation faults
2158 if the stacksize is limited.
2160 @item
2161 On glibc-based systems, OpenMP enabled applications cannot be statically
2162 linked due to limitations of the underlying pthreads-implementation.  It
2163 might be possible to get a working solution if 
2164 @command{-Wl,--whole-archive -lpthread -Wl,--no-whole-archive} is added
2165 to the command line.  However, this is not supported by @command{gcc} and
2166 thus not recommended.
2167 @end itemize
2169 @node OpenACC
2170 @subsection OpenACC
2171 @cindex OpenACC
2173 OpenACC is an application programming interface (API) that supports
2174 offloading of code to accelerator devices.  It consists of a set of
2175 compiler directives, library routines, and environment variables that
2176 influence run-time behavior.
2178 GNU Fortran strives to be compatible to the
2179 @uref{http://www.openacc.org/, OpenACC Application Programming
2180 Interface v2.0}.
2182 To enable the processing of the OpenACC directive @code{!$acc} in
2183 free-form source code; the @code{c$acc}, @code{*$acc} and @code{!$acc}
2184 directives in fixed form; the @code{!$} conditional compilation
2185 sentinels in free form; and the @code{c$}, @code{*$} and @code{!$}
2186 sentinels in fixed form, @command{gfortran} needs to be invoked with
2187 the @option{-fopenacc}.  This also arranges for automatic linking of
2188 the GNU Offloading and Multi Processing Runtime Library
2189 @ref{Top,,libgomp,libgomp,GNU Offloading and Multi Processing Runtime
2190 Library}.
2192 The OpenACC Fortran runtime library routines are provided both in a
2193 form of a Fortran 90 module named @code{openacc} and in a form of a
2194 Fortran @code{include} file named @file{openacc_lib.h}.
2196 Note that this is an experimental feature, incomplete, and subject to
2197 change in future versions of GCC.  See
2198 @uref{https://gcc.gnu.org/wiki/OpenACC} for more information.
2200 @node Argument list functions
2201 @subsection Argument list functions @code{%VAL}, @code{%REF} and @code{%LOC}
2202 @cindex argument list functions
2203 @cindex @code{%VAL}
2204 @cindex @code{%REF}
2205 @cindex @code{%LOC}
2207 GNU Fortran supports argument list functions @code{%VAL}, @code{%REF} 
2208 and @code{%LOC} statements, for backward compatibility with g77. 
2209 It is recommended that these should be used only for code that is 
2210 accessing facilities outside of GNU Fortran, such as operating system 
2211 or windowing facilities.  It is best to constrain such uses to isolated 
2212 portions of a program--portions that deal specifically and exclusively 
2213 with low-level, system-dependent facilities.  Such portions might well 
2214 provide a portable interface for use by the program as a whole, but are 
2215 themselves not portable, and should be thoroughly tested each time they 
2216 are rebuilt using a new compiler or version of a compiler.
2218 @code{%VAL} passes a scalar argument by value, @code{%REF} passes it by 
2219 reference and @code{%LOC} passes its memory location.  Since gfortran 
2220 already passes scalar arguments by reference, @code{%REF} is in effect 
2221 a do-nothing.  @code{%LOC} has the same effect as a Fortran pointer.
2223 An example of passing an argument by value to a C subroutine foo.:
2224 @smallexample
2226 C prototype      void foo_ (float x);
2228       external foo
2229       real*4 x
2230       x = 3.14159
2231       call foo (%VAL (x))
2232       end
2233 @end smallexample
2235 For details refer to the g77 manual
2236 @uref{https://gcc.gnu.org/@/onlinedocs/@/gcc-3.4.6/@/g77/@/index.html#Top}.
2238 Also, @code{c_by_val.f} and its partner @code{c_by_val.c} of the
2239 GNU Fortran testsuite are worth a look.
2241 @node Read/Write after EOF marker
2242 @subsection Read/Write after EOF marker
2243 @cindex @code{EOF}
2244 @cindex @code{BACKSPACE}
2245 @cindex @code{REWIND}
2247 Some legacy codes rely on allowing @code{READ} or @code{WRITE} after the
2248 EOF file marker in order to find the end of a file. GNU Fortran normally
2249 rejects these codes with a run-time error message and suggests the user
2250 consider @code{BACKSPACE} or @code{REWIND} to properly position
2251 the file before the EOF marker.  As an extension, the run-time error may
2252 be disabled using -std=legacy.
2255 @node STRUCTURE and RECORD
2256 @subsection @code{STRUCTURE} and @code{RECORD}
2257 @cindex @code{STRUCTURE}
2258 @cindex @code{RECORD}
2260 Record structures are a pre-Fortran-90 vendor extension to create
2261 user-defined aggregate data types.  Support for record structures in GNU
2262 Fortran can be enabled with the @option{-fdec-structure} compile flag.
2263 If you have a choice, you should instead use Fortran 90's ``derived types'',
2264 which have a different syntax.
2266 In many cases, record structures can easily be converted to derived types.
2267 To convert, replace @code{STRUCTURE /}@var{structure-name}@code{/}
2268 by @code{TYPE} @var{type-name}.  Additionally, replace
2269 @code{RECORD /}@var{structure-name}@code{/} by
2270 @code{TYPE(}@var{type-name}@code{)}. Finally, in the component access,
2271 replace the period (@code{.}) by the percent sign (@code{%}).
2273 Here is an example of code using the non portable record structure syntax:
2275 @example
2276 ! Declaring a structure named ``item'' and containing three fields:
2277 ! an integer ID, an description string and a floating-point price.
2278 STRUCTURE /item/
2279   INTEGER id
2280   CHARACTER(LEN=200) description
2281   REAL price
2282 END STRUCTURE
2284 ! Define two variables, an single record of type ``item''
2285 ! named ``pear'', and an array of items named ``store_catalog''
2286 RECORD /item/ pear, store_catalog(100)
2288 ! We can directly access the fields of both variables
2289 pear.id = 92316
2290 pear.description = "juicy D'Anjou pear"
2291 pear.price = 0.15
2292 store_catalog(7).id = 7831
2293 store_catalog(7).description = "milk bottle"
2294 store_catalog(7).price = 1.2
2296 ! We can also manipulate the whole structure
2297 store_catalog(12) = pear
2298 print *, store_catalog(12)
2299 @end example
2301 @noindent
2302 This code can easily be rewritten in the Fortran 90 syntax as following:
2304 @example
2305 ! ``STRUCTURE /name/ ... END STRUCTURE'' becomes
2306 ! ``TYPE name ... END TYPE''
2307 TYPE item
2308   INTEGER id
2309   CHARACTER(LEN=200) description
2310   REAL price
2311 END TYPE
2313 ! ``RECORD /name/ variable'' becomes ``TYPE(name) variable''
2314 TYPE(item) pear, store_catalog(100)
2316 ! Instead of using a dot (.) to access fields of a record, the
2317 ! standard syntax uses a percent sign (%)
2318 pear%id = 92316
2319 pear%description = "juicy D'Anjou pear"
2320 pear%price = 0.15
2321 store_catalog(7)%id = 7831
2322 store_catalog(7)%description = "milk bottle"
2323 store_catalog(7)%price = 1.2
2325 ! Assignments of a whole variable do not change
2326 store_catalog(12) = pear
2327 print *, store_catalog(12)
2328 @end example
2330 @noindent
2331 GNU Fortran implements STRUCTURES like derived types with the following
2332 rules and exceptions:
2334 @itemize @bullet
2335 @item Structures act like derived types with the @code{SEQUENCE} attribute.
2336 Otherwise they may contain no specifiers.
2338 @item Structures may contain a special field with the name @code{%FILL}.
2339 This will create an anonymous component which cannot be accessed but occupies
2340 space just as if a component of the same type was declared in its place, useful
2341 for alignment purposes.  As an example, the following structure will consist
2342 of at least sixteen bytes:
2344 @smallexample
2345 structure /padded/
2346   character(4) start
2347   character(8) %FILL
2348   character(4) end
2349 end structure
2350 @end smallexample
2352 @item Structures may share names with other symbols. For example, the following
2353 is invalid for derived types, but valid for structures:
2355 @smallexample
2356 structure /header/
2357   ! ...
2358 end structure
2359 record /header/ header
2360 @end smallexample
2362 @item Structure types may be declared nested within another parent structure.
2363 The syntax is:
2364 @smallexample
2365 structure /type-name/
2366     ...
2367     structure [/<type-name>/] <field-list>
2369 @end smallexample
2371 The type name may be ommitted, in which case the structure type itself is
2372 anonymous, and other structures of the same type cannot be instantiated. The
2373 following shows some examples:
2375 @example
2376 structure /appointment/
2377   ! nested structure definition: app_time is an array of two 'time'
2378   structure /time/ app_time (2) 
2379     integer(1) hour, minute
2380   end structure
2381   character(10) memo
2382 end structure
2384 ! The 'time' structure is still usable
2385 record /time/ now
2386 now = time(5, 30)
2390 structure /appointment/
2391   ! anonymous nested structure definition
2392   structure start, end
2393     integer(1) hour, minute
2394   end structure
2395   character(10) memo
2396 end structure
2397 @end example
2399 @item Structures may contain @code{UNION} blocks. For more detail see the
2400 section on @ref{UNION and MAP}.
2402 @item Structures support old-style initialization of components, like
2403 those described in @ref{Old-style variable initialization}. For array
2404 initializers, an initializer may contain a repeat specification of the form
2405 @code{<literal-integer> * <constant-initializer>}. The value of the integer
2406 indicates the number of times to repeat the constant initializer when expanding
2407 the initializer list.
2408 @end itemize
2410 @node UNION and MAP
2411 @subsection @code{UNION} and @code{MAP}
2412 @cindex @code{UNION}
2413 @cindex @code{MAP}
2415 Unions are an old vendor extension which were commonly used with the
2416 non-standard @ref{STRUCTURE and RECORD} extensions. Use of @code{UNION} and
2417 @code{MAP} is automatically enabled with @option{-fdec-structure}.
2419 A @code{UNION} declaration occurs within a structure; within the definition of
2420 each union is a number of @code{MAP} blocks. Each @code{MAP} shares storage
2421 with its sibling maps (in the same union), and the size of the union is the
2422 size of the largest map within it, just as with unions in C. The major
2423 difference is that component references do not indicate which union or map the
2424 component is in (the compiler gets to figure that out).
2426 Here is a small example:
2427 @smallexample
2428 structure /myunion/
2429 union
2430   map
2431     character(2) w0, w1, w2
2432   end map
2433   map
2434     character(6) long
2435   end map
2436 end union
2437 end structure
2439 record /myunion/ rec
2440 ! After this assignment...
2441 rec.long = 'hello!'
2443 ! The following is true:
2444 ! rec.w0 === 'he'
2445 ! rec.w1 === 'll'
2446 ! rec.w2 === 'o!'
2447 @end smallexample
2449 The two maps share memory, and the size of the union is ultimately six bytes:
2451 @example
2452 0    1    2    3    4   5   6     Byte offset
2453 -------------------------------
2454 |    |    |    |    |    |    |
2455 -------------------------------
2457 ^    W0   ^    W1   ^    W2   ^
2458  \-------/ \-------/ \-------/
2460 ^             LONG            ^
2461  \---------------------------/
2462 @end example
2464 Following is an example mirroring the layout of an Intel x86_64 register:
2466 @example
2467 structure /reg/
2468   union ! U0                ! rax
2469     map
2470       character(16) rx
2471     end map
2472     map
2473       character(8) rh         ! rah
2474       union ! U1
2475         map
2476           character(8) rl     ! ral
2477         end map
2478         map
2479           character(8) ex     ! eax
2480         end map
2481         map
2482           character(4) eh     ! eah
2483           union ! U2
2484             map
2485               character(4) el ! eal
2486             end map
2487             map
2488               character(4) x  ! ax
2489             end map
2490             map
2491               character(2) h  ! ah
2492               character(2) l  ! al
2493             end map
2494           end union
2495         end map
2496       end union
2497     end map
2498   end union
2499 end structure
2500 record /reg/ a
2502 ! After this assignment...
2503 a.rx     =     'AAAAAAAA.BBB.C.D'
2505 ! The following is true:
2506 a.rx === 'AAAAAAAA.BBB.C.D'
2507 a.rh === 'AAAAAAAA'
2508 a.rl ===         '.BBB.C.D'
2509 a.ex ===         '.BBB.C.D'
2510 a.eh ===         '.BBB'
2511 a.el ===             '.C.D'
2512 a.x  ===             '.C.D'
2513 a.h  ===             '.C'
2514 a.l  ===               '.D'
2515 @end example
2517 @node Type variants for integer intrinsics
2518 @subsection Type variants for integer intrinsics
2519 @cindex intrinsics, integer
2521 Similar to the D/C prefixes to real functions to specify the input/output
2522 types, GNU Fortran offers B/I/J/K prefixes to integer functions for
2523 compatibility with DEC programs. The types implied by each are:
2525 @example
2526 @code{B} - @code{INTEGER(kind=1)}
2527 @code{I} - @code{INTEGER(kind=2)}
2528 @code{J} - @code{INTEGER(kind=4)}
2529 @code{K} - @code{INTEGER(kind=8)}
2530 @end example
2532 GNU Fortran supports these with the flag @option{-fdec-intrinsic-ints}.
2533 Intrinsics for which prefixed versions are available and in what form are noted
2534 in @ref{Intrinsic Procedures}. The complete list of supported intrinsics is
2535 here:
2537 @multitable @columnfractions .2 .2 .2 .2 .2
2539 @headitem Intrinsic @tab B @tab I @tab J @tab K
2541 @item @code{@ref{ABS}}
2542   @tab @code{BABS} @tab @code{IIABS} @tab @code{JIABS} @tab @code{KIABS}
2543 @item @code{@ref{BTEST}}
2544   @tab @code{BBTEST} @tab @code{BITEST} @tab @code{BJTEST} @tab @code{BKTEST}
2545 @item @code{@ref{IAND}}
2546   @tab @code{BIAND} @tab @code{IIAND} @tab @code{JIAND} @tab @code{KIAND}
2547 @item @code{@ref{IBCLR}}
2548   @tab @code{BBCLR} @tab @code{IIBCLR} @tab @code{JIBCLR} @tab @code{KIBCLR}
2549 @item @code{@ref{IBITS}}
2550   @tab @code{BBITS} @tab @code{IIBITS} @tab @code{JIBITS} @tab @code{KIBITS}
2551 @item @code{@ref{IBSET}}
2552   @tab @code{BBSET} @tab @code{IIBSET} @tab @code{JIBSET} @tab @code{KIBSET}
2553 @item @code{@ref{IEOR}}
2554   @tab @code{BIEOR} @tab @code{IIEOR} @tab @code{JIEOR} @tab @code{KIEOR}
2555 @item @code{@ref{IOR}}
2556   @tab @code{BIOR} @tab @code{IIOR} @tab @code{JIOR} @tab @code{KIOR}
2557 @item @code{@ref{ISHFT}}
2558   @tab @code{BSHFT} @tab @code{IISHFT} @tab @code{JISHFT} @tab @code{KISHFT}
2559 @item @code{@ref{ISHFTC}}
2560   @tab @code{BSHFTC} @tab @code{IISHFTC} @tab @code{JISHFTC} @tab @code{KISHFTC}
2561 @item @code{@ref{MOD}}
2562   @tab @code{BMOD} @tab @code{IMOD} @tab @code{JMOD} @tab @code{KMOD}
2563 @item @code{@ref{NOT}}
2564   @tab @code{BNOT} @tab @code{INOT} @tab @code{JNOT} @tab @code{KNOT}
2565 @item @code{@ref{REAL}}
2566   @tab @code{--} @tab @code{FLOATI} @tab @code{FLOATJ} @tab @code{FLOATK}
2567 @end multitable
2569 @node AUTOMATIC and STATIC attributes
2570 @subsection @code{AUTOMATIC} and @code{STATIC} attributes
2571 @cindex variable attributes
2572 @cindex @code{AUTOMATIC}
2573 @cindex @code{STATIC}
2575 With @option{-fdec-static} GNU Fortran supports the DEC extended attributes
2576 @code{STATIC} and @code{AUTOMATIC} to provide explicit specification of entity
2577 storage.  These follow the syntax of the Fortran standard @code{SAVE} attribute.
2579 @code{STATIC} is exactly equivalent to @code{SAVE}, and specifies that
2580 an entity should be allocated in static memory.  As an example, @code{STATIC}
2581 local variables will retain their values across multiple calls to a function.
2583 Entities marked @code{AUTOMATIC} will be stack automatic whenever possible.
2584 @code{AUTOMATIC} is the default for local variables smaller than
2585 @option{-fmax-stack-var-size}, unless @option{-fno-automatic} is given.  This
2586 attribute overrides @option{-fno-automatic}, @option{-fmax-stack-var-size}, and
2587 blanket @code{SAVE} statements.
2590 Examples:
2592 @example
2593 subroutine f
2594   integer, automatic :: i  ! automatic variable
2595   integer x, y             ! static variables
2596   save
2597   ...
2598 endsubroutine
2599 @end example
2600 @example
2601 subroutine f
2602   integer a, b, c, x, y, z
2603   static :: x
2604   save y
2605   automatic z, c
2606   ! a, b, c, and z are automatic
2607   ! x and y are static
2608 endsubroutine
2609 @end example
2610 @example
2611 ! Compiled with -fno-automatic
2612 subroutine f
2613   integer a, b, c, d
2614   automatic :: a
2615   ! a is automatic; b, c, and d are static
2616 endsubroutine
2617 @end example
2619 @node Extended math intrinsics
2620 @subsection Extended math intrinsics
2621 @cindex intrinsics, math
2622 @cindex intrinsics, trigonometric functions
2624 GNU Fortran supports an extended list of mathematical intrinsics with the
2625 compile flag @option{-fdec-math} for compatability with legacy code.
2626 These intrinsics are described fully in @ref{Intrinsic Procedures} where it is
2627 noted that they are extensions and should be avoided whenever possible.
2629 Specifically, @option{-fdec-math} enables the @ref{COTAN} intrinsic, and
2630 trigonometric intrinsics which accept or produce values in degrees instead of
2631 radians.  Here is a summary of the new intrinsics:
2633 @multitable @columnfractions .5 .5
2634 @headitem Radians @tab Degrees
2635 @item @code{@ref{ACOS}}   @tab @code{@ref{ACOSD}}*
2636 @item @code{@ref{ASIN}}   @tab @code{@ref{ASIND}}*
2637 @item @code{@ref{ATAN}}   @tab @code{@ref{ATAND}}*
2638 @item @code{@ref{ATAN2}}  @tab @code{@ref{ATAN2D}}*
2639 @item @code{@ref{COS}}    @tab @code{@ref{COSD}}*
2640 @item @code{@ref{COTAN}}* @tab @code{@ref{COTAND}}*
2641 @item @code{@ref{SIN}}    @tab @code{@ref{SIND}}*
2642 @item @code{@ref{TAN}}    @tab @code{@ref{TAND}}*
2643 @end multitable
2645 * Enabled with @option{-fdec-math}.
2647 For advanced users, it may be important to know the implementation of these
2648 functions. They are simply wrappers around the standard radian functions, which
2649 have more accurate builtin versions. These functions convert their arguments
2650 (or results) to degrees (or radians) by taking the value modulus 360 (or 2*pi)
2651 and then multiplying it by a constant radian-to-degree (or degree-to-radian)
2652 factor, as appropriate. The factor is computed at compile-time as 180/pi (or
2653 pi/180).
2655 @node Form feed as whitespace
2656 @subsection Form feed as whitespace
2657 @cindex form feed whitespace
2659 Historically, legacy compilers allowed insertion of form feed characters ('\f',
2660 ASCII 0xC) at the beginning of lines for formatted output to line printers,
2661 though the Fortran standard does not mention this. GNU Fortran supports the
2662 interpretation of form feed characters in source as whitespace for
2663 compatibility.
2665 @node TYPE as an alias for PRINT
2666 @subsection TYPE as an alias for PRINT
2667 @cindex type alias print
2668 For compatibility, GNU Fortran will interpret @code{TYPE} statements as
2669 @code{PRINT} statements with the flag @option{-fdec}.  With this flag asserted,
2670 the following two examples are equivalent:
2672 @smallexample
2673 TYPE *, 'hello world'
2674 @end smallexample
2676 @smallexample
2677 PRINT *, 'hello world'
2678 @end smallexample
2680 @node %LOC as an rvalue
2681 @subsection %LOC as an rvalue
2682 @cindex LOC
2683 Normally @code{%LOC} is allowed only in parameter lists.  However the intrinsic
2684 function @code{LOC} does the same thing, and is usable as the right-hand-side of
2685 assignments. For compatibility, GNU Fortran supports the use of @code{%LOC} as
2686 an alias for the builtin @code{LOC} with @option{-std=legacy}.  With this
2687 feature enabled the following two examples are equivalent:
2689 @smallexample
2690 integer :: i, l
2691 l = %loc(i)
2692 call sub(l)
2693 @end smallexample
2695 @smallexample
2696 integer :: i
2697 call sub(%loc(i))
2698 @end smallexample
2700 @node .XOR. operator
2701 @subsection .XOR. operator
2702 @cindex operators, xor
2704 GNU Fortran supports @code{.XOR.} as a logical operator with @code{-std=legacy}
2705 for compatibility with legacy code. @code{.XOR.} is equivalent to
2706 @code{.NEQV.}. That is, the output is true if and only if the inputs differ.
2708 @node Bitwise logical operators
2709 @subsection Bitwise logical operators
2710 @cindex logical, bitwise
2712 With @option{-fdec}, GNU Fortran relaxes the type constraints on
2713 logical operators to allow integer operands, and performs the corresponding
2714 bitwise operation instead.  This flag is for compatibility only, and should be
2715 avoided in new code.  Consider:
2717 @smallexample
2718   INTEGER :: i, j
2719   i = z'33'
2720   j = z'cc'
2721   print *, i .AND. j
2722 @end smallexample
2724 In this example, compiled with @option{-fdec}, GNU Fortran will
2725 replace the @code{.AND.} operation with a call to the intrinsic
2726 @code{@ref{IAND}} function, yielding the bitwise-and of @code{i} and @code{j}.
2728 Note that this conversion will occur if at least one operand is of integral
2729 type.  As a result, a logical operand will be converted to an integer when the
2730 other operand is an integer in a logical operation.  In this case,
2731 @code{.TRUE.} is converted to @code{1} and @code{.FALSE.} to @code{0}.
2733 Here is the mapping of logical operator to bitwise intrinsic used with
2734 @option{-fdec}:
2736 @multitable @columnfractions .25 .25 .5
2737 @headitem Operator @tab Intrinsic @tab Bitwise operation
2738 @item @code{.NOT.} @tab @code{@ref{NOT}} @tab complement
2739 @item @code{.AND.} @tab @code{@ref{IAND}} @tab intersection
2740 @item @code{.OR.} @tab @code{@ref{IOR}} @tab union
2741 @item @code{.NEQV.} @tab @code{@ref{IEOR}} @tab exclusive or
2742 @item @code{.EQV.} @tab @code{@ref{NOT}(@ref{IEOR})} @tab complement of exclusive or
2743 @end multitable
2745 @node Extended I/O specifiers
2746 @subsection Extended I/O specifiers
2747 @cindex @code{CARRIAGECONTROL}
2748 @cindex @code{READONLY}
2749 @cindex @code{SHARE}
2750 @cindex @code{SHARED}
2751 @cindex @code{NOSHARED}
2752 @cindex I/O specifiers
2754 GNU Fortran supports the additional legacy I/O specifiers
2755 @code{CARRIAGECONTROL}, @code{READONLY}, and @code{SHARE} with the
2756 compile flag @option{-fdec}, for compatibility.
2758 @table @code
2759 @item CARRIAGECONTROL
2760 The @code{CARRIAGECONTROL} specifier allows a user to control line
2761 termination settings between output records for an I/O unit. The specifier has
2762 no meaning for readonly files. When @code{CARRAIGECONTROL} is specified upon
2763 opening a unit for formatted writing, the exact @code{CARRIAGECONTROL} setting
2764 determines what characters to write between output records. The syntax is:
2766 @smallexample
2767 OPEN(..., CARRIAGECONTROL=cc)
2768 @end smallexample
2770 Where @emph{cc} is a character expression that evaluates to one of the
2771 following values:
2773 @multitable @columnfractions .2 .8
2774 @item @code{'LIST'} @tab One line feed between records (default)
2775 @item @code{'FORTRAN'} @tab Legacy interpretation of the first character (see below)
2776 @item @code{'NONE'} @tab No separator between records
2777 @end multitable
2779 With @code{CARRIAGECONTROL='FORTRAN'}, when a record is written, the first
2780 character of the input record is not written, and instead determines the output
2781 record separator as follows:
2783 @multitable @columnfractions .3 .3 .4
2784 @headitem Leading character @tab Meaning @tab Output separating character(s)
2785 @item @code{'+'} @tab Overprinting @tab Carriage return only
2786 @item @code{'-'} @tab New line @tab Line feed and carriage return
2787 @item @code{'0'} @tab Skip line @tab Two line feeds and carriage return
2788 @item @code{'1'} @tab New page @tab Form feed and carriage return
2789 @item @code{'$'} @tab Prompting @tab Line feed (no carriage return)
2790 @item @code{CHAR(0)} @tab Overprinting (no advance) @tab None
2791 @end multitable
2793 @item READONLY
2794 The @code{READONLY} specifier may be given upon opening a unit, and is
2795 equivalent to specifying @code{ACTION='READ'}, except that the file may not be
2796 deleted on close (i.e. @code{CLOSE} with @code{STATUS="DELETE"}). The syntax
2799 @smallexample
2800 @code{OPEN(..., READONLY)}
2801 @end smallexample
2803 @item SHARE
2804 The @code{SHARE} specifier allows system-level locking on a unit upon opening
2805 it for controlled access from multiple processes/threads. The @code{SHARE}
2806 specifier has several forms:
2808 @smallexample
2809 OPEN(..., SHARE=sh)
2810 OPEN(..., SHARED)
2811 OPEN(..., NOSHARED)
2812 @end smallexample
2814 Where @emph{sh} in the first form is a character expression that evaluates to
2815 a value as seen in the table below. The latter two forms are aliases
2816 for particular values of @emph{sh}:
2818 @multitable @columnfractions .3 .3 .4
2819 @headitem Explicit form @tab Short form @tab Meaning
2820 @item @code{SHARE='DENYRW'} @tab @code{NOSHARED} @tab Exclusive (write) lock
2821 @item @code{SHARE='DENYNONE'} @tab @code{SHARED} @tab Shared (read) lock
2822 @end multitable
2824 In general only one process may hold an exclusive (write) lock for a given file
2825 at a time, whereas many processes may hold shared (read) locks for the same
2826 file.
2828 The behavior of locking may vary with your operating system. On POSIX systems,
2829 locking is implemented with @code{fcntl}. Consult your corresponding operating
2830 system's manual pages for further details. Locking via @code{SHARE=} is not
2831 supported on other systems.
2833 @end table
2835 @node Legacy PARAMETER statements
2836 @subsection Legacy PARAMETER statements
2837 @cindex PARAMETER
2839 For compatibility, GNU Fortran supports legacy PARAMETER statements without
2840 parentheses with @option{-std=legacy}.  A warning is emitted if used with
2841 @option{-std=gnu}, and an error is acknowledged with a real Fortran standard
2842 flag (@option{-std=f95}, etc...).  These statements take the following form:
2844 @smallexample
2845 implicit real (E)
2846 parameter e = 2.718282
2847 real c
2848 parameter c = 3.0e8
2849 @end smallexample
2851 @node Default exponents
2852 @subsection Default exponents
2853 @cindex exponent
2855 For compatibility, GNU Fortran supports a default exponent of zero in real
2856 constants with @option{-fdec}.  For example, @code{9e} would be
2857 interpreted as @code{9e0}, rather than an error.
2860 @node Extensions not implemented in GNU Fortran
2861 @section Extensions not implemented in GNU Fortran
2862 @cindex extensions, not implemented
2864 The long history of the Fortran language, its wide use and broad
2865 userbase, the large number of different compiler vendors and the lack of
2866 some features crucial to users in the first standards have lead to the
2867 existence of a number of important extensions to the language.  While
2868 some of the most useful or popular extensions are supported by the GNU
2869 Fortran compiler, not all existing extensions are supported.  This section
2870 aims at listing these extensions and offering advice on how best make
2871 code that uses them running with the GNU Fortran compiler.
2873 @c More can be found here:
2874 @c   -- https://gcc.gnu.org/onlinedocs/gcc-3.4.6/g77/Missing-Features.html
2875 @c   -- the list of Fortran and libgfortran bugs closed as WONTFIX:
2876 @c      http://tinyurl.com/2u4h5y
2878 @menu
2879 * ENCODE and DECODE statements::
2880 * Variable FORMAT expressions::
2881 @c * Q edit descriptor::
2882 @c * TYPE and ACCEPT I/O Statements::
2883 @c * DEFAULTFILE, DISPOSE and RECORDTYPE I/O specifiers::
2884 @c * Omitted arguments in procedure call::
2885 * Alternate complex function syntax::
2886 * Volatile COMMON blocks::
2887 * OPEN( ... NAME=)::
2888 @end menu
2890 @node ENCODE and DECODE statements
2891 @subsection @code{ENCODE} and @code{DECODE} statements
2892 @cindex @code{ENCODE}
2893 @cindex @code{DECODE}
2895 GNU Fortran does not support the @code{ENCODE} and @code{DECODE}
2896 statements.  These statements are best replaced by @code{READ} and
2897 @code{WRITE} statements involving internal files (@code{CHARACTER}
2898 variables and arrays), which have been part of the Fortran standard since
2899 Fortran 77.  For example, replace a code fragment like
2901 @smallexample
2902       INTEGER*1 LINE(80)
2903       REAL A, B, C
2904 c     ... Code that sets LINE
2905       DECODE (80, 9000, LINE) A, B, C
2906  9000 FORMAT (1X, 3(F10.5))
2907 @end smallexample
2909 @noindent
2910 with the following:
2912 @smallexample
2913       CHARACTER(LEN=80) LINE
2914       REAL A, B, C
2915 c     ... Code that sets LINE
2916       READ (UNIT=LINE, FMT=9000) A, B, C
2917  9000 FORMAT (1X, 3(F10.5))
2918 @end smallexample
2920 Similarly, replace a code fragment like
2922 @smallexample
2923       INTEGER*1 LINE(80)
2924       REAL A, B, C
2925 c     ... Code that sets A, B and C
2926       ENCODE (80, 9000, LINE) A, B, C
2927  9000 FORMAT (1X, 'OUTPUT IS ', 3(F10.5))
2928 @end smallexample
2930 @noindent
2931 with the following:
2933 @smallexample
2934       CHARACTER(LEN=80) LINE
2935       REAL A, B, C
2936 c     ... Code that sets A, B and C
2937       WRITE (UNIT=LINE, FMT=9000) A, B, C
2938  9000 FORMAT (1X, 'OUTPUT IS ', 3(F10.5))
2939 @end smallexample
2942 @node Variable FORMAT expressions
2943 @subsection Variable @code{FORMAT} expressions
2944 @cindex @code{FORMAT}
2946 A variable @code{FORMAT} expression is format statement which includes
2947 angle brackets enclosing a Fortran expression: @code{FORMAT(I<N>)}.  GNU
2948 Fortran does not support this legacy extension.  The effect of variable
2949 format expressions can be reproduced by using the more powerful (and
2950 standard) combination of internal output and string formats.  For example,
2951 replace a code fragment like this:
2953 @smallexample
2954       WRITE(6,20) INT1
2955  20   FORMAT(I<N+1>)
2956 @end smallexample
2958 @noindent
2959 with the following:
2961 @smallexample
2962 c     Variable declaration
2963       CHARACTER(LEN=20) FMT
2964 c     
2965 c     Other code here...
2967       WRITE(FMT,'("(I", I0, ")")') N+1
2968       WRITE(6,FMT) INT1
2969 @end smallexample
2971 @noindent
2972 or with:
2974 @smallexample
2975 c     Variable declaration
2976       CHARACTER(LEN=20) FMT
2977 c     
2978 c     Other code here...
2980       WRITE(FMT,*) N+1
2981       WRITE(6,"(I" // ADJUSTL(FMT) // ")") INT1
2982 @end smallexample
2985 @node Alternate complex function syntax
2986 @subsection Alternate complex function syntax
2987 @cindex Complex function
2989 Some Fortran compilers, including @command{g77}, let the user declare
2990 complex functions with the syntax @code{COMPLEX FUNCTION name*16()}, as
2991 well as @code{COMPLEX*16 FUNCTION name()}.  Both are non-standard, legacy
2992 extensions.  @command{gfortran} accepts the latter form, which is more
2993 common, but not the former.
2996 @node Volatile COMMON blocks
2997 @subsection Volatile @code{COMMON} blocks
2998 @cindex @code{VOLATILE}
2999 @cindex @code{COMMON}
3001 Some Fortran compilers, including @command{g77}, let the user declare
3002 @code{COMMON} with the @code{VOLATILE} attribute. This is
3003 invalid standard Fortran syntax and is not supported by
3004 @command{gfortran}.  Note that @command{gfortran} accepts
3005 @code{VOLATILE} variables in @code{COMMON} blocks since revision 4.3.
3008 @node OPEN( ... NAME=)
3009 @subsection @code{OPEN( ... NAME=)}
3010 @cindex @code{NAM}
3012 Some Fortran compilers, including @command{g77}, let the user declare
3013 @code{OPEN( ... NAME=)}. This is
3014 invalid standard Fortran syntax and is not supported by
3015 @command{gfortran}.  @code{OPEN( ... NAME=)} should be replaced
3016 with @code{OPEN( ... FILE=)}.
3020 @c ---------------------------------------------------------------------
3021 @c ---------------------------------------------------------------------
3022 @c Mixed-Language Programming
3023 @c ---------------------------------------------------------------------
3025 @node Mixed-Language Programming
3026 @chapter Mixed-Language Programming
3027 @cindex Interoperability
3028 @cindex Mixed-language programming
3030 @menu
3031 * Interoperability with C::
3032 * GNU Fortran Compiler Directives::
3033 * Non-Fortran Main Program::
3034 * Naming and argument-passing conventions::
3035 @end menu
3037 This chapter is about mixed-language interoperability, but also applies
3038 if one links Fortran code compiled by different compilers.  In most cases,
3039 use of the C Binding features of the Fortran 2003 standard is sufficient,
3040 and their use is highly recommended.
3043 @node Interoperability with C
3044 @section Interoperability with C
3046 @menu
3047 * Intrinsic Types::
3048 * Derived Types and struct::
3049 * Interoperable Global Variables::
3050 * Interoperable Subroutines and Functions::
3051 * Working with Pointers::
3052 * Further Interoperability of Fortran with C::
3053 @end menu
3055 Since Fortran 2003 (ISO/IEC 1539-1:2004(E)) there is a
3056 standardized way to generate procedure and derived-type
3057 declarations and global variables which are interoperable with C
3058 (ISO/IEC 9899:1999).  The @code{bind(C)} attribute has been added
3059 to inform the compiler that a symbol shall be interoperable with C;
3060 also, some constraints are added.  Note, however, that not
3061 all C features have a Fortran equivalent or vice versa.  For instance,
3062 neither C's unsigned integers nor C's functions with variable number
3063 of arguments have an equivalent in Fortran.
3065 Note that array dimensions are reversely ordered in C and that arrays in
3066 C always start with index 0 while in Fortran they start by default with
3067 1.  Thus, an array declaration @code{A(n,m)} in Fortran matches
3068 @code{A[m][n]} in C and accessing the element @code{A(i,j)} matches
3069 @code{A[j-1][i-1]}.  The element following @code{A(i,j)} (C: @code{A[j-1][i-1]};
3070 assuming @math{i < n}) in memory is @code{A(i+1,j)} (C: @code{A[j-1][i]}).
3072 @node Intrinsic Types
3073 @subsection Intrinsic Types
3075 In order to ensure that exactly the same variable type and kind is used
3076 in C and Fortran, the named constants shall be used which are defined in the
3077 @code{ISO_C_BINDING} intrinsic module.  That module contains named constants
3078 for kind parameters and character named constants for the escape sequences
3079 in C.  For a list of the constants, see @ref{ISO_C_BINDING}.
3081 For logical types, please note that the Fortran standard only guarantees
3082 interoperability between C99's @code{_Bool} and Fortran's @code{C_Bool}-kind
3083 logicals and C99 defines that @code{true} has the value 1 and @code{false}
3084 the value 0.  Using any other integer value with GNU Fortran's @code{LOGICAL}
3085 (with any kind parameter) gives an undefined result.  (Passing other integer
3086 values than 0 and 1 to GCC's @code{_Bool} is also undefined, unless the
3087 integer is explicitly or implicitly casted to @code{_Bool}.)
3091 @node Derived Types and struct
3092 @subsection Derived Types and struct
3094 For compatibility of derived types with @code{struct}, one needs to use
3095 the @code{BIND(C)} attribute in the type declaration.  For instance, the
3096 following type declaration
3098 @smallexample
3099  USE ISO_C_BINDING
3100  TYPE, BIND(C) :: myType
3101    INTEGER(C_INT) :: i1, i2
3102    INTEGER(C_SIGNED_CHAR) :: i3
3103    REAL(C_DOUBLE) :: d1
3104    COMPLEX(C_FLOAT_COMPLEX) :: c1
3105    CHARACTER(KIND=C_CHAR) :: str(5)
3106  END TYPE
3107 @end smallexample
3109 matches the following @code{struct} declaration in C
3111 @smallexample
3112  struct @{
3113    int i1, i2;
3114    /* Note: "char" might be signed or unsigned.  */
3115    signed char i3;
3116    double d1;
3117    float _Complex c1;
3118    char str[5];
3119  @} myType;
3120 @end smallexample
3122 Derived types with the C binding attribute shall not have the @code{sequence}
3123 attribute, type parameters, the @code{extends} attribute, nor type-bound
3124 procedures.  Every component must be of interoperable type and kind and may not
3125 have the @code{pointer} or @code{allocatable} attribute.  The names of the
3126 components are irrelevant for interoperability.
3128 As there exist no direct Fortran equivalents, neither unions nor structs
3129 with bit field or variable-length array members are interoperable.
3131 @node Interoperable Global Variables
3132 @subsection Interoperable Global Variables
3134 Variables can be made accessible from C using the C binding attribute,
3135 optionally together with specifying a binding name.  Those variables
3136 have to be declared in the declaration part of a @code{MODULE},
3137 be of interoperable type, and have neither the @code{pointer} nor
3138 the @code{allocatable} attribute.
3140 @smallexample
3141   MODULE m
3142     USE myType_module
3143     USE ISO_C_BINDING
3144     integer(C_INT), bind(C, name="_MyProject_flags") :: global_flag
3145     type(myType), bind(C) :: tp
3146   END MODULE
3147 @end smallexample
3149 Here, @code{_MyProject_flags} is the case-sensitive name of the variable
3150 as seen from C programs while @code{global_flag} is the case-insensitive
3151 name as seen from Fortran.  If no binding name is specified, as for
3152 @var{tp}, the C binding name is the (lowercase) Fortran binding name.
3153 If a binding name is specified, only a single variable may be after the
3154 double colon.  Note of warning: You cannot use a global variable to
3155 access @var{errno} of the C library as the C standard allows it to be
3156 a macro.  Use the @code{IERRNO} intrinsic (GNU extension) instead.
3158 @node Interoperable Subroutines and Functions
3159 @subsection Interoperable Subroutines and Functions
3161 Subroutines and functions have to have the @code{BIND(C)} attribute to
3162 be compatible with C.  The dummy argument declaration is relatively
3163 straightforward.  However, one needs to be careful because C uses
3164 call-by-value by default while Fortran behaves usually similar to
3165 call-by-reference.  Furthermore, strings and pointers are handled
3166 differently.  Note that in Fortran 2003 and 2008 only explicit size
3167 and assumed-size arrays are supported but not assumed-shape or
3168 deferred-shape (i.e. allocatable or pointer) arrays.  However, those
3169 are allowed since the Technical Specification 29113, see
3170 @ref{Further Interoperability of Fortran with C}
3172 To pass a variable by value, use the @code{VALUE} attribute.
3173 Thus, the following C prototype
3175 @smallexample
3176 @code{int func(int i, int *j)}
3177 @end smallexample
3179 matches the Fortran declaration
3181 @smallexample
3182   integer(c_int) function func(i,j)
3183     use iso_c_binding, only: c_int
3184     integer(c_int), VALUE :: i
3185     integer(c_int) :: j
3186 @end smallexample
3188 Note that pointer arguments also frequently need the @code{VALUE} attribute,
3189 see @ref{Working with Pointers}.
3191 Strings are handled quite differently in C and Fortran.  In C a string
3192 is a @code{NUL}-terminated array of characters while in Fortran each string
3193 has a length associated with it and is thus not terminated (by e.g.
3194 @code{NUL}).  For example, if one wants to use the following C function,
3196 @smallexample
3197   #include <stdio.h>
3198   void print_C(char *string) /* equivalent: char string[]  */
3199   @{
3200      printf("%s\n", string);
3201   @}
3202 @end smallexample
3204 to print ``Hello World'' from Fortran, one can call it using
3206 @smallexample
3207   use iso_c_binding, only: C_CHAR, C_NULL_CHAR
3208   interface
3209     subroutine print_c(string) bind(C, name="print_C")
3210       use iso_c_binding, only: c_char
3211       character(kind=c_char) :: string(*)
3212     end subroutine print_c
3213   end interface
3214   call print_c(C_CHAR_"Hello World"//C_NULL_CHAR)
3215 @end smallexample
3217 As the example shows, one needs to ensure that the
3218 string is @code{NUL} terminated.  Additionally, the dummy argument
3219 @var{string} of @code{print_C} is a length-one assumed-size
3220 array; using @code{character(len=*)} is not allowed.  The example
3221 above uses @code{c_char_"Hello World"} to ensure the string
3222 literal has the right type; typically the default character
3223 kind and @code{c_char} are the same and thus @code{"Hello World"}
3224 is equivalent.  However, the standard does not guarantee this.
3226 The use of strings is now further illustrated using the C library
3227 function @code{strncpy}, whose prototype is
3229 @smallexample
3230   char *strncpy(char *restrict s1, const char *restrict s2, size_t n);
3231 @end smallexample
3233 The function @code{strncpy} copies at most @var{n} characters from
3234 string @var{s2} to @var{s1} and returns @var{s1}.  In the following
3235 example, we ignore the return value:
3237 @smallexample
3238   use iso_c_binding
3239   implicit none
3240   character(len=30) :: str,str2
3241   interface
3242     ! Ignore the return value of strncpy -> subroutine
3243     ! "restrict" is always assumed if we do not pass a pointer
3244     subroutine strncpy(dest, src, n) bind(C)
3245       import
3246       character(kind=c_char),  intent(out) :: dest(*)
3247       character(kind=c_char),  intent(in)  :: src(*)
3248       integer(c_size_t), value, intent(in) :: n
3249     end subroutine strncpy
3250   end interface
3251   str = repeat('X',30) ! Initialize whole string with 'X'
3252   call strncpy(str, c_char_"Hello World"//C_NULL_CHAR, &
3253                len(c_char_"Hello World",kind=c_size_t))
3254   print '(a)', str ! prints: "Hello WorldXXXXXXXXXXXXXXXXXXX"
3255   end
3256 @end smallexample
3258 The intrinsic procedures are described in @ref{Intrinsic Procedures}.
3260 @node Working with Pointers
3261 @subsection Working with Pointers
3263 C pointers are represented in Fortran via the special opaque derived type
3264 @code{type(c_ptr)} (with private components).  Thus one needs to
3265 use intrinsic conversion procedures to convert from or to C pointers.
3267 For some applications, using an assumed type (@code{TYPE(*)}) can be an
3268 alternative to a C pointer; see
3269 @ref{Further Interoperability of Fortran with C}.
3271 For example,
3273 @smallexample
3274   use iso_c_binding
3275   type(c_ptr) :: cptr1, cptr2
3276   integer, target :: array(7), scalar
3277   integer, pointer :: pa(:), ps
3278   cptr1 = c_loc(array(1)) ! The programmer needs to ensure that the
3279                           ! array is contiguous if required by the C
3280                           ! procedure
3281   cptr2 = c_loc(scalar)
3282   call c_f_pointer(cptr2, ps)
3283   call c_f_pointer(cptr2, pa, shape=[7])
3284 @end smallexample
3286 When converting C to Fortran arrays, the one-dimensional @code{SHAPE} argument
3287 has to be passed.
3289 If a pointer is a dummy-argument of an interoperable procedure, it usually
3290 has to be declared using the @code{VALUE} attribute.  @code{void*}
3291 matches @code{TYPE(C_PTR), VALUE}, while @code{TYPE(C_PTR)} alone
3292 matches @code{void**}.
3294 Procedure pointers are handled analogously to pointers; the C type is
3295 @code{TYPE(C_FUNPTR)} and the intrinsic conversion procedures are
3296 @code{C_F_PROCPOINTER} and @code{C_FUNLOC}.
3298 Let us consider two examples of actually passing a procedure pointer from
3299 C to Fortran and vice versa.  Note that these examples are also very
3300 similar to passing ordinary pointers between both languages. First,
3301 consider this code in C:
3303 @smallexample
3304 /* Procedure implemented in Fortran.  */
3305 void get_values (void (*)(double));
3307 /* Call-back routine we want called from Fortran.  */
3308 void
3309 print_it (double x)
3311   printf ("Number is %f.\n", x);
3314 /* Call Fortran routine and pass call-back to it.  */
3315 void
3316 foobar ()
3318   get_values (&print_it);
3320 @end smallexample
3322 A matching implementation for @code{get_values} in Fortran, that correctly
3323 receives the procedure pointer from C and is able to call it, is given
3324 in the following @code{MODULE}:
3326 @smallexample
3327 MODULE m
3328   IMPLICIT NONE
3330   ! Define interface of call-back routine.
3331   ABSTRACT INTERFACE
3332     SUBROUTINE callback (x)
3333       USE, INTRINSIC :: ISO_C_BINDING
3334       REAL(KIND=C_DOUBLE), INTENT(IN), VALUE :: x
3335     END SUBROUTINE callback
3336   END INTERFACE
3338 CONTAINS
3340   ! Define C-bound procedure.
3341   SUBROUTINE get_values (cproc) BIND(C)
3342     USE, INTRINSIC :: ISO_C_BINDING
3343     TYPE(C_FUNPTR), INTENT(IN), VALUE :: cproc
3345     PROCEDURE(callback), POINTER :: proc
3347     ! Convert C to Fortran procedure pointer.
3348     CALL C_F_PROCPOINTER (cproc, proc)
3350     ! Call it.
3351     CALL proc (1.0_C_DOUBLE)
3352     CALL proc (-42.0_C_DOUBLE)
3353     CALL proc (18.12_C_DOUBLE)
3354   END SUBROUTINE get_values
3356 END MODULE m
3357 @end smallexample
3359 Next, we want to call a C routine that expects a procedure pointer argument
3360 and pass it a Fortran procedure (which clearly must be interoperable!).
3361 Again, the C function may be:
3363 @smallexample
3365 call_it (int (*func)(int), int arg)
3367   return func (arg);
3369 @end smallexample
3371 It can be used as in the following Fortran code:
3373 @smallexample
3374 MODULE m
3375   USE, INTRINSIC :: ISO_C_BINDING
3376   IMPLICIT NONE
3378   ! Define interface of C function.
3379   INTERFACE
3380     INTEGER(KIND=C_INT) FUNCTION call_it (func, arg) BIND(C)
3381       USE, INTRINSIC :: ISO_C_BINDING
3382       TYPE(C_FUNPTR), INTENT(IN), VALUE :: func
3383       INTEGER(KIND=C_INT), INTENT(IN), VALUE :: arg
3384     END FUNCTION call_it
3385   END INTERFACE
3387 CONTAINS
3389   ! Define procedure passed to C function.
3390   ! It must be interoperable!
3391   INTEGER(KIND=C_INT) FUNCTION double_it (arg) BIND(C)
3392     INTEGER(KIND=C_INT), INTENT(IN), VALUE :: arg
3393     double_it = arg + arg
3394   END FUNCTION double_it
3396   ! Call C function.
3397   SUBROUTINE foobar ()
3398     TYPE(C_FUNPTR) :: cproc
3399     INTEGER(KIND=C_INT) :: i
3401     ! Get C procedure pointer.
3402     cproc = C_FUNLOC (double_it)
3404     ! Use it.
3405     DO i = 1_C_INT, 10_C_INT
3406       PRINT *, call_it (cproc, i)
3407     END DO
3408   END SUBROUTINE foobar
3410 END MODULE m
3411 @end smallexample
3413 @node Further Interoperability of Fortran with C
3414 @subsection Further Interoperability of Fortran with C
3416 The Technical Specification ISO/IEC TS 29113:2012 on further
3417 interoperability of Fortran with C extends the interoperability support
3418 of Fortran 2003 and Fortran 2008. Besides removing some restrictions
3419 and constraints, it adds assumed-type (@code{TYPE(*)}) and assumed-rank
3420 (@code{dimension}) variables and allows for interoperability of
3421 assumed-shape, assumed-rank and deferred-shape arrays, including
3422 allocatables and pointers.
3424 Note: Currently, GNU Fortran does not support the array descriptor
3425 (dope vector) as specified in the Technical Specification, but uses
3426 an array descriptor with different fields. The Chasm Language
3427 Interoperability Tools, @url{http://chasm-interop.sourceforge.net/},
3428 provide an interface to GNU Fortran's array descriptor.
3430 The Technical Specification adds the following new features, which
3431 are supported by GNU Fortran:
3433 @itemize @bullet
3435 @item The @code{ASYNCHRONOUS} attribute has been clarified and
3436 extended to allow its use with asynchronous communication in
3437 user-provided libraries such as in implementations of the
3438 Message Passing Interface specification.
3440 @item Many constraints have been relaxed, in particular for
3441 the @code{C_LOC} and @code{C_F_POINTER} intrinsics.
3443 @item The @code{OPTIONAL} attribute is now allowed for dummy
3444 arguments; an absent argument matches a @code{NULL} pointer.
3446 @item Assumed types (@code{TYPE(*)}) have been added, which may
3447 only be used for dummy arguments.  They are unlimited polymorphic
3448 but contrary to @code{CLASS(*)} they do not contain any type
3449 information, similar to C's @code{void *} pointers.  Expressions
3450 of any type and kind can be passed; thus, it can be used as
3451 replacement for @code{TYPE(C_PTR)}, avoiding the use of
3452 @code{C_LOC} in the caller.
3454 Note, however, that @code{TYPE(*)} only accepts scalar arguments,
3455 unless the @code{DIMENSION} is explicitly specified.  As
3456 @code{DIMENSION(*)} only supports array (including array elements) but
3457 no scalars, it is not a full replacement for @code{C_LOC}.  On the
3458 other hand, assumed-type assumed-rank dummy arguments
3459 (@code{TYPE(*), DIMENSION(..)}) allow for both scalars and arrays, but
3460 require special code on the callee side to handle the array descriptor.
3462 @item Assumed-rank arrays (@code{DIMENSION(..)}) as dummy argument
3463 allow that scalars and arrays of any rank can be passed as actual
3464 argument. As the Technical Specification does not provide for direct
3465 means to operate with them, they have to be used either from the C side
3466 or be converted using @code{C_LOC} and @code{C_F_POINTER} to scalars
3467 or arrays of a specific rank. The rank can be determined using the
3468 @code{RANK} intrinisic.
3469 @end itemize
3472 Currently unimplemented:
3474 @itemize @bullet
3476 @item GNU Fortran always uses an array descriptor, which does not
3477 match the one of the Technical Specification. The
3478 @code{ISO_Fortran_binding.h} header file and the C functions it
3479 specifies are not available.
3481 @item Using assumed-shape, assumed-rank and deferred-shape arrays in
3482 @code{BIND(C)} procedures is not fully supported. In particular,
3483 C interoperable strings of other length than one are not supported
3484 as this requires the new array descriptor.
3485 @end itemize
3488 @node GNU Fortran Compiler Directives
3489 @section GNU Fortran Compiler Directives
3491 @menu
3492 * ATTRIBUTES directive::
3493 * UNROLL directive::
3494 @end menu
3496 @node ATTRIBUTES directive
3497 @subsection ATTRIBUTES directive
3499 The Fortran standard describes how a conforming program shall
3500 behave; however, the exact implementation is not standardized.  In order
3501 to allow the user to choose specific implementation details, compiler
3502 directives can be used to set attributes of variables and procedures
3503 which are not part of the standard.  Whether a given attribute is
3504 supported and its exact effects depend on both the operating system and
3505 on the processor; see
3506 @ref{Top,,C Extensions,gcc,Using the GNU Compiler Collection (GCC)}
3507 for details.
3509 For procedures and procedure pointers, the following attributes can
3510 be used to change the calling convention:
3512 @itemize
3513 @item @code{CDECL} -- standard C calling convention
3514 @item @code{STDCALL} -- convention where the called procedure pops the stack
3515 @item @code{FASTCALL} -- part of the arguments are passed via registers
3516 instead using the stack
3517 @end itemize
3519 Besides changing the calling convention, the attributes also influence
3520 the decoration of the symbol name, e.g., by a leading underscore or by
3521 a trailing at-sign followed by the number of bytes on the stack.  When
3522 assigning a procedure to a procedure pointer, both should use the same
3523 calling convention.
3525 On some systems, procedures and global variables (module variables and
3526 @code{COMMON} blocks) need special handling to be accessible when they
3527 are in a shared library.  The following attributes are available:
3529 @itemize
3530 @item @code{DLLEXPORT} -- provide a global pointer to a pointer in the DLL
3531 @item @code{DLLIMPORT} -- reference the function or variable using a
3532 global pointer
3533 @end itemize
3535 For dummy arguments, the @code{NO_ARG_CHECK} attribute can be used; in
3536 other compilers, it is also known as @code{IGNORE_TKR}.  For dummy arguments
3537 with this attribute actual arguments of any type and kind (similar to
3538 @code{TYPE(*)}), scalars and arrays of any rank (no equivalent
3539 in Fortran standard) are accepted.  As with @code{TYPE(*)}, the argument
3540 is unlimited polymorphic and no type information is available.
3541 Additionally, the argument may only be passed to dummy arguments
3542 with the @code{NO_ARG_CHECK} attribute and as argument to the
3543 @code{PRESENT} intrinsic function and to @code{C_LOC} of the
3544 @code{ISO_C_BINDING} module.
3546 Variables with @code{NO_ARG_CHECK} attribute shall be of assumed-type
3547 (@code{TYPE(*)}; recommended) or of type @code{INTEGER}, @code{LOGICAL},
3548 @code{REAL} or @code{COMPLEX}. They shall not have the @code{ALLOCATE},
3549 @code{CODIMENSION}, @code{INTENT(OUT)}, @code{POINTER} or @code{VALUE}
3550 attribute; furthermore, they shall be either scalar or of assumed-size
3551 (@code{dimension(*)}). As @code{TYPE(*)}, the @code{NO_ARG_CHECK} attribute
3552 requires an explicit interface.
3554 @itemize
3555 @item @code{NO_ARG_CHECK} -- disable the type, kind and rank checking
3556 @end itemize
3559 The attributes are specified using the syntax
3561 @code{!GCC$ ATTRIBUTES} @var{attribute-list} @code{::} @var{variable-list}
3563 where in free-form source code only whitespace is allowed before @code{!GCC$}
3564 and in fixed-form source code @code{!GCC$}, @code{cGCC$} or @code{*GCC$} shall
3565 start in the first column.
3567 For procedures, the compiler directives shall be placed into the body
3568 of the procedure; for variables and procedure pointers, they shall be in
3569 the same declaration part as the variable or procedure pointer.
3572 @node UNROLL directive
3573 @subsection UNROLL directive
3575 The syntax of the directive is
3577 @code{!GCC$ unroll N}
3579 You can use this directive to control how many times a loop should be unrolled.
3580 It must be placed immediately before a @code{DO} loop and applies only to the
3581 loop that follows.  N is an integer constant specifying the unrolling factor.
3582 The values of 0 and 1 block any unrolling of the loop.
3586 @node Non-Fortran Main Program
3587 @section Non-Fortran Main Program
3589 @menu
3590 * _gfortran_set_args:: Save command-line arguments
3591 * _gfortran_set_options:: Set library option flags
3592 * _gfortran_set_convert:: Set endian conversion
3593 * _gfortran_set_record_marker:: Set length of record markers
3594 * _gfortran_set_fpe:: Set when a Floating Point Exception should be raised
3595 * _gfortran_set_max_subrecord_length:: Set subrecord length
3596 @end menu
3598 Even if you are doing mixed-language programming, it is very
3599 likely that you do not need to know or use the information in this
3600 section.  Since it is about the internal structure of GNU Fortran,
3601 it may also change in GCC minor releases.
3603 When you compile a @code{PROGRAM} with GNU Fortran, a function
3604 with the name @code{main} (in the symbol table of the object file)
3605 is generated, which initializes the libgfortran library and then
3606 calls the actual program which uses the name @code{MAIN__}, for
3607 historic reasons.  If you link GNU Fortran compiled procedures
3608 to, e.g., a C or C++ program or to a Fortran program compiled by
3609 a different compiler, the libgfortran library is not initialized
3610 and thus a few intrinsic procedures do not work properly, e.g.
3611 those for obtaining the command-line arguments.
3613 Therefore, if your @code{PROGRAM} is not compiled with
3614 GNU Fortran and the GNU Fortran compiled procedures require
3615 intrinsics relying on the library initialization, you need to
3616 initialize the library yourself.  Using the default options,
3617 gfortran calls @code{_gfortran_set_args} and
3618 @code{_gfortran_set_options}.  The initialization of the former
3619 is needed if the called procedures access the command line
3620 (and for backtracing); the latter sets some flags based on the
3621 standard chosen or to enable backtracing.  In typical programs,
3622 it is not necessary to call any initialization function.
3624 If your @code{PROGRAM} is compiled with GNU Fortran, you shall
3625 not call any of the following functions.  The libgfortran
3626 initialization functions are shown in C syntax but using C
3627 bindings they are also accessible from Fortran.
3630 @node _gfortran_set_args
3631 @subsection @code{_gfortran_set_args} --- Save command-line arguments
3632 @fnindex _gfortran_set_args
3633 @cindex libgfortran initialization, set_args
3635 @table @asis
3636 @item @emph{Description}:
3637 @code{_gfortran_set_args} saves the command-line arguments; this
3638 initialization is required if any of the command-line intrinsics
3639 is called.  Additionally, it shall be called if backtracing is
3640 enabled (see @code{_gfortran_set_options}).
3642 @item @emph{Syntax}:
3643 @code{void _gfortran_set_args (int argc, char *argv[])}
3645 @item @emph{Arguments}:
3646 @multitable @columnfractions .15 .70
3647 @item @var{argc} @tab number of command line argument strings
3648 @item @var{argv} @tab the command-line argument strings; argv[0]
3649 is the pathname of the executable itself.
3650 @end multitable
3652 @item @emph{Example}:
3653 @smallexample
3654 int main (int argc, char *argv[])
3656   /* Initialize libgfortran.  */
3657   _gfortran_set_args (argc, argv);
3658   return 0;
3660 @end smallexample
3661 @end table
3664 @node _gfortran_set_options
3665 @subsection @code{_gfortran_set_options} --- Set library option flags
3666 @fnindex _gfortran_set_options
3667 @cindex libgfortran initialization, set_options
3669 @table @asis
3670 @item @emph{Description}:
3671 @code{_gfortran_set_options} sets several flags related to the Fortran
3672 standard to be used, whether backtracing should be enabled
3673 and whether range checks should be performed.  The syntax allows for
3674 upward compatibility since the number of passed flags is specified; for
3675 non-passed flags, the default value is used.  See also
3676 @pxref{Code Gen Options}.  Please note that not all flags are actually
3677 used.
3679 @item @emph{Syntax}:
3680 @code{void _gfortran_set_options (int num, int options[])}
3682 @item @emph{Arguments}:
3683 @multitable @columnfractions .15 .70
3684 @item @var{num} @tab number of options passed
3685 @item @var{argv} @tab The list of flag values
3686 @end multitable
3688 @item @emph{option flag list}:
3689 @multitable @columnfractions .15 .70
3690 @item @var{option}[0] @tab Allowed standard; can give run-time errors
3691 if e.g. an input-output edit descriptor is invalid in a given
3692 standard.  Possible values are (bitwise or-ed) @code{GFC_STD_F77} (1),
3693 @code{GFC_STD_F95_OBS} (2), @code{GFC_STD_F95_DEL} (4),
3694 @code{GFC_STD_F95} (8), @code{GFC_STD_F2003} (16), @code{GFC_STD_GNU}
3695 (32), @code{GFC_STD_LEGACY} (64), @code{GFC_STD_F2008} (128),
3696 @code{GFC_STD_F2008_OBS} (256), @code{GFC_STD_F2008_TS} (512),
3697 @code{GFC_STD_F2018} (1024), @code{GFC_STD_F2018_OBS} (2048), and
3698 @code{GFC_STD=F2018_DEL} (4096). Default: @code{GFC_STD_F95_OBS |
3699 GFC_STD_F95_DEL | GFC_STD_F95 | GFC_STD_F2003 | GFC_STD_F2008 |
3700 GFC_STD_F2008_TS | GFC_STD_F2008_OBS | GFC_STD_F77 | GFC_STD_F2018 |
3701 GFC_STD_F2018_OBS | GFC_STD_F2018_DEL | GFC_STD_GNU | GFC_STD_LEGACY}.
3702 @item @var{option}[1] @tab Standard-warning flag; prints a warning to
3703 standard error.  Default: @code{GFC_STD_F95_DEL | GFC_STD_LEGACY}.
3704 @item @var{option}[2] @tab If non zero, enable pedantic checking.
3705 Default: off.
3706 @item @var{option}[3] @tab Unused.
3707 @item @var{option}[4] @tab If non zero, enable backtracing on run-time
3708 errors.  Default: off. (Default in the compiler: on.)
3709 Note: Installs a signal handler and requires command-line
3710 initialization using @code{_gfortran_set_args}.
3711 @item @var{option}[5] @tab If non zero, supports signed zeros.
3712 Default: enabled.
3713 @item @var{option}[6] @tab Enables run-time checking.  Possible values
3714 are (bitwise or-ed): GFC_RTCHECK_BOUNDS (1), GFC_RTCHECK_ARRAY_TEMPS (2),
3715 GFC_RTCHECK_RECURSION (4), GFC_RTCHECK_DO (16), GFC_RTCHECK_POINTER (32).
3716 Default: disabled.
3717 @item @var{option}[7] @tab Unused.
3718 @item @var{option}[8] @tab Show a warning when invoking @code{STOP} and
3719 @code{ERROR STOP} if a floating-point exception occurred. Possible values
3720 are (bitwise or-ed) @code{GFC_FPE_INVALID} (1), @code{GFC_FPE_DENORMAL} (2),
3721 @code{GFC_FPE_ZERO} (4), @code{GFC_FPE_OVERFLOW} (8),
3722 @code{GFC_FPE_UNDERFLOW} (16), @code{GFC_FPE_INEXACT} (32). Default: None (0).
3723 (Default in the compiler: @code{GFC_FPE_INVALID | GFC_FPE_DENORMAL |
3724 GFC_FPE_ZERO | GFC_FPE_OVERFLOW | GFC_FPE_UNDERFLOW}.)
3725 @end multitable
3727 @item @emph{Example}:
3728 @smallexample
3729   /* Use gfortran 4.9 default options.  */
3730   static int options[] = @{68, 511, 0, 0, 1, 1, 0, 0, 31@};
3731   _gfortran_set_options (9, &options);
3732 @end smallexample
3733 @end table
3736 @node _gfortran_set_convert
3737 @subsection @code{_gfortran_set_convert} --- Set endian conversion
3738 @fnindex _gfortran_set_convert
3739 @cindex libgfortran initialization, set_convert
3741 @table @asis
3742 @item @emph{Description}:
3743 @code{_gfortran_set_convert} set the representation of data for
3744 unformatted files.
3746 @item @emph{Syntax}:
3747 @code{void _gfortran_set_convert (int conv)}
3749 @item @emph{Arguments}:
3750 @multitable @columnfractions .15 .70
3751 @item @var{conv} @tab Endian conversion, possible values:
3752 GFC_CONVERT_NATIVE (0, default), GFC_CONVERT_SWAP (1),
3753 GFC_CONVERT_BIG (2), GFC_CONVERT_LITTLE (3).
3754 @end multitable
3756 @item @emph{Example}:
3757 @smallexample
3758 int main (int argc, char *argv[])
3760   /* Initialize libgfortran.  */
3761   _gfortran_set_args (argc, argv);
3762   _gfortran_set_convert (1);
3763   return 0;
3765 @end smallexample
3766 @end table
3769 @node _gfortran_set_record_marker
3770 @subsection @code{_gfortran_set_record_marker} --- Set length of record markers
3771 @fnindex _gfortran_set_record_marker
3772 @cindex libgfortran initialization, set_record_marker
3774 @table @asis
3775 @item @emph{Description}:
3776 @code{_gfortran_set_record_marker} sets the length of record markers
3777 for unformatted files.
3779 @item @emph{Syntax}:
3780 @code{void _gfortran_set_record_marker (int val)}
3782 @item @emph{Arguments}:
3783 @multitable @columnfractions .15 .70
3784 @item @var{val} @tab Length of the record marker; valid values
3785 are 4 and 8.  Default is 4.
3786 @end multitable
3788 @item @emph{Example}:
3789 @smallexample
3790 int main (int argc, char *argv[])
3792   /* Initialize libgfortran.  */
3793   _gfortran_set_args (argc, argv);
3794   _gfortran_set_record_marker (8);
3795   return 0;
3797 @end smallexample
3798 @end table
3801 @node _gfortran_set_fpe
3802 @subsection @code{_gfortran_set_fpe} --- Enable floating point exception traps
3803 @fnindex _gfortran_set_fpe
3804 @cindex libgfortran initialization, set_fpe
3806 @table @asis
3807 @item @emph{Description}:
3808 @code{_gfortran_set_fpe} enables floating point exception traps for
3809 the specified exceptions.  On most systems, this will result in a
3810 SIGFPE signal being sent and the program being aborted.
3812 @item @emph{Syntax}:
3813 @code{void _gfortran_set_fpe (int val)}
3815 @item @emph{Arguments}:
3816 @multitable @columnfractions .15 .70
3817 @item @var{option}[0] @tab IEEE exceptions.  Possible values are
3818 (bitwise or-ed) zero (0, default) no trapping,
3819 @code{GFC_FPE_INVALID} (1), @code{GFC_FPE_DENORMAL} (2),
3820 @code{GFC_FPE_ZERO} (4), @code{GFC_FPE_OVERFLOW} (8),
3821 @code{GFC_FPE_UNDERFLOW} (16), and @code{GFC_FPE_INEXACT} (32).
3822 @end multitable
3824 @item @emph{Example}:
3825 @smallexample
3826 int main (int argc, char *argv[])
3828   /* Initialize libgfortran.  */
3829   _gfortran_set_args (argc, argv);
3830   /* FPE for invalid operations such as SQRT(-1.0).  */
3831   _gfortran_set_fpe (1);
3832   return 0;
3834 @end smallexample
3835 @end table
3838 @node _gfortran_set_max_subrecord_length
3839 @subsection @code{_gfortran_set_max_subrecord_length} --- Set subrecord length
3840 @fnindex _gfortran_set_max_subrecord_length
3841 @cindex libgfortran initialization, set_max_subrecord_length
3843 @table @asis
3844 @item @emph{Description}:
3845 @code{_gfortran_set_max_subrecord_length} set the maximum length
3846 for a subrecord.  This option only makes sense for testing and
3847 debugging of unformatted I/O.
3849 @item @emph{Syntax}:
3850 @code{void _gfortran_set_max_subrecord_length (int val)}
3852 @item @emph{Arguments}:
3853 @multitable @columnfractions .15 .70
3854 @item @var{val} @tab the maximum length for a subrecord;
3855 the maximum permitted value is 2147483639, which is also
3856 the default.
3857 @end multitable
3859 @item @emph{Example}:
3860 @smallexample
3861 int main (int argc, char *argv[])
3863   /* Initialize libgfortran.  */
3864   _gfortran_set_args (argc, argv);
3865   _gfortran_set_max_subrecord_length (8);
3866   return 0;
3868 @end smallexample
3869 @end table
3872 @node Naming and argument-passing conventions
3873 @section Naming and argument-passing conventions
3875 This section gives an overview about the naming convention of procedures
3876 and global variables and about the argument passing conventions used by
3877 GNU Fortran.  If a C binding has been specified, the naming convention
3878 and some of the argument-passing conventions change.  If possible,
3879 mixed-language and mixed-compiler projects should use the better defined
3880 C binding for interoperability.  See @pxref{Interoperability with C}.
3882 @menu
3883 * Naming conventions::
3884 * Argument passing conventions::
3885 @end menu
3888 @node Naming conventions
3889 @subsection Naming conventions
3891 According the Fortran standard, valid Fortran names consist of a letter
3892 between @code{A} to @code{Z}, @code{a} to @code{z}, digits @code{0},
3893 @code{1} to @code{9} and underscores (@code{_}) with the restriction
3894 that names may only start with a letter.  As vendor extension, the
3895 dollar sign (@code{$}) is additionally permitted with the option
3896 @option{-fdollar-ok}, but not as first character and only if the
3897 target system supports it.
3899 By default, the procedure name is the lower-cased Fortran name with an
3900 appended underscore (@code{_}); using @option{-fno-underscoring} no
3901 underscore is appended while @code{-fsecond-underscore} appends two
3902 underscores.  Depending on the target system and the calling convention,
3903 the procedure might be additionally dressed; for instance, on 32bit
3904 Windows with @code{stdcall}, an at-sign @code{@@} followed by an integer
3905 number is appended.  For the changing the calling convention, see
3906 @pxref{GNU Fortran Compiler Directives}.
3908 For common blocks, the same convention is used, i.e. by default an
3909 underscore is appended to the lower-cased Fortran name.  Blank commons
3910 have the name @code{__BLNK__}.
3912 For procedures and variables declared in the specification space of a
3913 module, the name is formed by @code{__}, followed by the lower-cased
3914 module name, @code{_MOD_}, and the lower-cased Fortran name.  Note that
3915 no underscore is appended.
3918 @node Argument passing conventions
3919 @subsection Argument passing conventions
3921 Subroutines do not return a value (matching C99's @code{void}) while
3922 functions either return a value as specified in the platform ABI or
3923 the result variable is passed as hidden argument to the function and
3924 no result is returned.  A hidden result variable is used when the
3925 result variable is an array or of type @code{CHARACTER}.
3927 Arguments are passed according to the platform ABI. In particular,
3928 complex arguments might not be compatible to a struct with two real
3929 components for the real and imaginary part. The argument passing
3930 matches the one of C99's @code{_Complex}.  Functions with scalar
3931 complex result variables return their value and do not use a
3932 by-reference argument.  Note that with the @option{-ff2c} option,
3933 the argument passing is modified and no longer completely matches
3934 the platform ABI.  Some other Fortran compilers use @code{f2c}
3935 semantic by default; this might cause problems with
3936 interoperablility.
3938 GNU Fortran passes most arguments by reference, i.e. by passing a
3939 pointer to the data.  Note that the compiler might use a temporary
3940 variable into which the actual argument has been copied, if required
3941 semantically (copy-in/copy-out).
3943 For arguments with @code{ALLOCATABLE} and @code{POINTER}
3944 attribute (including procedure pointers), a pointer to the pointer
3945 is passed such that the pointer address can be modified in the
3946 procedure.
3948 For dummy arguments with the @code{VALUE} attribute: Scalar arguments
3949 of the type @code{INTEGER}, @code{LOGICAL}, @code{REAL} and
3950 @code{COMPLEX} are passed by value according to the platform ABI.
3951 (As vendor extension and not recommended, using @code{%VAL()} in the
3952 call to a procedure has the same effect.) For @code{TYPE(C_PTR)} and
3953 procedure pointers, the pointer itself is passed such that it can be
3954 modified without affecting the caller.
3955 @c FIXME: Document how VALUE is handled for CHARACTER, TYPE,
3956 @c CLASS and arrays, i.e. whether the copy-in is done in the caller
3957 @c or in the callee.
3959 For Boolean (@code{LOGICAL}) arguments, please note that GCC expects
3960 only the integer value 0 and 1.  If a GNU Fortran @code{LOGICAL}
3961 variable contains another integer value, the result is undefined.
3962 As some other Fortran compilers use @math{-1} for @code{.TRUE.},
3963 extra care has to be taken -- such as passing the value as
3964 @code{INTEGER}.  (The same value restriction also applies to other
3965 front ends of GCC, e.g. to GCC's C99 compiler for @code{_Bool}
3966 or GCC's Ada compiler for @code{Boolean}.)
3968 For arguments of @code{CHARACTER} type, the character length is passed
3969 as a hidden argument at the end of the argument list.  For
3970 deferred-length strings, the value is passed by reference, otherwise
3971 by value.  The character length has the C type @code{size_t} (or
3972 @code{INTEGER(kind=C_SIZE_T)} in Fortran).  Note that this is
3973 different to older versions of the GNU Fortran compiler, where the
3974 type of the hidden character length argument was a C @code{int}.  In
3975 order to retain compatibility with older versions, one can e.g. for
3976 the following Fortran procedure
3978 @smallexample
3979 subroutine fstrlen (s, a)
3980    character(len=*) :: s
3981    integer :: a
3982    print*, len(s)
3983 end subroutine fstrlen
3984 @end smallexample
3986 define the corresponding C prototype as follows:
3988 @smallexample
3989 #if __GNUC__ > 7
3990 typedef size_t fortran_charlen_t;
3991 #else
3992 typedef int fortran_charlen_t;
3993 #endif
3995 void fstrlen_ (char*, int*, fortran_charlen_t);
3996 @end smallexample
3998 In order to avoid such compiler-specific details, for new code it is
3999 instead recommended to use the ISO_C_BINDING feature.
4001 Note with C binding, @code{CHARACTER(len=1)} result variables are
4002 returned according to the platform ABI and no hidden length argument
4003 is used for dummy arguments; with @code{VALUE}, those variables are
4004 passed by value.
4006 For @code{OPTIONAL} dummy arguments, an absent argument is denoted
4007 by a NULL pointer, except for scalar dummy arguments of type
4008 @code{INTEGER}, @code{LOGICAL}, @code{REAL} and @code{COMPLEX}
4009 which have the @code{VALUE} attribute.  For those, a hidden Boolean
4010 argument (@code{logical(kind=C_bool),value}) is used to indicate
4011 whether the argument is present.
4013 Arguments which are assumed-shape, assumed-rank or deferred-rank
4014 arrays or, with @option{-fcoarray=lib}, allocatable scalar coarrays use
4015 an array descriptor.  All other arrays pass the address of the
4016 first element of the array.  With @option{-fcoarray=lib}, the token
4017 and the offset belonging to nonallocatable coarrays dummy arguments
4018 are passed as hidden argument along the character length hidden
4019 arguments.  The token is an oparque pointer identifying the coarray
4020 and the offset is a passed-by-value integer of kind @code{C_PTRDIFF_T},
4021 denoting the byte offset between the base address of the coarray and
4022 the passed scalar or first element of the passed array.
4024 The arguments are passed in the following order
4025 @itemize @bullet
4026 @item Result variable, when the function result is passed by reference
4027 @item Character length of the function result, if it is a of type
4028 @code{CHARACTER} and no C binding is used
4029 @item The arguments in the order in which they appear in the Fortran
4030 declaration
4031 @item The the present status for optional arguments with value attribute,
4032 which are internally passed by value
4033 @item The character length and/or coarray token and offset for the first
4034 argument which is a @code{CHARACTER} or a nonallocatable coarray dummy
4035 argument, followed by the hidden arguments of the next dummy argument
4036 of such a type
4037 @end itemize
4040 @c ---------------------------------------------------------------------
4041 @c Coarray Programming
4042 @c ---------------------------------------------------------------------
4044 @node Coarray Programming
4045 @chapter Coarray Programming
4046 @cindex Coarrays
4048 @menu
4049 * Type and enum ABI Documentation::
4050 * Function ABI Documentation::
4051 @end menu
4054 @node Type and enum ABI Documentation
4055 @section Type and enum ABI Documentation
4057 @menu
4058 * caf_token_t::
4059 * caf_register_t::
4060 * caf_deregister_t::
4061 * caf_reference_t::
4062 * caf_team_t::
4063 @end menu
4065 @node caf_token_t
4066 @subsection @code{caf_token_t}
4068 Typedef of type @code{void *} on the compiler side. Can be any data
4069 type on the library side.
4071 @node caf_register_t
4072 @subsection @code{caf_register_t}
4074 Indicates which kind of coarray variable should be registered.
4076 @verbatim
4077 typedef enum caf_register_t {
4078   CAF_REGTYPE_COARRAY_STATIC,
4079   CAF_REGTYPE_COARRAY_ALLOC,
4080   CAF_REGTYPE_LOCK_STATIC,
4081   CAF_REGTYPE_LOCK_ALLOC,
4082   CAF_REGTYPE_CRITICAL,
4083   CAF_REGTYPE_EVENT_STATIC,
4084   CAF_REGTYPE_EVENT_ALLOC,
4085   CAF_REGTYPE_COARRAY_ALLOC_REGISTER_ONLY,
4086   CAF_REGTYPE_COARRAY_ALLOC_ALLOCATE_ONLY
4088 caf_register_t;
4089 @end verbatim
4091 The values @code{CAF_REGTYPE_COARRAY_ALLOC_REGISTER_ONLY} and
4092 @code{CAF_REGTYPE_COARRAY_ALLOC_ALLOCATE_ONLY} are for allocatable components
4093 in derived type coarrays only.  The first one sets up the token without
4094 allocating memory for allocatable component.  The latter one only allocates the
4095 memory for an allocatable component in a derived type coarray.  The token
4096 needs to be setup previously by the REGISTER_ONLY.  This allows to have
4097 allocatable components un-allocated on some images.  The status whether an
4098 allocatable component is allocated on a remote image can be queried by
4099 @code{_caf_is_present} which used internally by the @code{ALLOCATED}
4100 intrinsic.
4102 @node caf_deregister_t
4103 @subsection @code{caf_deregister_t}
4105 @verbatim
4106 typedef enum caf_deregister_t {
4107   CAF_DEREGTYPE_COARRAY_DEREGISTER,
4108   CAF_DEREGTYPE_COARRAY_DEALLOCATE_ONLY
4110 caf_deregister_t;
4111 @end verbatim
4113 Allows to specifiy the type of deregistration of a coarray object.  The
4114 @code{CAF_DEREGTYPE_COARRAY_DEALLOCATE_ONLY} flag is only allowed for
4115 allocatable components in derived type coarrays.
4117 @node caf_reference_t
4118 @subsection @code{caf_reference_t}
4120 The structure used for implementing arbitrary reference chains.
4121 A @code{CAF_REFERENCE_T} allows to specify a component reference or any kind
4122 of array reference of any rank supported by gfortran.  For array references all
4123 kinds as known by the compiler/Fortran standard are supported indicated by
4124 a @code{MODE}.
4126 @verbatim
4127 typedef enum caf_ref_type_t {
4128   /* Reference a component of a derived type, either regular one or an
4129      allocatable or pointer type.  For regular ones idx in caf_reference_t is
4130      set to -1.  */
4131   CAF_REF_COMPONENT,
4132   /* Reference an allocatable array.  */
4133   CAF_REF_ARRAY,
4134   /* Reference a non-allocatable/non-pointer array.  I.e., the coarray object
4135      has no array descriptor associated and the addressing is done
4136      completely using the ref.  */
4137   CAF_REF_STATIC_ARRAY
4138 } caf_ref_type_t;
4139 @end verbatim
4141 @verbatim
4142 typedef enum caf_array_ref_t {
4143   /* No array ref.  This terminates the array ref.  */
4144   CAF_ARR_REF_NONE = 0,
4145   /* Reference array elements given by a vector.  Only for this mode
4146      caf_reference_t.u.a.dim[i].v is valid.  */
4147   CAF_ARR_REF_VECTOR,
4148   /* A full array ref (:).  */
4149   CAF_ARR_REF_FULL,
4150   /* Reference a range on elements given by start, end and stride.  */
4151   CAF_ARR_REF_RANGE,
4152   /* Only a single item is referenced given in the start member.  */
4153   CAF_ARR_REF_SINGLE,
4154   /* An array ref of the kind (i:), where i is an arbitrary valid index in the
4155      array.  The index i is given in the start member.  */
4156   CAF_ARR_REF_OPEN_END,
4157   /* An array ref of the kind (:i), where the lower bound of the array ref
4158      is given by the remote side.  The index i is given in the end member.  */
4159   CAF_ARR_REF_OPEN_START
4160 } caf_array_ref_t;
4161 @end verbatim
4163 @verbatim
4164 /* References to remote components of a derived type.  */
4165 typedef struct caf_reference_t {
4166   /* A pointer to the next ref or NULL.  */
4167   struct caf_reference_t *next;
4168   /* The type of the reference.  */
4169   /* caf_ref_type_t, replaced by int to allow specification in fortran FE.  */
4170   int type;
4171   /* The size of an item referenced in bytes.  I.e. in an array ref this is
4172      the factor to advance the array pointer with to get to the next item.
4173      For component refs this gives just the size of the element referenced.  */
4174   size_t item_size;
4175   union {
4176     struct {
4177       /* The offset (in bytes) of the component in the derived type.
4178          Unused for allocatable or pointer components.  */
4179       ptrdiff_t offset;
4180       /* The offset (in bytes) to the caf_token associated with this
4181          component.  NULL, when not allocatable/pointer ref.  */
4182       ptrdiff_t caf_token_offset;
4183     } c;
4184     struct {
4185       /* The mode of the array ref.  See CAF_ARR_REF_*.  */
4186       /* caf_array_ref_t, replaced by unsigend char to allow specification in
4187          fortran FE.  */
4188      unsigned char mode[GFC_MAX_DIMENSIONS];
4189       /* The type of a static array.  Unset for array's with descriptors.  */
4190       int static_array_type;
4191       /* Subscript refs (s) or vector refs (v).  */
4192       union {
4193         struct {
4194           /* The start and end boundary of the ref and the stride.  */
4195           index_type start, end, stride;
4196         } s;
4197         struct {
4198           /* nvec entries of kind giving the elements to reference.  */
4199           void *vector;
4200           /* The number of entries in vector.  */
4201           size_t nvec;
4202           /* The integer kind used for the elements in vector.  */
4203           int kind;
4204         } v;
4205       } dim[GFC_MAX_DIMENSIONS];
4206     } a;
4207   } u;
4208 } caf_reference_t;
4209 @end verbatim
4211 The references make up a single linked list of reference operations.  The
4212 @code{NEXT} member links to the next reference or NULL to indicate the end of
4213 the chain.  Component and array refs can be arbitrarly mixed as long as they
4214 comply to the Fortran standard.
4216 @emph{NOTES}
4217 The member @code{STATIC_ARRAY_TYPE} is used only when the @code{TYPE} is
4218 @code{CAF_REF_STATIC_ARRAY}.  The member gives the type of the data referenced.
4219 Because no array descriptor is available for a descriptor-less array and
4220 type conversion still needs to take place the type is transported here.
4222 At the moment @code{CAF_ARR_REF_VECTOR} is not implemented in the front end for
4223 descriptor-less arrays.  The library caf_single has untested support for it.
4225 @node caf_team_t
4226 @subsection @code{caf_team_t}
4228 Opaque pointer to represent a team-handle.  This type is a stand-in for the
4229 future implementation of teams.  It is about to change without further notice.
4231 @node Function ABI Documentation
4232 @section Function ABI Documentation
4234 @menu
4235 * _gfortran_caf_init:: Initialiation function
4236 * _gfortran_caf_finish:: Finalization function
4237 * _gfortran_caf_this_image:: Querying the image number
4238 * _gfortran_caf_num_images:: Querying the maximal number of images
4239 * _gfortran_caf_image_status :: Query the status of an image
4240 * _gfortran_caf_failed_images :: Get an array of the indexes of the failed images
4241 * _gfortran_caf_stopped_images :: Get an array of the indexes of the stopped images
4242 * _gfortran_caf_register:: Registering coarrays
4243 * _gfortran_caf_deregister:: Deregistering coarrays
4244 * _gfortran_caf_is_present:: Query whether an allocatable or pointer component in a derived type coarray is allocated
4245 * _gfortran_caf_send:: Sending data from a local image to a remote image
4246 * _gfortran_caf_get:: Getting data from a remote image
4247 * _gfortran_caf_sendget:: Sending data between remote images
4248 * _gfortran_caf_send_by_ref:: Sending data from a local image to a remote image using enhanced references
4249 * _gfortran_caf_get_by_ref:: Getting data from a remote image using enhanced references
4250 * _gfortran_caf_sendget_by_ref:: Sending data between remote images using enhanced references
4251 * _gfortran_caf_lock:: Locking a lock variable
4252 * _gfortran_caf_unlock:: Unlocking a lock variable
4253 * _gfortran_caf_event_post:: Post an event
4254 * _gfortran_caf_event_wait:: Wait that an event occurred
4255 * _gfortran_caf_event_query:: Query event count
4256 * _gfortran_caf_sync_all:: All-image barrier
4257 * _gfortran_caf_sync_images:: Barrier for selected images
4258 * _gfortran_caf_sync_memory:: Wait for completion of segment-memory operations
4259 * _gfortran_caf_error_stop:: Error termination with exit code
4260 * _gfortran_caf_error_stop_str:: Error termination with string
4261 * _gfortran_caf_fail_image :: Mark the image failed and end its execution
4262 * _gfortran_caf_atomic_define:: Atomic variable assignment
4263 * _gfortran_caf_atomic_ref:: Atomic variable reference
4264 * _gfortran_caf_atomic_cas:: Atomic compare and swap
4265 * _gfortran_caf_atomic_op:: Atomic operation
4266 * _gfortran_caf_co_broadcast:: Sending data to all images
4267 * _gfortran_caf_co_max:: Collective maximum reduction
4268 * _gfortran_caf_co_min:: Collective minimum reduction
4269 * _gfortran_caf_co_sum:: Collective summing reduction
4270 * _gfortran_caf_co_reduce:: Generic collective reduction
4271 @end menu
4274 @node _gfortran_caf_init
4275 @subsection @code{_gfortran_caf_init} --- Initialiation function
4276 @cindex Coarray, _gfortran_caf_init
4278 @table @asis
4279 @item @emph{Description}:
4280 This function is called at startup of the program before the Fortran main
4281 program, if the latter has been compiled with @option{-fcoarray=lib}.
4282 It takes as arguments the command-line arguments of the program.  It is
4283 permitted to pass two @code{NULL} pointers as argument; if non-@code{NULL},
4284 the library is permitted to modify the arguments.
4286 @item @emph{Syntax}:
4287 @code{void _gfortran_caf_init (int *argc, char ***argv)}
4289 @item @emph{Arguments}:
4290 @multitable @columnfractions .15 .70
4291 @item @var{argc} @tab intent(inout) An integer pointer with the number of
4292 arguments passed to the program or @code{NULL}.
4293 @item @var{argv} @tab intent(inout) A pointer to an array of strings with the
4294 command-line arguments or @code{NULL}.
4295 @end multitable
4297 @item @emph{NOTES}
4298 The function is modelled after the initialization function of the Message
4299 Passing Interface (MPI) specification.  Due to the way coarray registration
4300 works, it might not be the first call to the library.  If the main program is
4301 not written in Fortran and only a library uses coarrays, it can happen that
4302 this function is never called.  Therefore, it is recommended that the library
4303 does not rely on the passed arguments and whether the call has been done.
4304 @end table
4307 @node _gfortran_caf_finish
4308 @subsection @code{_gfortran_caf_finish} --- Finalization function
4309 @cindex Coarray, _gfortran_caf_finish
4311 @table @asis
4312 @item @emph{Description}:
4313 This function is called at the end of the Fortran main program, if it has
4314 been compiled with the @option{-fcoarray=lib} option.
4316 @item @emph{Syntax}:
4317 @code{void _gfortran_caf_finish (void)}
4319 @item @emph{NOTES}
4320 For non-Fortran programs, it is recommended to call the function at the end
4321 of the main program.  To ensure that the shutdown is also performed for
4322 programs where this function is not explicitly invoked, for instance
4323 non-Fortran programs or calls to the system's exit() function, the library
4324 can use a destructor function.  Note that programs can also be terminated
4325 using the STOP and ERROR STOP statements; those use different library calls.
4326 @end table
4329 @node _gfortran_caf_this_image
4330 @subsection @code{_gfortran_caf_this_image} --- Querying the image number
4331 @cindex Coarray, _gfortran_caf_this_image
4333 @table @asis
4334 @item @emph{Description}:
4335 This function returns the current image number, which is a positive number.
4337 @item @emph{Syntax}:
4338 @code{int _gfortran_caf_this_image (int distance)}
4340 @item @emph{Arguments}:
4341 @multitable @columnfractions .15 .70
4342 @item @var{distance} @tab As specified for the @code{this_image} intrinsic
4343 in TS18508.  Shall be a non-negative number.
4344 @end multitable
4346 @item @emph{NOTES}
4347 If the Fortran intrinsic @code{this_image} is invoked without an argument, which
4348 is the only permitted form in Fortran 2008, GCC passes @code{0} as
4349 first argument.
4350 @end table
4353 @node _gfortran_caf_num_images
4354 @subsection @code{_gfortran_caf_num_images} --- Querying the maximal number of images
4355 @cindex Coarray, _gfortran_caf_num_images
4357 @table @asis
4358 @item @emph{Description}:
4359 This function returns the number of images in the current team, if
4360 @var{distance} is 0 or the number of images in the parent team at the specified
4361 distance. If failed is -1, the function returns the number of all images at
4362 the specified distance; if it is 0, the function returns the number of
4363 nonfailed images, and if it is 1, it returns the number of failed images.
4365 @item @emph{Syntax}:
4366 @code{int _gfortran_caf_num_images(int distance, int failed)}
4368 @item @emph{Arguments}:
4369 @multitable @columnfractions .15 .70
4370 @item @var{distance} @tab the distance from this image to the ancestor.
4371 Shall be positive.
4372 @item @var{failed} @tab shall be -1, 0, or 1
4373 @end multitable
4375 @item @emph{NOTES}
4376 This function follows TS18508. If the num_image intrinsic has no arguments,
4377 then the compiler passes @code{distance=0} and @code{failed=-1} to the function.
4378 @end table
4381 @node _gfortran_caf_image_status
4382 @subsection @code{_gfortran_caf_image_status} --- Query the status of an image
4383 @cindex Coarray, _gfortran_caf_image_status
4385 @table @asis
4386 @item @emph{Description}:
4387 Get the status of the image given by the id @var{image} of the team given by
4388 @var{team}.  Valid results are zero, for image is ok, @code{STAT_STOPPED_IMAGE}
4389 from the ISO_FORTRAN_ENV module to indicate that the image has been stopped and
4390 @code{STAT_FAILED_IMAGE} also from ISO_FORTRAN_ENV to indicate that the image
4391 has executed a @code{FAIL IMAGE} statement.
4393 @item @emph{Syntax}:
4394 @code{int _gfortran_caf_image_status (int image, caf_team_t * team)}
4396 @item @emph{Arguments}:
4397 @multitable @columnfractions .15 .70
4398 @item @var{image} @tab the positive scalar id of the image in the current TEAM.
4399 @item @var{team} @tab optional; team on the which the inquiry is to be
4400 performed.
4401 @end multitable
4403 @item @emph{NOTES}
4404 This function follows TS18508.  Because team-functionality is not yet
4405 implemented a null-pointer is passed for the @var{team} argument at the moment.
4406 @end table
4409 @node _gfortran_caf_failed_images
4410 @subsection @code{_gfortran_caf_failed_images} --- Get an array of the indexes of the failed images
4411 @cindex Coarray, _gfortran_caf_failed_images
4413 @table @asis
4414 @item @emph{Description}:
4415 Get an array of image indexes in the current @var{team} that have failed.  The
4416 array is sorted ascendingly.  When @var{team} is not provided the current team
4417 is to be used.  When @var{kind} is provided then the resulting array is of that
4418 integer kind else it is of default integer kind.  The returns an unallocated
4419 size zero array when no images have failed.
4421 @item @emph{Syntax}:
4422 @code{int _gfortran_caf_failed_images (caf_team_t * team, int * kind)}
4424 @item @emph{Arguments}:
4425 @multitable @columnfractions .15 .70
4426 @item @var{team} @tab optional; team on the which the inquiry is to be
4427 performed.
4428 @item @var{image} @tab optional; the kind of the resulting integer array.
4429 @end multitable
4431 @item @emph{NOTES}
4432 This function follows TS18508.  Because team-functionality is not yet
4433 implemented a null-pointer is passed for the @var{team} argument at the moment.
4434 @end table
4437 @node _gfortran_caf_stopped_images
4438 @subsection @code{_gfortran_caf_stopped_images} --- Get an array of the indexes of the stopped images
4439 @cindex Coarray, _gfortran_caf_stopped_images
4441 @table @asis
4442 @item @emph{Description}:
4443 Get an array of image indexes in the current @var{team} that have stopped.  The
4444 array is sorted ascendingly.  When @var{team} is not provided the current team
4445 is to be used.  When @var{kind} is provided then the resulting array is of that
4446 integer kind else it is of default integer kind.  The returns an unallocated
4447 size zero array when no images have failed.
4449 @item @emph{Syntax}:
4450 @code{int _gfortran_caf_stopped_images (caf_team_t * team, int * kind)}
4452 @item @emph{Arguments}:
4453 @multitable @columnfractions .15 .70
4454 @item @var{team} @tab optional; team on the which the inquiry is to be
4455 performed.
4456 @item @var{image} @tab optional; the kind of the resulting integer array.
4457 @end multitable
4459 @item @emph{NOTES}
4460 This function follows TS18508.  Because team-functionality is not yet
4461 implemented a null-pointer is passed for the @var{team} argument at the moment.
4462 @end table
4465 @node _gfortran_caf_register
4466 @subsection @code{_gfortran_caf_register} --- Registering coarrays
4467 @cindex Coarray, _gfortran_caf_register
4469 @table @asis
4470 @item @emph{Description}:
4471 Registers memory for a coarray and creates a token to identify the coarray.  The
4472 routine is called for both coarrays with @code{SAVE} attribute and using an
4473 explicit @code{ALLOCATE} statement.  If an error occurs and @var{STAT} is a
4474 @code{NULL} pointer, the function shall abort with printing an error message
4475 and starting the error termination.  If no error occurs and @var{STAT} is
4476 present, it shall be set to zero.  Otherwise, it shall be set to a positive
4477 value and, if not-@code{NULL}, @var{ERRMSG} shall be set to a string describing
4478 the failure.  The routine shall register the memory provided in the
4479 @code{DATA}-component of the array descriptor @var{DESC}, when that component
4480 is non-@code{NULL}, else it shall allocate sufficient memory and provide a
4481 pointer to it in the @code{DATA}-component of @var{DESC}.  The array descriptor
4482 has rank zero, when a scalar object is to be registered and the array
4483 descriptor may be invalid after the call to @code{_gfortran_caf_register}.
4484 When an array is to be allocated the descriptor persists.
4486 For @code{CAF_REGTYPE_COARRAY_STATIC} and @code{CAF_REGTYPE_COARRAY_ALLOC},
4487 the passed size is the byte size requested.  For @code{CAF_REGTYPE_LOCK_STATIC},
4488 @code{CAF_REGTYPE_LOCK_ALLOC} and @code{CAF_REGTYPE_CRITICAL} it is the array
4489 size or one for a scalar.
4491 When @code{CAF_REGTYPE_COARRAY_ALLOC_REGISTER_ONLY} is used, then only a token
4492 for an allocatable or pointer component is created.  The @code{SIZE} parameter
4493 is not used then.  On the contrary when
4494 @code{CAF_REGTYPE_COARRAY_ALLOC_ALLOCATE_ONLY} is specified, then the
4495 @var{token} needs to be registered by a previous call with regtype
4496 @code{CAF_REGTYPE_COARRAY_ALLOC_REGISTER_ONLY} and either the memory specified
4497 in the @var{DESC}'s data-ptr is registered or allocate when the data-ptr is
4498 @code{NULL}.
4500 @item @emph{Syntax}:
4501 @code{void caf_register (size_t size, caf_register_t type, caf_token_t *token,
4502 gfc_descriptor_t *desc, int *stat, char *errmsg, size_t errmsg_len)}
4504 @item @emph{Arguments}:
4505 @multitable @columnfractions .15 .70
4506 @item @var{size} @tab For normal coarrays, the byte size of the coarray to be
4507 allocated; for lock types and event types, the number of elements.
4508 @item @var{type} @tab one of the caf_register_t types.
4509 @item @var{token} @tab intent(out) An opaque pointer identifying the coarray.
4510 @item @var{desc} @tab intent(inout) The (pseudo) array descriptor.
4511 @item @var{stat} @tab intent(out) For allocatable coarrays, stores the STAT=;
4512 may be @code{NULL}
4513 @item @var{errmsg} @tab intent(out) When an error occurs, this will be set to
4514 an error message; may be @code{NULL}
4515 @item @var{errmsg_len} @tab the buffer size of errmsg.
4516 @end multitable
4518 @item @emph{NOTES}
4519 Nonallocatable coarrays have to be registered prior use from remote images.
4520 In order to guarantee this, they have to be registered before the main
4521 program. This can be achieved by creating constructor functions. That is what
4522 GCC does such that also for nonallocatable coarrays the memory is allocated and
4523 no static memory is used.  The token permits to identify the coarray; to the
4524 processor, the token is a nonaliasing pointer. The library can, for instance,
4525 store the base address of the coarray in the token, some handle or a more
4526 complicated struct.  The library may also store the array descriptor
4527 @var{DESC} when its rank is non-zero.
4529 For lock types, the value shall only be used for checking the allocation
4530 status. Note that for critical blocks, the locking is only required on one
4531 image; in the locking statement, the processor shall always pass an
4532 image index of one for critical-block lock variables
4533 (@code{CAF_REGTYPE_CRITICAL}). For lock types and critical-block variables,
4534 the initial value shall be unlocked (or, respecitively, not in critical
4535 section) such as the value false; for event types, the initial state should
4536 be no event, e.g. zero.
4537 @end table
4540 @node _gfortran_caf_deregister
4541 @subsection @code{_gfortran_caf_deregister} --- Deregistering coarrays
4542 @cindex Coarray, _gfortran_caf_deregister
4544 @table @asis
4545 @item @emph{Description}:
4546 Called to free or deregister the memory of a coarray; the processor calls this
4547 function for automatic and explicit deallocation.  In case of an error, this
4548 function shall fail with an error message, unless the @var{STAT} variable is
4549 not null.  The library is only expected to free memory it allocated itself
4550 during a call to @code{_gfortran_caf_register}.
4552 @item @emph{Syntax}:
4553 @code{void caf_deregister (caf_token_t *token, caf_deregister_t type,
4554 int *stat, char *errmsg, size_t errmsg_len)}
4556 @item @emph{Arguments}:
4557 @multitable @columnfractions .15 .70
4558 @item @var{token} @tab the token to free.
4559 @item @var{type} @tab the type of action to take for the coarray.  A
4560 @code{CAF_DEREGTYPE_COARRAY_DEALLOCATE_ONLY} is allowed only for allocatable or
4561 pointer components of derived type coarrays.  The action only deallocates the
4562 local memory without deleting the token.
4563 @item @var{stat} @tab intent(out) Stores the STAT=; may be NULL
4564 @item @var{errmsg} @tab intent(out) When an error occurs, this will be set
4565 to an error message; may be NULL
4566 @item @var{errmsg_len} @tab the buffer size of errmsg.
4567 @end multitable
4569 @item @emph{NOTES}
4570 For nonalloatable coarrays this function is never called.  If a cleanup is
4571 required, it has to be handled via the finish, stop and error stop functions,
4572 and via destructors.
4573 @end table
4576 @node _gfortran_caf_is_present
4577 @subsection @code{_gfortran_caf_is_present} --- Query whether an allocatable or pointer component in a derived type coarray is allocated
4578 @cindex Coarray, _gfortran_caf_is_present
4580 @table @asis
4581 @item @emph{Description}:
4582 Used to query the coarray library whether an allocatable component in a derived
4583 type coarray is allocated on a remote image.
4585 @item @emph{Syntax}:
4586 @code{void _gfortran_caf_is_present (caf_token_t token, int image_index,
4587 gfc_reference_t *ref)}
4589 @item @emph{Arguments}:
4590 @multitable @columnfractions .15 .70
4591 @item @var{token} @tab An opaque pointer identifying the coarray.
4592 @item @var{image_index} @tab The ID of the remote image; must be a positive
4593 number.
4594 @item @var{ref} @tab A chain of references to address the allocatable or
4595 pointer component in the derived type coarray.  The object reference needs to be
4596 a scalar or a full array reference, respectively.
4597 @end multitable
4599 @end table
4601 @node _gfortran_caf_send
4602 @subsection @code{_gfortran_caf_send} --- Sending data from a local image to a remote image
4603 @cindex Coarray, _gfortran_caf_send
4605 @table @asis
4606 @item @emph{Description}:
4607 Called to send a scalar, an array section or a whole array from a local
4608 to a remote image identified by the image_index.
4610 @item @emph{Syntax}:
4611 @code{void _gfortran_caf_send (caf_token_t token, size_t offset,
4612 int image_index, gfc_descriptor_t *dest, caf_vector_t *dst_vector,
4613 gfc_descriptor_t *src, int dst_kind, int src_kind, bool may_require_tmp,
4614 int *stat)}
4616 @item @emph{Arguments}:
4617 @multitable @columnfractions .15 .70
4618 @item @var{token} @tab intent(in)  An opaque pointer identifying the coarray.
4619 @item @var{offset} @tab intent(in)  By which amount of bytes the actual data is
4620 shifted compared to the base address of the coarray.
4621 @item @var{image_index} @tab intent(in)  The ID of the remote image; must be a
4622 positive number.
4623 @item @var{dest} @tab intent(in)  Array descriptor for the remote image for the
4624 bounds and the size.  The @code{base_addr} shall not be accessed.
4625 @item @var{dst_vector} @tab intent(in)  If not NULL, it contains the vector
4626 subscript of the destination array; the values are relative to the dimension
4627 triplet of the dest argument.
4628 @item @var{src} @tab intent(in)  Array descriptor of the local array to be
4629 transferred to the remote image
4630 @item @var{dst_kind} @tab intent(in)  Kind of the destination argument
4631 @item @var{src_kind} @tab intent(in)  Kind of the source argument
4632 @item @var{may_require_tmp} @tab intent(in)  The variable is @code{false} when
4633 it is known at compile time that the @var{dest} and @var{src} either cannot
4634 overlap or overlap (fully or partially) such that walking @var{src} and
4635 @var{dest} in element wise element order (honoring the stride value) will not
4636 lead to wrong results.  Otherwise, the value is @code{true}.
4637 @item @var{stat} @tab intent(out) when non-NULL give the result of the
4638 operation, i.e., zero on success and non-zero on error.  When NULL and an error
4639 occurs, then an error message is printed and the program is terminated.
4640 @end multitable
4642 @item @emph{NOTES}
4643 It is permitted to have @var{image_index} equal the current image; the memory
4644 of the send-to and the send-from might (partially) overlap in that case.  The
4645 implementation has to take care that it handles this case, e.g. using
4646 @code{memmove} which handles (partially) overlapping memory. If
4647 @var{may_require_tmp} is true, the library might additionally create a
4648 temporary variable, unless additional checks show that this is not required
4649 (e.g. because walking backward is possible or because both arrays are
4650 contiguous and @code{memmove} takes care of overlap issues).
4652 Note that the assignment of a scalar to an array is permitted. In addition,
4653 the library has to handle numeric-type conversion and for strings, padding
4654 and different character kinds.
4655 @end table
4658 @node _gfortran_caf_get
4659 @subsection @code{_gfortran_caf_get} --- Getting data from a remote image
4660 @cindex Coarray, _gfortran_caf_get
4662 @table @asis
4663 @item @emph{Description}:
4664 Called to get an array section or a whole array from a remote,
4665 image identified by the image_index.
4667 @item @emph{Syntax}:
4668 @code{void _gfortran_caf_get (caf_token_t token, size_t offset,
4669 int image_index, gfc_descriptor_t *src, caf_vector_t *src_vector,
4670 gfc_descriptor_t *dest, int src_kind, int dst_kind, bool may_require_tmp,
4671 int *stat)}
4673 @item @emph{Arguments}:
4674 @multitable @columnfractions .15 .70
4675 @item @var{token} @tab intent(in)  An opaque pointer identifying the coarray.
4676 @item @var{offset} @tab intent(in)  By which amount of bytes the actual data is
4677 shifted compared to the base address of the coarray.
4678 @item @var{image_index} @tab intent(in)  The ID of the remote image; must be a
4679 positive number.
4680 @item @var{dest} @tab intent(out) Array descriptor of the local array to store
4681 the data retrieved from the remote image
4682 @item @var{src} @tab intent(in) Array descriptor for the remote image for the
4683 bounds and the size.  The @code{base_addr} shall not be accessed.
4684 @item @var{src_vector} @tab intent(in)  If not NULL, it contains the vector
4685 subscript of the source array; the values are relative to the dimension
4686 triplet of the @var{src} argument.
4687 @item @var{dst_kind} @tab intent(in)  Kind of the destination argument
4688 @item @var{src_kind} @tab intent(in)  Kind of the source argument
4689 @item @var{may_require_tmp} @tab intent(in)  The variable is @code{false} when
4690 it is known at compile time that the @var{dest} and @var{src} either cannot
4691 overlap or overlap (fully or partially) such that walking @var{src} and
4692 @var{dest} in element wise element order (honoring the stride value) will not
4693 lead to wrong results.  Otherwise, the value is @code{true}.
4694 @item @var{stat} @tab intent(out) When non-NULL give the result of the
4695 operation, i.e., zero on success and non-zero on error.  When NULL and an error
4696 occurs, then an error message is printed and the program is terminated.
4697 @end multitable
4699 @item @emph{NOTES}
4700 It is permitted to have @var{image_index} equal the current image; the memory of
4701 the send-to and the send-from might (partially) overlap in that case.  The
4702 implementation has to take care that it handles this case, e.g. using
4703 @code{memmove} which handles (partially) overlapping memory. If
4704 @var{may_require_tmp} is true, the library might additionally create a
4705 temporary variable, unless additional checks show that this is not required
4706 (e.g. because walking backward is possible or because both arrays are
4707 contiguous and @code{memmove} takes care of overlap issues).
4709 Note that the library has to handle numeric-type conversion and for strings,
4710 padding and different character kinds.
4711 @end table
4714 @node _gfortran_caf_sendget
4715 @subsection @code{_gfortran_caf_sendget} --- Sending data between remote images
4716 @cindex Coarray, _gfortran_caf_sendget
4718 @table @asis
4719 @item @emph{Description}:
4720 Called to send a scalar, an array section or a whole array from a remote image
4721 identified by the @var{src_image_index} to a remote image identified by the
4722 @var{dst_image_index}.
4724 @item @emph{Syntax}:
4725 @code{void _gfortran_caf_sendget (caf_token_t dst_token, size_t dst_offset,
4726 int dst_image_index, gfc_descriptor_t *dest, caf_vector_t *dst_vector,
4727 caf_token_t src_token, size_t src_offset, int src_image_index,
4728 gfc_descriptor_t *src, caf_vector_t *src_vector, int dst_kind, int src_kind,
4729 bool may_require_tmp, int *stat)}
4731 @item @emph{Arguments}:
4732 @multitable @columnfractions .15 .70
4733 @item @var{dst_token} @tab intent(in)  An opaque pointer identifying the
4734 destination coarray.
4735 @item @var{dst_offset} @tab intent(in)  By which amount of bytes the actual data
4736 is shifted compared to the base address of the destination coarray.
4737 @item @var{dst_image_index} @tab intent(in)  The ID of the destination remote
4738 image; must be a positive number.
4739 @item @var{dest} @tab intent(in) Array descriptor for the destination
4740 remote image for the bounds and the size.  The @code{base_addr} shall not be
4741 accessed.
4742 @item @var{dst_vector} @tab intent(int)  If not NULL, it contains the vector
4743 subscript of the destination array; the values are relative to the dimension
4744 triplet of the @var{dest} argument.
4745 @item @var{src_token} @tab intent(in)  An opaque pointer identifying the source
4746 coarray.
4747 @item @var{src_offset} @tab intent(in)  By which amount of bytes the actual data
4748 is shifted compared to the base address of the source coarray.
4749 @item @var{src_image_index} @tab intent(in)  The ID of the source remote image;
4750 must be a positive number.
4751 @item @var{src} @tab intent(in) Array descriptor of the local array to be
4752 transferred to the remote image.
4753 @item @var{src_vector} @tab intent(in) Array descriptor of the local array to
4754 be transferred to the remote image
4755 @item @var{dst_kind} @tab intent(in)  Kind of the destination argument
4756 @item @var{src_kind} @tab intent(in)  Kind of the source argument
4757 @item @var{may_require_tmp} @tab intent(in)  The variable is @code{false} when
4758 it is known at compile time that the @var{dest} and @var{src} either cannot
4759 overlap or overlap (fully or partially) such that walking @var{src} and
4760 @var{dest} in element wise element order (honoring the stride value) will not
4761 lead to wrong results.  Otherwise, the value is @code{true}.
4762 @item @var{stat} @tab intent(out) when non-NULL give the result of the
4763 operation, i.e., zero on success and non-zero on error.  When NULL and an error
4764 occurs, then an error message is printed and the program is terminated.
4765 @end multitable
4767 @item @emph{NOTES}
4768 It is permitted to have the same image index for both @var{src_image_index} and
4769 @var{dst_image_index}; the memory of the send-to and the send-from might
4770 (partially) overlap in that case.  The implementation has to take care that it
4771 handles this case, e.g. using @code{memmove} which handles (partially)
4772 overlapping memory.  If @var{may_require_tmp} is true, the library
4773 might additionally create a temporary variable, unless additional checks show
4774 that this is not required (e.g. because walking backward is possible or because
4775 both arrays are contiguous and @code{memmove} takes care of overlap issues).
4777 Note that the assignment of a scalar to an array is permitted. In addition,
4778 the library has to handle numeric-type conversion and for strings, padding and
4779 different character kinds.
4780 @end table
4782 @node _gfortran_caf_send_by_ref
4783 @subsection @code{_gfortran_caf_send_by_ref} --- Sending data from a local image to a remote image with enhanced referencing options
4784 @cindex Coarray, _gfortran_caf_send_by_ref
4786 @table @asis
4787 @item @emph{Description}:
4788 Called to send a scalar, an array section or a whole array from a local to a
4789 remote image identified by the @var{image_index}.
4791 @item @emph{Syntax}:
4792 @code{void _gfortran_caf_send_by_ref (caf_token_t token, int image_index,
4793 gfc_descriptor_t *src, caf_reference_t *refs, int dst_kind, int src_kind,
4794 bool may_require_tmp, bool dst_reallocatable, int *stat, int dst_type)}
4796 @item @emph{Arguments}:
4797 @multitable @columnfractions .15 .70
4798 @item @var{token} @tab intent(in)  An opaque pointer identifying the coarray.
4799 @item @var{image_index} @tab intent(in)  The ID of the remote image; must be a
4800 positive number.
4801 @item @var{src} @tab intent(in) Array descriptor of the local array to be
4802 transferred to the remote image
4803 @item @var{refs} @tab intent(in) The references on the remote array to store
4804 the data given by src.  Guaranteed to have at least one entry.
4805 @item @var{dst_kind} @tab intent(in)  Kind of the destination argument
4806 @item @var{src_kind} @tab intent(in)  Kind of the source argument
4807 @item @var{may_require_tmp} @tab intent(in)  The variable is @code{false} when
4808 it is known at compile time that the @var{dest} and @var{src} either cannot
4809 overlap or overlap (fully or partially) such that walking @var{src} and
4810 @var{dest} in element wise element order (honoring the stride value) will not
4811 lead to wrong results.  Otherwise, the value is @code{true}.
4812 @item @var{dst_reallocatable} @tab intent(in)  Set when the destination is of
4813 allocatable or pointer type and the refs will allow reallocation, i.e., the ref
4814 is a full array or component ref.
4815 @item @var{stat} @tab intent(out) When non-@code{NULL} give the result of the
4816 operation, i.e., zero on success and non-zero on error.  When @code{NULL} and
4817 an error occurs, then an error message is printed and the program is terminated.
4818 @item @var{dst_type} @tab intent(in)  Give the type of the destination.  When
4819 the destination is not an array, than the precise type, e.g. of a component in
4820 a derived type, is not known, but provided here.
4821 @end multitable
4823 @item @emph{NOTES}
4824 It is permitted to have @var{image_index} equal the current image; the memory of
4825 the send-to and the send-from might (partially) overlap in that case.  The
4826 implementation has to take care that it handles this case, e.g. using
4827 @code{memmove} which handles (partially) overlapping memory.  If
4828 @var{may_require_tmp} is true, the library might additionally create a
4829 temporary variable, unless additional checks show that this is not required
4830 (e.g. because walking backward is possible or because both arrays are
4831 contiguous and @code{memmove} takes care of overlap issues).
4833 Note that the assignment of a scalar to an array is permitted.  In addition,
4834 the library has to handle numeric-type conversion and for strings, padding
4835 and different character kinds.
4837 Because of the more complicated references possible some operations may be
4838 unsupported by certain libraries.  The library is expected to issue a precise
4839 error message why the operation is not permitted.
4840 @end table
4843 @node _gfortran_caf_get_by_ref
4844 @subsection @code{_gfortran_caf_get_by_ref} --- Getting data from a remote image using enhanced references
4845 @cindex Coarray, _gfortran_caf_get_by_ref
4847 @table @asis
4848 @item @emph{Description}:
4849 Called to get a scalar, an array section or a whole array from a remote image
4850 identified by the @var{image_index}.
4852 @item @emph{Syntax}:
4853 @code{void _gfortran_caf_get_by_ref (caf_token_t token, int image_index,
4854 caf_reference_t *refs, gfc_descriptor_t *dst, int dst_kind, int src_kind,
4855 bool may_require_tmp, bool dst_reallocatable, int *stat, int src_type)}
4857 @item @emph{Arguments}:
4858 @multitable @columnfractions .15 .70
4859 @item @var{token} @tab intent(in)  An opaque pointer identifying the coarray.
4860 @item @var{image_index} @tab intent(in)  The ID of the remote image; must be a
4861 positive number.
4862 @item @var{refs} @tab intent(in) The references to apply to the remote structure
4863 to get the data.
4864 @item @var{dst} @tab intent(in) Array descriptor of the local array to store
4865 the data transferred from the remote image.  May be reallocated where needed
4866 and when @var{DST_REALLOCATABLE} allows it.
4867 @item @var{dst_kind} @tab intent(in)  Kind of the destination argument
4868 @item @var{src_kind} @tab intent(in)  Kind of the source argument
4869 @item @var{may_require_tmp} @tab intent(in)  The variable is @code{false} when
4870 it is known at compile time that the @var{dest} and @var{src} either cannot
4871 overlap or overlap (fully or partially) such that walking @var{src} and
4872 @var{dest} in element wise element order (honoring the stride value) will not
4873 lead to wrong results.  Otherwise, the value is @code{true}.
4874 @item @var{dst_reallocatable} @tab intent(in)  Set when @var{DST} is of
4875 allocatable or pointer type and its refs allow reallocation, i.e., the full
4876 array or a component is referenced.
4877 @item @var{stat} @tab intent(out) When non-@code{NULL} give the result of the
4878 operation, i.e., zero on success and non-zero on error.  When @code{NULL} and an
4879 error occurs, then an error message is printed and the program is terminated.
4880 @item @var{src_type} @tab intent(in)  Give the type of the source.  When the
4881 source is not an array, than the precise type, e.g. of a component in a
4882 derived type, is not known, but provided here.
4883 @end multitable
4885 @item @emph{NOTES}
4886 It is permitted to have @code{image_index} equal the current image; the memory
4887 of the send-to and the send-from might (partially) overlap in that case.  The
4888 implementation has to take care that it handles this case, e.g. using
4889 @code{memmove} which handles (partially) overlapping memory.  If
4890 @var{may_require_tmp} is true, the library might additionally create a
4891 temporary variable, unless additional checks show that this is not required
4892 (e.g. because walking backward is possible or because both arrays are
4893 contiguous and @code{memmove} takes care of overlap issues).
4895 Note that the library has to handle numeric-type conversion and for strings,
4896 padding and different character kinds.
4898 Because of the more complicated references possible some operations may be
4899 unsupported by certain libraries.  The library is expected to issue a precise
4900 error message why the operation is not permitted.
4901 @end table
4904 @node _gfortran_caf_sendget_by_ref
4905 @subsection @code{_gfortran_caf_sendget_by_ref} --- Sending data between remote images using enhanced references on both sides
4906 @cindex Coarray, _gfortran_caf_sendget_by_ref
4908 @table @asis
4909 @item @emph{Description}:
4910 Called to send a scalar, an array section or a whole array from a remote image
4911 identified by the @var{src_image_index} to a remote image identified by the
4912 @var{dst_image_index}.
4914 @item @emph{Syntax}:
4915 @code{void _gfortran_caf_sendget_by_ref (caf_token_t dst_token,
4916 int dst_image_index, caf_reference_t *dst_refs,
4917 caf_token_t src_token, int src_image_index, caf_reference_t *src_refs,
4918 int dst_kind, int src_kind, bool may_require_tmp, int *dst_stat,
4919 int *src_stat, int dst_type, int src_type)}
4921 @item @emph{Arguments}:
4922 @multitable @columnfractions .15 .70
4923 @item @var{dst_token} @tab intent(in)  An opaque pointer identifying the
4924 destination coarray.
4925 @item @var{dst_image_index} @tab intent(in)  The ID of the destination remote
4926 image; must be a positive number.
4927 @item @var{dst_refs} @tab intent(in) The references on the remote array to store
4928 the data given by the source.  Guaranteed to have at least one entry.
4929 @item @var{src_token} @tab intent(in)  An opaque pointer identifying the source
4930 coarray.
4931 @item @var{src_image_index} @tab intent(in)  The ID of the source remote image;
4932 must be a positive number.
4933 @item @var{src_refs} @tab intent(in) The references to apply to the remote
4934 structure to get the data.
4935 @item @var{dst_kind} @tab intent(in)  Kind of the destination argument
4936 @item @var{src_kind} @tab intent(in)  Kind of the source argument
4937 @item @var{may_require_tmp} @tab intent(in)  The variable is @code{false} when
4938 it is known at compile time that the @var{dest} and @var{src} either cannot
4939 overlap or overlap (fully or partially) such that walking @var{src} and
4940 @var{dest} in element wise element order (honoring the stride value) will not
4941 lead to wrong results.  Otherwise, the value is @code{true}.
4942 @item @var{dst_stat} @tab intent(out) when non-@code{NULL} give the result of
4943 the send-operation, i.e., zero on success and non-zero on error.  When
4944 @code{NULL} and an error occurs, then an error message is printed and the
4945 program is terminated.
4946 @item @var{src_stat} @tab intent(out) When non-@code{NULL} give the result of
4947 the get-operation, i.e., zero on success and non-zero on error.  When
4948 @code{NULL} and an error occurs, then an error message is printed and the
4949 program is terminated.
4950 @item @var{dst_type} @tab intent(in)  Give the type of the destination.  When
4951 the destination is not an array, than the precise type, e.g. of a component in
4952 a derived type, is not known, but provided here.
4953 @item @var{src_type} @tab intent(in)  Give the type of the source.  When the
4954 source is not an array, than the precise type, e.g. of a component in a
4955 derived type, is not known, but provided here.
4956 @end multitable
4958 @item @emph{NOTES}
4959 It is permitted to have the same image index for both @var{src_image_index} and
4960 @var{dst_image_index}; the memory of the send-to and the send-from might
4961 (partially) overlap in that case.  The implementation has to take care that it
4962 handles this case, e.g. using @code{memmove} which handles (partially)
4963 overlapping memory.  If @var{may_require_tmp} is true, the library
4964 might additionally create a temporary variable, unless additional checks show
4965 that this is not required (e.g. because walking backward is possible or because
4966 both arrays are contiguous and @code{memmove} takes care of overlap issues).
4968 Note that the assignment of a scalar to an array is permitted.  In addition,
4969 the library has to handle numeric-type conversion and for strings, padding and
4970 different character kinds.
4972 Because of the more complicated references possible some operations may be
4973 unsupported by certain libraries.  The library is expected to issue a precise
4974 error message why the operation is not permitted.
4975 @end table
4978 @node _gfortran_caf_lock
4979 @subsection @code{_gfortran_caf_lock} --- Locking a lock variable
4980 @cindex Coarray, _gfortran_caf_lock
4982 @table @asis
4983 @item @emph{Description}:
4984 Acquire a lock on the given image on a scalar locking variable or for the
4985 given array element for an array-valued variable.  If the @var{aquired_lock}
4986 is @code{NULL}, the function returns after having obtained the lock.  If it is
4987 non-@code{NULL}, then @var{acquired_lock} is assigned the value true (one) when
4988 the lock could be obtained and false (zero) otherwise.  Locking a lock variable
4989 which has already been locked by the same image is an error.
4991 @item @emph{Syntax}:
4992 @code{void _gfortran_caf_lock (caf_token_t token, size_t index, int image_index,
4993 int *aquired_lock, int *stat, char *errmsg, size_t errmsg_len)}
4995 @item @emph{Arguments}:
4996 @multitable @columnfractions .15 .70
4997 @item @var{token} @tab intent(in)  An opaque pointer identifying the coarray.
4998 @item @var{index} @tab intent(in)  Array index; first array index is 0.  For
4999 scalars, it is always 0.
5000 @item @var{image_index} @tab intent(in)  The ID of the remote image; must be a
5001 positive number.
5002 @item @var{aquired_lock} @tab intent(out) If not NULL, it returns whether lock
5003 could be obtained.
5004 @item @var{stat} @tab intent(out) Stores the STAT=; may be NULL.
5005 @item @var{errmsg} @tab intent(out) When an error occurs, this will be set to
5006 an error message; may be NULL.
5007 @item @var{errmsg_len} @tab intent(in)  the buffer size of errmsg
5008 @end multitable
5010 @item @emph{NOTES}
5011 This function is also called for critical blocks; for those, the array index
5012 is always zero and the image index is one.  Libraries are permitted to use other
5013 images for critical-block locking variables.
5014 @end table
5016 @node _gfortran_caf_unlock
5017 @subsection @code{_gfortran_caf_lock} --- Unlocking a lock variable
5018 @cindex Coarray, _gfortran_caf_unlock
5020 @table @asis
5021 @item @emph{Description}:
5022 Release a lock on the given image on a scalar locking variable or for the
5023 given array element for an array-valued variable. Unlocking a lock variable
5024 which is unlocked or has been locked by a different image is an error.
5026 @item @emph{Syntax}:
5027 @code{void _gfortran_caf_unlock (caf_token_t token, size_t index, int image_index,
5028 int *stat, char *errmsg, size_t errmsg_len)}
5030 @item @emph{Arguments}:
5031 @multitable @columnfractions .15 .70
5032 @item @var{token} @tab intent(in)  An opaque pointer identifying the coarray.
5033 @item @var{index} @tab intent(in)  Array index; first array index is 0.  For
5034 scalars, it is always 0.
5035 @item @var{image_index} @tab intent(in)  The ID of the remote image; must be a
5036 positive number.
5037 @item @var{stat} @tab intent(out) For allocatable coarrays, stores the STAT=;
5038 may be NULL.
5039 @item @var{errmsg} @tab intent(out) When an error occurs, this will be set to
5040 an error message; may be NULL.
5041 @item @var{errmsg_len} @tab intent(in)  the buffer size of errmsg
5042 @end multitable
5044 @item @emph{NOTES}
5045 This function is also called for critical block; for those, the array index
5046 is always zero and the image index is one.  Libraries are permitted to use other
5047 images for critical-block locking variables.
5048 @end table
5050 @node _gfortran_caf_event_post
5051 @subsection @code{_gfortran_caf_event_post} --- Post an event
5052 @cindex Coarray, _gfortran_caf_event_post
5054 @table @asis
5055 @item @emph{Description}:
5056 Increment the event count of the specified event variable.
5058 @item @emph{Syntax}:
5059 @code{void _gfortran_caf_event_post (caf_token_t token, size_t index,
5060 int image_index, int *stat, char *errmsg, size_t errmsg_len)}
5062 @item @emph{Arguments}:
5063 @multitable @columnfractions .15 .70
5064 @item @var{token} @tab intent(in)  An opaque pointer identifying the coarray.
5065 @item @var{index} @tab intent(in)  Array index; first array index is 0.  For
5066 scalars, it is always 0.
5067 @item @var{image_index} @tab intent(in)  The ID of the remote image; must be a
5068 positive number; zero indicates the current image, when accessed noncoindexed.
5069 @item @var{stat} @tab intent(out)  Stores the STAT=; may be NULL.
5070 @item @var{errmsg} @tab intent(out)  When an error occurs, this will be set to
5071 an error message; may be NULL.
5072 @item @var{errmsg_len} @tab intent(in)  the buffer size of errmsg
5073 @end multitable
5075 @item @emph{NOTES}
5076 This acts like an atomic add of one to the remote image's event variable.
5077 The statement is an image-control statement but does not imply sync memory.
5078 Still, all preceeding push communications of this image to the specified
5079 remote image have to be completed before @code{event_wait} on the remote
5080 image returns.
5081 @end table
5085 @node _gfortran_caf_event_wait
5086 @subsection @code{_gfortran_caf_event_wait} --- Wait that an event occurred
5087 @cindex Coarray, _gfortran_caf_event_wait
5089 @table @asis
5090 @item @emph{Description}:
5091 Wait until the event count has reached at least the specified
5092 @var{until_count}; if so, atomically decrement the event variable by this
5093 amount and return.
5095 @item @emph{Syntax}:
5096 @code{void _gfortran_caf_event_wait (caf_token_t token, size_t index,
5097 int until_count, int *stat, char *errmsg, size_t errmsg_len)}
5099 @item @emph{Arguments}:
5100 @multitable @columnfractions .15 .70
5101 @item @var{token} @tab intent(in)  An opaque pointer identifying the coarray.
5102 @item @var{index} @tab intent(in)  Array index; first array index is 0.  For
5103 scalars, it is always 0.
5104 @item @var{until_count} @tab intent(in)  The number of events which have to be
5105 available before the function returns.
5106 @item @var{stat} @tab intent(out)  Stores the STAT=; may be NULL.
5107 @item @var{errmsg} @tab intent(out)  When an error occurs, this will be set to
5108 an error message; may be NULL.
5109 @item @var{errmsg_len} @tab intent(in)  the buffer size of errmsg
5110 @end multitable
5112 @item @emph{NOTES}
5113 This function only operates on a local coarray. It acts like a loop checking
5114 atomically the value of the event variable, breaking if the value is greater
5115 or equal the requested number of counts. Before the function returns, the
5116 event variable has to be decremented by the requested @var{until_count} value.
5117 A possible implementation would be a busy loop for a certain number of spins
5118 (possibly depending on the number of threads relative to the number of available
5119 cores) followed by another waiting strategy such as a sleeping wait (possibly
5120 with an increasing number of sleep time) or, if possible, a futex wait.
5122 The statement is an image-control statement but does not imply sync memory.
5123 Still, all preceeding push communications of this image to the specified
5124 remote image have to be completed before @code{event_wait} on the remote
5125 image returns.
5126 @end table
5130 @node _gfortran_caf_event_query
5131 @subsection @code{_gfortran_caf_event_query} --- Query event count
5132 @cindex Coarray, _gfortran_caf_event_query
5134 @table @asis
5135 @item @emph{Description}:
5136 Return the event count of the specified event variable.
5138 @item @emph{Syntax}:
5139 @code{void _gfortran_caf_event_query (caf_token_t token, size_t index,
5140 int image_index, int *count, int *stat)}
5142 @item @emph{Arguments}:
5143 @multitable @columnfractions .15 .70
5144 @item @var{token} @tab intent(in)  An opaque pointer identifying the coarray.
5145 @item @var{index} @tab intent(in)  Array index; first array index is 0.  For
5146 scalars, it is always 0.
5147 @item @var{image_index} @tab intent(in)  The ID of the remote image; must be a
5148 positive number; zero indicates the current image when accessed noncoindexed.
5149 @item @var{count} @tab intent(out)  The number of events currently posted to
5150 the event variable.
5151 @item @var{stat} @tab intent(out)  Stores the STAT=; may be NULL.
5152 @end multitable
5154 @item @emph{NOTES}
5155 The typical use is to check the local event variable to only call
5156 @code{event_wait} when the data is available. However, a coindexed variable
5157 is permitted; there is no ordering or synchronization implied.  It acts like
5158 an atomic fetch of the value of the event variable.
5159 @end table
5163 @node _gfortran_caf_sync_all
5164 @subsection @code{_gfortran_caf_sync_all} --- All-image barrier
5165 @cindex Coarray, _gfortran_caf_sync_all
5167 @table @asis
5168 @item @emph{Description}:
5169 Synchronization of all images in the current team; the program only continues
5170 on a given image after this function has been called on all images of the
5171 current team.  Additionally, it ensures that all pending data transfers of
5172 previous segment have completed.
5174 @item @emph{Syntax}:
5175 @code{void _gfortran_caf_sync_all (int *stat, char *errmsg, size_t errmsg_len)}
5177 @item @emph{Arguments}:
5178 @multitable @columnfractions .15 .70
5179 @item @var{stat} @tab intent(out)  Stores the status STAT= and may be NULL.
5180 @item @var{errmsg} @tab intent(out)  When an error occurs, this will be set to
5181 an error message; may be NULL.
5182 @item @var{errmsg_len} @tab intent(in)  the buffer size of errmsg
5183 @end multitable
5184 @end table
5188 @node _gfortran_caf_sync_images
5189 @subsection @code{_gfortran_caf_sync_images} --- Barrier for selected images
5190 @cindex Coarray, _gfortran_caf_sync_images
5192 @table @asis
5193 @item @emph{Description}:
5194 Synchronization between the specified images; the program only continues on a
5195 given image after this function has been called on all images specified for
5196 that image. Note that one image can wait for all other images in the current
5197 team (e.g. via @code{sync images(*)}) while those only wait for that specific
5198 image.  Additionally, @code{sync images} ensures that all pending data
5199 transfers of previous segments have completed.
5201 @item @emph{Syntax}:
5202 @code{void _gfortran_caf_sync_images (int count, int images[], int *stat,
5203 char *errmsg, size_t errmsg_len)}
5205 @item @emph{Arguments}:
5206 @multitable @columnfractions .15 .70
5207 @item @var{count} @tab intent(in)  The number of images which are provided in
5208 the next argument.  For a zero-sized array, the value is zero.  For
5209 @code{sync images (*)}, the value is @math{-1}.
5210 @item @var{images} @tab intent(in)  An array with the images provided by the
5211 user.  If @var{count} is zero, a NULL pointer is passed.
5212 @item @var{stat} @tab intent(out)  Stores the status STAT= and may be NULL.
5213 @item @var{errmsg} @tab intent(out)  When an error occurs, this will be set to
5214 an error message; may be NULL.
5215 @item @var{errmsg_len} @tab intent(in)  the buffer size of errmsg
5216 @end multitable
5217 @end table
5221 @node _gfortran_caf_sync_memory
5222 @subsection @code{_gfortran_caf_sync_memory} --- Wait for completion of segment-memory operations
5223 @cindex Coarray, _gfortran_caf_sync_memory
5225 @table @asis
5226 @item @emph{Description}:
5227 Acts as optimization barrier between different segments. It also ensures that
5228 all pending memory operations of this image have been completed.
5230 @item @emph{Syntax}:
5231 @code{void _gfortran_caf_sync_memory (int *stat, char *errmsg, size_t errmsg_len)}
5233 @item @emph{Arguments}:
5234 @multitable @columnfractions .15 .70
5235 @item @var{stat} @tab intent(out)  Stores the status STAT= and may be NULL.
5236 @item @var{errmsg} @tab intent(out)  When an error occurs, this will be set to
5237 an error message; may be NULL.
5238 @item @var{errmsg_len} @tab intent(in)  the buffer size of errmsg
5239 @end multitable
5241 @item @emph{NOTE} A simple implementation could be
5242 @code{__asm__ __volatile__ ("":::"memory")} to prevent code movements.
5243 @end table
5247 @node _gfortran_caf_error_stop
5248 @subsection @code{_gfortran_caf_error_stop} --- Error termination with exit code
5249 @cindex Coarray, _gfortran_caf_error_stop
5251 @table @asis
5252 @item @emph{Description}:
5253 Invoked for an @code{ERROR STOP} statement which has an integer argument.  The
5254 function should terminate the program with the specified exit code.
5257 @item @emph{Syntax}:
5258 @code{void _gfortran_caf_error_stop (int error)}
5260 @item @emph{Arguments}:
5261 @multitable @columnfractions .15 .70
5262 @item @var{error} @tab intent(in)  The exit status to be used.
5263 @end multitable
5264 @end table
5268 @node _gfortran_caf_error_stop_str
5269 @subsection @code{_gfortran_caf_error_stop_str} --- Error termination with string
5270 @cindex Coarray, _gfortran_caf_error_stop_str
5272 @table @asis
5273 @item @emph{Description}:
5274 Invoked for an @code{ERROR STOP} statement which has a string as argument.  The
5275 function should terminate the program with a nonzero-exit code.
5277 @item @emph{Syntax}:
5278 @code{void _gfortran_caf_error_stop (const char *string, size_t len)}
5280 @item @emph{Arguments}:
5281 @multitable @columnfractions .15 .70
5282 @item @var{string} @tab intent(in)  the error message (not zero terminated)
5283 @item @var{len} @tab intent(in)  the length of the string
5284 @end multitable
5285 @end table
5289 @node _gfortran_caf_fail_image
5290 @subsection @code{_gfortran_caf_fail_image} --- Mark the image failed and end its execution
5291 @cindex Coarray, _gfortran_caf_fail_image
5293 @table @asis
5294 @item @emph{Description}:
5295 Invoked for an @code{FAIL IMAGE} statement.  The function should terminate the
5296 current image.
5298 @item @emph{Syntax}:
5299 @code{void _gfortran_caf_fail_image ()}
5301 @item @emph{NOTES}
5302 This function follows TS18508.
5303 @end table
5307 @node _gfortran_caf_atomic_define
5308 @subsection @code{_gfortran_caf_atomic_define} --- Atomic variable assignment
5309 @cindex Coarray, _gfortran_caf_atomic_define
5311 @table @asis
5312 @item @emph{Description}:
5313 Assign atomically a value to an integer or logical variable.
5315 @item @emph{Syntax}:
5316 @code{void _gfortran_caf_atomic_define (caf_token_t token, size_t offset,
5317 int image_index, void *value, int *stat, int type, int kind)}
5319 @item @emph{Arguments}:
5320 @multitable @columnfractions .15 .70
5321 @item @var{token} @tab intent(in)  An opaque pointer identifying the coarray.
5322 @item @var{offset} @tab intent(in)  By which amount of bytes the actual data is
5323 shifted compared to the base address of the coarray.
5324 @item @var{image_index} @tab intent(in)  The ID of the remote image; must be a
5325 positive number; zero indicates the current image when used noncoindexed.
5326 @item @var{value} @tab intent(in)  the value to be assigned, passed by reference
5327 @item @var{stat} @tab intent(out)  Stores the status STAT= and may be NULL.
5328 @item @var{type} @tab intent(in)  The data type, i.e. @code{BT_INTEGER} (1) or
5329 @code{BT_LOGICAL} (2).
5330 @item @var{kind} @tab intent(in)  The kind value (only 4; always @code{int})
5331 @end multitable
5332 @end table
5336 @node _gfortran_caf_atomic_ref
5337 @subsection @code{_gfortran_caf_atomic_ref} --- Atomic variable reference
5338 @cindex Coarray, _gfortran_caf_atomic_ref
5340 @table @asis
5341 @item @emph{Description}:
5342 Reference atomically a value of a kind-4 integer or logical variable.
5344 @item @emph{Syntax}:
5345 @code{void _gfortran_caf_atomic_ref (caf_token_t token, size_t offset,
5346 int image_index, void *value, int *stat, int type, int kind)}
5348 @item @emph{Arguments}:
5349 @multitable @columnfractions .15 .70
5350 @item @var{token} @tab intent(in)  An opaque pointer identifying the coarray.
5351 @item @var{offset} @tab intent(in)  By which amount of bytes the actual data is
5352 shifted compared to the base address of the coarray.
5353 @item @var{image_index} @tab intent(in)  The ID of the remote image; must be a
5354 positive number; zero indicates the current image when used noncoindexed.
5355 @item @var{value} @tab intent(out)  The variable assigned the atomically
5356 referenced variable.
5357 @item @var{stat} @tab intent(out) Stores the status STAT= and may be NULL.
5358 @item @var{type} @tab the data type, i.e. @code{BT_INTEGER} (1) or
5359 @code{BT_LOGICAL} (2).
5360 @item @var{kind} @tab The kind value (only 4; always @code{int})
5361 @end multitable
5362 @end table
5366 @node _gfortran_caf_atomic_cas
5367 @subsection @code{_gfortran_caf_atomic_cas} --- Atomic compare and swap
5368 @cindex Coarray, _gfortran_caf_atomic_cas
5370 @table @asis
5371 @item @emph{Description}:
5372 Atomic compare and swap of a kind-4 integer or logical variable. Assigns
5373 atomically the specified value to the atomic variable, if the latter has
5374 the value specified by the passed condition value.
5376 @item @emph{Syntax}:
5377 @code{void _gfortran_caf_atomic_cas (caf_token_t token, size_t offset,
5378 int image_index, void *old, void *compare, void *new_val, int *stat,
5379 int type, int kind)}
5381 @item @emph{Arguments}:
5382 @multitable @columnfractions .15 .70
5383 @item @var{token} @tab intent(in)  An opaque pointer identifying the coarray.
5384 @item @var{offset} @tab intent(in)  By which amount of bytes the actual data is
5385 shifted compared to the base address of the coarray.
5386 @item @var{image_index} @tab intent(in)  The ID of the remote image; must be a
5387 positive number; zero indicates the current image when used noncoindexed.
5388 @item @var{old} @tab intent(out)  The value which the atomic variable had
5389 just before the cas operation.
5390 @item @var{compare} @tab intent(in)  The value used for comparision.
5391 @item @var{new_val} @tab intent(in)  The new value for the atomic variable,
5392 assigned to the atomic variable, if @code{compare} equals the value of the
5393 atomic variable.
5394 @item @var{stat} @tab intent(out)  Stores the status STAT= and may be NULL.
5395 @item @var{type} @tab intent(in)  the data type, i.e. @code{BT_INTEGER} (1) or
5396 @code{BT_LOGICAL} (2).
5397 @item @var{kind} @tab intent(in)  The kind value (only 4; always @code{int})
5398 @end multitable
5399 @end table
5403 @node _gfortran_caf_atomic_op
5404 @subsection @code{_gfortran_caf_atomic_op} --- Atomic operation
5405 @cindex Coarray, _gfortran_caf_atomic_op
5407 @table @asis
5408 @item @emph{Description}:
5409 Apply an operation atomically to an atomic integer or logical variable.
5410 After the operation, @var{old} contains the value just before the operation,
5411 which, respectively, adds (GFC_CAF_ATOMIC_ADD) atomically the @code{value} to
5412 the atomic integer variable or does a bitwise AND, OR or exclusive OR
5413 between the atomic variable and @var{value}; the result is then stored in the
5414 atomic variable.
5416 @item @emph{Syntax}:
5417 @code{void _gfortran_caf_atomic_op (int op, caf_token_t token, size_t offset,
5418 int image_index, void *value, void *old, int *stat, int type, int kind)}
5420 @item @emph{Arguments}:
5421 @multitable @columnfractions .15 .70
5422 @item @var{op} @tab intent(in)  the operation to be performed; possible values
5423 @code{GFC_CAF_ATOMIC_ADD} (1), @code{GFC_CAF_ATOMIC_AND} (2),
5424 @code{GFC_CAF_ATOMIC_OR} (3), @code{GFC_CAF_ATOMIC_XOR} (4).
5425 @item @var{token} @tab intent(in)  An opaque pointer identifying the coarray.
5426 @item @var{offset} @tab intent(in)  By which amount of bytes the actual data is
5427 shifted compared to the base address of the coarray.
5428 @item @var{image_index} @tab intent(in)  The ID of the remote image; must be a
5429 positive number; zero indicates the current image when used noncoindexed.
5430 @item @var{old} @tab intent(out)  The value which the atomic variable had
5431 just before the atomic operation.
5432 @item @var{val} @tab intent(in)  The new value for the atomic variable,
5433 assigned to the atomic variable, if @code{compare} equals the value of the
5434 atomic variable.
5435 @item @var{stat} @tab intent(out)  Stores the status STAT= and may be NULL.
5436 @item @var{type} @tab intent(in)  the data type, i.e. @code{BT_INTEGER} (1) or
5437 @code{BT_LOGICAL} (2)
5438 @item @var{kind} @tab intent(in)  the kind value (only 4; always @code{int})
5439 @end multitable
5440 @end table
5445 @node _gfortran_caf_co_broadcast
5446 @subsection @code{_gfortran_caf_co_broadcast} --- Sending data to all images
5447 @cindex Coarray, _gfortran_caf_co_broadcast
5449 @table @asis
5450 @item @emph{Description}:
5451 Distribute a value from a given image to all other images in the team. Has to
5452 be called collectively.
5454 @item @emph{Syntax}:
5455 @code{void _gfortran_caf_co_broadcast (gfc_descriptor_t *a,
5456 int source_image, int *stat, char *errmsg, size_t errmsg_len)}
5458 @item @emph{Arguments}:
5459 @multitable @columnfractions .15 .70
5460 @item @var{a} @tab intent(inout)  An array descriptor with the data to be
5461 broadcasted (on @var{source_image}) or to be received (other images).
5462 @item @var{source_image} @tab intent(in)  The ID of the image from which the
5463 data should be broadcasted.
5464 @item @var{stat} @tab intent(out)  Stores the status STAT= and may be NULL.
5465 @item @var{errmsg} @tab intent(out)  When an error occurs, this will be set to
5466 an error message; may be NULL.
5467 @item @var{errmsg_len} @tab intent(in)  the buffer size of errmsg.
5468 @end multitable
5469 @end table
5473 @node _gfortran_caf_co_max
5474 @subsection @code{_gfortran_caf_co_max} --- Collective maximum reduction
5475 @cindex Coarray, _gfortran_caf_co_max
5477 @table @asis
5478 @item @emph{Description}:
5479 Calculates for each array element of the variable @var{a} the maximum
5480 value for that element in the current team; if @var{result_image} has the
5481 value 0, the result shall be stored on all images, otherwise, only on the
5482 specified image. This function operates on numeric values and character
5483 strings.
5485 @item @emph{Syntax}:
5486 @code{void _gfortran_caf_co_max (gfc_descriptor_t *a, int result_image,
5487 int *stat, char *errmsg, int a_len, size_t errmsg_len)}
5489 @item @emph{Arguments}:
5490 @multitable @columnfractions .15 .70
5491 @item @var{a} @tab intent(inout)  An array descriptor for the data to be
5492 processed.  On the destination image(s) the result overwrites the old content.
5493 @item @var{result_image} @tab intent(in)  The ID of the image to which the
5494 reduced value should be copied to; if zero, it has to be copied to all images.
5495 @item @var{stat} @tab intent(out)  Stores the status STAT= and may be NULL.
5496 @item @var{errmsg} @tab intent(out)  When an error occurs, this will be set to
5497 an error message; may be NULL.
5498 @item @var{a_len} @tab intent(in)  the string length of argument @var{a}
5499 @item @var{errmsg_len} @tab intent(in)  the buffer size of errmsg
5500 @end multitable
5502 @item @emph{NOTES}
5503 If @var{result_image} is nonzero, the data in the array descriptor @var{a} on
5504 all images except of the specified one become undefined; hence, the library may
5505 make use of this.
5506 @end table
5510 @node _gfortran_caf_co_min
5511 @subsection @code{_gfortran_caf_co_min} --- Collective minimum reduction
5512 @cindex Coarray, _gfortran_caf_co_min
5514 @table @asis
5515 @item @emph{Description}:
5516 Calculates for each array element of the variable @var{a} the minimum
5517 value for that element in the current team; if @var{result_image} has the
5518 value 0, the result shall be stored on all images, otherwise, only on the
5519 specified image. This function operates on numeric values and character
5520 strings.
5522 @item @emph{Syntax}:
5523 @code{void _gfortran_caf_co_min (gfc_descriptor_t *a, int result_image,
5524 int *stat, char *errmsg, int a_len, size_t errmsg_len)}
5526 @item @emph{Arguments}:
5527 @multitable @columnfractions .15 .70
5528 @item @var{a} @tab intent(inout)  An array descriptor for the data to be
5529 processed.  On the destination image(s) the result overwrites the old content.
5530 @item @var{result_image} @tab intent(in)  The ID of the image to which the
5531 reduced value should be copied to; if zero, it has to be copied to all images.
5532 @item @var{stat} @tab intent(out)  Stores the status STAT= and may be NULL.
5533 @item @var{errmsg} @tab intent(out)  When an error occurs, this will be set to
5534 an error message; may be NULL.
5535 @item @var{a_len} @tab intent(in)  the string length of argument @var{a}
5536 @item @var{errmsg_len} @tab intent(in)  the buffer size of errmsg
5537 @end multitable
5539 @item @emph{NOTES}
5540 If @var{result_image} is nonzero, the data in the array descriptor @var{a} on
5541 all images except of the specified one become undefined; hence, the library may
5542 make use of this.
5543 @end table
5547 @node _gfortran_caf_co_sum
5548 @subsection @code{_gfortran_caf_co_sum} --- Collective summing reduction
5549 @cindex Coarray, _gfortran_caf_co_sum
5551 @table @asis
5552 @item @emph{Description}:
5553 Calculates for each array element of the variable @var{a} the sum of all
5554 values for that element in the current team; if @var{result_image} has the
5555 value 0, the result shall be stored on all images, otherwise, only on the
5556 specified image.  This function operates on numeric values only.
5558 @item @emph{Syntax}:
5559 @code{void _gfortran_caf_co_sum (gfc_descriptor_t *a, int result_image,
5560 int *stat, char *errmsg, size_t errmsg_len)}
5562 @item @emph{Arguments}:
5563 @multitable @columnfractions .15 .70
5564 @item @var{a} @tab intent(inout)  An array descriptor with the data to be
5565 processed.  On the destination image(s) the result overwrites the old content.
5566 @item @var{result_image} @tab intent(in)  The ID of the image to which the
5567 reduced value should be copied to; if zero, it has to be copied to all images.
5568 @item @var{stat} @tab intent(out)  Stores the status STAT= and may be NULL.
5569 @item @var{errmsg} @tab intent(out)  When an error occurs, this will be set to
5570 an error message; may be NULL.
5571 @item @var{errmsg_len} @tab intent(in)  the buffer size of errmsg
5572 @end multitable
5574 @item @emph{NOTES}
5575 If @var{result_image} is nonzero, the data in the array descriptor @var{a} on
5576 all images except of the specified one become undefined; hence, the library may
5577 make use of this.
5578 @end table
5582 @node _gfortran_caf_co_reduce
5583 @subsection @code{_gfortran_caf_co_reduce} --- Generic collective reduction
5584 @cindex Coarray, _gfortran_caf_co_reduce
5586 @table @asis
5587 @item @emph{Description}:
5588 Calculates for each array element of the variable @var{a} the reduction
5589 value for that element in the current team; if @var{result_image} has the
5590 value 0, the result shall be stored on all images, otherwise, only on the
5591 specified image.  The @var{opr} is a pure function doing a mathematically
5592 commutative and associative operation.
5594 The @var{opr_flags} denote the following; the values are bitwise ored.
5595 @code{GFC_CAF_BYREF} (1) if the result should be returned
5596 by reference; @code{GFC_CAF_HIDDENLEN} (2) whether the result and argument
5597 string lengths shall be specified as hidden arguments;
5598 @code{GFC_CAF_ARG_VALUE} (4) whether the arguments shall be passed by value,
5599 @code{GFC_CAF_ARG_DESC} (8) whether the arguments shall be passed by descriptor.
5602 @item @emph{Syntax}:
5603 @code{void _gfortran_caf_co_reduce (gfc_descriptor_t *a,
5604 void * (*opr) (void *, void *), int opr_flags, int result_image,
5605 int *stat, char *errmsg, int a_len, size_t errmsg_len)}
5607 @item @emph{Arguments}:
5608 @multitable @columnfractions .15 .70
5609 @item @var{a} @tab intent(inout)  An array descriptor with the data to be
5610 processed.  On the destination image(s) the result overwrites the old content.
5611 @item @var{opr} @tab intent(in)  Function pointer to the reduction function
5612 @item @var{opr_flags} @tab intent(in)  Flags regarding the reduction function
5613 @item @var{result_image} @tab intent(in)  The ID of the image to which the
5614 reduced value should be copied to; if zero, it has to be copied to all images.
5615 @item @var{stat} @tab intent(out)  Stores the status STAT= and may be NULL.
5616 @item @var{errmsg} @tab intent(out)  When an error occurs, this will be set to
5617 an error message; may be NULL.
5618 @item @var{a_len} @tab intent(in)  the string length of argument @var{a}
5619 @item @var{errmsg_len} @tab intent(in)  the buffer size of errmsg
5620 @end multitable
5622 @item @emph{NOTES}
5623 If @var{result_image} is nonzero, the data in the array descriptor @var{a} on
5624 all images except of the specified one become undefined; hence, the library may
5625 make use of this.
5627 For character arguments, the result is passed as first argument, followed
5628 by the result string length, next come the two string arguments, followed
5629 by the two hidden string length arguments.  With C binding, there are no hidden
5630 arguments and by-reference passing and either only a single character is passed
5631 or an array descriptor.
5632 @end table
5635 @c Intrinsic Procedures
5636 @c ---------------------------------------------------------------------
5638 @include intrinsic.texi
5641 @tex
5642 \blankpart
5643 @end tex
5645 @c ---------------------------------------------------------------------
5646 @c Contributing
5647 @c ---------------------------------------------------------------------
5649 @node Contributing
5650 @unnumbered Contributing
5651 @cindex Contributing
5653 Free software is only possible if people contribute to efforts
5654 to create it.
5655 We're always in need of more people helping out with ideas
5656 and comments, writing documentation and contributing code.
5658 If you want to contribute to GNU Fortran,
5659 have a look at the long lists of projects you can take on.
5660 Some of these projects are small,
5661 some of them are large;
5662 some are completely orthogonal to the rest of what is
5663 happening on GNU Fortran,
5664 but others are ``mainstream'' projects in need of enthusiastic hackers.
5665 All of these projects are important!
5666 We will eventually get around to the things here,
5667 but they are also things doable by someone who is willing and able.
5669 @menu
5670 * Contributors::
5671 * Projects::
5672 * Proposed Extensions::
5673 @end menu
5676 @node Contributors
5677 @section Contributors to GNU Fortran
5678 @cindex Contributors
5679 @cindex Credits
5680 @cindex Authors
5682 Most of the parser was hand-crafted by @emph{Andy Vaught}, who is
5683 also the initiator of the whole project.  Thanks Andy!
5684 Most of the interface with GCC was written by @emph{Paul Brook}.
5686 The following individuals have contributed code and/or
5687 ideas and significant help to the GNU Fortran project
5688 (in alphabetical order):
5690 @itemize @minus
5691 @item Janne Blomqvist
5692 @item Steven Bosscher
5693 @item Paul Brook
5694 @item Tobias Burnus
5695 @item Fran@,{c}ois-Xavier Coudert
5696 @item Bud Davis
5697 @item Jerry DeLisle
5698 @item Erik Edelmann
5699 @item Bernhard Fischer
5700 @item Daniel Franke
5701 @item Richard Guenther
5702 @item Richard Henderson
5703 @item Katherine Holcomb
5704 @item Jakub Jelinek
5705 @item Niels Kristian Bech Jensen
5706 @item Steven Johnson
5707 @item Steven G. Kargl
5708 @item Thomas Koenig
5709 @item Asher Langton
5710 @item H. J. Lu
5711 @item Toon Moene
5712 @item Brooks Moses
5713 @item Andrew Pinski
5714 @item Tim Prince
5715 @item Christopher D. Rickett
5716 @item Richard Sandiford
5717 @item Tobias Schl@"uter
5718 @item Roger Sayle
5719 @item Paul Thomas
5720 @item Andy Vaught
5721 @item Feng Wang
5722 @item Janus Weil
5723 @item Daniel Kraft
5724 @end itemize
5726 The following people have contributed bug reports,
5727 smaller or larger patches,
5728 and much needed feedback and encouragement for the
5729 GNU Fortran project: 
5731 @itemize @minus
5732 @item Bill Clodius
5733 @item Dominique d'Humi@`eres
5734 @item Kate Hedstrom
5735 @item Erik Schnetter
5736 @item Joost VandeVondele
5737 @end itemize
5739 Many other individuals have helped debug,
5740 test and improve the GNU Fortran compiler over the past few years,
5741 and we welcome you to do the same!
5742 If you already have done so,
5743 and you would like to see your name listed in the
5744 list above, please contact us.
5747 @node Projects
5748 @section Projects
5750 @table @emph
5752 @item Help build the test suite
5753 Solicit more code for donation to the test suite: the more extensive the
5754 testsuite, the smaller the risk of breaking things in the future! We can
5755 keep code private on request.
5757 @item Bug hunting/squishing
5758 Find bugs and write more test cases! Test cases are especially very
5759 welcome, because it allows us to concentrate on fixing bugs instead of
5760 isolating them.  Going through the bugzilla database at
5761 @url{https://gcc.gnu.org/@/bugzilla/} to reduce testcases posted there and
5762 add more information (for example, for which version does the testcase
5763 work, for which versions does it fail?) is also very helpful.
5765 @end table
5768 @node Proposed Extensions
5769 @section Proposed Extensions
5771 Here's a list of proposed extensions for the GNU Fortran compiler, in no particular
5772 order.  Most of these are necessary to be fully compatible with
5773 existing Fortran compilers, but they are not part of the official
5774 J3 Fortran 95 standard.
5776 @subsection Compiler extensions:
5777 @itemize @bullet
5778 @item
5779 User-specified alignment rules for structures.
5781 @item
5782 Automatically extend single precision constants to double.
5784 @item
5785 Compile code that conserves memory by dynamically allocating common and
5786 module storage either on stack or heap.
5788 @item
5789 Compile flag to generate code for array conformance checking (suggest -CC).
5791 @item
5792 User control of symbol names (underscores, etc).
5794 @item
5795 Compile setting for maximum size of stack frame size before spilling
5796 parts to static or heap.
5798 @item
5799 Flag to force local variables into static space.
5801 @item
5802 Flag to force local variables onto stack.
5803 @end itemize
5806 @subsection Environment Options
5807 @itemize @bullet
5808 @item
5809 Pluggable library modules for random numbers, linear algebra.
5810 LA should use BLAS calling conventions.
5812 @item
5813 Environment variables controlling actions on arithmetic exceptions like
5814 overflow, underflow, precision loss---Generate NaN, abort, default.
5815 action.
5817 @item
5818 Set precision for fp units that support it (i387).
5820 @item
5821 Variable for setting fp rounding mode.
5823 @item
5824 Variable to fill uninitialized variables with a user-defined bit
5825 pattern.
5827 @item
5828 Environment variable controlling filename that is opened for that unit
5829 number.
5831 @item
5832 Environment variable to clear/trash memory being freed.
5834 @item
5835 Environment variable to control tracing of allocations and frees.
5837 @item
5838 Environment variable to display allocated memory at normal program end.
5840 @item
5841 Environment variable for filename for * IO-unit.
5843 @item
5844 Environment variable for temporary file directory.
5846 @item
5847 Environment variable forcing standard output to be line buffered (Unix).
5849 @end itemize
5852 @c ---------------------------------------------------------------------
5853 @c GNU General Public License
5854 @c ---------------------------------------------------------------------
5856 @include gpl_v3.texi
5860 @c ---------------------------------------------------------------------
5861 @c GNU Free Documentation License
5862 @c ---------------------------------------------------------------------
5864 @include fdl.texi
5868 @c ---------------------------------------------------------------------
5869 @c Funding Free Software
5870 @c ---------------------------------------------------------------------
5872 @include funding.texi
5874 @c ---------------------------------------------------------------------
5875 @c Indices
5876 @c ---------------------------------------------------------------------
5878 @node Option Index
5879 @unnumbered Option Index
5880 @command{gfortran}'s command line options are indexed here without any
5881 initial @samp{-} or @samp{--}.  Where an option has both positive and
5882 negative forms (such as -foption and -fno-option), relevant entries in
5883 the manual are indexed under the most appropriate form; it may sometimes
5884 be useful to look up both forms.
5885 @printindex op
5887 @node Keyword Index
5888 @unnumbered Keyword Index
5889 @printindex cp
5891 @bye