PR tree-optimization/86415 - strlen() not folded for substrings within constant arrays
[official-gcc.git] / gcc / fortran / gfortran.texi
blob1aa2bb2f0c684bbb0ad628e877a4477a5ad3fe2d
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 syntax; however, the
883 data transfer is currently always synchronously performed. 
885 @item
886 @cindex @code{FLUSH} statement
887 @cindex statement, @code{FLUSH}
888 @code{FLUSH} statement.
890 @item
891 @cindex @code{IOMSG=} specifier
892 @code{IOMSG=} specifier for I/O statements.
894 @item
895 @cindex @code{ENUM} statement
896 @cindex @code{ENUMERATOR} statement
897 @cindex statement, @code{ENUM}
898 @cindex statement, @code{ENUMERATOR}
899 @opindex @code{fshort-enums}
900 Support for the declaration of enumeration constants via the
901 @code{ENUM} and @code{ENUMERATOR} statements.  Interoperability with
902 @command{gcc} is guaranteed also for the case where the
903 @command{-fshort-enums} command line option is given.
905 @item
906 @cindex TR 15581
907 TR 15581:
908 @itemize
909 @item
910 @cindex @code{ALLOCATABLE} dummy arguments
911 @code{ALLOCATABLE} dummy arguments.
912 @item
913 @cindex @code{ALLOCATABLE} function results
914 @code{ALLOCATABLE} function results
915 @item
916 @cindex @code{ALLOCATABLE} components of derived types
917 @code{ALLOCATABLE} components of derived types
918 @end itemize
920 @item
921 @cindex @code{STREAM} I/O
922 @cindex @code{ACCESS='STREAM'} I/O
923 The @code{OPEN} statement supports the @code{ACCESS='STREAM'} specifier,
924 allowing I/O without any record structure.
926 @item
927 Namelist input/output for internal files.
929 @item Minor I/O features: Rounding during formatted output, using of
930 a decimal comma instead of a decimal point, setting whether a plus sign
931 should appear for positive numbers. On systems where @code{strtod} honours
932 the rounding mode, the rounding mode is also supported for input.
934 @item
935 @cindex @code{PROTECTED} statement
936 @cindex statement, @code{PROTECTED}
937 The @code{PROTECTED} statement and attribute.
939 @item
940 @cindex @code{VALUE} statement
941 @cindex statement, @code{VALUE}
942 The @code{VALUE} statement and attribute.
944 @item
945 @cindex @code{VOLATILE} statement
946 @cindex statement, @code{VOLATILE}
947 The @code{VOLATILE} statement and attribute.
949 @item
950 @cindex @code{IMPORT} statement
951 @cindex statement, @code{IMPORT}
952 The @code{IMPORT} statement, allowing to import
953 host-associated derived types.
955 @item The intrinsic modules @code{ISO_FORTRAN_ENVIRONMENT} is supported,
956 which contains parameters of the I/O units, storage sizes. Additionally,
957 procedures for C interoperability are available in the @code{ISO_C_BINDING}
958 module.
960 @item
961 @cindex @code{USE, INTRINSIC} statement
962 @cindex statement, @code{USE, INTRINSIC}
963 @cindex @code{ISO_FORTRAN_ENV} statement
964 @cindex statement, @code{ISO_FORTRAN_ENV}
965 @code{USE} statement with @code{INTRINSIC} and @code{NON_INTRINSIC}
966 attribute; supported intrinsic modules: @code{ISO_FORTRAN_ENV},
967 @code{ISO_C_BINDING}, @code{OMP_LIB} and @code{OMP_LIB_KINDS},
968 and @code{OPENACC}.
970 @item
971 Renaming of operators in the @code{USE} statement.
973 @end itemize
976 @node Fortran 2008 status
977 @section Fortran 2008 status
979 The latest version of the Fortran standard is ISO/IEC 1539-1:2010, informally
980 known as Fortran 2008.  The official version is available from International
981 Organization for Standardization (ISO) or its national member organizations.
982 The the final draft (FDIS) can be downloaded free of charge from
983 @url{http://www.nag.co.uk/@/sc22wg5/@/links.html}.  Fortran is developed by the
984 Working Group 5 of Sub-Committee 22 of the Joint Technical Committee 1 of the
985 International Organization for Standardization and the International
986 Electrotechnical Commission (IEC).  This group is known as
987 @uref{http://www.nag.co.uk/sc22wg5/, WG5}.
989 The GNU Fortran compiler supports several of the new features of Fortran 2008;
990 the @uref{https://gcc.gnu.org/wiki/Fortran2008Status, wiki} has some information
991 about the current Fortran 2008 implementation status.  In particular, the
992 following is implemented.
994 @itemize
995 @item The @option{-std=f2008} option and support for the file extensions 
996 @file{.f08} and @file{.F08}.
998 @item The @code{OPEN} statement now supports the @code{NEWUNIT=} option,
999 which returns a unique file unit, thus preventing inadvertent use of the
1000 same unit in different parts of the program.
1002 @item The @code{g0} format descriptor and unlimited format items.
1004 @item The mathematical intrinsics @code{ASINH}, @code{ACOSH}, @code{ATANH},
1005 @code{ERF}, @code{ERFC}, @code{GAMMA}, @code{LOG_GAMMA}, @code{BESSEL_J0},
1006 @code{BESSEL_J1}, @code{BESSEL_JN}, @code{BESSEL_Y0}, @code{BESSEL_Y1},
1007 @code{BESSEL_YN}, @code{HYPOT}, @code{NORM2}, and @code{ERFC_SCALED}.
1009 @item Using complex arguments with @code{TAN}, @code{SINH}, @code{COSH},
1010 @code{TANH}, @code{ASIN}, @code{ACOS}, and @code{ATAN} is now possible;
1011 @code{ATAN}(@var{Y},@var{X}) is now an alias for @code{ATAN2}(@var{Y},@var{X}).
1013 @item Support of the @code{PARITY} intrinsic functions.
1015 @item The following bit intrinsics: @code{LEADZ} and @code{TRAILZ} for
1016 counting the number of leading and trailing zero bits, @code{POPCNT} and
1017 @code{POPPAR} for counting the number of one bits and returning the parity;
1018 @code{BGE}, @code{BGT}, @code{BLE}, and @code{BLT} for bitwise comparisons;
1019 @code{DSHIFTL} and @code{DSHIFTR} for combined left and right shifts,
1020 @code{MASKL} and @code{MASKR} for simple left and right justified masks,
1021 @code{MERGE_BITS} for a bitwise merge using a mask, @code{SHIFTA},
1022 @code{SHIFTL} and @code{SHIFTR} for shift operations, and the
1023 transformational bit intrinsics @code{IALL}, @code{IANY} and @code{IPARITY}.
1025 @item Support of the @code{EXECUTE_COMMAND_LINE} intrinsic subroutine.
1027 @item Support for the @code{STORAGE_SIZE} intrinsic inquiry function.
1029 @item The @code{INT@{8,16,32@}} and @code{REAL@{32,64,128@}} kind type
1030 parameters and the array-valued named constants @code{INTEGER_KINDS},
1031 @code{LOGICAL_KINDS}, @code{REAL_KINDS} and @code{CHARACTER_KINDS} of
1032 the intrinsic module @code{ISO_FORTRAN_ENV}.
1034 @item The module procedures @code{C_SIZEOF} of the intrinsic module
1035 @code{ISO_C_BINDINGS} and @code{COMPILER_VERSION} and @code{COMPILER_OPTIONS}
1036 of @code{ISO_FORTRAN_ENV}.
1038 @item Coarray support for serial programs with @option{-fcoarray=single} flag
1039 and experimental support for multiple images with the @option{-fcoarray=lib}
1040 flag.
1042 @item Submodules are supported. It should noted that @code{MODULEs} do not
1043 produce the smod file needed by the descendent @code{SUBMODULEs} unless they
1044 contain at least one @code{MODULE PROCEDURE} interface. The reason for this is
1045 that @code{SUBMODULEs} are useless without @code{MODULE PROCEDUREs}. See
1046 http://j3-fortran.org/doc/meeting/207/15-209.txt for a discussion and a draft
1047 interpretation. Adopting this interpretation has the advantage that code that
1048 does not use submodules does not generate smod files.
1050 @item The @code{DO CONCURRENT} construct is supported.
1052 @item The @code{BLOCK} construct is supported.
1054 @item The @code{STOP} and the new @code{ERROR STOP} statements now
1055 support all constant expressions. Both show the signals which were signaling
1056 at termination.
1058 @item Support for the @code{CONTIGUOUS} attribute.
1060 @item Support for @code{ALLOCATE} with @code{MOLD}.
1062 @item Support for the @code{IMPURE} attribute for procedures, which
1063 allows for @code{ELEMENTAL} procedures without the restrictions of
1064 @code{PURE}.
1066 @item Null pointers (including @code{NULL()}) and not-allocated variables
1067 can be used as actual argument to optional non-pointer, non-allocatable
1068 dummy arguments, denoting an absent argument.
1070 @item Non-pointer variables with @code{TARGET} attribute can be used as
1071 actual argument to @code{POINTER} dummies with @code{INTENT(IN)}.
1073 @item Pointers including procedure pointers and those in a derived
1074 type (pointer components) can now be initialized by a target instead
1075 of only by @code{NULL}.
1077 @item The @code{EXIT} statement (with construct-name) can be now be
1078 used to leave not only the @code{DO} but also the @code{ASSOCIATE},
1079 @code{BLOCK}, @code{IF}, @code{SELECT CASE} and @code{SELECT TYPE}
1080 constructs.
1082 @item Internal procedures can now be used as actual argument.
1084 @item Minor features: obsolesce diagnostics for @code{ENTRY} with
1085 @option{-std=f2008}; a line may start with a semicolon; for internal
1086 and module procedures @code{END} can be used instead of
1087 @code{END SUBROUTINE} and @code{END FUNCTION}; @code{SELECTED_REAL_KIND}
1088 now also takes a @code{RADIX} argument; intrinsic types are supported
1089 for @code{TYPE}(@var{intrinsic-type-spec}); multiple type-bound procedures
1090 can be declared in a single @code{PROCEDURE} statement; implied-shape
1091 arrays are supported for named constants (@code{PARAMETER}).
1092 @end itemize
1096 @node Fortran 2018 status
1097 @section Status of Fortran 2018 support
1099 So far very little work has been done to support Fortran 2018.
1101 @itemize
1102 @item ERROR STOP in a PURE procedure
1103 An @code{ERROR STOP} statement is permitted in a @code{PURE}
1104 procedure.
1106 @item IMPLICIT NONE with a spec-list
1107 Support the @code{IMPLICIT NONE} statement with an
1108 @code{implicit-none-spec-list}.
1110 @item Behavior of INQUIRE with the RECL= specifier
1112 The behavior of the @code{INQUIRE} statement with the @code{RECL=}
1113 specifier now conforms to Fortran 2018.
1115 @end itemize
1118 @subsection TS 29113 Status (Further Interoperability with C)
1120 GNU Fortran supports some of the new features of the Technical
1121 Specification (TS) 29113 on Further Interoperability of Fortran with C.
1122 The @uref{https://gcc.gnu.org/wiki/TS29113Status, wiki} has some information
1123 about the current TS 29113 implementation status.  In particular, the
1124 following is implemented.
1126 See also @ref{Further Interoperability of Fortran with C}.
1128 @itemize
1129 @item The @code{OPTIONAL} attribute is allowed for dummy arguments
1130 of @code{BIND(C) procedures.}
1132 @item The @code{RANK} intrinsic is supported.
1134 @item GNU Fortran's implementation for variables with @code{ASYNCHRONOUS}
1135 attribute is compatible with TS 29113.
1137 @item Assumed types (@code{TYPE(*)}).
1139 @item Assumed-rank (@code{DIMENSION(..)}). However, the array descriptor
1140 of the TS is not yet supported.
1141 @end itemize
1145 @subsection TS 18508 Status (Additional Parallel Features)
1147 GNU Fortran supports the following new features of the Technical
1148 Specification 18508 on Additional Parallel Features in Fortran:
1150 @itemize
1151 @item The new atomic ADD, CAS, FETCH and ADD/OR/XOR, OR and XOR intrinsics.
1153 @item The @code{CO_MIN} and @code{CO_MAX} and @code{SUM} reduction intrinsics.
1154 And the @code{CO_BROADCAST} and @code{CO_REDUCE} intrinsic, except that those
1155 do not support polymorphic types or types with allocatable, pointer or
1156 polymorphic components.
1158 @item Events (@code{EVENT POST}, @code{EVENT WAIT}, @code{EVENT_QUERY})
1160 @item Failed images (@code{FAIL IMAGE}, @code{IMAGE_STATUS},
1161 @code{FAILED_IMAGES}, @code{STOPPED_IMAGES})
1163 @end itemize
1166 @c ---------------------------------------------------------------------
1167 @c Compiler Characteristics
1168 @c ---------------------------------------------------------------------
1170 @node Compiler Characteristics
1171 @chapter Compiler Characteristics
1173 This chapter describes certain characteristics of the GNU Fortran
1174 compiler, that are not specified by the Fortran standard, but which
1175 might in some way or another become visible to the programmer.
1177 @menu
1178 * KIND Type Parameters::
1179 * Internal representation of LOGICAL variables::
1180 * Thread-safety of the runtime library::
1181 * Data consistency and durability::
1182 * Files opened without an explicit ACTION= specifier::
1183 * File operations on symbolic links::
1184 * File format of unformatted sequential files::
1185 @end menu
1188 @node KIND Type Parameters
1189 @section KIND Type Parameters
1190 @cindex kind
1192 The @code{KIND} type parameters supported by GNU Fortran for the primitive
1193 data types are:
1195 @table @code
1197 @item INTEGER
1198 1, 2, 4, 8*, 16*, default: 4**
1200 @item LOGICAL
1201 1, 2, 4, 8*, 16*, default: 4**
1203 @item REAL
1204 4, 8, 10*, 16*, default: 4***
1206 @item COMPLEX
1207 4, 8, 10*, 16*, default: 4***
1209 @item DOUBLE PRECISION
1210 4, 8, 10*, 16*, default: 8***
1212 @item CHARACTER
1213 1, 4, default: 1
1215 @end table
1217 @noindent
1218 * not available on all systems @*
1219 ** unless @option{-fdefault-integer-8} is used @*
1220 *** unless @option{-fdefault-real-8} is used (see @ref{Fortran Dialect Options})
1222 @noindent
1223 The @code{KIND} value matches the storage size in bytes, except for
1224 @code{COMPLEX} where the storage size is twice as much (or both real and
1225 imaginary part are a real value of the given size).  It is recommended to use
1226 the @ref{SELECTED_CHAR_KIND}, @ref{SELECTED_INT_KIND} and
1227 @ref{SELECTED_REAL_KIND} intrinsics or the @code{INT8}, @code{INT16},
1228 @code{INT32}, @code{INT64}, @code{REAL32}, @code{REAL64}, and @code{REAL128}
1229 parameters of the @code{ISO_FORTRAN_ENV} module instead of the concrete values.
1230 The available kind parameters can be found in the constant arrays
1231 @code{CHARACTER_KINDS}, @code{INTEGER_KINDS}, @code{LOGICAL_KINDS} and
1232 @code{REAL_KINDS} in the @ref{ISO_FORTRAN_ENV} module.  For C interoperability,
1233 the kind parameters of the @ref{ISO_C_BINDING} module should be used.
1236 @node Internal representation of LOGICAL variables
1237 @section Internal representation of LOGICAL variables
1238 @cindex logical, variable representation
1240 The Fortran standard does not specify how variables of @code{LOGICAL}
1241 type are represented, beyond requiring that @code{LOGICAL} variables
1242 of default kind have the same storage size as default @code{INTEGER}
1243 and @code{REAL} variables.  The GNU Fortran internal representation is
1244 as follows.
1246 A @code{LOGICAL(KIND=N)} variable is represented as an
1247 @code{INTEGER(KIND=N)} variable, however, with only two permissible
1248 values: @code{1} for @code{.TRUE.} and @code{0} for
1249 @code{.FALSE.}.  Any other integer value results in undefined behavior.
1251 See also @ref{Argument passing conventions} and @ref{Interoperability with C}.
1254 @node Thread-safety of the runtime library
1255 @section Thread-safety of the runtime library
1256 @cindex thread-safety, threads
1258 GNU Fortran can be used in programs with multiple threads, e.g.@: by
1259 using OpenMP, by calling OS thread handling functions via the
1260 @code{ISO_C_BINDING} facility, or by GNU Fortran compiled library code
1261 being called from a multi-threaded program.
1263 The GNU Fortran runtime library, (@code{libgfortran}), supports being
1264 called concurrently from multiple threads with the following
1265 exceptions. 
1267 During library initialization, the C @code{getenv} function is used,
1268 which need not be thread-safe.  Similarly, the @code{getenv}
1269 function is used to implement the @code{GET_ENVIRONMENT_VARIABLE} and
1270 @code{GETENV} intrinsics.  It is the responsibility of the user to
1271 ensure that the environment is not being updated concurrently when any
1272 of these actions are taking place.
1274 The @code{EXECUTE_COMMAND_LINE} and @code{SYSTEM} intrinsics are
1275 implemented with the @code{system} function, which need not be
1276 thread-safe.  It is the responsibility of the user to ensure that
1277 @code{system} is not called concurrently.
1279 For platforms not supporting thread-safe POSIX functions, further
1280 functionality might not be thread-safe.  For details, please consult
1281 the documentation for your operating system.
1283 The GNU Fortran runtime library uses various C library functions that
1284 depend on the locale, such as @code{strtod} and @code{snprintf}.  In
1285 order to work correctly in locale-aware programs that set the locale
1286 using @code{setlocale}, the locale is reset to the default ``C''
1287 locale while executing a formatted @code{READ} or @code{WRITE}
1288 statement.  On targets supporting the POSIX 2008 per-thread locale
1289 functions (e.g. @code{newlocale}, @code{uselocale},
1290 @code{freelocale}), these are used and thus the global locale set
1291 using @code{setlocale} or the per-thread locales in other threads are
1292 not affected.  However, on targets lacking this functionality, the
1293 global LC_NUMERIC locale is set to ``C'' during the formatted I/O.
1294 Thus, on such targets it's not safe to call @code{setlocale}
1295 concurrently from another thread while a Fortran formatted I/O
1296 operation is in progress.  Also, other threads doing something
1297 dependent on the LC_NUMERIC locale might not work correctly if a
1298 formatted I/O operation is in progress in another thread.
1300 @node Data consistency and durability
1301 @section Data consistency and durability
1302 @cindex consistency, durability
1304 This section contains a brief overview of data and metadata
1305 consistency and durability issues when doing I/O.
1307 With respect to durability, GNU Fortran makes no effort to ensure that
1308 data is committed to stable storage. If this is required, the GNU
1309 Fortran programmer can use the intrinsic @code{FNUM} to retrieve the
1310 low level file descriptor corresponding to an open Fortran unit. Then,
1311 using e.g. the @code{ISO_C_BINDING} feature, one can call the
1312 underlying system call to flush dirty data to stable storage, such as
1313 @code{fsync} on POSIX, @code{_commit} on MingW, or @code{fcntl(fd,
1314 F_FULLSYNC, 0)} on Mac OS X. The following example shows how to call
1315 fsync:
1317 @smallexample
1318   ! Declare the interface for POSIX fsync function
1319   interface
1320     function fsync (fd) bind(c,name="fsync")
1321     use iso_c_binding, only: c_int
1322       integer(c_int), value :: fd
1323       integer(c_int) :: fsync
1324     end function fsync
1325   end interface
1327   ! Variable declaration
1328   integer :: ret
1330   ! Opening unit 10
1331   open (10,file="foo")
1333   ! ...
1334   ! Perform I/O on unit 10
1335   ! ...
1337   ! Flush and sync
1338   flush(10)
1339   ret = fsync(fnum(10))
1341   ! Handle possible error
1342   if (ret /= 0) stop "Error calling FSYNC"
1343 @end smallexample
1345 With respect to consistency, for regular files GNU Fortran uses
1346 buffered I/O in order to improve performance. This buffer is flushed
1347 automatically when full and in some other situations, e.g. when
1348 closing a unit. It can also be explicitly flushed with the
1349 @code{FLUSH} statement. Also, the buffering can be turned off with the
1350 @code{GFORTRAN_UNBUFFERED_ALL} and
1351 @code{GFORTRAN_UNBUFFERED_PRECONNECTED} environment variables. Special
1352 files, such as terminals and pipes, are always unbuffered. Sometimes,
1353 however, further things may need to be done in order to allow other
1354 processes to see data that GNU Fortran has written, as follows.
1356 The Windows platform supports a relaxed metadata consistency model,
1357 where file metadata is written to the directory lazily. This means
1358 that, for instance, the @code{dir} command can show a stale size for a
1359 file. One can force a directory metadata update by closing the unit,
1360 or by calling @code{_commit} on the file descriptor. Note, though,
1361 that @code{_commit} will force all dirty data to stable storage, which
1362 is often a very slow operation.
1364 The Network File System (NFS) implements a relaxed consistency model
1365 called open-to-close consistency. Closing a file forces dirty data and
1366 metadata to be flushed to the server, and opening a file forces the
1367 client to contact the server in order to revalidate cached
1368 data. @code{fsync} will also force a flush of dirty data and metadata
1369 to the server. Similar to @code{open} and @code{close}, acquiring and
1370 releasing @code{fcntl} file locks, if the server supports them, will
1371 also force cache validation and flushing dirty data and metadata.
1374 @node Files opened without an explicit ACTION= specifier
1375 @section Files opened without an explicit ACTION= specifier
1376 @cindex open, action
1378 The Fortran standard says that if an @code{OPEN} statement is executed
1379 without an explicit @code{ACTION=} specifier, the default value is
1380 processor dependent.  GNU Fortran behaves as follows:
1382 @enumerate
1383 @item Attempt to open the file with @code{ACTION='READWRITE'}
1384 @item If that fails, try to open with @code{ACTION='READ'}
1385 @item If that fails, try to open with @code{ACTION='WRITE'}
1386 @item If that fails, generate an error
1387 @end enumerate
1390 @node File operations on symbolic links
1391 @section File operations on symbolic links
1392 @cindex file, symbolic link
1394 This section documents the behavior of GNU Fortran for file operations on
1395 symbolic links, on systems that support them. 
1397 @itemize
1399 @item Results of INQUIRE statements of the ``inquire by file'' form will
1400 relate to the target of the symbolic link. For example,
1401 @code{INQUIRE(FILE="foo",EXIST=ex)} will set @var{ex} to @var{.true.} if
1402 @var{foo} is a symbolic link pointing to an existing file, and @var{.false.}
1403 if @var{foo} points to an non-existing file (``dangling'' symbolic link).
1405 @item Using the @code{OPEN} statement with a @code{STATUS="NEW"} specifier
1406 on a symbolic link will result in an error condition, whether the symbolic
1407 link points to an existing target or is dangling.
1409 @item If a symbolic link was connected, using the @code{CLOSE} statement
1410 with a @code{STATUS="DELETE"} specifier will cause the symbolic link itself
1411 to be deleted, not its target.
1413 @end itemize
1415 @node File format of unformatted sequential files
1416 @section File format of unformatted sequential files
1417 @cindex file, unformatted sequential
1418 @cindex unformatted sequential
1419 @cindex sequential, unformatted
1420 @cindex record marker
1421 @cindex subrecord
1423 Unformatted sequential files are stored as logical records using
1424 record markers.  Each logical record consists of one of more
1425 subrecords.
1427 Each subrecord consists of a leading record marker, the data written
1428 by the user program, and a trailing record marker.  The record markers
1429 are four-byte integers by default, and eight-byte integers if the
1430 @option{-fmax-subrecord-length=8} option (which exists for backwards
1431 compability only) is in effect.
1433 The representation of the record markers is that of unformatted files
1434 given with the @option{-fconvert} option, the @xref{CONVERT specifier}
1435 on the open statement or the @xref{GFORTRAN_CONVERT_UNIT} environment
1436 variable.
1438 The maximum number of bytes of user data in a subrecord is 2147483639
1439 (2 GiB - 9) for a four-byte record marker.  This limit can be lowered
1440 with the @option{-fmax-subrecord-length} option, altough this is
1441 rarely useful. If the length of a logical record exceeds this limit,
1442 the data is distributed among several subrecords.
1444 The absolute of the number stored in the record markers is the number
1445 of bytes of user data in the corresponding subrecord.  If the leading
1446 record marker of a subrecord contains a negative number, another
1447 subrecord follows the current one.  If the trailing record marker
1448 contains a negative number, then there is a preceding subrecord.
1450 In the most simple case, with only one subrecord per logical record,
1451 both record markers contain the number of bytes of user data in the
1452 record,
1454 The format for unformatted sequential data can be duplicated using
1455 unformatted stream, as shown in the example program for an unformatted
1456 record containing a single subrecord:
1458 @smallexample
1459 program main
1460   use iso_fortran_env, only: int32
1461   implicit none
1462   integer(int32) :: i 
1463   real, dimension(10) :: a, b
1464   call random_number(a)
1465   open (10,file='test.dat',form='unformatted',access='stream')
1466   inquire (iolength=i) a
1467   write (10) i, a, i
1468   close (10)
1469   open (10,file='test.dat',form='unformatted')
1470   read (10) b
1471   if (all (a == b)) print *,'success!'
1472 end program main
1473 @end smallexample
1475 @c ---------------------------------------------------------------------
1476 @c Extensions
1477 @c ---------------------------------------------------------------------
1479 @c Maybe this chapter should be merged with the 'Standards' section,
1480 @c whenever that is written :-)
1482 @node Extensions
1483 @chapter Extensions
1484 @cindex extensions
1486 The two sections below detail the extensions to standard Fortran that are
1487 implemented in GNU Fortran, as well as some of the popular or
1488 historically important extensions that are not (or not yet) implemented.
1489 For the latter case, we explain the alternatives available to GNU Fortran
1490 users, including replacement by standard-conforming code or GNU
1491 extensions.
1493 @menu
1494 * Extensions implemented in GNU Fortran::
1495 * Extensions not implemented in GNU Fortran::
1496 @end menu
1499 @node Extensions implemented in GNU Fortran
1500 @section Extensions implemented in GNU Fortran
1501 @cindex extensions, implemented
1503 GNU Fortran implements a number of extensions over standard Fortran.
1504 This chapter contains information on their syntax and meaning.  There
1505 are currently two categories of GNU Fortran extensions, those that
1506 provide functionality beyond that provided by any standard, and those
1507 that are supported by GNU Fortran purely for backward compatibility
1508 with legacy compilers.  By default, @option{-std=gnu} allows the
1509 compiler to accept both types of extensions, but to warn about the use
1510 of the latter.  Specifying either @option{-std=f95},
1511 @option{-std=f2003}, @option{-std=f2008}, or @option{-std=f2018}
1512 disables both types of extensions, and @option{-std=legacy} allows
1513 both without warning.  The special compile flag @option{-fdec} enables
1514 additional compatibility extensions along with those enabled by
1515 @option{-std=legacy}.
1517 @menu
1518 * Old-style kind specifications::
1519 * Old-style variable initialization::
1520 * Extensions to namelist::
1521 * X format descriptor without count field::
1522 * Commas in FORMAT specifications::
1523 * Missing period in FORMAT specifications::
1524 * I/O item lists::
1525 * @code{Q} exponent-letter::
1526 * BOZ literal constants::
1527 * Real array indices::
1528 * Unary operators::
1529 * Implicitly convert LOGICAL and INTEGER values::
1530 * Hollerith constants support::
1531 * Cray pointers::
1532 * CONVERT specifier::
1533 * OpenMP::
1534 * OpenACC::
1535 * Argument list functions::
1536 * Read/Write after EOF marker::
1537 * STRUCTURE and RECORD::
1538 * UNION and MAP::
1539 * Type variants for integer intrinsics::
1540 * AUTOMATIC and STATIC attributes::
1541 * Extended math intrinsics::
1542 * Form feed as whitespace::
1543 * TYPE as an alias for PRINT::
1544 * %LOC as an rvalue::
1545 * .XOR. operator::
1546 * Bitwise logical operators::
1547 * Extended I/O specifiers::
1548 * Legacy PARAMETER statements::
1549 * Default exponents::
1550 @end menu
1552 @node Old-style kind specifications
1553 @subsection Old-style kind specifications
1554 @cindex kind, old-style
1556 GNU Fortran allows old-style kind specifications in declarations.  These
1557 look like:
1558 @smallexample
1559       TYPESPEC*size x,y,z
1560 @end smallexample
1561 @noindent
1562 where @code{TYPESPEC} is a basic type (@code{INTEGER}, @code{REAL},
1563 etc.), and where @code{size} is a byte count corresponding to the
1564 storage size of a valid kind for that type.  (For @code{COMPLEX}
1565 variables, @code{size} is the total size of the real and imaginary
1566 parts.)  The statement then declares @code{x}, @code{y} and @code{z} to
1567 be of type @code{TYPESPEC} with the appropriate kind.  This is
1568 equivalent to the standard-conforming declaration
1569 @smallexample
1570       TYPESPEC(k) x,y,z
1571 @end smallexample
1572 @noindent
1573 where @code{k} is the kind parameter suitable for the intended precision.  As
1574 kind parameters are implementation-dependent, use the @code{KIND},
1575 @code{SELECTED_INT_KIND} and @code{SELECTED_REAL_KIND} intrinsics to retrieve
1576 the correct value, for instance @code{REAL*8 x} can be replaced by:
1577 @smallexample
1578 INTEGER, PARAMETER :: dbl = KIND(1.0d0)
1579 REAL(KIND=dbl) :: x
1580 @end smallexample
1582 @node Old-style variable initialization
1583 @subsection Old-style variable initialization
1585 GNU Fortran allows old-style initialization of variables of the
1586 form:
1587 @smallexample
1588       INTEGER i/1/,j/2/
1589       REAL x(2,2) /3*0.,1./
1590 @end smallexample
1591 The syntax for the initializers is as for the @code{DATA} statement, but
1592 unlike in a @code{DATA} statement, an initializer only applies to the
1593 variable immediately preceding the initialization.  In other words,
1594 something like @code{INTEGER I,J/2,3/} is not valid.  This style of
1595 initialization is only allowed in declarations without double colons
1596 (@code{::}); the double colons were introduced in Fortran 90, which also
1597 introduced a standard syntax for initializing variables in type
1598 declarations.
1600 Examples of standard-conforming code equivalent to the above example
1601 are:
1602 @smallexample
1603 ! Fortran 90
1604       INTEGER :: i = 1, j = 2
1605       REAL :: x(2,2) = RESHAPE((/0.,0.,0.,1./),SHAPE(x))
1606 ! Fortran 77
1607       INTEGER i, j
1608       REAL x(2,2)
1609       DATA i/1/, j/2/, x/3*0.,1./
1610 @end smallexample
1612 Note that variables which are explicitly initialized in declarations
1613 or in @code{DATA} statements automatically acquire the @code{SAVE}
1614 attribute.
1616 @node Extensions to namelist
1617 @subsection Extensions to namelist
1618 @cindex Namelist
1620 GNU Fortran fully supports the Fortran 95 standard for namelist I/O
1621 including array qualifiers, substrings and fully qualified derived types.
1622 The output from a namelist write is compatible with namelist read.  The
1623 output has all names in upper case and indentation to column 1 after the
1624 namelist name.  Two extensions are permitted:
1626 Old-style use of @samp{$} instead of @samp{&}
1627 @smallexample
1628 $MYNML
1629  X(:)%Y(2) = 1.0 2.0 3.0
1630  CH(1:4) = "abcd"
1631 $END
1632 @end smallexample
1634 It should be noted that the default terminator is @samp{/} rather than
1635 @samp{&END}.
1637 Querying of the namelist when inputting from stdin.  After at least
1638 one space, entering @samp{?} sends to stdout the namelist name and the names of
1639 the variables in the namelist:
1640 @smallexample
1643 &mynml
1645  x%y
1646  ch
1647 &end
1648 @end smallexample
1650 Entering @samp{=?} outputs the namelist to stdout, as if
1651 @code{WRITE(*,NML = mynml)} had been called:
1652 @smallexample
1655 &MYNML
1656  X(1)%Y=  0.000000    ,  1.000000    ,  0.000000    ,
1657  X(2)%Y=  0.000000    ,  2.000000    ,  0.000000    ,
1658  X(3)%Y=  0.000000    ,  3.000000    ,  0.000000    ,
1659  CH=abcd,  /
1660 @end smallexample
1662 To aid this dialog, when input is from stdin, errors send their
1663 messages to stderr and execution continues, even if @code{IOSTAT} is set.
1665 @code{PRINT} namelist is permitted.  This causes an error if
1666 @option{-std=f95} is used.
1667 @smallexample
1668 PROGRAM test_print
1669   REAL, dimension (4)  ::  x = (/1.0, 2.0, 3.0, 4.0/)
1670   NAMELIST /mynml/ x
1671   PRINT mynml
1672 END PROGRAM test_print
1673 @end smallexample
1675 Expanded namelist reads are permitted.  This causes an error if 
1676 @option{-std=f95} is used.  In the following example, the first element
1677 of the array will be given the value 0.00 and the two succeeding
1678 elements will be given the values 1.00 and 2.00.
1679 @smallexample
1680 &MYNML
1681   X(1,1) = 0.00 , 1.00 , 2.00
1683 @end smallexample
1685 When writing a namelist, if no @code{DELIM=} is specified, by default a
1686 double quote is used to delimit character strings. If -std=F95, F2003,
1687 or F2008, etc, the delim status is set to 'none'.  Defaulting to
1688 quotes ensures that namelists with character strings can be subsequently
1689 read back in accurately.
1691 @node X format descriptor without count field
1692 @subsection @code{X} format descriptor without count field
1694 To support legacy codes, GNU Fortran permits the count field of the
1695 @code{X} edit descriptor in @code{FORMAT} statements to be omitted.
1696 When omitted, the count is implicitly assumed to be one.
1698 @smallexample
1699        PRINT 10, 2, 3
1700 10     FORMAT (I1, X, I1)
1701 @end smallexample
1703 @node Commas in FORMAT specifications
1704 @subsection Commas in @code{FORMAT} specifications
1706 To support legacy codes, GNU Fortran allows the comma separator
1707 to be omitted immediately before and after character string edit
1708 descriptors in @code{FORMAT} statements.
1710 @smallexample
1711        PRINT 10, 2, 3
1712 10     FORMAT ('FOO='I1' BAR='I2)
1713 @end smallexample
1716 @node Missing period in FORMAT specifications
1717 @subsection Missing period in @code{FORMAT} specifications
1719 To support legacy codes, GNU Fortran allows missing periods in format
1720 specifications if and only if @option{-std=legacy} is given on the
1721 command line.  This is considered non-conforming code and is
1722 discouraged.
1724 @smallexample
1725        REAL :: value
1726        READ(*,10) value
1727 10     FORMAT ('F4')
1728 @end smallexample
1730 @node I/O item lists
1731 @subsection I/O item lists
1732 @cindex I/O item lists
1734 To support legacy codes, GNU Fortran allows the input item list
1735 of the @code{READ} statement, and the output item lists of the
1736 @code{WRITE} and @code{PRINT} statements, to start with a comma.
1738 @node @code{Q} exponent-letter
1739 @subsection @code{Q} exponent-letter
1740 @cindex @code{Q} exponent-letter
1742 GNU Fortran accepts real literal constants with an exponent-letter
1743 of @code{Q}, for example, @code{1.23Q45}.  The constant is interpreted
1744 as a @code{REAL(16)} entity on targets that support this type.  If
1745 the target does not support @code{REAL(16)} but has a @code{REAL(10)}
1746 type, then the real-literal-constant will be interpreted as a
1747 @code{REAL(10)} entity.  In the absence of @code{REAL(16)} and
1748 @code{REAL(10)}, an error will occur.
1750 @node BOZ literal constants
1751 @subsection BOZ literal constants
1752 @cindex BOZ literal constants
1754 Besides decimal constants, Fortran also supports binary (@code{b}),
1755 octal (@code{o}) and hexadecimal (@code{z}) integer constants.  The
1756 syntax is: @samp{prefix quote digits quote}, were the prefix is
1757 either @code{b}, @code{o} or @code{z}, quote is either @code{'} or
1758 @code{"} and the digits are for binary @code{0} or @code{1}, for
1759 octal between @code{0} and @code{7}, and for hexadecimal between
1760 @code{0} and @code{F}.  (Example: @code{b'01011101'}.)
1762 Up to Fortran 95, BOZ literals were only allowed to initialize
1763 integer variables in DATA statements.  Since Fortran 2003 BOZ literals
1764 are also allowed as argument of @code{REAL}, @code{DBLE}, @code{INT}
1765 and @code{CMPLX}; the result is the same as if the integer BOZ
1766 literal had been converted by @code{TRANSFER} to, respectively,
1767 @code{real}, @code{double precision}, @code{integer} or @code{complex}.
1768 As GNU Fortran extension the intrinsic procedures @code{FLOAT},
1769 @code{DFLOAT}, @code{COMPLEX} and @code{DCMPLX} are treated alike.
1771 As an extension, GNU Fortran allows hexadecimal BOZ literal constants to
1772 be specified using the @code{X} prefix, in addition to the standard
1773 @code{Z} prefix.  The BOZ literal can also be specified by adding a
1774 suffix to the string, for example, @code{Z'ABC'} and @code{'ABC'Z} are
1775 equivalent.
1777 Furthermore, GNU Fortran allows using BOZ literal constants outside
1778 DATA statements and the four intrinsic functions allowed by Fortran 2003.
1779 In DATA statements, in direct assignments, where the right-hand side
1780 only contains a BOZ literal constant, and for old-style initializers of
1781 the form @code{integer i /o'0173'/}, the constant is transferred
1782 as if @code{TRANSFER} had been used; for @code{COMPLEX} numbers, only
1783 the real part is initialized unless @code{CMPLX} is used.  In all other
1784 cases, the BOZ literal constant is converted to an @code{INTEGER} value with
1785 the largest decimal representation.  This value is then converted
1786 numerically to the type and kind of the variable in question.
1787 (For instance, @code{real :: r = b'0000001' + 1} initializes @code{r}
1788 with @code{2.0}.) As different compilers implement the extension
1789 differently, one should be careful when doing bitwise initialization
1790 of non-integer variables.
1792 Note that initializing an @code{INTEGER} variable with a statement such
1793 as @code{DATA i/Z'FFFFFFFF'/} will give an integer overflow error rather
1794 than the desired result of @math{-1} when @code{i} is a 32-bit integer
1795 on a system that supports 64-bit integers.  The @samp{-fno-range-check}
1796 option can be used as a workaround for legacy code that initializes
1797 integers in this manner.
1799 @node Real array indices
1800 @subsection Real array indices
1801 @cindex array, indices of type real
1803 As an extension, GNU Fortran allows the use of @code{REAL} expressions
1804 or variables as array indices.
1806 @node Unary operators
1807 @subsection Unary operators
1808 @cindex operators, unary
1810 As an extension, GNU Fortran allows unary plus and unary minus operators
1811 to appear as the second operand of binary arithmetic operators without
1812 the need for parenthesis.
1814 @smallexample
1815        X = Y * -Z
1816 @end smallexample
1818 @node Implicitly convert LOGICAL and INTEGER values
1819 @subsection Implicitly convert @code{LOGICAL} and @code{INTEGER} values
1820 @cindex conversion, to integer
1821 @cindex conversion, to logical
1823 As an extension for backwards compatibility with other compilers, GNU
1824 Fortran allows the implicit conversion of @code{LOGICAL} values to
1825 @code{INTEGER} values and vice versa.  When converting from a
1826 @code{LOGICAL} to an @code{INTEGER}, @code{.FALSE.} is interpreted as
1827 zero, and @code{.TRUE.} is interpreted as one.  When converting from
1828 @code{INTEGER} to @code{LOGICAL}, the value zero is interpreted as
1829 @code{.FALSE.} and any nonzero value is interpreted as @code{.TRUE.}.
1831 @smallexample
1832         LOGICAL :: l
1833         l = 1
1834 @end smallexample
1835 @smallexample
1836         INTEGER :: i
1837         i = .TRUE.
1838 @end smallexample
1840 However, there is no implicit conversion of @code{INTEGER} values in
1841 @code{if}-statements, nor of @code{LOGICAL} or @code{INTEGER} values
1842 in I/O operations.
1844 @node Hollerith constants support
1845 @subsection Hollerith constants support
1846 @cindex Hollerith constants
1848 GNU Fortran supports Hollerith constants in assignments, function
1849 arguments, and @code{DATA} and @code{ASSIGN} statements.  A Hollerith
1850 constant is written as a string of characters preceded by an integer
1851 constant indicating the character count, and the letter @code{H} or
1852 @code{h}, and stored in bytewise fashion in a numeric (@code{INTEGER},
1853 @code{REAL}, or @code{complex}) or @code{LOGICAL} variable.  The
1854 constant will be padded or truncated to fit the size of the variable in
1855 which it is stored.
1857 Examples of valid uses of Hollerith constants:
1858 @smallexample
1859       complex*16 x(2)
1860       data x /16Habcdefghijklmnop, 16Hqrstuvwxyz012345/
1861       x(1) = 16HABCDEFGHIJKLMNOP
1862       call foo (4h abc)
1863 @end smallexample
1865 Invalid Hollerith constants examples:
1866 @smallexample
1867       integer*4 a
1868       a = 8H12345678 ! Valid, but the Hollerith constant will be truncated.
1869       a = 0H         ! At least one character is needed.
1870 @end smallexample
1872 In general, Hollerith constants were used to provide a rudimentary
1873 facility for handling character strings in early Fortran compilers,
1874 prior to the introduction of @code{CHARACTER} variables in Fortran 77;
1875 in those cases, the standard-compliant equivalent is to convert the
1876 program to use proper character strings.  On occasion, there may be a
1877 case where the intent is specifically to initialize a numeric variable
1878 with a given byte sequence.  In these cases, the same result can be
1879 obtained by using the @code{TRANSFER} statement, as in this example.
1880 @smallexample
1881       INTEGER(KIND=4) :: a
1882       a = TRANSFER ("abcd", a)     ! equivalent to: a = 4Habcd
1883 @end smallexample
1886 @node Cray pointers
1887 @subsection Cray pointers
1888 @cindex pointer, Cray
1890 Cray pointers are part of a non-standard extension that provides a
1891 C-like pointer in Fortran.  This is accomplished through a pair of
1892 variables: an integer "pointer" that holds a memory address, and a
1893 "pointee" that is used to dereference the pointer.
1895 Pointer/pointee pairs are declared in statements of the form:
1896 @smallexample
1897         pointer ( <pointer> , <pointee> )
1898 @end smallexample
1900 @smallexample
1901         pointer ( <pointer1> , <pointee1> ), ( <pointer2> , <pointee2> ), ...
1902 @end smallexample
1903 The pointer is an integer that is intended to hold a memory address.
1904 The pointee may be an array or scalar.
1905 If an assumed-size array is permitted within the scoping unit, a
1906 pointee can be an assumed-size array.
1907 That is, the last dimension may be left unspecified by using a @code{*}
1908 in place of a value. A pointee cannot be an assumed shape array.
1909 No space is allocated for the pointee.
1911 The pointee may have its type declared before or after the pointer
1912 statement, and its array specification (if any) may be declared
1913 before, during, or after the pointer statement.  The pointer may be
1914 declared as an integer prior to the pointer statement.  However, some
1915 machines have default integer sizes that are different than the size
1916 of a pointer, and so the following code is not portable:
1917 @smallexample
1918         integer ipt
1919         pointer (ipt, iarr)
1920 @end smallexample
1921 If a pointer is declared with a kind that is too small, the compiler
1922 will issue a warning; the resulting binary will probably not work
1923 correctly, because the memory addresses stored in the pointers may be
1924 truncated.  It is safer to omit the first line of the above example;
1925 if explicit declaration of ipt's type is omitted, then the compiler
1926 will ensure that ipt is an integer variable large enough to hold a
1927 pointer.
1929 Pointer arithmetic is valid with Cray pointers, but it is not the same
1930 as C pointer arithmetic.  Cray pointers are just ordinary integers, so
1931 the user is responsible for determining how many bytes to add to a
1932 pointer in order to increment it.  Consider the following example:
1933 @smallexample
1934         real target(10)
1935         real pointee(10)
1936         pointer (ipt, pointee)
1937         ipt = loc (target)
1938         ipt = ipt + 1       
1939 @end smallexample
1940 The last statement does not set @code{ipt} to the address of
1941 @code{target(1)}, as it would in C pointer arithmetic.  Adding @code{1}
1942 to @code{ipt} just adds one byte to the address stored in @code{ipt}.
1944 Any expression involving the pointee will be translated to use the
1945 value stored in the pointer as the base address.
1947 To get the address of elements, this extension provides an intrinsic
1948 function @code{LOC()}.  The @code{LOC()} function is equivalent to the
1949 @code{&} operator in C, except the address is cast to an integer type:
1950 @smallexample
1951         real ar(10)
1952         pointer(ipt, arpte(10))
1953         real arpte
1954         ipt = loc(ar)  ! Makes arpte is an alias for ar
1955         arpte(1) = 1.0 ! Sets ar(1) to 1.0
1956 @end smallexample
1957 The pointer can also be set by a call to the @code{MALLOC} intrinsic
1958 (see @ref{MALLOC}).
1960 Cray pointees often are used to alias an existing variable.  For
1961 example:
1962 @smallexample
1963         integer target(10)
1964         integer iarr(10)
1965         pointer (ipt, iarr)
1966         ipt = loc(target)
1967 @end smallexample
1968 As long as @code{ipt} remains unchanged, @code{iarr} is now an alias for
1969 @code{target}.  The optimizer, however, will not detect this aliasing, so
1970 it is unsafe to use @code{iarr} and @code{target} simultaneously.  Using
1971 a pointee in any way that violates the Fortran aliasing rules or
1972 assumptions is illegal.  It is the user's responsibility to avoid doing
1973 this; the compiler works under the assumption that no such aliasing
1974 occurs.
1976 Cray pointers will work correctly when there is no aliasing (i.e., when
1977 they are used to access a dynamically allocated block of memory), and
1978 also in any routine where a pointee is used, but any variable with which
1979 it shares storage is not used.  Code that violates these rules may not
1980 run as the user intends.  This is not a bug in the optimizer; any code
1981 that violates the aliasing rules is illegal.  (Note that this is not
1982 unique to GNU Fortran; any Fortran compiler that supports Cray pointers
1983 will ``incorrectly'' optimize code with illegal aliasing.)
1985 There are a number of restrictions on the attributes that can be applied
1986 to Cray pointers and pointees.  Pointees may not have the
1987 @code{ALLOCATABLE}, @code{INTENT}, @code{OPTIONAL}, @code{DUMMY},
1988 @code{TARGET}, @code{INTRINSIC}, or @code{POINTER} attributes.  Pointers
1989 may not have the @code{DIMENSION}, @code{POINTER}, @code{TARGET},
1990 @code{ALLOCATABLE}, @code{EXTERNAL}, or @code{INTRINSIC} attributes, nor
1991 may they be function results.  Pointees may not occur in more than one
1992 pointer statement.  A pointee cannot be a pointer.  Pointees cannot occur
1993 in equivalence, common, or data statements.
1995 A Cray pointer may also point to a function or a subroutine.  For
1996 example, the following excerpt is valid:
1997 @smallexample
1998   implicit none
1999   external sub
2000   pointer (subptr,subpte)
2001   external subpte
2002   subptr = loc(sub)
2003   call subpte()
2004   [...]
2005   subroutine sub
2006   [...]
2007   end subroutine sub
2008 @end smallexample
2010 A pointer may be modified during the course of a program, and this
2011 will change the location to which the pointee refers.  However, when
2012 pointees are passed as arguments, they are treated as ordinary
2013 variables in the invoked function.  Subsequent changes to the pointer
2014 will not change the base address of the array that was passed.
2016 @node CONVERT specifier
2017 @subsection @code{CONVERT} specifier
2018 @cindex @code{CONVERT} specifier
2020 GNU Fortran allows the conversion of unformatted data between little-
2021 and big-endian representation to facilitate moving of data
2022 between different systems.  The conversion can be indicated with
2023 the @code{CONVERT} specifier on the @code{OPEN} statement.
2024 @xref{GFORTRAN_CONVERT_UNIT}, for an alternative way of specifying
2025 the data format via an environment variable.
2027 Valid values for @code{CONVERT} are:
2028 @itemize @w{}
2029 @item @code{CONVERT='NATIVE'} Use the native format.  This is the default.
2030 @item @code{CONVERT='SWAP'} Swap between little- and big-endian.
2031 @item @code{CONVERT='LITTLE_ENDIAN'} Use the little-endian representation
2032 for unformatted files.
2033 @item @code{CONVERT='BIG_ENDIAN'} Use the big-endian representation for
2034 unformatted files.
2035 @end itemize
2037 Using the option could look like this:
2038 @smallexample
2039   open(file='big.dat',form='unformatted',access='sequential', &
2040        convert='big_endian')
2041 @end smallexample
2043 The value of the conversion can be queried by using
2044 @code{INQUIRE(CONVERT=ch)}.  The values returned are
2045 @code{'BIG_ENDIAN'} and @code{'LITTLE_ENDIAN'}.
2047 @code{CONVERT} works between big- and little-endian for
2048 @code{INTEGER} values of all supported kinds and for @code{REAL}
2049 on IEEE systems of kinds 4 and 8.  Conversion between different
2050 ``extended double'' types on different architectures such as
2051 m68k and x86_64, which GNU Fortran
2052 supports as @code{REAL(KIND=10)} and @code{REAL(KIND=16)}, will
2053 probably not work.
2055 @emph{Note that the values specified via the GFORTRAN_CONVERT_UNIT
2056 environment variable will override the CONVERT specifier in the
2057 open statement}.  This is to give control over data formats to
2058 users who do not have the source code of their program available.
2060 Using anything but the native representation for unformatted data
2061 carries a significant speed overhead.  If speed in this area matters
2062 to you, it is best if you use this only for data that needs to be
2063 portable.
2065 @node OpenMP
2066 @subsection OpenMP
2067 @cindex OpenMP
2069 OpenMP (Open Multi-Processing) is an application programming
2070 interface (API) that supports multi-platform shared memory 
2071 multiprocessing programming in C/C++ and Fortran on many 
2072 architectures, including Unix and Microsoft Windows platforms.
2073 It consists of a set of compiler directives, library routines,
2074 and environment variables that influence run-time behavior.
2076 GNU Fortran strives to be compatible to the 
2077 @uref{http://openmp.org/wp/openmp-specifications/,
2078 OpenMP Application Program Interface v4.5}.
2080 To enable the processing of the OpenMP directive @code{!$omp} in
2081 free-form source code; the @code{c$omp}, @code{*$omp} and @code{!$omp}
2082 directives in fixed form; the @code{!$} conditional compilation sentinels
2083 in free form; and the @code{c$}, @code{*$} and @code{!$} sentinels
2084 in fixed form, @command{gfortran} needs to be invoked with the
2085 @option{-fopenmp}.  This also arranges for automatic linking of the
2086 GNU Offloading and Multi Processing Runtime Library
2087 @ref{Top,,libgomp,libgomp,GNU Offloading and Multi Processing Runtime
2088 Library}.
2090 The OpenMP Fortran runtime library routines are provided both in a
2091 form of a Fortran 90 module named @code{omp_lib} and in a form of
2092 a Fortran @code{include} file named @file{omp_lib.h}.
2094 An example of a parallelized loop taken from Appendix A.1 of
2095 the OpenMP Application Program Interface v2.5:
2096 @smallexample
2097 SUBROUTINE A1(N, A, B)
2098   INTEGER I, N
2099   REAL B(N), A(N)
2100 !$OMP PARALLEL DO !I is private by default
2101   DO I=2,N
2102     B(I) = (A(I) + A(I-1)) / 2.0
2103   ENDDO
2104 !$OMP END PARALLEL DO
2105 END SUBROUTINE A1
2106 @end smallexample
2108 Please note:
2109 @itemize
2110 @item
2111 @option{-fopenmp} implies @option{-frecursive}, i.e., all local arrays
2112 will be allocated on the stack.  When porting existing code to OpenMP,
2113 this may lead to surprising results, especially to segmentation faults
2114 if the stacksize is limited.
2116 @item
2117 On glibc-based systems, OpenMP enabled applications cannot be statically
2118 linked due to limitations of the underlying pthreads-implementation.  It
2119 might be possible to get a working solution if 
2120 @command{-Wl,--whole-archive -lpthread -Wl,--no-whole-archive} is added
2121 to the command line.  However, this is not supported by @command{gcc} and
2122 thus not recommended.
2123 @end itemize
2125 @node OpenACC
2126 @subsection OpenACC
2127 @cindex OpenACC
2129 OpenACC is an application programming interface (API) that supports
2130 offloading of code to accelerator devices.  It consists of a set of
2131 compiler directives, library routines, and environment variables that
2132 influence run-time behavior.
2134 GNU Fortran strives to be compatible to the
2135 @uref{http://www.openacc.org/, OpenACC Application Programming
2136 Interface v2.0}.
2138 To enable the processing of the OpenACC directive @code{!$acc} in
2139 free-form source code; the @code{c$acc}, @code{*$acc} and @code{!$acc}
2140 directives in fixed form; the @code{!$} conditional compilation
2141 sentinels in free form; and the @code{c$}, @code{*$} and @code{!$}
2142 sentinels in fixed form, @command{gfortran} needs to be invoked with
2143 the @option{-fopenacc}.  This also arranges for automatic linking of
2144 the GNU Offloading and Multi Processing Runtime Library
2145 @ref{Top,,libgomp,libgomp,GNU Offloading and Multi Processing Runtime
2146 Library}.
2148 The OpenACC Fortran runtime library routines are provided both in a
2149 form of a Fortran 90 module named @code{openacc} and in a form of a
2150 Fortran @code{include} file named @file{openacc_lib.h}.
2152 Note that this is an experimental feature, incomplete, and subject to
2153 change in future versions of GCC.  See
2154 @uref{https://gcc.gnu.org/wiki/OpenACC} for more information.
2156 @node Argument list functions
2157 @subsection Argument list functions @code{%VAL}, @code{%REF} and @code{%LOC}
2158 @cindex argument list functions
2159 @cindex @code{%VAL}
2160 @cindex @code{%REF}
2161 @cindex @code{%LOC}
2163 GNU Fortran supports argument list functions @code{%VAL}, @code{%REF} 
2164 and @code{%LOC} statements, for backward compatibility with g77. 
2165 It is recommended that these should be used only for code that is 
2166 accessing facilities outside of GNU Fortran, such as operating system 
2167 or windowing facilities.  It is best to constrain such uses to isolated 
2168 portions of a program--portions that deal specifically and exclusively 
2169 with low-level, system-dependent facilities.  Such portions might well 
2170 provide a portable interface for use by the program as a whole, but are 
2171 themselves not portable, and should be thoroughly tested each time they 
2172 are rebuilt using a new compiler or version of a compiler.
2174 @code{%VAL} passes a scalar argument by value, @code{%REF} passes it by 
2175 reference and @code{%LOC} passes its memory location.  Since gfortran 
2176 already passes scalar arguments by reference, @code{%REF} is in effect 
2177 a do-nothing.  @code{%LOC} has the same effect as a Fortran pointer.
2179 An example of passing an argument by value to a C subroutine foo.:
2180 @smallexample
2182 C prototype      void foo_ (float x);
2184       external foo
2185       real*4 x
2186       x = 3.14159
2187       call foo (%VAL (x))
2188       end
2189 @end smallexample
2191 For details refer to the g77 manual
2192 @uref{https://gcc.gnu.org/@/onlinedocs/@/gcc-3.4.6/@/g77/@/index.html#Top}.
2194 Also, @code{c_by_val.f} and its partner @code{c_by_val.c} of the
2195 GNU Fortran testsuite are worth a look.
2197 @node Read/Write after EOF marker
2198 @subsection Read/Write after EOF marker
2199 @cindex @code{EOF}
2200 @cindex @code{BACKSPACE}
2201 @cindex @code{REWIND}
2203 Some legacy codes rely on allowing @code{READ} or @code{WRITE} after the
2204 EOF file marker in order to find the end of a file. GNU Fortran normally
2205 rejects these codes with a run-time error message and suggests the user
2206 consider @code{BACKSPACE} or @code{REWIND} to properly position
2207 the file before the EOF marker.  As an extension, the run-time error may
2208 be disabled using -std=legacy.
2211 @node STRUCTURE and RECORD
2212 @subsection @code{STRUCTURE} and @code{RECORD}
2213 @cindex @code{STRUCTURE}
2214 @cindex @code{RECORD}
2216 Record structures are a pre-Fortran-90 vendor extension to create
2217 user-defined aggregate data types.  Support for record structures in GNU
2218 Fortran can be enabled with the @option{-fdec-structure} compile flag.
2219 If you have a choice, you should instead use Fortran 90's ``derived types'',
2220 which have a different syntax.
2222 In many cases, record structures can easily be converted to derived types.
2223 To convert, replace @code{STRUCTURE /}@var{structure-name}@code{/}
2224 by @code{TYPE} @var{type-name}.  Additionally, replace
2225 @code{RECORD /}@var{structure-name}@code{/} by
2226 @code{TYPE(}@var{type-name}@code{)}. Finally, in the component access,
2227 replace the period (@code{.}) by the percent sign (@code{%}).
2229 Here is an example of code using the non portable record structure syntax:
2231 @example
2232 ! Declaring a structure named ``item'' and containing three fields:
2233 ! an integer ID, an description string and a floating-point price.
2234 STRUCTURE /item/
2235   INTEGER id
2236   CHARACTER(LEN=200) description
2237   REAL price
2238 END STRUCTURE
2240 ! Define two variables, an single record of type ``item''
2241 ! named ``pear'', and an array of items named ``store_catalog''
2242 RECORD /item/ pear, store_catalog(100)
2244 ! We can directly access the fields of both variables
2245 pear.id = 92316
2246 pear.description = "juicy D'Anjou pear"
2247 pear.price = 0.15
2248 store_catalog(7).id = 7831
2249 store_catalog(7).description = "milk bottle"
2250 store_catalog(7).price = 1.2
2252 ! We can also manipulate the whole structure
2253 store_catalog(12) = pear
2254 print *, store_catalog(12)
2255 @end example
2257 @noindent
2258 This code can easily be rewritten in the Fortran 90 syntax as following:
2260 @example
2261 ! ``STRUCTURE /name/ ... END STRUCTURE'' becomes
2262 ! ``TYPE name ... END TYPE''
2263 TYPE item
2264   INTEGER id
2265   CHARACTER(LEN=200) description
2266   REAL price
2267 END TYPE
2269 ! ``RECORD /name/ variable'' becomes ``TYPE(name) variable''
2270 TYPE(item) pear, store_catalog(100)
2272 ! Instead of using a dot (.) to access fields of a record, the
2273 ! standard syntax uses a percent sign (%)
2274 pear%id = 92316
2275 pear%description = "juicy D'Anjou pear"
2276 pear%price = 0.15
2277 store_catalog(7)%id = 7831
2278 store_catalog(7)%description = "milk bottle"
2279 store_catalog(7)%price = 1.2
2281 ! Assignments of a whole variable do not change
2282 store_catalog(12) = pear
2283 print *, store_catalog(12)
2284 @end example
2286 @noindent
2287 GNU Fortran implements STRUCTURES like derived types with the following
2288 rules and exceptions:
2290 @itemize @bullet
2291 @item Structures act like derived types with the @code{SEQUENCE} attribute.
2292 Otherwise they may contain no specifiers.
2294 @item Structures may contain a special field with the name @code{%FILL}.
2295 This will create an anonymous component which cannot be accessed but occupies
2296 space just as if a component of the same type was declared in its place, useful
2297 for alignment purposes.  As an example, the following structure will consist
2298 of at least sixteen bytes:
2300 @smallexample
2301 structure /padded/
2302   character(4) start
2303   character(8) %FILL
2304   character(4) end
2305 end structure
2306 @end smallexample
2308 @item Structures may share names with other symbols. For example, the following
2309 is invalid for derived types, but valid for structures:
2311 @smallexample
2312 structure /header/
2313   ! ...
2314 end structure
2315 record /header/ header
2316 @end smallexample
2318 @item Structure types may be declared nested within another parent structure.
2319 The syntax is:
2320 @smallexample
2321 structure /type-name/
2322     ...
2323     structure [/<type-name>/] <field-list>
2325 @end smallexample
2327 The type name may be ommitted, in which case the structure type itself is
2328 anonymous, and other structures of the same type cannot be instantiated. The
2329 following shows some examples:
2331 @example
2332 structure /appointment/
2333   ! nested structure definition: app_time is an array of two 'time'
2334   structure /time/ app_time (2) 
2335     integer(1) hour, minute
2336   end structure
2337   character(10) memo
2338 end structure
2340 ! The 'time' structure is still usable
2341 record /time/ now
2342 now = time(5, 30)
2346 structure /appointment/
2347   ! anonymous nested structure definition
2348   structure start, end
2349     integer(1) hour, minute
2350   end structure
2351   character(10) memo
2352 end structure
2353 @end example
2355 @item Structures may contain @code{UNION} blocks. For more detail see the
2356 section on @ref{UNION and MAP}.
2358 @item Structures support old-style initialization of components, like
2359 those described in @ref{Old-style variable initialization}. For array
2360 initializers, an initializer may contain a repeat specification of the form
2361 @code{<literal-integer> * <constant-initializer>}. The value of the integer
2362 indicates the number of times to repeat the constant initializer when expanding
2363 the initializer list.
2364 @end itemize
2366 @node UNION and MAP
2367 @subsection @code{UNION} and @code{MAP}
2368 @cindex @code{UNION}
2369 @cindex @code{MAP}
2371 Unions are an old vendor extension which were commonly used with the
2372 non-standard @ref{STRUCTURE and RECORD} extensions. Use of @code{UNION} and
2373 @code{MAP} is automatically enabled with @option{-fdec-structure}.
2375 A @code{UNION} declaration occurs within a structure; within the definition of
2376 each union is a number of @code{MAP} blocks. Each @code{MAP} shares storage
2377 with its sibling maps (in the same union), and the size of the union is the
2378 size of the largest map within it, just as with unions in C. The major
2379 difference is that component references do not indicate which union or map the
2380 component is in (the compiler gets to figure that out).
2382 Here is a small example:
2383 @smallexample
2384 structure /myunion/
2385 union
2386   map
2387     character(2) w0, w1, w2
2388   end map
2389   map
2390     character(6) long
2391   end map
2392 end union
2393 end structure
2395 record /myunion/ rec
2396 ! After this assignment...
2397 rec.long = 'hello!'
2399 ! The following is true:
2400 ! rec.w0 === 'he'
2401 ! rec.w1 === 'll'
2402 ! rec.w2 === 'o!'
2403 @end smallexample
2405 The two maps share memory, and the size of the union is ultimately six bytes:
2407 @example
2408 0    1    2    3    4   5   6     Byte offset
2409 -------------------------------
2410 |    |    |    |    |    |    |
2411 -------------------------------
2413 ^    W0   ^    W1   ^    W2   ^
2414  \-------/ \-------/ \-------/
2416 ^             LONG            ^
2417  \---------------------------/
2418 @end example
2420 Following is an example mirroring the layout of an Intel x86_64 register:
2422 @example
2423 structure /reg/
2424   union ! U0                ! rax
2425     map
2426       character(16) rx
2427     end map
2428     map
2429       character(8) rh         ! rah
2430       union ! U1
2431         map
2432           character(8) rl     ! ral
2433         end map
2434         map
2435           character(8) ex     ! eax
2436         end map
2437         map
2438           character(4) eh     ! eah
2439           union ! U2
2440             map
2441               character(4) el ! eal
2442             end map
2443             map
2444               character(4) x  ! ax
2445             end map
2446             map
2447               character(2) h  ! ah
2448               character(2) l  ! al
2449             end map
2450           end union
2451         end map
2452       end union
2453     end map
2454   end union
2455 end structure
2456 record /reg/ a
2458 ! After this assignment...
2459 a.rx     =     'AAAAAAAA.BBB.C.D'
2461 ! The following is true:
2462 a.rx === 'AAAAAAAA.BBB.C.D'
2463 a.rh === 'AAAAAAAA'
2464 a.rl ===         '.BBB.C.D'
2465 a.ex ===         '.BBB.C.D'
2466 a.eh ===         '.BBB'
2467 a.el ===             '.C.D'
2468 a.x  ===             '.C.D'
2469 a.h  ===             '.C'
2470 a.l  ===               '.D'
2471 @end example
2473 @node Type variants for integer intrinsics
2474 @subsection Type variants for integer intrinsics
2475 @cindex intrinsics, integer
2477 Similar to the D/C prefixes to real functions to specify the input/output
2478 types, GNU Fortran offers B/I/J/K prefixes to integer functions for
2479 compatibility with DEC programs. The types implied by each are:
2481 @example
2482 @code{B} - @code{INTEGER(kind=1)}
2483 @code{I} - @code{INTEGER(kind=2)}
2484 @code{J} - @code{INTEGER(kind=4)}
2485 @code{K} - @code{INTEGER(kind=8)}
2486 @end example
2488 GNU Fortran supports these with the flag @option{-fdec-intrinsic-ints}.
2489 Intrinsics for which prefixed versions are available and in what form are noted
2490 in @ref{Intrinsic Procedures}. The complete list of supported intrinsics is
2491 here:
2493 @multitable @columnfractions .2 .2 .2 .2 .2
2495 @headitem Intrinsic @tab B @tab I @tab J @tab K
2497 @item @code{@ref{ABS}}
2498   @tab @code{BABS} @tab @code{IIABS} @tab @code{JIABS} @tab @code{KIABS}
2499 @item @code{@ref{BTEST}}
2500   @tab @code{BBTEST} @tab @code{BITEST} @tab @code{BJTEST} @tab @code{BKTEST}
2501 @item @code{@ref{IAND}}
2502   @tab @code{BIAND} @tab @code{IIAND} @tab @code{JIAND} @tab @code{KIAND}
2503 @item @code{@ref{IBCLR}}
2504   @tab @code{BBCLR} @tab @code{IIBCLR} @tab @code{JIBCLR} @tab @code{KIBCLR}
2505 @item @code{@ref{IBITS}}
2506   @tab @code{BBITS} @tab @code{IIBITS} @tab @code{JIBITS} @tab @code{KIBITS}
2507 @item @code{@ref{IBSET}}
2508   @tab @code{BBSET} @tab @code{IIBSET} @tab @code{JIBSET} @tab @code{KIBSET}
2509 @item @code{@ref{IEOR}}
2510   @tab @code{BIEOR} @tab @code{IIEOR} @tab @code{JIEOR} @tab @code{KIEOR}
2511 @item @code{@ref{IOR}}
2512   @tab @code{BIOR} @tab @code{IIOR} @tab @code{JIOR} @tab @code{KIOR}
2513 @item @code{@ref{ISHFT}}
2514   @tab @code{BSHFT} @tab @code{IISHFT} @tab @code{JISHFT} @tab @code{KISHFT}
2515 @item @code{@ref{ISHFTC}}
2516   @tab @code{BSHFTC} @tab @code{IISHFTC} @tab @code{JISHFTC} @tab @code{KISHFTC}
2517 @item @code{@ref{MOD}}
2518   @tab @code{BMOD} @tab @code{IMOD} @tab @code{JMOD} @tab @code{KMOD}
2519 @item @code{@ref{NOT}}
2520   @tab @code{BNOT} @tab @code{INOT} @tab @code{JNOT} @tab @code{KNOT}
2521 @item @code{@ref{REAL}}
2522   @tab @code{--} @tab @code{FLOATI} @tab @code{FLOATJ} @tab @code{FLOATK}
2523 @end multitable
2525 @node AUTOMATIC and STATIC attributes
2526 @subsection @code{AUTOMATIC} and @code{STATIC} attributes
2527 @cindex variable attributes
2528 @cindex @code{AUTOMATIC}
2529 @cindex @code{STATIC}
2531 With @option{-fdec-static} GNU Fortran supports the DEC extended attributes
2532 @code{STATIC} and @code{AUTOMATIC} to provide explicit specification of entity
2533 storage.  These follow the syntax of the Fortran standard @code{SAVE} attribute.
2535 @code{STATIC} is exactly equivalent to @code{SAVE}, and specifies that
2536 an entity should be allocated in static memory.  As an example, @code{STATIC}
2537 local variables will retain their values across multiple calls to a function.
2539 Entities marked @code{AUTOMATIC} will be stack automatic whenever possible.
2540 @code{AUTOMATIC} is the default for local variables smaller than
2541 @option{-fmax-stack-var-size}, unless @option{-fno-automatic} is given.  This
2542 attribute overrides @option{-fno-automatic}, @option{-fmax-stack-var-size}, and
2543 blanket @code{SAVE} statements.
2546 Examples:
2548 @example
2549 subroutine f
2550   integer, automatic :: i  ! automatic variable
2551   integer x, y             ! static variables
2552   save
2553   ...
2554 endsubroutine
2555 @end example
2556 @example
2557 subroutine f
2558   integer a, b, c, x, y, z
2559   static :: x
2560   save y
2561   automatic z, c
2562   ! a, b, c, and z are automatic
2563   ! x and y are static
2564 endsubroutine
2565 @end example
2566 @example
2567 ! Compiled with -fno-automatic
2568 subroutine f
2569   integer a, b, c, d
2570   automatic :: a
2571   ! a is automatic; b, c, and d are static
2572 endsubroutine
2573 @end example
2575 @node Extended math intrinsics
2576 @subsection Extended math intrinsics
2577 @cindex intrinsics, math
2578 @cindex intrinsics, trigonometric functions
2580 GNU Fortran supports an extended list of mathematical intrinsics with the
2581 compile flag @option{-fdec-math} for compatability with legacy code.
2582 These intrinsics are described fully in @ref{Intrinsic Procedures} where it is
2583 noted that they are extensions and should be avoided whenever possible.
2585 Specifically, @option{-fdec-math} enables the @ref{COTAN} intrinsic, and
2586 trigonometric intrinsics which accept or produce values in degrees instead of
2587 radians.  Here is a summary of the new intrinsics:
2589 @multitable @columnfractions .5 .5
2590 @headitem Radians @tab Degrees
2591 @item @code{@ref{ACOS}}   @tab @code{@ref{ACOSD}}*
2592 @item @code{@ref{ASIN}}   @tab @code{@ref{ASIND}}*
2593 @item @code{@ref{ATAN}}   @tab @code{@ref{ATAND}}*
2594 @item @code{@ref{ATAN2}}  @tab @code{@ref{ATAN2D}}*
2595 @item @code{@ref{COS}}    @tab @code{@ref{COSD}}*
2596 @item @code{@ref{COTAN}}* @tab @code{@ref{COTAND}}*
2597 @item @code{@ref{SIN}}    @tab @code{@ref{SIND}}*
2598 @item @code{@ref{TAN}}    @tab @code{@ref{TAND}}*
2599 @end multitable
2601 * Enabled with @option{-fdec-math}.
2603 For advanced users, it may be important to know the implementation of these
2604 functions. They are simply wrappers around the standard radian functions, which
2605 have more accurate builtin versions. These functions convert their arguments
2606 (or results) to degrees (or radians) by taking the value modulus 360 (or 2*pi)
2607 and then multiplying it by a constant radian-to-degree (or degree-to-radian)
2608 factor, as appropriate. The factor is computed at compile-time as 180/pi (or
2609 pi/180).
2611 @node Form feed as whitespace
2612 @subsection Form feed as whitespace
2613 @cindex form feed whitespace
2615 Historically, legacy compilers allowed insertion of form feed characters ('\f',
2616 ASCII 0xC) at the beginning of lines for formatted output to line printers,
2617 though the Fortran standard does not mention this. GNU Fortran supports the
2618 interpretation of form feed characters in source as whitespace for
2619 compatibility.
2621 @node TYPE as an alias for PRINT
2622 @subsection TYPE as an alias for PRINT
2623 @cindex type alias print
2624 For compatibility, GNU Fortran will interpret @code{TYPE} statements as
2625 @code{PRINT} statements with the flag @option{-fdec}.  With this flag asserted,
2626 the following two examples are equivalent:
2628 @smallexample
2629 TYPE *, 'hello world'
2630 @end smallexample
2632 @smallexample
2633 PRINT *, 'hello world'
2634 @end smallexample
2636 @node %LOC as an rvalue
2637 @subsection %LOC as an rvalue
2638 @cindex LOC
2639 Normally @code{%LOC} is allowed only in parameter lists.  However the intrinsic
2640 function @code{LOC} does the same thing, and is usable as the right-hand-side of
2641 assignments. For compatibility, GNU Fortran supports the use of @code{%LOC} as
2642 an alias for the builtin @code{LOC} with @option{-std=legacy}.  With this
2643 feature enabled the following two examples are equivalent:
2645 @smallexample
2646 integer :: i, l
2647 l = %loc(i)
2648 call sub(l)
2649 @end smallexample
2651 @smallexample
2652 integer :: i
2653 call sub(%loc(i))
2654 @end smallexample
2656 @node .XOR. operator
2657 @subsection .XOR. operator
2658 @cindex operators, xor
2660 GNU Fortran supports @code{.XOR.} as a logical operator with @code{-std=legacy}
2661 for compatibility with legacy code. @code{.XOR.} is equivalent to
2662 @code{.NEQV.}. That is, the output is true if and only if the inputs differ.
2664 @node Bitwise logical operators
2665 @subsection Bitwise logical operators
2666 @cindex logical, bitwise
2668 With @option{-fdec}, GNU Fortran relaxes the type constraints on
2669 logical operators to allow integer operands, and performs the corresponding
2670 bitwise operation instead.  This flag is for compatibility only, and should be
2671 avoided in new code.  Consider:
2673 @smallexample
2674   INTEGER :: i, j
2675   i = z'33'
2676   j = z'cc'
2677   print *, i .AND. j
2678 @end smallexample
2680 In this example, compiled with @option{-fdec}, GNU Fortran will
2681 replace the @code{.AND.} operation with a call to the intrinsic
2682 @code{@ref{IAND}} function, yielding the bitwise-and of @code{i} and @code{j}.
2684 Note that this conversion will occur if at least one operand is of integral
2685 type.  As a result, a logical operand will be converted to an integer when the
2686 other operand is an integer in a logical operation.  In this case,
2687 @code{.TRUE.} is converted to @code{1} and @code{.FALSE.} to @code{0}.
2689 Here is the mapping of logical operator to bitwise intrinsic used with
2690 @option{-fdec}:
2692 @multitable @columnfractions .25 .25 .5
2693 @headitem Operator @tab Intrinsic @tab Bitwise operation
2694 @item @code{.NOT.} @tab @code{@ref{NOT}} @tab complement
2695 @item @code{.AND.} @tab @code{@ref{IAND}} @tab intersection
2696 @item @code{.OR.} @tab @code{@ref{IOR}} @tab union
2697 @item @code{.NEQV.} @tab @code{@ref{IEOR}} @tab exclusive or
2698 @item @code{.EQV.} @tab @code{@ref{NOT}(@ref{IEOR})} @tab complement of exclusive or
2699 @end multitable
2701 @node Extended I/O specifiers
2702 @subsection Extended I/O specifiers
2703 @cindex @code{CARRIAGECONTROL}
2704 @cindex @code{READONLY}
2705 @cindex @code{SHARE}
2706 @cindex @code{SHARED}
2707 @cindex @code{NOSHARED}
2708 @cindex I/O specifiers
2710 GNU Fortran supports the additional legacy I/O specifiers
2711 @code{CARRIAGECONTROL}, @code{READONLY}, and @code{SHARE} with the
2712 compile flag @option{-fdec}, for compatibility.
2714 @table @code
2715 @item CARRIAGECONTROL
2716 The @code{CARRIAGECONTROL} specifier allows a user to control line
2717 termination settings between output records for an I/O unit. The specifier has
2718 no meaning for readonly files. When @code{CARRAIGECONTROL} is specified upon
2719 opening a unit for formatted writing, the exact @code{CARRIAGECONTROL} setting
2720 determines what characters to write between output records. The syntax is:
2722 @smallexample
2723 OPEN(..., CARRIAGECONTROL=cc)
2724 @end smallexample
2726 Where @emph{cc} is a character expression that evaluates to one of the
2727 following values:
2729 @multitable @columnfractions .2 .8
2730 @item @code{'LIST'} @tab One line feed between records (default)
2731 @item @code{'FORTRAN'} @tab Legacy interpretation of the first character (see below)
2732 @item @code{'NONE'} @tab No separator between records
2733 @end multitable
2735 With @code{CARRIAGECONTROL='FORTRAN'}, when a record is written, the first
2736 character of the input record is not written, and instead determines the output
2737 record separator as follows:
2739 @multitable @columnfractions .3 .3 .4
2740 @headitem Leading character @tab Meaning @tab Output separating character(s)
2741 @item @code{'+'} @tab Overprinting @tab Carriage return only
2742 @item @code{'-'} @tab New line @tab Line feed and carriage return
2743 @item @code{'0'} @tab Skip line @tab Two line feeds and carriage return
2744 @item @code{'1'} @tab New page @tab Form feed and carriage return
2745 @item @code{'$'} @tab Prompting @tab Line feed (no carriage return)
2746 @item @code{CHAR(0)} @tab Overprinting (no advance) @tab None
2747 @end multitable
2749 @item READONLY
2750 The @code{READONLY} specifier may be given upon opening a unit, and is
2751 equivalent to specifying @code{ACTION='READ'}, except that the file may not be
2752 deleted on close (i.e. @code{CLOSE} with @code{STATUS="DELETE"}). The syntax
2755 @smallexample
2756 @code{OPEN(..., READONLY)}
2757 @end smallexample
2759 @item SHARE
2760 The @code{SHARE} specifier allows system-level locking on a unit upon opening
2761 it for controlled access from multiple processes/threads. The @code{SHARE}
2762 specifier has several forms:
2764 @smallexample
2765 OPEN(..., SHARE=sh)
2766 OPEN(..., SHARED)
2767 OPEN(..., NOSHARED)
2768 @end smallexample
2770 Where @emph{sh} in the first form is a character expression that evaluates to
2771 a value as seen in the table below. The latter two forms are aliases
2772 for particular values of @emph{sh}:
2774 @multitable @columnfractions .3 .3 .4
2775 @headitem Explicit form @tab Short form @tab Meaning
2776 @item @code{SHARE='DENYRW'} @tab @code{NOSHARED} @tab Exclusive (write) lock
2777 @item @code{SHARE='DENYNONE'} @tab @code{SHARED} @tab Shared (read) lock
2778 @end multitable
2780 In general only one process may hold an exclusive (write) lock for a given file
2781 at a time, whereas many processes may hold shared (read) locks for the same
2782 file.
2784 The behavior of locking may vary with your operating system. On POSIX systems,
2785 locking is implemented with @code{fcntl}. Consult your corresponding operating
2786 system's manual pages for further details. Locking via @code{SHARE=} is not
2787 supported on other systems.
2789 @end table
2791 @node Legacy PARAMETER statements
2792 @subsection Legacy PARAMETER statements
2793 @cindex PARAMETER
2795 For compatibility, GNU Fortran supports legacy PARAMETER statements without
2796 parentheses with @option{-std=legacy}.  A warning is emitted if used with
2797 @option{-std=gnu}, and an error is acknowledged with a real Fortran standard
2798 flag (@option{-std=f95}, etc...).  These statements take the following form:
2800 @smallexample
2801 implicit real (E)
2802 parameter e = 2.718282
2803 real c
2804 parameter c = 3.0e8
2805 @end smallexample
2807 @node Default exponents
2808 @subsection Default exponents
2809 @cindex exponent
2811 For compatibility, GNU Fortran supports a default exponent of zero in real
2812 constants with @option{-fdec}.  For example, @code{9e} would be
2813 interpreted as @code{9e0}, rather than an error.
2816 @node Extensions not implemented in GNU Fortran
2817 @section Extensions not implemented in GNU Fortran
2818 @cindex extensions, not implemented
2820 The long history of the Fortran language, its wide use and broad
2821 userbase, the large number of different compiler vendors and the lack of
2822 some features crucial to users in the first standards have lead to the
2823 existence of a number of important extensions to the language.  While
2824 some of the most useful or popular extensions are supported by the GNU
2825 Fortran compiler, not all existing extensions are supported.  This section
2826 aims at listing these extensions and offering advice on how best make
2827 code that uses them running with the GNU Fortran compiler.
2829 @c More can be found here:
2830 @c   -- https://gcc.gnu.org/onlinedocs/gcc-3.4.6/g77/Missing-Features.html
2831 @c   -- the list of Fortran and libgfortran bugs closed as WONTFIX:
2832 @c      http://tinyurl.com/2u4h5y
2834 @menu
2835 * ENCODE and DECODE statements::
2836 * Variable FORMAT expressions::
2837 @c * Q edit descriptor::
2838 @c * TYPE and ACCEPT I/O Statements::
2839 @c * DEFAULTFILE, DISPOSE and RECORDTYPE I/O specifiers::
2840 @c * Omitted arguments in procedure call::
2841 * Alternate complex function syntax::
2842 * Volatile COMMON blocks::
2843 * OPEN( ... NAME=)::
2844 @end menu
2846 @node ENCODE and DECODE statements
2847 @subsection @code{ENCODE} and @code{DECODE} statements
2848 @cindex @code{ENCODE}
2849 @cindex @code{DECODE}
2851 GNU Fortran does not support the @code{ENCODE} and @code{DECODE}
2852 statements.  These statements are best replaced by @code{READ} and
2853 @code{WRITE} statements involving internal files (@code{CHARACTER}
2854 variables and arrays), which have been part of the Fortran standard since
2855 Fortran 77.  For example, replace a code fragment like
2857 @smallexample
2858       INTEGER*1 LINE(80)
2859       REAL A, B, C
2860 c     ... Code that sets LINE
2861       DECODE (80, 9000, LINE) A, B, C
2862  9000 FORMAT (1X, 3(F10.5))
2863 @end smallexample
2865 @noindent
2866 with the following:
2868 @smallexample
2869       CHARACTER(LEN=80) LINE
2870       REAL A, B, C
2871 c     ... Code that sets LINE
2872       READ (UNIT=LINE, FMT=9000) A, B, C
2873  9000 FORMAT (1X, 3(F10.5))
2874 @end smallexample
2876 Similarly, replace a code fragment like
2878 @smallexample
2879       INTEGER*1 LINE(80)
2880       REAL A, B, C
2881 c     ... Code that sets A, B and C
2882       ENCODE (80, 9000, LINE) A, B, C
2883  9000 FORMAT (1X, 'OUTPUT IS ', 3(F10.5))
2884 @end smallexample
2886 @noindent
2887 with the following:
2889 @smallexample
2890       CHARACTER(LEN=80) LINE
2891       REAL A, B, C
2892 c     ... Code that sets A, B and C
2893       WRITE (UNIT=LINE, FMT=9000) A, B, C
2894  9000 FORMAT (1X, 'OUTPUT IS ', 3(F10.5))
2895 @end smallexample
2898 @node Variable FORMAT expressions
2899 @subsection Variable @code{FORMAT} expressions
2900 @cindex @code{FORMAT}
2902 A variable @code{FORMAT} expression is format statement which includes
2903 angle brackets enclosing a Fortran expression: @code{FORMAT(I<N>)}.  GNU
2904 Fortran does not support this legacy extension.  The effect of variable
2905 format expressions can be reproduced by using the more powerful (and
2906 standard) combination of internal output and string formats.  For example,
2907 replace a code fragment like this:
2909 @smallexample
2910       WRITE(6,20) INT1
2911  20   FORMAT(I<N+1>)
2912 @end smallexample
2914 @noindent
2915 with the following:
2917 @smallexample
2918 c     Variable declaration
2919       CHARACTER(LEN=20) FMT
2920 c     
2921 c     Other code here...
2923       WRITE(FMT,'("(I", I0, ")")') N+1
2924       WRITE(6,FMT) INT1
2925 @end smallexample
2927 @noindent
2928 or with:
2930 @smallexample
2931 c     Variable declaration
2932       CHARACTER(LEN=20) FMT
2933 c     
2934 c     Other code here...
2936       WRITE(FMT,*) N+1
2937       WRITE(6,"(I" // ADJUSTL(FMT) // ")") INT1
2938 @end smallexample
2941 @node Alternate complex function syntax
2942 @subsection Alternate complex function syntax
2943 @cindex Complex function
2945 Some Fortran compilers, including @command{g77}, let the user declare
2946 complex functions with the syntax @code{COMPLEX FUNCTION name*16()}, as
2947 well as @code{COMPLEX*16 FUNCTION name()}.  Both are non-standard, legacy
2948 extensions.  @command{gfortran} accepts the latter form, which is more
2949 common, but not the former.
2952 @node Volatile COMMON blocks
2953 @subsection Volatile @code{COMMON} blocks
2954 @cindex @code{VOLATILE}
2955 @cindex @code{COMMON}
2957 Some Fortran compilers, including @command{g77}, let the user declare
2958 @code{COMMON} with the @code{VOLATILE} attribute. This is
2959 invalid standard Fortran syntax and is not supported by
2960 @command{gfortran}.  Note that @command{gfortran} accepts
2961 @code{VOLATILE} variables in @code{COMMON} blocks since revision 4.3.
2964 @node OPEN( ... NAME=)
2965 @subsection @code{OPEN( ... NAME=)}
2966 @cindex @code{NAM}
2968 Some Fortran compilers, including @command{g77}, let the user declare
2969 @code{OPEN( ... NAME=)}. This is
2970 invalid standard Fortran syntax and is not supported by
2971 @command{gfortran}.  @code{OPEN( ... NAME=)} should be replaced
2972 with @code{OPEN( ... FILE=)}.
2976 @c ---------------------------------------------------------------------
2977 @c ---------------------------------------------------------------------
2978 @c Mixed-Language Programming
2979 @c ---------------------------------------------------------------------
2981 @node Mixed-Language Programming
2982 @chapter Mixed-Language Programming
2983 @cindex Interoperability
2984 @cindex Mixed-language programming
2986 @menu
2987 * Interoperability with C::
2988 * GNU Fortran Compiler Directives::
2989 * Non-Fortran Main Program::
2990 * Naming and argument-passing conventions::
2991 @end menu
2993 This chapter is about mixed-language interoperability, but also applies
2994 if one links Fortran code compiled by different compilers.  In most cases,
2995 use of the C Binding features of the Fortran 2003 standard is sufficient,
2996 and their use is highly recommended.
2999 @node Interoperability with C
3000 @section Interoperability with C
3002 @menu
3003 * Intrinsic Types::
3004 * Derived Types and struct::
3005 * Interoperable Global Variables::
3006 * Interoperable Subroutines and Functions::
3007 * Working with Pointers::
3008 * Further Interoperability of Fortran with C::
3009 @end menu
3011 Since Fortran 2003 (ISO/IEC 1539-1:2004(E)) there is a
3012 standardized way to generate procedure and derived-type
3013 declarations and global variables which are interoperable with C
3014 (ISO/IEC 9899:1999).  The @code{bind(C)} attribute has been added
3015 to inform the compiler that a symbol shall be interoperable with C;
3016 also, some constraints are added.  Note, however, that not
3017 all C features have a Fortran equivalent or vice versa.  For instance,
3018 neither C's unsigned integers nor C's functions with variable number
3019 of arguments have an equivalent in Fortran.
3021 Note that array dimensions are reversely ordered in C and that arrays in
3022 C always start with index 0 while in Fortran they start by default with
3023 1.  Thus, an array declaration @code{A(n,m)} in Fortran matches
3024 @code{A[m][n]} in C and accessing the element @code{A(i,j)} matches
3025 @code{A[j-1][i-1]}.  The element following @code{A(i,j)} (C: @code{A[j-1][i-1]};
3026 assuming @math{i < n}) in memory is @code{A(i+1,j)} (C: @code{A[j-1][i]}).
3028 @node Intrinsic Types
3029 @subsection Intrinsic Types
3031 In order to ensure that exactly the same variable type and kind is used
3032 in C and Fortran, the named constants shall be used which are defined in the
3033 @code{ISO_C_BINDING} intrinsic module.  That module contains named constants
3034 for kind parameters and character named constants for the escape sequences
3035 in C.  For a list of the constants, see @ref{ISO_C_BINDING}.
3037 For logical types, please note that the Fortran standard only guarantees
3038 interoperability between C99's @code{_Bool} and Fortran's @code{C_Bool}-kind
3039 logicals and C99 defines that @code{true} has the value 1 and @code{false}
3040 the value 0.  Using any other integer value with GNU Fortran's @code{LOGICAL}
3041 (with any kind parameter) gives an undefined result.  (Passing other integer
3042 values than 0 and 1 to GCC's @code{_Bool} is also undefined, unless the
3043 integer is explicitly or implicitly casted to @code{_Bool}.)
3047 @node Derived Types and struct
3048 @subsection Derived Types and struct
3050 For compatibility of derived types with @code{struct}, one needs to use
3051 the @code{BIND(C)} attribute in the type declaration.  For instance, the
3052 following type declaration
3054 @smallexample
3055  USE ISO_C_BINDING
3056  TYPE, BIND(C) :: myType
3057    INTEGER(C_INT) :: i1, i2
3058    INTEGER(C_SIGNED_CHAR) :: i3
3059    REAL(C_DOUBLE) :: d1
3060    COMPLEX(C_FLOAT_COMPLEX) :: c1
3061    CHARACTER(KIND=C_CHAR) :: str(5)
3062  END TYPE
3063 @end smallexample
3065 matches the following @code{struct} declaration in C
3067 @smallexample
3068  struct @{
3069    int i1, i2;
3070    /* Note: "char" might be signed or unsigned.  */
3071    signed char i3;
3072    double d1;
3073    float _Complex c1;
3074    char str[5];
3075  @} myType;
3076 @end smallexample
3078 Derived types with the C binding attribute shall not have the @code{sequence}
3079 attribute, type parameters, the @code{extends} attribute, nor type-bound
3080 procedures.  Every component must be of interoperable type and kind and may not
3081 have the @code{pointer} or @code{allocatable} attribute.  The names of the
3082 components are irrelevant for interoperability.
3084 As there exist no direct Fortran equivalents, neither unions nor structs
3085 with bit field or variable-length array members are interoperable.
3087 @node Interoperable Global Variables
3088 @subsection Interoperable Global Variables
3090 Variables can be made accessible from C using the C binding attribute,
3091 optionally together with specifying a binding name.  Those variables
3092 have to be declared in the declaration part of a @code{MODULE},
3093 be of interoperable type, and have neither the @code{pointer} nor
3094 the @code{allocatable} attribute.
3096 @smallexample
3097   MODULE m
3098     USE myType_module
3099     USE ISO_C_BINDING
3100     integer(C_INT), bind(C, name="_MyProject_flags") :: global_flag
3101     type(myType), bind(C) :: tp
3102   END MODULE
3103 @end smallexample
3105 Here, @code{_MyProject_flags} is the case-sensitive name of the variable
3106 as seen from C programs while @code{global_flag} is the case-insensitive
3107 name as seen from Fortran.  If no binding name is specified, as for
3108 @var{tp}, the C binding name is the (lowercase) Fortran binding name.
3109 If a binding name is specified, only a single variable may be after the
3110 double colon.  Note of warning: You cannot use a global variable to
3111 access @var{errno} of the C library as the C standard allows it to be
3112 a macro.  Use the @code{IERRNO} intrinsic (GNU extension) instead.
3114 @node Interoperable Subroutines and Functions
3115 @subsection Interoperable Subroutines and Functions
3117 Subroutines and functions have to have the @code{BIND(C)} attribute to
3118 be compatible with C.  The dummy argument declaration is relatively
3119 straightforward.  However, one needs to be careful because C uses
3120 call-by-value by default while Fortran behaves usually similar to
3121 call-by-reference.  Furthermore, strings and pointers are handled
3122 differently.  Note that in Fortran 2003 and 2008 only explicit size
3123 and assumed-size arrays are supported but not assumed-shape or
3124 deferred-shape (i.e. allocatable or pointer) arrays.  However, those
3125 are allowed since the Technical Specification 29113, see
3126 @ref{Further Interoperability of Fortran with C}
3128 To pass a variable by value, use the @code{VALUE} attribute.
3129 Thus, the following C prototype
3131 @smallexample
3132 @code{int func(int i, int *j)}
3133 @end smallexample
3135 matches the Fortran declaration
3137 @smallexample
3138   integer(c_int) function func(i,j)
3139     use iso_c_binding, only: c_int
3140     integer(c_int), VALUE :: i
3141     integer(c_int) :: j
3142 @end smallexample
3144 Note that pointer arguments also frequently need the @code{VALUE} attribute,
3145 see @ref{Working with Pointers}.
3147 Strings are handled quite differently in C and Fortran.  In C a string
3148 is a @code{NUL}-terminated array of characters while in Fortran each string
3149 has a length associated with it and is thus not terminated (by e.g.
3150 @code{NUL}).  For example, if one wants to use the following C function,
3152 @smallexample
3153   #include <stdio.h>
3154   void print_C(char *string) /* equivalent: char string[]  */
3155   @{
3156      printf("%s\n", string);
3157   @}
3158 @end smallexample
3160 to print ``Hello World'' from Fortran, one can call it using
3162 @smallexample
3163   use iso_c_binding, only: C_CHAR, C_NULL_CHAR
3164   interface
3165     subroutine print_c(string) bind(C, name="print_C")
3166       use iso_c_binding, only: c_char
3167       character(kind=c_char) :: string(*)
3168     end subroutine print_c
3169   end interface
3170   call print_c(C_CHAR_"Hello World"//C_NULL_CHAR)
3171 @end smallexample
3173 As the example shows, one needs to ensure that the
3174 string is @code{NUL} terminated.  Additionally, the dummy argument
3175 @var{string} of @code{print_C} is a length-one assumed-size
3176 array; using @code{character(len=*)} is not allowed.  The example
3177 above uses @code{c_char_"Hello World"} to ensure the string
3178 literal has the right type; typically the default character
3179 kind and @code{c_char} are the same and thus @code{"Hello World"}
3180 is equivalent.  However, the standard does not guarantee this.
3182 The use of strings is now further illustrated using the C library
3183 function @code{strncpy}, whose prototype is
3185 @smallexample
3186   char *strncpy(char *restrict s1, const char *restrict s2, size_t n);
3187 @end smallexample
3189 The function @code{strncpy} copies at most @var{n} characters from
3190 string @var{s2} to @var{s1} and returns @var{s1}.  In the following
3191 example, we ignore the return value:
3193 @smallexample
3194   use iso_c_binding
3195   implicit none
3196   character(len=30) :: str,str2
3197   interface
3198     ! Ignore the return value of strncpy -> subroutine
3199     ! "restrict" is always assumed if we do not pass a pointer
3200     subroutine strncpy(dest, src, n) bind(C)
3201       import
3202       character(kind=c_char),  intent(out) :: dest(*)
3203       character(kind=c_char),  intent(in)  :: src(*)
3204       integer(c_size_t), value, intent(in) :: n
3205     end subroutine strncpy
3206   end interface
3207   str = repeat('X',30) ! Initialize whole string with 'X'
3208   call strncpy(str, c_char_"Hello World"//C_NULL_CHAR, &
3209                len(c_char_"Hello World",kind=c_size_t))
3210   print '(a)', str ! prints: "Hello WorldXXXXXXXXXXXXXXXXXXX"
3211   end
3212 @end smallexample
3214 The intrinsic procedures are described in @ref{Intrinsic Procedures}.
3216 @node Working with Pointers
3217 @subsection Working with Pointers
3219 C pointers are represented in Fortran via the special opaque derived type
3220 @code{type(c_ptr)} (with private components).  Thus one needs to
3221 use intrinsic conversion procedures to convert from or to C pointers.
3223 For some applications, using an assumed type (@code{TYPE(*)}) can be an
3224 alternative to a C pointer; see
3225 @ref{Further Interoperability of Fortran with C}.
3227 For example,
3229 @smallexample
3230   use iso_c_binding
3231   type(c_ptr) :: cptr1, cptr2
3232   integer, target :: array(7), scalar
3233   integer, pointer :: pa(:), ps
3234   cptr1 = c_loc(array(1)) ! The programmer needs to ensure that the
3235                           ! array is contiguous if required by the C
3236                           ! procedure
3237   cptr2 = c_loc(scalar)
3238   call c_f_pointer(cptr2, ps)
3239   call c_f_pointer(cptr2, pa, shape=[7])
3240 @end smallexample
3242 When converting C to Fortran arrays, the one-dimensional @code{SHAPE} argument
3243 has to be passed.
3245 If a pointer is a dummy-argument of an interoperable procedure, it usually
3246 has to be declared using the @code{VALUE} attribute.  @code{void*}
3247 matches @code{TYPE(C_PTR), VALUE}, while @code{TYPE(C_PTR)} alone
3248 matches @code{void**}.
3250 Procedure pointers are handled analogously to pointers; the C type is
3251 @code{TYPE(C_FUNPTR)} and the intrinsic conversion procedures are
3252 @code{C_F_PROCPOINTER} and @code{C_FUNLOC}.
3254 Let us consider two examples of actually passing a procedure pointer from
3255 C to Fortran and vice versa.  Note that these examples are also very
3256 similar to passing ordinary pointers between both languages. First,
3257 consider this code in C:
3259 @smallexample
3260 /* Procedure implemented in Fortran.  */
3261 void get_values (void (*)(double));
3263 /* Call-back routine we want called from Fortran.  */
3264 void
3265 print_it (double x)
3267   printf ("Number is %f.\n", x);
3270 /* Call Fortran routine and pass call-back to it.  */
3271 void
3272 foobar ()
3274   get_values (&print_it);
3276 @end smallexample
3278 A matching implementation for @code{get_values} in Fortran, that correctly
3279 receives the procedure pointer from C and is able to call it, is given
3280 in the following @code{MODULE}:
3282 @smallexample
3283 MODULE m
3284   IMPLICIT NONE
3286   ! Define interface of call-back routine.
3287   ABSTRACT INTERFACE
3288     SUBROUTINE callback (x)
3289       USE, INTRINSIC :: ISO_C_BINDING
3290       REAL(KIND=C_DOUBLE), INTENT(IN), VALUE :: x
3291     END SUBROUTINE callback
3292   END INTERFACE
3294 CONTAINS
3296   ! Define C-bound procedure.
3297   SUBROUTINE get_values (cproc) BIND(C)
3298     USE, INTRINSIC :: ISO_C_BINDING
3299     TYPE(C_FUNPTR), INTENT(IN), VALUE :: cproc
3301     PROCEDURE(callback), POINTER :: proc
3303     ! Convert C to Fortran procedure pointer.
3304     CALL C_F_PROCPOINTER (cproc, proc)
3306     ! Call it.
3307     CALL proc (1.0_C_DOUBLE)
3308     CALL proc (-42.0_C_DOUBLE)
3309     CALL proc (18.12_C_DOUBLE)
3310   END SUBROUTINE get_values
3312 END MODULE m
3313 @end smallexample
3315 Next, we want to call a C routine that expects a procedure pointer argument
3316 and pass it a Fortran procedure (which clearly must be interoperable!).
3317 Again, the C function may be:
3319 @smallexample
3321 call_it (int (*func)(int), int arg)
3323   return func (arg);
3325 @end smallexample
3327 It can be used as in the following Fortran code:
3329 @smallexample
3330 MODULE m
3331   USE, INTRINSIC :: ISO_C_BINDING
3332   IMPLICIT NONE
3334   ! Define interface of C function.
3335   INTERFACE
3336     INTEGER(KIND=C_INT) FUNCTION call_it (func, arg) BIND(C)
3337       USE, INTRINSIC :: ISO_C_BINDING
3338       TYPE(C_FUNPTR), INTENT(IN), VALUE :: func
3339       INTEGER(KIND=C_INT), INTENT(IN), VALUE :: arg
3340     END FUNCTION call_it
3341   END INTERFACE
3343 CONTAINS
3345   ! Define procedure passed to C function.
3346   ! It must be interoperable!
3347   INTEGER(KIND=C_INT) FUNCTION double_it (arg) BIND(C)
3348     INTEGER(KIND=C_INT), INTENT(IN), VALUE :: arg
3349     double_it = arg + arg
3350   END FUNCTION double_it
3352   ! Call C function.
3353   SUBROUTINE foobar ()
3354     TYPE(C_FUNPTR) :: cproc
3355     INTEGER(KIND=C_INT) :: i
3357     ! Get C procedure pointer.
3358     cproc = C_FUNLOC (double_it)
3360     ! Use it.
3361     DO i = 1_C_INT, 10_C_INT
3362       PRINT *, call_it (cproc, i)
3363     END DO
3364   END SUBROUTINE foobar
3366 END MODULE m
3367 @end smallexample
3369 @node Further Interoperability of Fortran with C
3370 @subsection Further Interoperability of Fortran with C
3372 The Technical Specification ISO/IEC TS 29113:2012 on further
3373 interoperability of Fortran with C extends the interoperability support
3374 of Fortran 2003 and Fortran 2008. Besides removing some restrictions
3375 and constraints, it adds assumed-type (@code{TYPE(*)}) and assumed-rank
3376 (@code{dimension}) variables and allows for interoperability of
3377 assumed-shape, assumed-rank and deferred-shape arrays, including
3378 allocatables and pointers.
3380 Note: Currently, GNU Fortran does not support the array descriptor
3381 (dope vector) as specified in the Technical Specification, but uses
3382 an array descriptor with different fields. The Chasm Language
3383 Interoperability Tools, @url{http://chasm-interop.sourceforge.net/},
3384 provide an interface to GNU Fortran's array descriptor.
3386 The Technical Specification adds the following new features, which
3387 are supported by GNU Fortran:
3389 @itemize @bullet
3391 @item The @code{ASYNCHRONOUS} attribute has been clarified and
3392 extended to allow its use with asynchronous communication in
3393 user-provided libraries such as in implementations of the
3394 Message Passing Interface specification.
3396 @item Many constraints have been relaxed, in particular for
3397 the @code{C_LOC} and @code{C_F_POINTER} intrinsics.
3399 @item The @code{OPTIONAL} attribute is now allowed for dummy
3400 arguments; an absent argument matches a @code{NULL} pointer.
3402 @item Assumed types (@code{TYPE(*)}) have been added, which may
3403 only be used for dummy arguments.  They are unlimited polymorphic
3404 but contrary to @code{CLASS(*)} they do not contain any type
3405 information, similar to C's @code{void *} pointers.  Expressions
3406 of any type and kind can be passed; thus, it can be used as
3407 replacement for @code{TYPE(C_PTR)}, avoiding the use of
3408 @code{C_LOC} in the caller.
3410 Note, however, that @code{TYPE(*)} only accepts scalar arguments,
3411 unless the @code{DIMENSION} is explicitly specified.  As
3412 @code{DIMENSION(*)} only supports array (including array elements) but
3413 no scalars, it is not a full replacement for @code{C_LOC}.  On the
3414 other hand, assumed-type assumed-rank dummy arguments
3415 (@code{TYPE(*), DIMENSION(..)}) allow for both scalars and arrays, but
3416 require special code on the callee side to handle the array descriptor.
3418 @item Assumed-rank arrays (@code{DIMENSION(..)}) as dummy argument
3419 allow that scalars and arrays of any rank can be passed as actual
3420 argument. As the Technical Specification does not provide for direct
3421 means to operate with them, they have to be used either from the C side
3422 or be converted using @code{C_LOC} and @code{C_F_POINTER} to scalars
3423 or arrays of a specific rank. The rank can be determined using the
3424 @code{RANK} intrinisic.
3425 @end itemize
3428 Currently unimplemented:
3430 @itemize @bullet
3432 @item GNU Fortran always uses an array descriptor, which does not
3433 match the one of the Technical Specification. The
3434 @code{ISO_Fortran_binding.h} header file and the C functions it
3435 specifies are not available.
3437 @item Using assumed-shape, assumed-rank and deferred-shape arrays in
3438 @code{BIND(C)} procedures is not fully supported. In particular,
3439 C interoperable strings of other length than one are not supported
3440 as this requires the new array descriptor.
3441 @end itemize
3444 @node GNU Fortran Compiler Directives
3445 @section GNU Fortran Compiler Directives
3447 @menu
3448 * ATTRIBUTES directive::
3449 * UNROLL directive::
3450 @end menu
3452 @node ATTRIBUTES directive
3453 @subsection ATTRIBUTES directive
3455 The Fortran standard describes how a conforming program shall
3456 behave; however, the exact implementation is not standardized.  In order
3457 to allow the user to choose specific implementation details, compiler
3458 directives can be used to set attributes of variables and procedures
3459 which are not part of the standard.  Whether a given attribute is
3460 supported and its exact effects depend on both the operating system and
3461 on the processor; see
3462 @ref{Top,,C Extensions,gcc,Using the GNU Compiler Collection (GCC)}
3463 for details.
3465 For procedures and procedure pointers, the following attributes can
3466 be used to change the calling convention:
3468 @itemize
3469 @item @code{CDECL} -- standard C calling convention
3470 @item @code{STDCALL} -- convention where the called procedure pops the stack
3471 @item @code{FASTCALL} -- part of the arguments are passed via registers
3472 instead using the stack
3473 @end itemize
3475 Besides changing the calling convention, the attributes also influence
3476 the decoration of the symbol name, e.g., by a leading underscore or by
3477 a trailing at-sign followed by the number of bytes on the stack.  When
3478 assigning a procedure to a procedure pointer, both should use the same
3479 calling convention.
3481 On some systems, procedures and global variables (module variables and
3482 @code{COMMON} blocks) need special handling to be accessible when they
3483 are in a shared library.  The following attributes are available:
3485 @itemize
3486 @item @code{DLLEXPORT} -- provide a global pointer to a pointer in the DLL
3487 @item @code{DLLIMPORT} -- reference the function or variable using a
3488 global pointer
3489 @end itemize
3491 For dummy arguments, the @code{NO_ARG_CHECK} attribute can be used; in
3492 other compilers, it is also known as @code{IGNORE_TKR}.  For dummy arguments
3493 with this attribute actual arguments of any type and kind (similar to
3494 @code{TYPE(*)}), scalars and arrays of any rank (no equivalent
3495 in Fortran standard) are accepted.  As with @code{TYPE(*)}, the argument
3496 is unlimited polymorphic and no type information is available.
3497 Additionally, the argument may only be passed to dummy arguments
3498 with the @code{NO_ARG_CHECK} attribute and as argument to the
3499 @code{PRESENT} intrinsic function and to @code{C_LOC} of the
3500 @code{ISO_C_BINDING} module.
3502 Variables with @code{NO_ARG_CHECK} attribute shall be of assumed-type
3503 (@code{TYPE(*)}; recommended) or of type @code{INTEGER}, @code{LOGICAL},
3504 @code{REAL} or @code{COMPLEX}. They shall not have the @code{ALLOCATE},
3505 @code{CODIMENSION}, @code{INTENT(OUT)}, @code{POINTER} or @code{VALUE}
3506 attribute; furthermore, they shall be either scalar or of assumed-size
3507 (@code{dimension(*)}). As @code{TYPE(*)}, the @code{NO_ARG_CHECK} attribute
3508 requires an explicit interface.
3510 @itemize
3511 @item @code{NO_ARG_CHECK} -- disable the type, kind and rank checking
3512 @end itemize
3515 The attributes are specified using the syntax
3517 @code{!GCC$ ATTRIBUTES} @var{attribute-list} @code{::} @var{variable-list}
3519 where in free-form source code only whitespace is allowed before @code{!GCC$}
3520 and in fixed-form source code @code{!GCC$}, @code{cGCC$} or @code{*GCC$} shall
3521 start in the first column.
3523 For procedures, the compiler directives shall be placed into the body
3524 of the procedure; for variables and procedure pointers, they shall be in
3525 the same declaration part as the variable or procedure pointer.
3528 @node UNROLL directive
3529 @subsection UNROLL directive
3531 The syntax of the directive is
3533 @code{!GCC$ unroll N}
3535 You can use this directive to control how many times a loop should be unrolled.
3536 It must be placed immediately before a @code{DO} loop and applies only to the
3537 loop that follows.  N is an integer constant specifying the unrolling factor.
3538 The values of 0 and 1 block any unrolling of the loop.
3542 @node Non-Fortran Main Program
3543 @section Non-Fortran Main Program
3545 @menu
3546 * _gfortran_set_args:: Save command-line arguments
3547 * _gfortran_set_options:: Set library option flags
3548 * _gfortran_set_convert:: Set endian conversion
3549 * _gfortran_set_record_marker:: Set length of record markers
3550 * _gfortran_set_fpe:: Set when a Floating Point Exception should be raised
3551 * _gfortran_set_max_subrecord_length:: Set subrecord length
3552 @end menu
3554 Even if you are doing mixed-language programming, it is very
3555 likely that you do not need to know or use the information in this
3556 section.  Since it is about the internal structure of GNU Fortran,
3557 it may also change in GCC minor releases.
3559 When you compile a @code{PROGRAM} with GNU Fortran, a function
3560 with the name @code{main} (in the symbol table of the object file)
3561 is generated, which initializes the libgfortran library and then
3562 calls the actual program which uses the name @code{MAIN__}, for
3563 historic reasons.  If you link GNU Fortran compiled procedures
3564 to, e.g., a C or C++ program or to a Fortran program compiled by
3565 a different compiler, the libgfortran library is not initialized
3566 and thus a few intrinsic procedures do not work properly, e.g.
3567 those for obtaining the command-line arguments.
3569 Therefore, if your @code{PROGRAM} is not compiled with
3570 GNU Fortran and the GNU Fortran compiled procedures require
3571 intrinsics relying on the library initialization, you need to
3572 initialize the library yourself.  Using the default options,
3573 gfortran calls @code{_gfortran_set_args} and
3574 @code{_gfortran_set_options}.  The initialization of the former
3575 is needed if the called procedures access the command line
3576 (and for backtracing); the latter sets some flags based on the
3577 standard chosen or to enable backtracing.  In typical programs,
3578 it is not necessary to call any initialization function.
3580 If your @code{PROGRAM} is compiled with GNU Fortran, you shall
3581 not call any of the following functions.  The libgfortran
3582 initialization functions are shown in C syntax but using C
3583 bindings they are also accessible from Fortran.
3586 @node _gfortran_set_args
3587 @subsection @code{_gfortran_set_args} --- Save command-line arguments
3588 @fnindex _gfortran_set_args
3589 @cindex libgfortran initialization, set_args
3591 @table @asis
3592 @item @emph{Description}:
3593 @code{_gfortran_set_args} saves the command-line arguments; this
3594 initialization is required if any of the command-line intrinsics
3595 is called.  Additionally, it shall be called if backtracing is
3596 enabled (see @code{_gfortran_set_options}).
3598 @item @emph{Syntax}:
3599 @code{void _gfortran_set_args (int argc, char *argv[])}
3601 @item @emph{Arguments}:
3602 @multitable @columnfractions .15 .70
3603 @item @var{argc} @tab number of command line argument strings
3604 @item @var{argv} @tab the command-line argument strings; argv[0]
3605 is the pathname of the executable itself.
3606 @end multitable
3608 @item @emph{Example}:
3609 @smallexample
3610 int main (int argc, char *argv[])
3612   /* Initialize libgfortran.  */
3613   _gfortran_set_args (argc, argv);
3614   return 0;
3616 @end smallexample
3617 @end table
3620 @node _gfortran_set_options
3621 @subsection @code{_gfortran_set_options} --- Set library option flags
3622 @fnindex _gfortran_set_options
3623 @cindex libgfortran initialization, set_options
3625 @table @asis
3626 @item @emph{Description}:
3627 @code{_gfortran_set_options} sets several flags related to the Fortran
3628 standard to be used, whether backtracing should be enabled
3629 and whether range checks should be performed.  The syntax allows for
3630 upward compatibility since the number of passed flags is specified; for
3631 non-passed flags, the default value is used.  See also
3632 @pxref{Code Gen Options}.  Please note that not all flags are actually
3633 used.
3635 @item @emph{Syntax}:
3636 @code{void _gfortran_set_options (int num, int options[])}
3638 @item @emph{Arguments}:
3639 @multitable @columnfractions .15 .70
3640 @item @var{num} @tab number of options passed
3641 @item @var{argv} @tab The list of flag values
3642 @end multitable
3644 @item @emph{option flag list}:
3645 @multitable @columnfractions .15 .70
3646 @item @var{option}[0] @tab Allowed standard; can give run-time errors
3647 if e.g. an input-output edit descriptor is invalid in a given
3648 standard.  Possible values are (bitwise or-ed) @code{GFC_STD_F77} (1),
3649 @code{GFC_STD_F95_OBS} (2), @code{GFC_STD_F95_DEL} (4),
3650 @code{GFC_STD_F95} (8), @code{GFC_STD_F2003} (16), @code{GFC_STD_GNU}
3651 (32), @code{GFC_STD_LEGACY} (64), @code{GFC_STD_F2008} (128),
3652 @code{GFC_STD_F2008_OBS} (256), @code{GFC_STD_F2008_TS} (512),
3653 @code{GFC_STD_F2018} (1024), @code{GFC_STD_F2018_OBS} (2048), and
3654 @code{GFC_STD=F2018_DEL} (4096). Default: @code{GFC_STD_F95_OBS |
3655 GFC_STD_F95_DEL | GFC_STD_F95 | GFC_STD_F2003 | GFC_STD_F2008 |
3656 GFC_STD_F2008_TS | GFC_STD_F2008_OBS | GFC_STD_F77 | GFC_STD_F2018 |
3657 GFC_STD_F2018_OBS | GFC_STD_F2018_DEL | GFC_STD_GNU | GFC_STD_LEGACY}.
3658 @item @var{option}[1] @tab Standard-warning flag; prints a warning to
3659 standard error.  Default: @code{GFC_STD_F95_DEL | GFC_STD_LEGACY}.
3660 @item @var{option}[2] @tab If non zero, enable pedantic checking.
3661 Default: off.
3662 @item @var{option}[3] @tab Unused.
3663 @item @var{option}[4] @tab If non zero, enable backtracing on run-time
3664 errors.  Default: off. (Default in the compiler: on.)
3665 Note: Installs a signal handler and requires command-line
3666 initialization using @code{_gfortran_set_args}.
3667 @item @var{option}[5] @tab If non zero, supports signed zeros.
3668 Default: enabled.
3669 @item @var{option}[6] @tab Enables run-time checking.  Possible values
3670 are (bitwise or-ed): GFC_RTCHECK_BOUNDS (1), GFC_RTCHECK_ARRAY_TEMPS (2),
3671 GFC_RTCHECK_RECURSION (4), GFC_RTCHECK_DO (16), GFC_RTCHECK_POINTER (32).
3672 Default: disabled.
3673 @item @var{option}[7] @tab Unused.
3674 @item @var{option}[8] @tab Show a warning when invoking @code{STOP} and
3675 @code{ERROR STOP} if a floating-point exception occurred. Possible values
3676 are (bitwise or-ed) @code{GFC_FPE_INVALID} (1), @code{GFC_FPE_DENORMAL} (2),
3677 @code{GFC_FPE_ZERO} (4), @code{GFC_FPE_OVERFLOW} (8),
3678 @code{GFC_FPE_UNDERFLOW} (16), @code{GFC_FPE_INEXACT} (32). Default: None (0).
3679 (Default in the compiler: @code{GFC_FPE_INVALID | GFC_FPE_DENORMAL |
3680 GFC_FPE_ZERO | GFC_FPE_OVERFLOW | GFC_FPE_UNDERFLOW}.)
3681 @end multitable
3683 @item @emph{Example}:
3684 @smallexample
3685   /* Use gfortran 4.9 default options.  */
3686   static int options[] = @{68, 511, 0, 0, 1, 1, 0, 0, 31@};
3687   _gfortran_set_options (9, &options);
3688 @end smallexample
3689 @end table
3692 @node _gfortran_set_convert
3693 @subsection @code{_gfortran_set_convert} --- Set endian conversion
3694 @fnindex _gfortran_set_convert
3695 @cindex libgfortran initialization, set_convert
3697 @table @asis
3698 @item @emph{Description}:
3699 @code{_gfortran_set_convert} set the representation of data for
3700 unformatted files.
3702 @item @emph{Syntax}:
3703 @code{void _gfortran_set_convert (int conv)}
3705 @item @emph{Arguments}:
3706 @multitable @columnfractions .15 .70
3707 @item @var{conv} @tab Endian conversion, possible values:
3708 GFC_CONVERT_NATIVE (0, default), GFC_CONVERT_SWAP (1),
3709 GFC_CONVERT_BIG (2), GFC_CONVERT_LITTLE (3).
3710 @end multitable
3712 @item @emph{Example}:
3713 @smallexample
3714 int main (int argc, char *argv[])
3716   /* Initialize libgfortran.  */
3717   _gfortran_set_args (argc, argv);
3718   _gfortran_set_convert (1);
3719   return 0;
3721 @end smallexample
3722 @end table
3725 @node _gfortran_set_record_marker
3726 @subsection @code{_gfortran_set_record_marker} --- Set length of record markers
3727 @fnindex _gfortran_set_record_marker
3728 @cindex libgfortran initialization, set_record_marker
3730 @table @asis
3731 @item @emph{Description}:
3732 @code{_gfortran_set_record_marker} sets the length of record markers
3733 for unformatted files.
3735 @item @emph{Syntax}:
3736 @code{void _gfortran_set_record_marker (int val)}
3738 @item @emph{Arguments}:
3739 @multitable @columnfractions .15 .70
3740 @item @var{val} @tab Length of the record marker; valid values
3741 are 4 and 8.  Default is 4.
3742 @end multitable
3744 @item @emph{Example}:
3745 @smallexample
3746 int main (int argc, char *argv[])
3748   /* Initialize libgfortran.  */
3749   _gfortran_set_args (argc, argv);
3750   _gfortran_set_record_marker (8);
3751   return 0;
3753 @end smallexample
3754 @end table
3757 @node _gfortran_set_fpe
3758 @subsection @code{_gfortran_set_fpe} --- Enable floating point exception traps
3759 @fnindex _gfortran_set_fpe
3760 @cindex libgfortran initialization, set_fpe
3762 @table @asis
3763 @item @emph{Description}:
3764 @code{_gfortran_set_fpe} enables floating point exception traps for
3765 the specified exceptions.  On most systems, this will result in a
3766 SIGFPE signal being sent and the program being aborted.
3768 @item @emph{Syntax}:
3769 @code{void _gfortran_set_fpe (int val)}
3771 @item @emph{Arguments}:
3772 @multitable @columnfractions .15 .70
3773 @item @var{option}[0] @tab IEEE exceptions.  Possible values are
3774 (bitwise or-ed) zero (0, default) no trapping,
3775 @code{GFC_FPE_INVALID} (1), @code{GFC_FPE_DENORMAL} (2),
3776 @code{GFC_FPE_ZERO} (4), @code{GFC_FPE_OVERFLOW} (8),
3777 @code{GFC_FPE_UNDERFLOW} (16), and @code{GFC_FPE_INEXACT} (32).
3778 @end multitable
3780 @item @emph{Example}:
3781 @smallexample
3782 int main (int argc, char *argv[])
3784   /* Initialize libgfortran.  */
3785   _gfortran_set_args (argc, argv);
3786   /* FPE for invalid operations such as SQRT(-1.0).  */
3787   _gfortran_set_fpe (1);
3788   return 0;
3790 @end smallexample
3791 @end table
3794 @node _gfortran_set_max_subrecord_length
3795 @subsection @code{_gfortran_set_max_subrecord_length} --- Set subrecord length
3796 @fnindex _gfortran_set_max_subrecord_length
3797 @cindex libgfortran initialization, set_max_subrecord_length
3799 @table @asis
3800 @item @emph{Description}:
3801 @code{_gfortran_set_max_subrecord_length} set the maximum length
3802 for a subrecord.  This option only makes sense for testing and
3803 debugging of unformatted I/O.
3805 @item @emph{Syntax}:
3806 @code{void _gfortran_set_max_subrecord_length (int val)}
3808 @item @emph{Arguments}:
3809 @multitable @columnfractions .15 .70
3810 @item @var{val} @tab the maximum length for a subrecord;
3811 the maximum permitted value is 2147483639, which is also
3812 the default.
3813 @end multitable
3815 @item @emph{Example}:
3816 @smallexample
3817 int main (int argc, char *argv[])
3819   /* Initialize libgfortran.  */
3820   _gfortran_set_args (argc, argv);
3821   _gfortran_set_max_subrecord_length (8);
3822   return 0;
3824 @end smallexample
3825 @end table
3828 @node Naming and argument-passing conventions
3829 @section Naming and argument-passing conventions
3831 This section gives an overview about the naming convention of procedures
3832 and global variables and about the argument passing conventions used by
3833 GNU Fortran.  If a C binding has been specified, the naming convention
3834 and some of the argument-passing conventions change.  If possible,
3835 mixed-language and mixed-compiler projects should use the better defined
3836 C binding for interoperability.  See @pxref{Interoperability with C}.
3838 @menu
3839 * Naming conventions::
3840 * Argument passing conventions::
3841 @end menu
3844 @node Naming conventions
3845 @subsection Naming conventions
3847 According the Fortran standard, valid Fortran names consist of a letter
3848 between @code{A} to @code{Z}, @code{a} to @code{z}, digits @code{0},
3849 @code{1} to @code{9} and underscores (@code{_}) with the restriction
3850 that names may only start with a letter.  As vendor extension, the
3851 dollar sign (@code{$}) is additionally permitted with the option
3852 @option{-fdollar-ok}, but not as first character and only if the
3853 target system supports it.
3855 By default, the procedure name is the lower-cased Fortran name with an
3856 appended underscore (@code{_}); using @option{-fno-underscoring} no
3857 underscore is appended while @code{-fsecond-underscore} appends two
3858 underscores.  Depending on the target system and the calling convention,
3859 the procedure might be additionally dressed; for instance, on 32bit
3860 Windows with @code{stdcall}, an at-sign @code{@@} followed by an integer
3861 number is appended.  For the changing the calling convention, see
3862 @pxref{GNU Fortran Compiler Directives}.
3864 For common blocks, the same convention is used, i.e. by default an
3865 underscore is appended to the lower-cased Fortran name.  Blank commons
3866 have the name @code{__BLNK__}.
3868 For procedures and variables declared in the specification space of a
3869 module, the name is formed by @code{__}, followed by the lower-cased
3870 module name, @code{_MOD_}, and the lower-cased Fortran name.  Note that
3871 no underscore is appended.
3874 @node Argument passing conventions
3875 @subsection Argument passing conventions
3877 Subroutines do not return a value (matching C99's @code{void}) while
3878 functions either return a value as specified in the platform ABI or
3879 the result variable is passed as hidden argument to the function and
3880 no result is returned.  A hidden result variable is used when the
3881 result variable is an array or of type @code{CHARACTER}.
3883 Arguments are passed according to the platform ABI. In particular,
3884 complex arguments might not be compatible to a struct with two real
3885 components for the real and imaginary part. The argument passing
3886 matches the one of C99's @code{_Complex}.  Functions with scalar
3887 complex result variables return their value and do not use a
3888 by-reference argument.  Note that with the @option{-ff2c} option,
3889 the argument passing is modified and no longer completely matches
3890 the platform ABI.  Some other Fortran compilers use @code{f2c}
3891 semantic by default; this might cause problems with
3892 interoperablility.
3894 GNU Fortran passes most arguments by reference, i.e. by passing a
3895 pointer to the data.  Note that the compiler might use a temporary
3896 variable into which the actual argument has been copied, if required
3897 semantically (copy-in/copy-out).
3899 For arguments with @code{ALLOCATABLE} and @code{POINTER}
3900 attribute (including procedure pointers), a pointer to the pointer
3901 is passed such that the pointer address can be modified in the
3902 procedure.
3904 For dummy arguments with the @code{VALUE} attribute: Scalar arguments
3905 of the type @code{INTEGER}, @code{LOGICAL}, @code{REAL} and
3906 @code{COMPLEX} are passed by value according to the platform ABI.
3907 (As vendor extension and not recommended, using @code{%VAL()} in the
3908 call to a procedure has the same effect.) For @code{TYPE(C_PTR)} and
3909 procedure pointers, the pointer itself is passed such that it can be
3910 modified without affecting the caller.
3911 @c FIXME: Document how VALUE is handled for CHARACTER, TYPE,
3912 @c CLASS and arrays, i.e. whether the copy-in is done in the caller
3913 @c or in the callee.
3915 For Boolean (@code{LOGICAL}) arguments, please note that GCC expects
3916 only the integer value 0 and 1.  If a GNU Fortran @code{LOGICAL}
3917 variable contains another integer value, the result is undefined.
3918 As some other Fortran compilers use @math{-1} for @code{.TRUE.},
3919 extra care has to be taken -- such as passing the value as
3920 @code{INTEGER}.  (The same value restriction also applies to other
3921 front ends of GCC, e.g. to GCC's C99 compiler for @code{_Bool}
3922 or GCC's Ada compiler for @code{Boolean}.)
3924 For arguments of @code{CHARACTER} type, the character length is passed
3925 as a hidden argument at the end of the argument list.  For
3926 deferred-length strings, the value is passed by reference, otherwise
3927 by value.  The character length has the C type @code{size_t} (or
3928 @code{INTEGER(kind=C_SIZE_T)} in Fortran).  Note that this is
3929 different to older versions of the GNU Fortran compiler, where the
3930 type of the hidden character length argument was a C @code{int}.  In
3931 order to retain compatibility with older versions, one can e.g. for
3932 the following Fortran procedure
3934 @smallexample
3935 subroutine fstrlen (s, a)
3936    character(len=*) :: s
3937    integer :: a
3938    print*, len(s)
3939 end subroutine fstrlen
3940 @end smallexample
3942 define the corresponding C prototype as follows:
3944 @smallexample
3945 #if __GNUC__ > 7
3946 typedef size_t fortran_charlen_t;
3947 #else
3948 typedef int fortran_charlen_t;
3949 #endif
3951 void fstrlen_ (char*, int*, fortran_charlen_t);
3952 @end smallexample
3954 In order to avoid such compiler-specific details, for new code it is
3955 instead recommended to use the ISO_C_BINDING feature.
3957 Note with C binding, @code{CHARACTER(len=1)} result variables are
3958 returned according to the platform ABI and no hidden length argument
3959 is used for dummy arguments; with @code{VALUE}, those variables are
3960 passed by value.
3962 For @code{OPTIONAL} dummy arguments, an absent argument is denoted
3963 by a NULL pointer, except for scalar dummy arguments of type
3964 @code{INTEGER}, @code{LOGICAL}, @code{REAL} and @code{COMPLEX}
3965 which have the @code{VALUE} attribute.  For those, a hidden Boolean
3966 argument (@code{logical(kind=C_bool),value}) is used to indicate
3967 whether the argument is present.
3969 Arguments which are assumed-shape, assumed-rank or deferred-rank
3970 arrays or, with @option{-fcoarray=lib}, allocatable scalar coarrays use
3971 an array descriptor.  All other arrays pass the address of the
3972 first element of the array.  With @option{-fcoarray=lib}, the token
3973 and the offset belonging to nonallocatable coarrays dummy arguments
3974 are passed as hidden argument along the character length hidden
3975 arguments.  The token is an oparque pointer identifying the coarray
3976 and the offset is a passed-by-value integer of kind @code{C_PTRDIFF_T},
3977 denoting the byte offset between the base address of the coarray and
3978 the passed scalar or first element of the passed array.
3980 The arguments are passed in the following order
3981 @itemize @bullet
3982 @item Result variable, when the function result is passed by reference
3983 @item Character length of the function result, if it is a of type
3984 @code{CHARACTER} and no C binding is used
3985 @item The arguments in the order in which they appear in the Fortran
3986 declaration
3987 @item The the present status for optional arguments with value attribute,
3988 which are internally passed by value
3989 @item The character length and/or coarray token and offset for the first
3990 argument which is a @code{CHARACTER} or a nonallocatable coarray dummy
3991 argument, followed by the hidden arguments of the next dummy argument
3992 of such a type
3993 @end itemize
3996 @c ---------------------------------------------------------------------
3997 @c Coarray Programming
3998 @c ---------------------------------------------------------------------
4000 @node Coarray Programming
4001 @chapter Coarray Programming
4002 @cindex Coarrays
4004 @menu
4005 * Type and enum ABI Documentation::
4006 * Function ABI Documentation::
4007 @end menu
4010 @node Type and enum ABI Documentation
4011 @section Type and enum ABI Documentation
4013 @menu
4014 * caf_token_t::
4015 * caf_register_t::
4016 * caf_deregister_t::
4017 * caf_reference_t::
4018 * caf_team_t::
4019 @end menu
4021 @node caf_token_t
4022 @subsection @code{caf_token_t}
4024 Typedef of type @code{void *} on the compiler side. Can be any data
4025 type on the library side.
4027 @node caf_register_t
4028 @subsection @code{caf_register_t}
4030 Indicates which kind of coarray variable should be registered.
4032 @verbatim
4033 typedef enum caf_register_t {
4034   CAF_REGTYPE_COARRAY_STATIC,
4035   CAF_REGTYPE_COARRAY_ALLOC,
4036   CAF_REGTYPE_LOCK_STATIC,
4037   CAF_REGTYPE_LOCK_ALLOC,
4038   CAF_REGTYPE_CRITICAL,
4039   CAF_REGTYPE_EVENT_STATIC,
4040   CAF_REGTYPE_EVENT_ALLOC,
4041   CAF_REGTYPE_COARRAY_ALLOC_REGISTER_ONLY,
4042   CAF_REGTYPE_COARRAY_ALLOC_ALLOCATE_ONLY
4044 caf_register_t;
4045 @end verbatim
4047 The values @code{CAF_REGTYPE_COARRAY_ALLOC_REGISTER_ONLY} and
4048 @code{CAF_REGTYPE_COARRAY_ALLOC_ALLOCATE_ONLY} are for allocatable components
4049 in derived type coarrays only.  The first one sets up the token without
4050 allocating memory for allocatable component.  The latter one only allocates the
4051 memory for an allocatable component in a derived type coarray.  The token
4052 needs to be setup previously by the REGISTER_ONLY.  This allows to have
4053 allocatable components un-allocated on some images.  The status whether an
4054 allocatable component is allocated on a remote image can be queried by
4055 @code{_caf_is_present} which used internally by the @code{ALLOCATED}
4056 intrinsic.
4058 @node caf_deregister_t
4059 @subsection @code{caf_deregister_t}
4061 @verbatim
4062 typedef enum caf_deregister_t {
4063   CAF_DEREGTYPE_COARRAY_DEREGISTER,
4064   CAF_DEREGTYPE_COARRAY_DEALLOCATE_ONLY
4066 caf_deregister_t;
4067 @end verbatim
4069 Allows to specifiy the type of deregistration of a coarray object.  The
4070 @code{CAF_DEREGTYPE_COARRAY_DEALLOCATE_ONLY} flag is only allowed for
4071 allocatable components in derived type coarrays.
4073 @node caf_reference_t
4074 @subsection @code{caf_reference_t}
4076 The structure used for implementing arbitrary reference chains.
4077 A @code{CAF_REFERENCE_T} allows to specify a component reference or any kind
4078 of array reference of any rank supported by gfortran.  For array references all
4079 kinds as known by the compiler/Fortran standard are supported indicated by
4080 a @code{MODE}.
4082 @verbatim
4083 typedef enum caf_ref_type_t {
4084   /* Reference a component of a derived type, either regular one or an
4085      allocatable or pointer type.  For regular ones idx in caf_reference_t is
4086      set to -1.  */
4087   CAF_REF_COMPONENT,
4088   /* Reference an allocatable array.  */
4089   CAF_REF_ARRAY,
4090   /* Reference a non-allocatable/non-pointer array.  I.e., the coarray object
4091      has no array descriptor associated and the addressing is done
4092      completely using the ref.  */
4093   CAF_REF_STATIC_ARRAY
4094 } caf_ref_type_t;
4095 @end verbatim
4097 @verbatim
4098 typedef enum caf_array_ref_t {
4099   /* No array ref.  This terminates the array ref.  */
4100   CAF_ARR_REF_NONE = 0,
4101   /* Reference array elements given by a vector.  Only for this mode
4102      caf_reference_t.u.a.dim[i].v is valid.  */
4103   CAF_ARR_REF_VECTOR,
4104   /* A full array ref (:).  */
4105   CAF_ARR_REF_FULL,
4106   /* Reference a range on elements given by start, end and stride.  */
4107   CAF_ARR_REF_RANGE,
4108   /* Only a single item is referenced given in the start member.  */
4109   CAF_ARR_REF_SINGLE,
4110   /* An array ref of the kind (i:), where i is an arbitrary valid index in the
4111      array.  The index i is given in the start member.  */
4112   CAF_ARR_REF_OPEN_END,
4113   /* An array ref of the kind (:i), where the lower bound of the array ref
4114      is given by the remote side.  The index i is given in the end member.  */
4115   CAF_ARR_REF_OPEN_START
4116 } caf_array_ref_t;
4117 @end verbatim
4119 @verbatim
4120 /* References to remote components of a derived type.  */
4121 typedef struct caf_reference_t {
4122   /* A pointer to the next ref or NULL.  */
4123   struct caf_reference_t *next;
4124   /* The type of the reference.  */
4125   /* caf_ref_type_t, replaced by int to allow specification in fortran FE.  */
4126   int type;
4127   /* The size of an item referenced in bytes.  I.e. in an array ref this is
4128      the factor to advance the array pointer with to get to the next item.
4129      For component refs this gives just the size of the element referenced.  */
4130   size_t item_size;
4131   union {
4132     struct {
4133       /* The offset (in bytes) of the component in the derived type.
4134          Unused for allocatable or pointer components.  */
4135       ptrdiff_t offset;
4136       /* The offset (in bytes) to the caf_token associated with this
4137          component.  NULL, when not allocatable/pointer ref.  */
4138       ptrdiff_t caf_token_offset;
4139     } c;
4140     struct {
4141       /* The mode of the array ref.  See CAF_ARR_REF_*.  */
4142       /* caf_array_ref_t, replaced by unsigend char to allow specification in
4143          fortran FE.  */
4144      unsigned char mode[GFC_MAX_DIMENSIONS];
4145       /* The type of a static array.  Unset for array's with descriptors.  */
4146       int static_array_type;
4147       /* Subscript refs (s) or vector refs (v).  */
4148       union {
4149         struct {
4150           /* The start and end boundary of the ref and the stride.  */
4151           index_type start, end, stride;
4152         } s;
4153         struct {
4154           /* nvec entries of kind giving the elements to reference.  */
4155           void *vector;
4156           /* The number of entries in vector.  */
4157           size_t nvec;
4158           /* The integer kind used for the elements in vector.  */
4159           int kind;
4160         } v;
4161       } dim[GFC_MAX_DIMENSIONS];
4162     } a;
4163   } u;
4164 } caf_reference_t;
4165 @end verbatim
4167 The references make up a single linked list of reference operations.  The
4168 @code{NEXT} member links to the next reference or NULL to indicate the end of
4169 the chain.  Component and array refs can be arbitrarly mixed as long as they
4170 comply to the Fortran standard.
4172 @emph{NOTES}
4173 The member @code{STATIC_ARRAY_TYPE} is used only when the @code{TYPE} is
4174 @code{CAF_REF_STATIC_ARRAY}.  The member gives the type of the data referenced.
4175 Because no array descriptor is available for a descriptor-less array and
4176 type conversion still needs to take place the type is transported here.
4178 At the moment @code{CAF_ARR_REF_VECTOR} is not implemented in the front end for
4179 descriptor-less arrays.  The library caf_single has untested support for it.
4181 @node caf_team_t
4182 @subsection @code{caf_team_t}
4184 Opaque pointer to represent a team-handle.  This type is a stand-in for the
4185 future implementation of teams.  It is about to change without further notice.
4187 @node Function ABI Documentation
4188 @section Function ABI Documentation
4190 @menu
4191 * _gfortran_caf_init:: Initialiation function
4192 * _gfortran_caf_finish:: Finalization function
4193 * _gfortran_caf_this_image:: Querying the image number
4194 * _gfortran_caf_num_images:: Querying the maximal number of images
4195 * _gfortran_caf_image_status :: Query the status of an image
4196 * _gfortran_caf_failed_images :: Get an array of the indexes of the failed images
4197 * _gfortran_caf_stopped_images :: Get an array of the indexes of the stopped images
4198 * _gfortran_caf_register:: Registering coarrays
4199 * _gfortran_caf_deregister:: Deregistering coarrays
4200 * _gfortran_caf_is_present:: Query whether an allocatable or pointer component in a derived type coarray is allocated
4201 * _gfortran_caf_send:: Sending data from a local image to a remote image
4202 * _gfortran_caf_get:: Getting data from a remote image
4203 * _gfortran_caf_sendget:: Sending data between remote images
4204 * _gfortran_caf_send_by_ref:: Sending data from a local image to a remote image using enhanced references
4205 * _gfortran_caf_get_by_ref:: Getting data from a remote image using enhanced references
4206 * _gfortran_caf_sendget_by_ref:: Sending data between remote images using enhanced references
4207 * _gfortran_caf_lock:: Locking a lock variable
4208 * _gfortran_caf_unlock:: Unlocking a lock variable
4209 * _gfortran_caf_event_post:: Post an event
4210 * _gfortran_caf_event_wait:: Wait that an event occurred
4211 * _gfortran_caf_event_query:: Query event count
4212 * _gfortran_caf_sync_all:: All-image barrier
4213 * _gfortran_caf_sync_images:: Barrier for selected images
4214 * _gfortran_caf_sync_memory:: Wait for completion of segment-memory operations
4215 * _gfortran_caf_error_stop:: Error termination with exit code
4216 * _gfortran_caf_error_stop_str:: Error termination with string
4217 * _gfortran_caf_fail_image :: Mark the image failed and end its execution
4218 * _gfortran_caf_atomic_define:: Atomic variable assignment
4219 * _gfortran_caf_atomic_ref:: Atomic variable reference
4220 * _gfortran_caf_atomic_cas:: Atomic compare and swap
4221 * _gfortran_caf_atomic_op:: Atomic operation
4222 * _gfortran_caf_co_broadcast:: Sending data to all images
4223 * _gfortran_caf_co_max:: Collective maximum reduction
4224 * _gfortran_caf_co_min:: Collective minimum reduction
4225 * _gfortran_caf_co_sum:: Collective summing reduction
4226 * _gfortran_caf_co_reduce:: Generic collective reduction
4227 @end menu
4230 @node _gfortran_caf_init
4231 @subsection @code{_gfortran_caf_init} --- Initialiation function
4232 @cindex Coarray, _gfortran_caf_init
4234 @table @asis
4235 @item @emph{Description}:
4236 This function is called at startup of the program before the Fortran main
4237 program, if the latter has been compiled with @option{-fcoarray=lib}.
4238 It takes as arguments the command-line arguments of the program.  It is
4239 permitted to pass two @code{NULL} pointers as argument; if non-@code{NULL},
4240 the library is permitted to modify the arguments.
4242 @item @emph{Syntax}:
4243 @code{void _gfortran_caf_init (int *argc, char ***argv)}
4245 @item @emph{Arguments}:
4246 @multitable @columnfractions .15 .70
4247 @item @var{argc} @tab intent(inout) An integer pointer with the number of
4248 arguments passed to the program or @code{NULL}.
4249 @item @var{argv} @tab intent(inout) A pointer to an array of strings with the
4250 command-line arguments or @code{NULL}.
4251 @end multitable
4253 @item @emph{NOTES}
4254 The function is modelled after the initialization function of the Message
4255 Passing Interface (MPI) specification.  Due to the way coarray registration
4256 works, it might not be the first call to the library.  If the main program is
4257 not written in Fortran and only a library uses coarrays, it can happen that
4258 this function is never called.  Therefore, it is recommended that the library
4259 does not rely on the passed arguments and whether the call has been done.
4260 @end table
4263 @node _gfortran_caf_finish
4264 @subsection @code{_gfortran_caf_finish} --- Finalization function
4265 @cindex Coarray, _gfortran_caf_finish
4267 @table @asis
4268 @item @emph{Description}:
4269 This function is called at the end of the Fortran main program, if it has
4270 been compiled with the @option{-fcoarray=lib} option.
4272 @item @emph{Syntax}:
4273 @code{void _gfortran_caf_finish (void)}
4275 @item @emph{NOTES}
4276 For non-Fortran programs, it is recommended to call the function at the end
4277 of the main program.  To ensure that the shutdown is also performed for
4278 programs where this function is not explicitly invoked, for instance
4279 non-Fortran programs or calls to the system's exit() function, the library
4280 can use a destructor function.  Note that programs can also be terminated
4281 using the STOP and ERROR STOP statements; those use different library calls.
4282 @end table
4285 @node _gfortran_caf_this_image
4286 @subsection @code{_gfortran_caf_this_image} --- Querying the image number
4287 @cindex Coarray, _gfortran_caf_this_image
4289 @table @asis
4290 @item @emph{Description}:
4291 This function returns the current image number, which is a positive number.
4293 @item @emph{Syntax}:
4294 @code{int _gfortran_caf_this_image (int distance)}
4296 @item @emph{Arguments}:
4297 @multitable @columnfractions .15 .70
4298 @item @var{distance} @tab As specified for the @code{this_image} intrinsic
4299 in TS18508.  Shall be a non-negative number.
4300 @end multitable
4302 @item @emph{NOTES}
4303 If the Fortran intrinsic @code{this_image} is invoked without an argument, which
4304 is the only permitted form in Fortran 2008, GCC passes @code{0} as
4305 first argument.
4306 @end table
4309 @node _gfortran_caf_num_images
4310 @subsection @code{_gfortran_caf_num_images} --- Querying the maximal number of images
4311 @cindex Coarray, _gfortran_caf_num_images
4313 @table @asis
4314 @item @emph{Description}:
4315 This function returns the number of images in the current team, if
4316 @var{distance} is 0 or the number of images in the parent team at the specified
4317 distance. If failed is -1, the function returns the number of all images at
4318 the specified distance; if it is 0, the function returns the number of
4319 nonfailed images, and if it is 1, it returns the number of failed images.
4321 @item @emph{Syntax}:
4322 @code{int _gfortran_caf_num_images(int distance, int failed)}
4324 @item @emph{Arguments}:
4325 @multitable @columnfractions .15 .70
4326 @item @var{distance} @tab the distance from this image to the ancestor.
4327 Shall be positive.
4328 @item @var{failed} @tab shall be -1, 0, or 1
4329 @end multitable
4331 @item @emph{NOTES}
4332 This function follows TS18508. If the num_image intrinsic has no arguments,
4333 then the compiler passes @code{distance=0} and @code{failed=-1} to the function.
4334 @end table
4337 @node _gfortran_caf_image_status
4338 @subsection @code{_gfortran_caf_image_status} --- Query the status of an image
4339 @cindex Coarray, _gfortran_caf_image_status
4341 @table @asis
4342 @item @emph{Description}:
4343 Get the status of the image given by the id @var{image} of the team given by
4344 @var{team}.  Valid results are zero, for image is ok, @code{STAT_STOPPED_IMAGE}
4345 from the ISO_FORTRAN_ENV module to indicate that the image has been stopped and
4346 @code{STAT_FAILED_IMAGE} also from ISO_FORTRAN_ENV to indicate that the image
4347 has executed a @code{FAIL IMAGE} statement.
4349 @item @emph{Syntax}:
4350 @code{int _gfortran_caf_image_status (int image, caf_team_t * team)}
4352 @item @emph{Arguments}:
4353 @multitable @columnfractions .15 .70
4354 @item @var{image} @tab the positive scalar id of the image in the current TEAM.
4355 @item @var{team} @tab optional; team on the which the inquiry is to be
4356 performed.
4357 @end multitable
4359 @item @emph{NOTES}
4360 This function follows TS18508.  Because team-functionality is not yet
4361 implemented a null-pointer is passed for the @var{team} argument at the moment.
4362 @end table
4365 @node _gfortran_caf_failed_images
4366 @subsection @code{_gfortran_caf_failed_images} --- Get an array of the indexes of the failed images
4367 @cindex Coarray, _gfortran_caf_failed_images
4369 @table @asis
4370 @item @emph{Description}:
4371 Get an array of image indexes in the current @var{team} that have failed.  The
4372 array is sorted ascendingly.  When @var{team} is not provided the current team
4373 is to be used.  When @var{kind} is provided then the resulting array is of that
4374 integer kind else it is of default integer kind.  The returns an unallocated
4375 size zero array when no images have failed.
4377 @item @emph{Syntax}:
4378 @code{int _gfortran_caf_failed_images (caf_team_t * team, int * kind)}
4380 @item @emph{Arguments}:
4381 @multitable @columnfractions .15 .70
4382 @item @var{team} @tab optional; team on the which the inquiry is to be
4383 performed.
4384 @item @var{image} @tab optional; the kind of the resulting integer array.
4385 @end multitable
4387 @item @emph{NOTES}
4388 This function follows TS18508.  Because team-functionality is not yet
4389 implemented a null-pointer is passed for the @var{team} argument at the moment.
4390 @end table
4393 @node _gfortran_caf_stopped_images
4394 @subsection @code{_gfortran_caf_stopped_images} --- Get an array of the indexes of the stopped images
4395 @cindex Coarray, _gfortran_caf_stopped_images
4397 @table @asis
4398 @item @emph{Description}:
4399 Get an array of image indexes in the current @var{team} that have stopped.  The
4400 array is sorted ascendingly.  When @var{team} is not provided the current team
4401 is to be used.  When @var{kind} is provided then the resulting array is of that
4402 integer kind else it is of default integer kind.  The returns an unallocated
4403 size zero array when no images have failed.
4405 @item @emph{Syntax}:
4406 @code{int _gfortran_caf_stopped_images (caf_team_t * team, int * kind)}
4408 @item @emph{Arguments}:
4409 @multitable @columnfractions .15 .70
4410 @item @var{team} @tab optional; team on the which the inquiry is to be
4411 performed.
4412 @item @var{image} @tab optional; the kind of the resulting integer array.
4413 @end multitable
4415 @item @emph{NOTES}
4416 This function follows TS18508.  Because team-functionality is not yet
4417 implemented a null-pointer is passed for the @var{team} argument at the moment.
4418 @end table
4421 @node _gfortran_caf_register
4422 @subsection @code{_gfortran_caf_register} --- Registering coarrays
4423 @cindex Coarray, _gfortran_caf_register
4425 @table @asis
4426 @item @emph{Description}:
4427 Registers memory for a coarray and creates a token to identify the coarray.  The
4428 routine is called for both coarrays with @code{SAVE} attribute and using an
4429 explicit @code{ALLOCATE} statement.  If an error occurs and @var{STAT} is a
4430 @code{NULL} pointer, the function shall abort with printing an error message
4431 and starting the error termination.  If no error occurs and @var{STAT} is
4432 present, it shall be set to zero.  Otherwise, it shall be set to a positive
4433 value and, if not-@code{NULL}, @var{ERRMSG} shall be set to a string describing
4434 the failure.  The routine shall register the memory provided in the
4435 @code{DATA}-component of the array descriptor @var{DESC}, when that component
4436 is non-@code{NULL}, else it shall allocate sufficient memory and provide a
4437 pointer to it in the @code{DATA}-component of @var{DESC}.  The array descriptor
4438 has rank zero, when a scalar object is to be registered and the array
4439 descriptor may be invalid after the call to @code{_gfortran_caf_register}.
4440 When an array is to be allocated the descriptor persists.
4442 For @code{CAF_REGTYPE_COARRAY_STATIC} and @code{CAF_REGTYPE_COARRAY_ALLOC},
4443 the passed size is the byte size requested.  For @code{CAF_REGTYPE_LOCK_STATIC},
4444 @code{CAF_REGTYPE_LOCK_ALLOC} and @code{CAF_REGTYPE_CRITICAL} it is the array
4445 size or one for a scalar.
4447 When @code{CAF_REGTYPE_COARRAY_ALLOC_REGISTER_ONLY} is used, then only a token
4448 for an allocatable or pointer component is created.  The @code{SIZE} parameter
4449 is not used then.  On the contrary when
4450 @code{CAF_REGTYPE_COARRAY_ALLOC_ALLOCATE_ONLY} is specified, then the
4451 @var{token} needs to be registered by a previous call with regtype
4452 @code{CAF_REGTYPE_COARRAY_ALLOC_REGISTER_ONLY} and either the memory specified
4453 in the @var{DESC}'s data-ptr is registered or allocate when the data-ptr is
4454 @code{NULL}.
4456 @item @emph{Syntax}:
4457 @code{void caf_register (size_t size, caf_register_t type, caf_token_t *token,
4458 gfc_descriptor_t *desc, int *stat, char *errmsg, size_t errmsg_len)}
4460 @item @emph{Arguments}:
4461 @multitable @columnfractions .15 .70
4462 @item @var{size} @tab For normal coarrays, the byte size of the coarray to be
4463 allocated; for lock types and event types, the number of elements.
4464 @item @var{type} @tab one of the caf_register_t types.
4465 @item @var{token} @tab intent(out) An opaque pointer identifying the coarray.
4466 @item @var{desc} @tab intent(inout) The (pseudo) array descriptor.
4467 @item @var{stat} @tab intent(out) For allocatable coarrays, stores the STAT=;
4468 may be @code{NULL}
4469 @item @var{errmsg} @tab intent(out) When an error occurs, this will be set to
4470 an error message; may be @code{NULL}
4471 @item @var{errmsg_len} @tab the buffer size of errmsg.
4472 @end multitable
4474 @item @emph{NOTES}
4475 Nonallocatable coarrays have to be registered prior use from remote images.
4476 In order to guarantee this, they have to be registered before the main
4477 program. This can be achieved by creating constructor functions. That is what
4478 GCC does such that also for nonallocatable coarrays the memory is allocated and
4479 no static memory is used.  The token permits to identify the coarray; to the
4480 processor, the token is a nonaliasing pointer. The library can, for instance,
4481 store the base address of the coarray in the token, some handle or a more
4482 complicated struct.  The library may also store the array descriptor
4483 @var{DESC} when its rank is non-zero.
4485 For lock types, the value shall only be used for checking the allocation
4486 status. Note that for critical blocks, the locking is only required on one
4487 image; in the locking statement, the processor shall always pass an
4488 image index of one for critical-block lock variables
4489 (@code{CAF_REGTYPE_CRITICAL}). For lock types and critical-block variables,
4490 the initial value shall be unlocked (or, respecitively, not in critical
4491 section) such as the value false; for event types, the initial state should
4492 be no event, e.g. zero.
4493 @end table
4496 @node _gfortran_caf_deregister
4497 @subsection @code{_gfortran_caf_deregister} --- Deregistering coarrays
4498 @cindex Coarray, _gfortran_caf_deregister
4500 @table @asis
4501 @item @emph{Description}:
4502 Called to free or deregister the memory of a coarray; the processor calls this
4503 function for automatic and explicit deallocation.  In case of an error, this
4504 function shall fail with an error message, unless the @var{STAT} variable is
4505 not null.  The library is only expected to free memory it allocated itself
4506 during a call to @code{_gfortran_caf_register}.
4508 @item @emph{Syntax}:
4509 @code{void caf_deregister (caf_token_t *token, caf_deregister_t type,
4510 int *stat, char *errmsg, size_t errmsg_len)}
4512 @item @emph{Arguments}:
4513 @multitable @columnfractions .15 .70
4514 @item @var{token} @tab the token to free.
4515 @item @var{type} @tab the type of action to take for the coarray.  A
4516 @code{CAF_DEREGTYPE_COARRAY_DEALLOCATE_ONLY} is allowed only for allocatable or
4517 pointer components of derived type coarrays.  The action only deallocates the
4518 local memory without deleting the token.
4519 @item @var{stat} @tab intent(out) Stores the STAT=; may be NULL
4520 @item @var{errmsg} @tab intent(out) When an error occurs, this will be set
4521 to an error message; may be NULL
4522 @item @var{errmsg_len} @tab the buffer size of errmsg.
4523 @end multitable
4525 @item @emph{NOTES}
4526 For nonalloatable coarrays this function is never called.  If a cleanup is
4527 required, it has to be handled via the finish, stop and error stop functions,
4528 and via destructors.
4529 @end table
4532 @node _gfortran_caf_is_present
4533 @subsection @code{_gfortran_caf_is_present} --- Query whether an allocatable or pointer component in a derived type coarray is allocated
4534 @cindex Coarray, _gfortran_caf_is_present
4536 @table @asis
4537 @item @emph{Description}:
4538 Used to query the coarray library whether an allocatable component in a derived
4539 type coarray is allocated on a remote image.
4541 @item @emph{Syntax}:
4542 @code{void _gfortran_caf_is_present (caf_token_t token, int image_index,
4543 gfc_reference_t *ref)}
4545 @item @emph{Arguments}:
4546 @multitable @columnfractions .15 .70
4547 @item @var{token} @tab An opaque pointer identifying the coarray.
4548 @item @var{image_index} @tab The ID of the remote image; must be a positive
4549 number.
4550 @item @var{ref} @tab A chain of references to address the allocatable or
4551 pointer component in the derived type coarray.  The object reference needs to be
4552 a scalar or a full array reference, respectively.
4553 @end multitable
4555 @end table
4557 @node _gfortran_caf_send
4558 @subsection @code{_gfortran_caf_send} --- Sending data from a local image to a remote image
4559 @cindex Coarray, _gfortran_caf_send
4561 @table @asis
4562 @item @emph{Description}:
4563 Called to send a scalar, an array section or a whole array from a local
4564 to a remote image identified by the image_index.
4566 @item @emph{Syntax}:
4567 @code{void _gfortran_caf_send (caf_token_t token, size_t offset,
4568 int image_index, gfc_descriptor_t *dest, caf_vector_t *dst_vector,
4569 gfc_descriptor_t *src, int dst_kind, int src_kind, bool may_require_tmp,
4570 int *stat)}
4572 @item @emph{Arguments}:
4573 @multitable @columnfractions .15 .70
4574 @item @var{token} @tab intent(in)  An opaque pointer identifying the coarray.
4575 @item @var{offset} @tab intent(in)  By which amount of bytes the actual data is
4576 shifted compared to the base address of the coarray.
4577 @item @var{image_index} @tab intent(in)  The ID of the remote image; must be a
4578 positive number.
4579 @item @var{dest} @tab intent(in)  Array descriptor for the remote image for the
4580 bounds and the size.  The @code{base_addr} shall not be accessed.
4581 @item @var{dst_vector} @tab intent(in)  If not NULL, it contains the vector
4582 subscript of the destination array; the values are relative to the dimension
4583 triplet of the dest argument.
4584 @item @var{src} @tab intent(in)  Array descriptor of the local array to be
4585 transferred to the remote image
4586 @item @var{dst_kind} @tab intent(in)  Kind of the destination argument
4587 @item @var{src_kind} @tab intent(in)  Kind of the source argument
4588 @item @var{may_require_tmp} @tab intent(in)  The variable is @code{false} when
4589 it is known at compile time that the @var{dest} and @var{src} either cannot
4590 overlap or overlap (fully or partially) such that walking @var{src} and
4591 @var{dest} in element wise element order (honoring the stride value) will not
4592 lead to wrong results.  Otherwise, the value is @code{true}.
4593 @item @var{stat} @tab intent(out) when non-NULL give the result of the
4594 operation, i.e., zero on success and non-zero on error.  When NULL and an error
4595 occurs, then an error message is printed and the program is terminated.
4596 @end multitable
4598 @item @emph{NOTES}
4599 It is permitted to have @var{image_index} equal the current image; the memory
4600 of the send-to and the send-from might (partially) overlap in that case.  The
4601 implementation has to take care that it handles this case, e.g. using
4602 @code{memmove} which handles (partially) overlapping memory. If
4603 @var{may_require_tmp} is true, the library might additionally create a
4604 temporary variable, unless additional checks show that this is not required
4605 (e.g. because walking backward is possible or because both arrays are
4606 contiguous and @code{memmove} takes care of overlap issues).
4608 Note that the assignment of a scalar to an array is permitted. In addition,
4609 the library has to handle numeric-type conversion and for strings, padding
4610 and different character kinds.
4611 @end table
4614 @node _gfortran_caf_get
4615 @subsection @code{_gfortran_caf_get} --- Getting data from a remote image
4616 @cindex Coarray, _gfortran_caf_get
4618 @table @asis
4619 @item @emph{Description}:
4620 Called to get an array section or a whole array from a remote,
4621 image identified by the image_index.
4623 @item @emph{Syntax}:
4624 @code{void _gfortran_caf_get (caf_token_t token, size_t offset,
4625 int image_index, gfc_descriptor_t *src, caf_vector_t *src_vector,
4626 gfc_descriptor_t *dest, int src_kind, int dst_kind, bool may_require_tmp,
4627 int *stat)}
4629 @item @emph{Arguments}:
4630 @multitable @columnfractions .15 .70
4631 @item @var{token} @tab intent(in)  An opaque pointer identifying the coarray.
4632 @item @var{offset} @tab intent(in)  By which amount of bytes the actual data is
4633 shifted compared to the base address of the coarray.
4634 @item @var{image_index} @tab intent(in)  The ID of the remote image; must be a
4635 positive number.
4636 @item @var{dest} @tab intent(out) Array descriptor of the local array to store
4637 the data retrieved from the remote image
4638 @item @var{src} @tab intent(in) Array descriptor for the remote image for the
4639 bounds and the size.  The @code{base_addr} shall not be accessed.
4640 @item @var{src_vector} @tab intent(in)  If not NULL, it contains the vector
4641 subscript of the source array; the values are relative to the dimension
4642 triplet of the @var{src} argument.
4643 @item @var{dst_kind} @tab intent(in)  Kind of the destination argument
4644 @item @var{src_kind} @tab intent(in)  Kind of the source argument
4645 @item @var{may_require_tmp} @tab intent(in)  The variable is @code{false} when
4646 it is known at compile time that the @var{dest} and @var{src} either cannot
4647 overlap or overlap (fully or partially) such that walking @var{src} and
4648 @var{dest} in element wise element order (honoring the stride value) will not
4649 lead to wrong results.  Otherwise, the value is @code{true}.
4650 @item @var{stat} @tab intent(out) When non-NULL give the result of the
4651 operation, i.e., zero on success and non-zero on error.  When NULL and an error
4652 occurs, then an error message is printed and the program is terminated.
4653 @end multitable
4655 @item @emph{NOTES}
4656 It is permitted to have @var{image_index} equal the current image; the memory of
4657 the send-to and the send-from might (partially) overlap in that case.  The
4658 implementation has to take care that it handles this case, e.g. using
4659 @code{memmove} which handles (partially) overlapping memory. If
4660 @var{may_require_tmp} is true, the library might additionally create a
4661 temporary variable, unless additional checks show that this is not required
4662 (e.g. because walking backward is possible or because both arrays are
4663 contiguous and @code{memmove} takes care of overlap issues).
4665 Note that the library has to handle numeric-type conversion and for strings,
4666 padding and different character kinds.
4667 @end table
4670 @node _gfortran_caf_sendget
4671 @subsection @code{_gfortran_caf_sendget} --- Sending data between remote images
4672 @cindex Coarray, _gfortran_caf_sendget
4674 @table @asis
4675 @item @emph{Description}:
4676 Called to send a scalar, an array section or a whole array from a remote image
4677 identified by the @var{src_image_index} to a remote image identified by the
4678 @var{dst_image_index}.
4680 @item @emph{Syntax}:
4681 @code{void _gfortran_caf_sendget (caf_token_t dst_token, size_t dst_offset,
4682 int dst_image_index, gfc_descriptor_t *dest, caf_vector_t *dst_vector,
4683 caf_token_t src_token, size_t src_offset, int src_image_index,
4684 gfc_descriptor_t *src, caf_vector_t *src_vector, int dst_kind, int src_kind,
4685 bool may_require_tmp, int *stat)}
4687 @item @emph{Arguments}:
4688 @multitable @columnfractions .15 .70
4689 @item @var{dst_token} @tab intent(in)  An opaque pointer identifying the
4690 destination coarray.
4691 @item @var{dst_offset} @tab intent(in)  By which amount of bytes the actual data
4692 is shifted compared to the base address of the destination coarray.
4693 @item @var{dst_image_index} @tab intent(in)  The ID of the destination remote
4694 image; must be a positive number.
4695 @item @var{dest} @tab intent(in) Array descriptor for the destination
4696 remote image for the bounds and the size.  The @code{base_addr} shall not be
4697 accessed.
4698 @item @var{dst_vector} @tab intent(int)  If not NULL, it contains the vector
4699 subscript of the destination array; the values are relative to the dimension
4700 triplet of the @var{dest} argument.
4701 @item @var{src_token} @tab intent(in)  An opaque pointer identifying the source
4702 coarray.
4703 @item @var{src_offset} @tab intent(in)  By which amount of bytes the actual data
4704 is shifted compared to the base address of the source coarray.
4705 @item @var{src_image_index} @tab intent(in)  The ID of the source remote image;
4706 must be a positive number.
4707 @item @var{src} @tab intent(in) Array descriptor of the local array to be
4708 transferred to the remote image.
4709 @item @var{src_vector} @tab intent(in) Array descriptor of the local array to
4710 be transferred to the remote image
4711 @item @var{dst_kind} @tab intent(in)  Kind of the destination argument
4712 @item @var{src_kind} @tab intent(in)  Kind of the source argument
4713 @item @var{may_require_tmp} @tab intent(in)  The variable is @code{false} when
4714 it is known at compile time that the @var{dest} and @var{src} either cannot
4715 overlap or overlap (fully or partially) such that walking @var{src} and
4716 @var{dest} in element wise element order (honoring the stride value) will not
4717 lead to wrong results.  Otherwise, the value is @code{true}.
4718 @item @var{stat} @tab intent(out) when non-NULL give the result of the
4719 operation, i.e., zero on success and non-zero on error.  When NULL and an error
4720 occurs, then an error message is printed and the program is terminated.
4721 @end multitable
4723 @item @emph{NOTES}
4724 It is permitted to have the same image index for both @var{src_image_index} and
4725 @var{dst_image_index}; the memory of the send-to and the send-from might
4726 (partially) overlap in that case.  The implementation has to take care that it
4727 handles this case, e.g. using @code{memmove} which handles (partially)
4728 overlapping memory.  If @var{may_require_tmp} is true, the library
4729 might additionally create a temporary variable, unless additional checks show
4730 that this is not required (e.g. because walking backward is possible or because
4731 both arrays are contiguous and @code{memmove} takes care of overlap issues).
4733 Note that the assignment of a scalar to an array is permitted. In addition,
4734 the library has to handle numeric-type conversion and for strings, padding and
4735 different character kinds.
4736 @end table
4738 @node _gfortran_caf_send_by_ref
4739 @subsection @code{_gfortran_caf_send_by_ref} --- Sending data from a local image to a remote image with enhanced referencing options
4740 @cindex Coarray, _gfortran_caf_send_by_ref
4742 @table @asis
4743 @item @emph{Description}:
4744 Called to send a scalar, an array section or a whole array from a local to a
4745 remote image identified by the @var{image_index}.
4747 @item @emph{Syntax}:
4748 @code{void _gfortran_caf_send_by_ref (caf_token_t token, int image_index,
4749 gfc_descriptor_t *src, caf_reference_t *refs, int dst_kind, int src_kind,
4750 bool may_require_tmp, bool dst_reallocatable, int *stat, int dst_type)}
4752 @item @emph{Arguments}:
4753 @multitable @columnfractions .15 .70
4754 @item @var{token} @tab intent(in)  An opaque pointer identifying the coarray.
4755 @item @var{image_index} @tab intent(in)  The ID of the remote image; must be a
4756 positive number.
4757 @item @var{src} @tab intent(in) Array descriptor of the local array to be
4758 transferred to the remote image
4759 @item @var{refs} @tab intent(in) The references on the remote array to store
4760 the data given by src.  Guaranteed to have at least one entry.
4761 @item @var{dst_kind} @tab intent(in)  Kind of the destination argument
4762 @item @var{src_kind} @tab intent(in)  Kind of the source argument
4763 @item @var{may_require_tmp} @tab intent(in)  The variable is @code{false} when
4764 it is known at compile time that the @var{dest} and @var{src} either cannot
4765 overlap or overlap (fully or partially) such that walking @var{src} and
4766 @var{dest} in element wise element order (honoring the stride value) will not
4767 lead to wrong results.  Otherwise, the value is @code{true}.
4768 @item @var{dst_reallocatable} @tab intent(in)  Set when the destination is of
4769 allocatable or pointer type and the refs will allow reallocation, i.e., the ref
4770 is a full array or component ref.
4771 @item @var{stat} @tab intent(out) When non-@code{NULL} give the result of the
4772 operation, i.e., zero on success and non-zero on error.  When @code{NULL} and
4773 an error occurs, then an error message is printed and the program is terminated.
4774 @item @var{dst_type} @tab intent(in)  Give the type of the destination.  When
4775 the destination is not an array, than the precise type, e.g. of a component in
4776 a derived type, is not known, but provided here.
4777 @end multitable
4779 @item @emph{NOTES}
4780 It is permitted to have @var{image_index} equal the current image; the memory of
4781 the send-to and the send-from might (partially) overlap in that case.  The
4782 implementation has to take care that it handles this case, e.g. using
4783 @code{memmove} which handles (partially) overlapping memory.  If
4784 @var{may_require_tmp} is true, the library might additionally create a
4785 temporary variable, unless additional checks show that this is not required
4786 (e.g. because walking backward is possible or because both arrays are
4787 contiguous and @code{memmove} takes care of overlap issues).
4789 Note that the assignment of a scalar to an array is permitted.  In addition,
4790 the library has to handle numeric-type conversion and for strings, padding
4791 and different character kinds.
4793 Because of the more complicated references possible some operations may be
4794 unsupported by certain libraries.  The library is expected to issue a precise
4795 error message why the operation is not permitted.
4796 @end table
4799 @node _gfortran_caf_get_by_ref
4800 @subsection @code{_gfortran_caf_get_by_ref} --- Getting data from a remote image using enhanced references
4801 @cindex Coarray, _gfortran_caf_get_by_ref
4803 @table @asis
4804 @item @emph{Description}:
4805 Called to get a scalar, an array section or a whole array from a remote image
4806 identified by the @var{image_index}.
4808 @item @emph{Syntax}:
4809 @code{void _gfortran_caf_get_by_ref (caf_token_t token, int image_index,
4810 caf_reference_t *refs, gfc_descriptor_t *dst, int dst_kind, int src_kind,
4811 bool may_require_tmp, bool dst_reallocatable, int *stat, int src_type)}
4813 @item @emph{Arguments}:
4814 @multitable @columnfractions .15 .70
4815 @item @var{token} @tab intent(in)  An opaque pointer identifying the coarray.
4816 @item @var{image_index} @tab intent(in)  The ID of the remote image; must be a
4817 positive number.
4818 @item @var{refs} @tab intent(in) The references to apply to the remote structure
4819 to get the data.
4820 @item @var{dst} @tab intent(in) Array descriptor of the local array to store
4821 the data transferred from the remote image.  May be reallocated where needed
4822 and when @var{DST_REALLOCATABLE} allows it.
4823 @item @var{dst_kind} @tab intent(in)  Kind of the destination argument
4824 @item @var{src_kind} @tab intent(in)  Kind of the source argument
4825 @item @var{may_require_tmp} @tab intent(in)  The variable is @code{false} when
4826 it is known at compile time that the @var{dest} and @var{src} either cannot
4827 overlap or overlap (fully or partially) such that walking @var{src} and
4828 @var{dest} in element wise element order (honoring the stride value) will not
4829 lead to wrong results.  Otherwise, the value is @code{true}.
4830 @item @var{dst_reallocatable} @tab intent(in)  Set when @var{DST} is of
4831 allocatable or pointer type and its refs allow reallocation, i.e., the full
4832 array or a component is referenced.
4833 @item @var{stat} @tab intent(out) When non-@code{NULL} give the result of the
4834 operation, i.e., zero on success and non-zero on error.  When @code{NULL} and an
4835 error occurs, then an error message is printed and the program is terminated.
4836 @item @var{src_type} @tab intent(in)  Give the type of the source.  When the
4837 source is not an array, than the precise type, e.g. of a component in a
4838 derived type, is not known, but provided here.
4839 @end multitable
4841 @item @emph{NOTES}
4842 It is permitted to have @code{image_index} equal the current image; the memory
4843 of the send-to and the send-from might (partially) overlap in that case.  The
4844 implementation has to take care that it handles this case, e.g. using
4845 @code{memmove} which handles (partially) overlapping memory.  If
4846 @var{may_require_tmp} is true, the library might additionally create a
4847 temporary variable, unless additional checks show that this is not required
4848 (e.g. because walking backward is possible or because both arrays are
4849 contiguous and @code{memmove} takes care of overlap issues).
4851 Note that the library has to handle numeric-type conversion and for strings,
4852 padding and different character kinds.
4854 Because of the more complicated references possible some operations may be
4855 unsupported by certain libraries.  The library is expected to issue a precise
4856 error message why the operation is not permitted.
4857 @end table
4860 @node _gfortran_caf_sendget_by_ref
4861 @subsection @code{_gfortran_caf_sendget_by_ref} --- Sending data between remote images using enhanced references on both sides
4862 @cindex Coarray, _gfortran_caf_sendget_by_ref
4864 @table @asis
4865 @item @emph{Description}:
4866 Called to send a scalar, an array section or a whole array from a remote image
4867 identified by the @var{src_image_index} to a remote image identified by the
4868 @var{dst_image_index}.
4870 @item @emph{Syntax}:
4871 @code{void _gfortran_caf_sendget_by_ref (caf_token_t dst_token,
4872 int dst_image_index, caf_reference_t *dst_refs,
4873 caf_token_t src_token, int src_image_index, caf_reference_t *src_refs,
4874 int dst_kind, int src_kind, bool may_require_tmp, int *dst_stat,
4875 int *src_stat, int dst_type, int src_type)}
4877 @item @emph{Arguments}:
4878 @multitable @columnfractions .15 .70
4879 @item @var{dst_token} @tab intent(in)  An opaque pointer identifying the
4880 destination coarray.
4881 @item @var{dst_image_index} @tab intent(in)  The ID of the destination remote
4882 image; must be a positive number.
4883 @item @var{dst_refs} @tab intent(in) The references on the remote array to store
4884 the data given by the source.  Guaranteed to have at least one entry.
4885 @item @var{src_token} @tab intent(in)  An opaque pointer identifying the source
4886 coarray.
4887 @item @var{src_image_index} @tab intent(in)  The ID of the source remote image;
4888 must be a positive number.
4889 @item @var{src_refs} @tab intent(in) The references to apply to the remote
4890 structure to get the data.
4891 @item @var{dst_kind} @tab intent(in)  Kind of the destination argument
4892 @item @var{src_kind} @tab intent(in)  Kind of the source argument
4893 @item @var{may_require_tmp} @tab intent(in)  The variable is @code{false} when
4894 it is known at compile time that the @var{dest} and @var{src} either cannot
4895 overlap or overlap (fully or partially) such that walking @var{src} and
4896 @var{dest} in element wise element order (honoring the stride value) will not
4897 lead to wrong results.  Otherwise, the value is @code{true}.
4898 @item @var{dst_stat} @tab intent(out) when non-@code{NULL} give the result of
4899 the send-operation, i.e., zero on success and non-zero on error.  When
4900 @code{NULL} and an error occurs, then an error message is printed and the
4901 program is terminated.
4902 @item @var{src_stat} @tab intent(out) When non-@code{NULL} give the result of
4903 the get-operation, i.e., zero on success and non-zero on error.  When
4904 @code{NULL} and an error occurs, then an error message is printed and the
4905 program is terminated.
4906 @item @var{dst_type} @tab intent(in)  Give the type of the destination.  When
4907 the destination is not an array, than the precise type, e.g. of a component in
4908 a derived type, is not known, but provided here.
4909 @item @var{src_type} @tab intent(in)  Give the type of the source.  When the
4910 source is not an array, than the precise type, e.g. of a component in a
4911 derived type, is not known, but provided here.
4912 @end multitable
4914 @item @emph{NOTES}
4915 It is permitted to have the same image index for both @var{src_image_index} and
4916 @var{dst_image_index}; the memory of the send-to and the send-from might
4917 (partially) overlap in that case.  The implementation has to take care that it
4918 handles this case, e.g. using @code{memmove} which handles (partially)
4919 overlapping memory.  If @var{may_require_tmp} is true, the library
4920 might additionally create a temporary variable, unless additional checks show
4921 that this is not required (e.g. because walking backward is possible or because
4922 both arrays are contiguous and @code{memmove} takes care of overlap issues).
4924 Note that the assignment of a scalar to an array is permitted.  In addition,
4925 the library has to handle numeric-type conversion and for strings, padding and
4926 different character kinds.
4928 Because of the more complicated references possible some operations may be
4929 unsupported by certain libraries.  The library is expected to issue a precise
4930 error message why the operation is not permitted.
4931 @end table
4934 @node _gfortran_caf_lock
4935 @subsection @code{_gfortran_caf_lock} --- Locking a lock variable
4936 @cindex Coarray, _gfortran_caf_lock
4938 @table @asis
4939 @item @emph{Description}:
4940 Acquire a lock on the given image on a scalar locking variable or for the
4941 given array element for an array-valued variable.  If the @var{aquired_lock}
4942 is @code{NULL}, the function returns after having obtained the lock.  If it is
4943 non-@code{NULL}, then @var{acquired_lock} is assigned the value true (one) when
4944 the lock could be obtained and false (zero) otherwise.  Locking a lock variable
4945 which has already been locked by the same image is an error.
4947 @item @emph{Syntax}:
4948 @code{void _gfortran_caf_lock (caf_token_t token, size_t index, int image_index,
4949 int *aquired_lock, int *stat, char *errmsg, size_t errmsg_len)}
4951 @item @emph{Arguments}:
4952 @multitable @columnfractions .15 .70
4953 @item @var{token} @tab intent(in)  An opaque pointer identifying the coarray.
4954 @item @var{index} @tab intent(in)  Array index; first array index is 0.  For
4955 scalars, it is always 0.
4956 @item @var{image_index} @tab intent(in)  The ID of the remote image; must be a
4957 positive number.
4958 @item @var{aquired_lock} @tab intent(out) If not NULL, it returns whether lock
4959 could be obtained.
4960 @item @var{stat} @tab intent(out) Stores the STAT=; may be NULL.
4961 @item @var{errmsg} @tab intent(out) When an error occurs, this will be set to
4962 an error message; may be NULL.
4963 @item @var{errmsg_len} @tab intent(in)  the buffer size of errmsg
4964 @end multitable
4966 @item @emph{NOTES}
4967 This function is also called for critical blocks; for those, the array index
4968 is always zero and the image index is one.  Libraries are permitted to use other
4969 images for critical-block locking variables.
4970 @end table
4972 @node _gfortran_caf_unlock
4973 @subsection @code{_gfortran_caf_lock} --- Unlocking a lock variable
4974 @cindex Coarray, _gfortran_caf_unlock
4976 @table @asis
4977 @item @emph{Description}:
4978 Release a lock on the given image on a scalar locking variable or for the
4979 given array element for an array-valued variable. Unlocking a lock variable
4980 which is unlocked or has been locked by a different image is an error.
4982 @item @emph{Syntax}:
4983 @code{void _gfortran_caf_unlock (caf_token_t token, size_t index, int image_index,
4984 int *stat, char *errmsg, size_t errmsg_len)}
4986 @item @emph{Arguments}:
4987 @multitable @columnfractions .15 .70
4988 @item @var{token} @tab intent(in)  An opaque pointer identifying the coarray.
4989 @item @var{index} @tab intent(in)  Array index; first array index is 0.  For
4990 scalars, it is always 0.
4991 @item @var{image_index} @tab intent(in)  The ID of the remote image; must be a
4992 positive number.
4993 @item @var{stat} @tab intent(out) For allocatable coarrays, stores the STAT=;
4994 may be NULL.
4995 @item @var{errmsg} @tab intent(out) When an error occurs, this will be set to
4996 an error message; may be NULL.
4997 @item @var{errmsg_len} @tab intent(in)  the buffer size of errmsg
4998 @end multitable
5000 @item @emph{NOTES}
5001 This function is also called for critical block; for those, the array index
5002 is always zero and the image index is one.  Libraries are permitted to use other
5003 images for critical-block locking variables.
5004 @end table
5006 @node _gfortran_caf_event_post
5007 @subsection @code{_gfortran_caf_event_post} --- Post an event
5008 @cindex Coarray, _gfortran_caf_event_post
5010 @table @asis
5011 @item @emph{Description}:
5012 Increment the event count of the specified event variable.
5014 @item @emph{Syntax}:
5015 @code{void _gfortran_caf_event_post (caf_token_t token, size_t index,
5016 int image_index, int *stat, char *errmsg, size_t errmsg_len)}
5018 @item @emph{Arguments}:
5019 @multitable @columnfractions .15 .70
5020 @item @var{token} @tab intent(in)  An opaque pointer identifying the coarray.
5021 @item @var{index} @tab intent(in)  Array index; first array index is 0.  For
5022 scalars, it is always 0.
5023 @item @var{image_index} @tab intent(in)  The ID of the remote image; must be a
5024 positive number; zero indicates the current image, when accessed noncoindexed.
5025 @item @var{stat} @tab intent(out)  Stores the STAT=; may be NULL.
5026 @item @var{errmsg} @tab intent(out)  When an error occurs, this will be set to
5027 an error message; may be NULL.
5028 @item @var{errmsg_len} @tab intent(in)  the buffer size of errmsg
5029 @end multitable
5031 @item @emph{NOTES}
5032 This acts like an atomic add of one to the remote image's event variable.
5033 The statement is an image-control statement but does not imply sync memory.
5034 Still, all preceeding push communications of this image to the specified
5035 remote image have to be completed before @code{event_wait} on the remote
5036 image returns.
5037 @end table
5041 @node _gfortran_caf_event_wait
5042 @subsection @code{_gfortran_caf_event_wait} --- Wait that an event occurred
5043 @cindex Coarray, _gfortran_caf_event_wait
5045 @table @asis
5046 @item @emph{Description}:
5047 Wait until the event count has reached at least the specified
5048 @var{until_count}; if so, atomically decrement the event variable by this
5049 amount and return.
5051 @item @emph{Syntax}:
5052 @code{void _gfortran_caf_event_wait (caf_token_t token, size_t index,
5053 int until_count, int *stat, char *errmsg, size_t errmsg_len)}
5055 @item @emph{Arguments}:
5056 @multitable @columnfractions .15 .70
5057 @item @var{token} @tab intent(in)  An opaque pointer identifying the coarray.
5058 @item @var{index} @tab intent(in)  Array index; first array index is 0.  For
5059 scalars, it is always 0.
5060 @item @var{until_count} @tab intent(in)  The number of events which have to be
5061 available before the function returns.
5062 @item @var{stat} @tab intent(out)  Stores the STAT=; may be NULL.
5063 @item @var{errmsg} @tab intent(out)  When an error occurs, this will be set to
5064 an error message; may be NULL.
5065 @item @var{errmsg_len} @tab intent(in)  the buffer size of errmsg
5066 @end multitable
5068 @item @emph{NOTES}
5069 This function only operates on a local coarray. It acts like a loop checking
5070 atomically the value of the event variable, breaking if the value is greater
5071 or equal the requested number of counts. Before the function returns, the
5072 event variable has to be decremented by the requested @var{until_count} value.
5073 A possible implementation would be a busy loop for a certain number of spins
5074 (possibly depending on the number of threads relative to the number of available
5075 cores) followed by another waiting strategy such as a sleeping wait (possibly
5076 with an increasing number of sleep time) or, if possible, a futex wait.
5078 The statement is an image-control statement but does not imply sync memory.
5079 Still, all preceeding push communications of this image to the specified
5080 remote image have to be completed before @code{event_wait} on the remote
5081 image returns.
5082 @end table
5086 @node _gfortran_caf_event_query
5087 @subsection @code{_gfortran_caf_event_query} --- Query event count
5088 @cindex Coarray, _gfortran_caf_event_query
5090 @table @asis
5091 @item @emph{Description}:
5092 Return the event count of the specified event variable.
5094 @item @emph{Syntax}:
5095 @code{void _gfortran_caf_event_query (caf_token_t token, size_t index,
5096 int image_index, int *count, int *stat)}
5098 @item @emph{Arguments}:
5099 @multitable @columnfractions .15 .70
5100 @item @var{token} @tab intent(in)  An opaque pointer identifying the coarray.
5101 @item @var{index} @tab intent(in)  Array index; first array index is 0.  For
5102 scalars, it is always 0.
5103 @item @var{image_index} @tab intent(in)  The ID of the remote image; must be a
5104 positive number; zero indicates the current image when accessed noncoindexed.
5105 @item @var{count} @tab intent(out)  The number of events currently posted to
5106 the event variable.
5107 @item @var{stat} @tab intent(out)  Stores the STAT=; may be NULL.
5108 @end multitable
5110 @item @emph{NOTES}
5111 The typical use is to check the local event variable to only call
5112 @code{event_wait} when the data is available. However, a coindexed variable
5113 is permitted; there is no ordering or synchronization implied.  It acts like
5114 an atomic fetch of the value of the event variable.
5115 @end table
5119 @node _gfortran_caf_sync_all
5120 @subsection @code{_gfortran_caf_sync_all} --- All-image barrier
5121 @cindex Coarray, _gfortran_caf_sync_all
5123 @table @asis
5124 @item @emph{Description}:
5125 Synchronization of all images in the current team; the program only continues
5126 on a given image after this function has been called on all images of the
5127 current team.  Additionally, it ensures that all pending data transfers of
5128 previous segment have completed.
5130 @item @emph{Syntax}:
5131 @code{void _gfortran_caf_sync_all (int *stat, char *errmsg, size_t errmsg_len)}
5133 @item @emph{Arguments}:
5134 @multitable @columnfractions .15 .70
5135 @item @var{stat} @tab intent(out)  Stores the status STAT= and may be NULL.
5136 @item @var{errmsg} @tab intent(out)  When an error occurs, this will be set to
5137 an error message; may be NULL.
5138 @item @var{errmsg_len} @tab intent(in)  the buffer size of errmsg
5139 @end multitable
5140 @end table
5144 @node _gfortran_caf_sync_images
5145 @subsection @code{_gfortran_caf_sync_images} --- Barrier for selected images
5146 @cindex Coarray, _gfortran_caf_sync_images
5148 @table @asis
5149 @item @emph{Description}:
5150 Synchronization between the specified images; the program only continues on a
5151 given image after this function has been called on all images specified for
5152 that image. Note that one image can wait for all other images in the current
5153 team (e.g. via @code{sync images(*)}) while those only wait for that specific
5154 image.  Additionally, @code{sync images} ensures that all pending data
5155 transfers of previous segments have completed.
5157 @item @emph{Syntax}:
5158 @code{void _gfortran_caf_sync_images (int count, int images[], int *stat,
5159 char *errmsg, size_t errmsg_len)}
5161 @item @emph{Arguments}:
5162 @multitable @columnfractions .15 .70
5163 @item @var{count} @tab intent(in)  The number of images which are provided in
5164 the next argument.  For a zero-sized array, the value is zero.  For
5165 @code{sync images (*)}, the value is @math{-1}.
5166 @item @var{images} @tab intent(in)  An array with the images provided by the
5167 user.  If @var{count} is zero, a NULL pointer is passed.
5168 @item @var{stat} @tab intent(out)  Stores the status STAT= and may be NULL.
5169 @item @var{errmsg} @tab intent(out)  When an error occurs, this will be set to
5170 an error message; may be NULL.
5171 @item @var{errmsg_len} @tab intent(in)  the buffer size of errmsg
5172 @end multitable
5173 @end table
5177 @node _gfortran_caf_sync_memory
5178 @subsection @code{_gfortran_caf_sync_memory} --- Wait for completion of segment-memory operations
5179 @cindex Coarray, _gfortran_caf_sync_memory
5181 @table @asis
5182 @item @emph{Description}:
5183 Acts as optimization barrier between different segments. It also ensures that
5184 all pending memory operations of this image have been completed.
5186 @item @emph{Syntax}:
5187 @code{void _gfortran_caf_sync_memory (int *stat, char *errmsg, size_t errmsg_len)}
5189 @item @emph{Arguments}:
5190 @multitable @columnfractions .15 .70
5191 @item @var{stat} @tab intent(out)  Stores the status STAT= and may be NULL.
5192 @item @var{errmsg} @tab intent(out)  When an error occurs, this will be set to
5193 an error message; may be NULL.
5194 @item @var{errmsg_len} @tab intent(in)  the buffer size of errmsg
5195 @end multitable
5197 @item @emph{NOTE} A simple implementation could be
5198 @code{__asm__ __volatile__ ("":::"memory")} to prevent code movements.
5199 @end table
5203 @node _gfortran_caf_error_stop
5204 @subsection @code{_gfortran_caf_error_stop} --- Error termination with exit code
5205 @cindex Coarray, _gfortran_caf_error_stop
5207 @table @asis
5208 @item @emph{Description}:
5209 Invoked for an @code{ERROR STOP} statement which has an integer argument.  The
5210 function should terminate the program with the specified exit code.
5213 @item @emph{Syntax}:
5214 @code{void _gfortran_caf_error_stop (int error)}
5216 @item @emph{Arguments}:
5217 @multitable @columnfractions .15 .70
5218 @item @var{error} @tab intent(in)  The exit status to be used.
5219 @end multitable
5220 @end table
5224 @node _gfortran_caf_error_stop_str
5225 @subsection @code{_gfortran_caf_error_stop_str} --- Error termination with string
5226 @cindex Coarray, _gfortran_caf_error_stop_str
5228 @table @asis
5229 @item @emph{Description}:
5230 Invoked for an @code{ERROR STOP} statement which has a string as argument.  The
5231 function should terminate the program with a nonzero-exit code.
5233 @item @emph{Syntax}:
5234 @code{void _gfortran_caf_error_stop (const char *string, size_t len)}
5236 @item @emph{Arguments}:
5237 @multitable @columnfractions .15 .70
5238 @item @var{string} @tab intent(in)  the error message (not zero terminated)
5239 @item @var{len} @tab intent(in)  the length of the string
5240 @end multitable
5241 @end table
5245 @node _gfortran_caf_fail_image
5246 @subsection @code{_gfortran_caf_fail_image} --- Mark the image failed and end its execution
5247 @cindex Coarray, _gfortran_caf_fail_image
5249 @table @asis
5250 @item @emph{Description}:
5251 Invoked for an @code{FAIL IMAGE} statement.  The function should terminate the
5252 current image.
5254 @item @emph{Syntax}:
5255 @code{void _gfortran_caf_fail_image ()}
5257 @item @emph{NOTES}
5258 This function follows TS18508.
5259 @end table
5263 @node _gfortran_caf_atomic_define
5264 @subsection @code{_gfortran_caf_atomic_define} --- Atomic variable assignment
5265 @cindex Coarray, _gfortran_caf_atomic_define
5267 @table @asis
5268 @item @emph{Description}:
5269 Assign atomically a value to an integer or logical variable.
5271 @item @emph{Syntax}:
5272 @code{void _gfortran_caf_atomic_define (caf_token_t token, size_t offset,
5273 int image_index, void *value, int *stat, int type, int kind)}
5275 @item @emph{Arguments}:
5276 @multitable @columnfractions .15 .70
5277 @item @var{token} @tab intent(in)  An opaque pointer identifying the coarray.
5278 @item @var{offset} @tab intent(in)  By which amount of bytes the actual data is
5279 shifted compared to the base address of the coarray.
5280 @item @var{image_index} @tab intent(in)  The ID of the remote image; must be a
5281 positive number; zero indicates the current image when used noncoindexed.
5282 @item @var{value} @tab intent(in)  the value to be assigned, passed by reference
5283 @item @var{stat} @tab intent(out)  Stores the status STAT= and may be NULL.
5284 @item @var{type} @tab intent(in)  The data type, i.e. @code{BT_INTEGER} (1) or
5285 @code{BT_LOGICAL} (2).
5286 @item @var{kind} @tab intent(in)  The kind value (only 4; always @code{int})
5287 @end multitable
5288 @end table
5292 @node _gfortran_caf_atomic_ref
5293 @subsection @code{_gfortran_caf_atomic_ref} --- Atomic variable reference
5294 @cindex Coarray, _gfortran_caf_atomic_ref
5296 @table @asis
5297 @item @emph{Description}:
5298 Reference atomically a value of a kind-4 integer or logical variable.
5300 @item @emph{Syntax}:
5301 @code{void _gfortran_caf_atomic_ref (caf_token_t token, size_t offset,
5302 int image_index, void *value, int *stat, int type, int kind)}
5304 @item @emph{Arguments}:
5305 @multitable @columnfractions .15 .70
5306 @item @var{token} @tab intent(in)  An opaque pointer identifying the coarray.
5307 @item @var{offset} @tab intent(in)  By which amount of bytes the actual data is
5308 shifted compared to the base address of the coarray.
5309 @item @var{image_index} @tab intent(in)  The ID of the remote image; must be a
5310 positive number; zero indicates the current image when used noncoindexed.
5311 @item @var{value} @tab intent(out)  The variable assigned the atomically
5312 referenced variable.
5313 @item @var{stat} @tab intent(out) Stores the status STAT= and may be NULL.
5314 @item @var{type} @tab the data type, i.e. @code{BT_INTEGER} (1) or
5315 @code{BT_LOGICAL} (2).
5316 @item @var{kind} @tab The kind value (only 4; always @code{int})
5317 @end multitable
5318 @end table
5322 @node _gfortran_caf_atomic_cas
5323 @subsection @code{_gfortran_caf_atomic_cas} --- Atomic compare and swap
5324 @cindex Coarray, _gfortran_caf_atomic_cas
5326 @table @asis
5327 @item @emph{Description}:
5328 Atomic compare and swap of a kind-4 integer or logical variable. Assigns
5329 atomically the specified value to the atomic variable, if the latter has
5330 the value specified by the passed condition value.
5332 @item @emph{Syntax}:
5333 @code{void _gfortran_caf_atomic_cas (caf_token_t token, size_t offset,
5334 int image_index, void *old, void *compare, void *new_val, int *stat,
5335 int type, int kind)}
5337 @item @emph{Arguments}:
5338 @multitable @columnfractions .15 .70
5339 @item @var{token} @tab intent(in)  An opaque pointer identifying the coarray.
5340 @item @var{offset} @tab intent(in)  By which amount of bytes the actual data is
5341 shifted compared to the base address of the coarray.
5342 @item @var{image_index} @tab intent(in)  The ID of the remote image; must be a
5343 positive number; zero indicates the current image when used noncoindexed.
5344 @item @var{old} @tab intent(out)  The value which the atomic variable had
5345 just before the cas operation.
5346 @item @var{compare} @tab intent(in)  The value used for comparision.
5347 @item @var{new_val} @tab intent(in)  The new value for the atomic variable,
5348 assigned to the atomic variable, if @code{compare} equals the value of the
5349 atomic variable.
5350 @item @var{stat} @tab intent(out)  Stores the status STAT= and may be NULL.
5351 @item @var{type} @tab intent(in)  the data type, i.e. @code{BT_INTEGER} (1) or
5352 @code{BT_LOGICAL} (2).
5353 @item @var{kind} @tab intent(in)  The kind value (only 4; always @code{int})
5354 @end multitable
5355 @end table
5359 @node _gfortran_caf_atomic_op
5360 @subsection @code{_gfortran_caf_atomic_op} --- Atomic operation
5361 @cindex Coarray, _gfortran_caf_atomic_op
5363 @table @asis
5364 @item @emph{Description}:
5365 Apply an operation atomically to an atomic integer or logical variable.
5366 After the operation, @var{old} contains the value just before the operation,
5367 which, respectively, adds (GFC_CAF_ATOMIC_ADD) atomically the @code{value} to
5368 the atomic integer variable or does a bitwise AND, OR or exclusive OR
5369 between the atomic variable and @var{value}; the result is then stored in the
5370 atomic variable.
5372 @item @emph{Syntax}:
5373 @code{void _gfortran_caf_atomic_op (int op, caf_token_t token, size_t offset,
5374 int image_index, void *value, void *old, int *stat, int type, int kind)}
5376 @item @emph{Arguments}:
5377 @multitable @columnfractions .15 .70
5378 @item @var{op} @tab intent(in)  the operation to be performed; possible values
5379 @code{GFC_CAF_ATOMIC_ADD} (1), @code{GFC_CAF_ATOMIC_AND} (2),
5380 @code{GFC_CAF_ATOMIC_OR} (3), @code{GFC_CAF_ATOMIC_XOR} (4).
5381 @item @var{token} @tab intent(in)  An opaque pointer identifying the coarray.
5382 @item @var{offset} @tab intent(in)  By which amount of bytes the actual data is
5383 shifted compared to the base address of the coarray.
5384 @item @var{image_index} @tab intent(in)  The ID of the remote image; must be a
5385 positive number; zero indicates the current image when used noncoindexed.
5386 @item @var{old} @tab intent(out)  The value which the atomic variable had
5387 just before the atomic operation.
5388 @item @var{val} @tab intent(in)  The new value for the atomic variable,
5389 assigned to the atomic variable, if @code{compare} equals the value of the
5390 atomic variable.
5391 @item @var{stat} @tab intent(out)  Stores the status STAT= and may be NULL.
5392 @item @var{type} @tab intent(in)  the data type, i.e. @code{BT_INTEGER} (1) or
5393 @code{BT_LOGICAL} (2)
5394 @item @var{kind} @tab intent(in)  the kind value (only 4; always @code{int})
5395 @end multitable
5396 @end table
5401 @node _gfortran_caf_co_broadcast
5402 @subsection @code{_gfortran_caf_co_broadcast} --- Sending data to all images
5403 @cindex Coarray, _gfortran_caf_co_broadcast
5405 @table @asis
5406 @item @emph{Description}:
5407 Distribute a value from a given image to all other images in the team. Has to
5408 be called collectively.
5410 @item @emph{Syntax}:
5411 @code{void _gfortran_caf_co_broadcast (gfc_descriptor_t *a,
5412 int source_image, int *stat, char *errmsg, size_t errmsg_len)}
5414 @item @emph{Arguments}:
5415 @multitable @columnfractions .15 .70
5416 @item @var{a} @tab intent(inout)  An array descriptor with the data to be
5417 broadcasted (on @var{source_image}) or to be received (other images).
5418 @item @var{source_image} @tab intent(in)  The ID of the image from which the
5419 data should be broadcasted.
5420 @item @var{stat} @tab intent(out)  Stores the status STAT= and may be NULL.
5421 @item @var{errmsg} @tab intent(out)  When an error occurs, this will be set to
5422 an error message; may be NULL.
5423 @item @var{errmsg_len} @tab intent(in)  the buffer size of errmsg.
5424 @end multitable
5425 @end table
5429 @node _gfortran_caf_co_max
5430 @subsection @code{_gfortran_caf_co_max} --- Collective maximum reduction
5431 @cindex Coarray, _gfortran_caf_co_max
5433 @table @asis
5434 @item @emph{Description}:
5435 Calculates for each array element of the variable @var{a} the maximum
5436 value for that element in the current team; if @var{result_image} has the
5437 value 0, the result shall be stored on all images, otherwise, only on the
5438 specified image. This function operates on numeric values and character
5439 strings.
5441 @item @emph{Syntax}:
5442 @code{void _gfortran_caf_co_max (gfc_descriptor_t *a, int result_image,
5443 int *stat, char *errmsg, int a_len, size_t errmsg_len)}
5445 @item @emph{Arguments}:
5446 @multitable @columnfractions .15 .70
5447 @item @var{a} @tab intent(inout)  An array descriptor for the data to be
5448 processed.  On the destination image(s) the result overwrites the old content.
5449 @item @var{result_image} @tab intent(in)  The ID of the image to which the
5450 reduced value should be copied to; if zero, it has to be copied to all images.
5451 @item @var{stat} @tab intent(out)  Stores the status STAT= and may be NULL.
5452 @item @var{errmsg} @tab intent(out)  When an error occurs, this will be set to
5453 an error message; may be NULL.
5454 @item @var{a_len} @tab intent(in)  the string length of argument @var{a}
5455 @item @var{errmsg_len} @tab intent(in)  the buffer size of errmsg
5456 @end multitable
5458 @item @emph{NOTES}
5459 If @var{result_image} is nonzero, the data in the array descriptor @var{a} on
5460 all images except of the specified one become undefined; hence, the library may
5461 make use of this.
5462 @end table
5466 @node _gfortran_caf_co_min
5467 @subsection @code{_gfortran_caf_co_min} --- Collective minimum reduction
5468 @cindex Coarray, _gfortran_caf_co_min
5470 @table @asis
5471 @item @emph{Description}:
5472 Calculates for each array element of the variable @var{a} the minimum
5473 value for that element in the current team; if @var{result_image} has the
5474 value 0, the result shall be stored on all images, otherwise, only on the
5475 specified image. This function operates on numeric values and character
5476 strings.
5478 @item @emph{Syntax}:
5479 @code{void _gfortran_caf_co_min (gfc_descriptor_t *a, int result_image,
5480 int *stat, char *errmsg, int a_len, size_t errmsg_len)}
5482 @item @emph{Arguments}:
5483 @multitable @columnfractions .15 .70
5484 @item @var{a} @tab intent(inout)  An array descriptor for the data to be
5485 processed.  On the destination image(s) the result overwrites the old content.
5486 @item @var{result_image} @tab intent(in)  The ID of the image to which the
5487 reduced value should be copied to; if zero, it has to be copied to all images.
5488 @item @var{stat} @tab intent(out)  Stores the status STAT= and may be NULL.
5489 @item @var{errmsg} @tab intent(out)  When an error occurs, this will be set to
5490 an error message; may be NULL.
5491 @item @var{a_len} @tab intent(in)  the string length of argument @var{a}
5492 @item @var{errmsg_len} @tab intent(in)  the buffer size of errmsg
5493 @end multitable
5495 @item @emph{NOTES}
5496 If @var{result_image} is nonzero, the data in the array descriptor @var{a} on
5497 all images except of the specified one become undefined; hence, the library may
5498 make use of this.
5499 @end table
5503 @node _gfortran_caf_co_sum
5504 @subsection @code{_gfortran_caf_co_sum} --- Collective summing reduction
5505 @cindex Coarray, _gfortran_caf_co_sum
5507 @table @asis
5508 @item @emph{Description}:
5509 Calculates for each array element of the variable @var{a} the sum of all
5510 values for that element in the current team; if @var{result_image} has the
5511 value 0, the result shall be stored on all images, otherwise, only on the
5512 specified image.  This function operates on numeric values only.
5514 @item @emph{Syntax}:
5515 @code{void _gfortran_caf_co_sum (gfc_descriptor_t *a, int result_image,
5516 int *stat, char *errmsg, size_t errmsg_len)}
5518 @item @emph{Arguments}:
5519 @multitable @columnfractions .15 .70
5520 @item @var{a} @tab intent(inout)  An array descriptor with the data to be
5521 processed.  On the destination image(s) the result overwrites the old content.
5522 @item @var{result_image} @tab intent(in)  The ID of the image to which the
5523 reduced value should be copied to; if zero, it has to be copied to all images.
5524 @item @var{stat} @tab intent(out)  Stores the status STAT= and may be NULL.
5525 @item @var{errmsg} @tab intent(out)  When an error occurs, this will be set to
5526 an error message; may be NULL.
5527 @item @var{errmsg_len} @tab intent(in)  the buffer size of errmsg
5528 @end multitable
5530 @item @emph{NOTES}
5531 If @var{result_image} is nonzero, the data in the array descriptor @var{a} on
5532 all images except of the specified one become undefined; hence, the library may
5533 make use of this.
5534 @end table
5538 @node _gfortran_caf_co_reduce
5539 @subsection @code{_gfortran_caf_co_reduce} --- Generic collective reduction
5540 @cindex Coarray, _gfortran_caf_co_reduce
5542 @table @asis
5543 @item @emph{Description}:
5544 Calculates for each array element of the variable @var{a} the reduction
5545 value for that element in the current team; if @var{result_image} has the
5546 value 0, the result shall be stored on all images, otherwise, only on the
5547 specified image.  The @var{opr} is a pure function doing a mathematically
5548 commutative and associative operation.
5550 The @var{opr_flags} denote the following; the values are bitwise ored.
5551 @code{GFC_CAF_BYREF} (1) if the result should be returned
5552 by reference; @code{GFC_CAF_HIDDENLEN} (2) whether the result and argument
5553 string lengths shall be specified as hidden arguments;
5554 @code{GFC_CAF_ARG_VALUE} (4) whether the arguments shall be passed by value,
5555 @code{GFC_CAF_ARG_DESC} (8) whether the arguments shall be passed by descriptor.
5558 @item @emph{Syntax}:
5559 @code{void _gfortran_caf_co_reduce (gfc_descriptor_t *a,
5560 void * (*opr) (void *, void *), int opr_flags, int result_image,
5561 int *stat, char *errmsg, int a_len, size_t errmsg_len)}
5563 @item @emph{Arguments}:
5564 @multitable @columnfractions .15 .70
5565 @item @var{a} @tab intent(inout)  An array descriptor with the data to be
5566 processed.  On the destination image(s) the result overwrites the old content.
5567 @item @var{opr} @tab intent(in)  Function pointer to the reduction function
5568 @item @var{opr_flags} @tab intent(in)  Flags regarding the reduction function
5569 @item @var{result_image} @tab intent(in)  The ID of the image to which the
5570 reduced value should be copied to; if zero, it has to be copied to all images.
5571 @item @var{stat} @tab intent(out)  Stores the status STAT= and may be NULL.
5572 @item @var{errmsg} @tab intent(out)  When an error occurs, this will be set to
5573 an error message; may be NULL.
5574 @item @var{a_len} @tab intent(in)  the string length of argument @var{a}
5575 @item @var{errmsg_len} @tab intent(in)  the buffer size of errmsg
5576 @end multitable
5578 @item @emph{NOTES}
5579 If @var{result_image} is nonzero, the data in the array descriptor @var{a} on
5580 all images except of the specified one become undefined; hence, the library may
5581 make use of this.
5583 For character arguments, the result is passed as first argument, followed
5584 by the result string length, next come the two string arguments, followed
5585 by the two hidden string length arguments.  With C binding, there are no hidden
5586 arguments and by-reference passing and either only a single character is passed
5587 or an array descriptor.
5588 @end table
5591 @c Intrinsic Procedures
5592 @c ---------------------------------------------------------------------
5594 @include intrinsic.texi
5597 @tex
5598 \blankpart
5599 @end tex
5601 @c ---------------------------------------------------------------------
5602 @c Contributing
5603 @c ---------------------------------------------------------------------
5605 @node Contributing
5606 @unnumbered Contributing
5607 @cindex Contributing
5609 Free software is only possible if people contribute to efforts
5610 to create it.
5611 We're always in need of more people helping out with ideas
5612 and comments, writing documentation and contributing code.
5614 If you want to contribute to GNU Fortran,
5615 have a look at the long lists of projects you can take on.
5616 Some of these projects are small,
5617 some of them are large;
5618 some are completely orthogonal to the rest of what is
5619 happening on GNU Fortran,
5620 but others are ``mainstream'' projects in need of enthusiastic hackers.
5621 All of these projects are important!
5622 We will eventually get around to the things here,
5623 but they are also things doable by someone who is willing and able.
5625 @menu
5626 * Contributors::
5627 * Projects::
5628 * Proposed Extensions::
5629 @end menu
5632 @node Contributors
5633 @section Contributors to GNU Fortran
5634 @cindex Contributors
5635 @cindex Credits
5636 @cindex Authors
5638 Most of the parser was hand-crafted by @emph{Andy Vaught}, who is
5639 also the initiator of the whole project.  Thanks Andy!
5640 Most of the interface with GCC was written by @emph{Paul Brook}.
5642 The following individuals have contributed code and/or
5643 ideas and significant help to the GNU Fortran project
5644 (in alphabetical order):
5646 @itemize @minus
5647 @item Janne Blomqvist
5648 @item Steven Bosscher
5649 @item Paul Brook
5650 @item Tobias Burnus
5651 @item Fran@,{c}ois-Xavier Coudert
5652 @item Bud Davis
5653 @item Jerry DeLisle
5654 @item Erik Edelmann
5655 @item Bernhard Fischer
5656 @item Daniel Franke
5657 @item Richard Guenther
5658 @item Richard Henderson
5659 @item Katherine Holcomb
5660 @item Jakub Jelinek
5661 @item Niels Kristian Bech Jensen
5662 @item Steven Johnson
5663 @item Steven G. Kargl
5664 @item Thomas Koenig
5665 @item Asher Langton
5666 @item H. J. Lu
5667 @item Toon Moene
5668 @item Brooks Moses
5669 @item Andrew Pinski
5670 @item Tim Prince
5671 @item Christopher D. Rickett
5672 @item Richard Sandiford
5673 @item Tobias Schl@"uter
5674 @item Roger Sayle
5675 @item Paul Thomas
5676 @item Andy Vaught
5677 @item Feng Wang
5678 @item Janus Weil
5679 @item Daniel Kraft
5680 @end itemize
5682 The following people have contributed bug reports,
5683 smaller or larger patches,
5684 and much needed feedback and encouragement for the
5685 GNU Fortran project: 
5687 @itemize @minus
5688 @item Bill Clodius
5689 @item Dominique d'Humi@`eres
5690 @item Kate Hedstrom
5691 @item Erik Schnetter
5692 @item Joost VandeVondele
5693 @end itemize
5695 Many other individuals have helped debug,
5696 test and improve the GNU Fortran compiler over the past few years,
5697 and we welcome you to do the same!
5698 If you already have done so,
5699 and you would like to see your name listed in the
5700 list above, please contact us.
5703 @node Projects
5704 @section Projects
5706 @table @emph
5708 @item Help build the test suite
5709 Solicit more code for donation to the test suite: the more extensive the
5710 testsuite, the smaller the risk of breaking things in the future! We can
5711 keep code private on request.
5713 @item Bug hunting/squishing
5714 Find bugs and write more test cases! Test cases are especially very
5715 welcome, because it allows us to concentrate on fixing bugs instead of
5716 isolating them.  Going through the bugzilla database at
5717 @url{https://gcc.gnu.org/@/bugzilla/} to reduce testcases posted there and
5718 add more information (for example, for which version does the testcase
5719 work, for which versions does it fail?) is also very helpful.
5721 @end table
5724 @node Proposed Extensions
5725 @section Proposed Extensions
5727 Here's a list of proposed extensions for the GNU Fortran compiler, in no particular
5728 order.  Most of these are necessary to be fully compatible with
5729 existing Fortran compilers, but they are not part of the official
5730 J3 Fortran 95 standard.
5732 @subsection Compiler extensions:
5733 @itemize @bullet
5734 @item
5735 User-specified alignment rules for structures.
5737 @item
5738 Automatically extend single precision constants to double.
5740 @item
5741 Compile code that conserves memory by dynamically allocating common and
5742 module storage either on stack or heap.
5744 @item
5745 Compile flag to generate code for array conformance checking (suggest -CC).
5747 @item
5748 User control of symbol names (underscores, etc).
5750 @item
5751 Compile setting for maximum size of stack frame size before spilling
5752 parts to static or heap.
5754 @item
5755 Flag to force local variables into static space.
5757 @item
5758 Flag to force local variables onto stack.
5759 @end itemize
5762 @subsection Environment Options
5763 @itemize @bullet
5764 @item
5765 Pluggable library modules for random numbers, linear algebra.
5766 LA should use BLAS calling conventions.
5768 @item
5769 Environment variables controlling actions on arithmetic exceptions like
5770 overflow, underflow, precision loss---Generate NaN, abort, default.
5771 action.
5773 @item
5774 Set precision for fp units that support it (i387).
5776 @item
5777 Variable for setting fp rounding mode.
5779 @item
5780 Variable to fill uninitialized variables with a user-defined bit
5781 pattern.
5783 @item
5784 Environment variable controlling filename that is opened for that unit
5785 number.
5787 @item
5788 Environment variable to clear/trash memory being freed.
5790 @item
5791 Environment variable to control tracing of allocations and frees.
5793 @item
5794 Environment variable to display allocated memory at normal program end.
5796 @item
5797 Environment variable for filename for * IO-unit.
5799 @item
5800 Environment variable for temporary file directory.
5802 @item
5803 Environment variable forcing standard output to be line buffered (Unix).
5805 @end itemize
5808 @c ---------------------------------------------------------------------
5809 @c GNU General Public License
5810 @c ---------------------------------------------------------------------
5812 @include gpl_v3.texi
5816 @c ---------------------------------------------------------------------
5817 @c GNU Free Documentation License
5818 @c ---------------------------------------------------------------------
5820 @include fdl.texi
5824 @c ---------------------------------------------------------------------
5825 @c Funding Free Software
5826 @c ---------------------------------------------------------------------
5828 @include funding.texi
5830 @c ---------------------------------------------------------------------
5831 @c Indices
5832 @c ---------------------------------------------------------------------
5834 @node Option Index
5835 @unnumbered Option Index
5836 @command{gfortran}'s command line options are indexed here without any
5837 initial @samp{-} or @samp{--}.  Where an option has both positive and
5838 negative forms (such as -foption and -fno-option), relevant entries in
5839 the manual are indexed under the most appropriate form; it may sometimes
5840 be useful to look up both forms.
5841 @printindex op
5843 @node Keyword Index
5844 @unnumbered Keyword Index
5845 @printindex cp
5847 @bye