* backtrace.c: Revert last two changes. Don't call mmap
[official-gcc.git] / gcc / fortran / gfortran.texi
blob6f894816c6273bd49aba23369bac00c927fbbb17
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}, @ref{TS 29113 status}, @ref{TS 18508 status} and @ref{Fortran
537 2018 status} sections of the documentation.
539 Additionally, the GNU Fortran compilers supports the OpenMP specification
540 (version 4.0 and most of the features of the 4.5 version,
541 @url{http://openmp.org/@/wp/@/openmp-specifications/}).
542 There also is initial support for the OpenACC specification (targeting
543 version 2.0, @uref{http://www.openacc.org/}).
544 Note that this is an experimental feature, incomplete, and subject to
545 change in future versions of GCC.  See
546 @uref{https://gcc.gnu.org/wiki/OpenACC} for more information.
548 @node Varying Length Character Strings
549 @subsection Varying Length Character Strings
550 @cindex Varying length character strings
551 @cindex Varying length strings
552 @cindex strings, varying length
554 The Fortran 95 standard specifies in Part 2 (ISO/IEC 1539-2:2000)
555 varying length character strings.  While GNU Fortran currently does not
556 support such strings directly, there exist two Fortran implementations
557 for them, which work with GNU Fortran.  They can be found at
558 @uref{http://www.fortran.com/@/iso_varying_string.f95} and at
559 @uref{ftp://ftp.nag.co.uk/@/sc22wg5/@/ISO_VARYING_STRING/}.
561 Deferred-length character strings of Fortran 2003 supports part of
562 the features of @code{ISO_VARYING_STRING} and should be considered as
563 replacement. (Namely, allocatable or pointers of the type
564 @code{character(len=:)}.)
567 @c =====================================================================
568 @c PART I: INVOCATION REFERENCE
569 @c =====================================================================
571 @tex
572 \part{I}{Invoking GNU Fortran}
573 @end tex
575 @c ---------------------------------------------------------------------
576 @c Compiler Options
577 @c ---------------------------------------------------------------------
579 @include invoke.texi
582 @c ---------------------------------------------------------------------
583 @c Runtime
584 @c ---------------------------------------------------------------------
586 @node Runtime
587 @chapter Runtime:  Influencing runtime behavior with environment variables
588 @cindex environment variable
590 The behavior of the @command{gfortran} can be influenced by
591 environment variables.
593 Malformed environment variables are silently ignored.
595 @menu
596 * TMPDIR:: Directory for scratch files
597 * GFORTRAN_STDIN_UNIT:: Unit number for standard input
598 * GFORTRAN_STDOUT_UNIT:: Unit number for standard output
599 * GFORTRAN_STDERR_UNIT:: Unit number for standard error
600 * GFORTRAN_UNBUFFERED_ALL:: Do not buffer I/O for all units.
601 * GFORTRAN_UNBUFFERED_PRECONNECTED:: Do not buffer I/O for preconnected units.
602 * GFORTRAN_SHOW_LOCUS::  Show location for runtime errors
603 * GFORTRAN_OPTIONAL_PLUS:: Print leading + where permitted
604 * GFORTRAN_LIST_SEPARATOR::  Separator for list output
605 * GFORTRAN_CONVERT_UNIT::  Set endianness for unformatted I/O
606 * GFORTRAN_ERROR_BACKTRACE:: Show backtrace on run-time errors
607 @end menu
609 @node TMPDIR
610 @section @env{TMPDIR}---Directory for scratch files
612 When opening a file with @code{STATUS='SCRATCH'}, GNU Fortran tries to
613 create the file in one of the potential directories by testing each
614 directory in the order below.
616 @enumerate
617 @item
618 The environment variable @env{TMPDIR}, if it exists.
620 @item
621 On the MinGW target, the directory returned by the @code{GetTempPath}
622 function. Alternatively, on the Cygwin target, the @env{TMP} and
623 @env{TEMP} environment variables, if they exist, in that order.
625 @item
626 The @code{P_tmpdir} macro if it is defined, otherwise the directory
627 @file{/tmp}.
628 @end enumerate
630 @node GFORTRAN_STDIN_UNIT
631 @section @env{GFORTRAN_STDIN_UNIT}---Unit number for standard input
633 This environment variable can be used to select the unit number
634 preconnected to standard input.  This must be a positive integer.
635 The default value is 5.
637 @node GFORTRAN_STDOUT_UNIT
638 @section @env{GFORTRAN_STDOUT_UNIT}---Unit number for standard output
640 This environment variable can be used to select the unit number
641 preconnected to standard output.  This must be a positive integer.
642 The default value is 6.
644 @node GFORTRAN_STDERR_UNIT
645 @section @env{GFORTRAN_STDERR_UNIT}---Unit number for standard error
647 This environment variable can be used to select the unit number
648 preconnected to standard error.  This must be a positive integer.
649 The default value is 0.
651 @node GFORTRAN_UNBUFFERED_ALL
652 @section @env{GFORTRAN_UNBUFFERED_ALL}---Do not buffer I/O on all units
654 This environment variable controls whether all I/O is unbuffered.  If
655 the first letter is @samp{y}, @samp{Y} or @samp{1}, all I/O is
656 unbuffered.  This will slow down small sequential reads and writes.  If
657 the first letter is @samp{n}, @samp{N} or @samp{0}, I/O is buffered.
658 This is the default.
660 @node GFORTRAN_UNBUFFERED_PRECONNECTED
661 @section @env{GFORTRAN_UNBUFFERED_PRECONNECTED}---Do not buffer I/O on preconnected units
663 The environment variable named @env{GFORTRAN_UNBUFFERED_PRECONNECTED} controls
664 whether I/O on a preconnected unit (i.e.@: STDOUT or STDERR) is unbuffered.  If 
665 the first letter is @samp{y}, @samp{Y} or @samp{1}, I/O is unbuffered.  This
666 will slow down small sequential reads and writes.  If the first letter
667 is @samp{n}, @samp{N} or @samp{0}, I/O is buffered.  This is the default.
669 @node GFORTRAN_SHOW_LOCUS
670 @section @env{GFORTRAN_SHOW_LOCUS}---Show location for runtime errors
672 If the first letter is @samp{y}, @samp{Y} or @samp{1}, filename and
673 line numbers for runtime errors are printed.  If the first letter is
674 @samp{n}, @samp{N} or @samp{0}, do not print filename and line numbers
675 for runtime errors.  The default is to print the location.
677 @node GFORTRAN_OPTIONAL_PLUS
678 @section @env{GFORTRAN_OPTIONAL_PLUS}---Print leading + where permitted
680 If the first letter is @samp{y}, @samp{Y} or @samp{1},
681 a plus sign is printed
682 where permitted by the Fortran standard.  If the first letter
683 is @samp{n}, @samp{N} or @samp{0}, a plus sign is not printed
684 in most cases.  Default is not to print plus signs.
686 @node GFORTRAN_LIST_SEPARATOR
687 @section @env{GFORTRAN_LIST_SEPARATOR}---Separator for list output
689 This environment variable specifies the separator when writing
690 list-directed output.  It may contain any number of spaces and
691 at most one comma.  If you specify this on the command line,
692 be sure to quote spaces, as in
693 @smallexample
694 $ GFORTRAN_LIST_SEPARATOR='  ,  ' ./a.out
695 @end smallexample
696 when @command{a.out} is the compiled Fortran program that you want to run.
697 Default is a single space.
699 @node GFORTRAN_CONVERT_UNIT
700 @section @env{GFORTRAN_CONVERT_UNIT}---Set endianness for unformatted I/O
702 By setting the @env{GFORTRAN_CONVERT_UNIT} variable, it is possible
703 to change the representation of data for unformatted files.
704 The syntax for the @env{GFORTRAN_CONVERT_UNIT} variable is:
705 @smallexample
706 GFORTRAN_CONVERT_UNIT: mode | mode ';' exception | exception ;
707 mode: 'native' | 'swap' | 'big_endian' | 'little_endian' ;
708 exception: mode ':' unit_list | unit_list ;
709 unit_list: unit_spec | unit_list unit_spec ;
710 unit_spec: INTEGER | INTEGER '-' INTEGER ;
711 @end smallexample
712 The variable consists of an optional default mode, followed by
713 a list of optional exceptions, which are separated by semicolons
714 from the preceding default and each other.  Each exception consists
715 of a format and a comma-separated list of units.  Valid values for
716 the modes are the same as for the @code{CONVERT} specifier:
718 @itemize @w{}
719 @item @code{NATIVE} Use the native format.  This is the default.
720 @item @code{SWAP} Swap between little- and big-endian.
721 @item @code{LITTLE_ENDIAN} Use the little-endian format
722 for unformatted files.
723 @item @code{BIG_ENDIAN} Use the big-endian format for unformatted files.
724 @end itemize
725 A missing mode for an exception is taken to mean @code{BIG_ENDIAN}.
726 Examples of values for @env{GFORTRAN_CONVERT_UNIT} are:
727 @itemize @w{}
728 @item @code{'big_endian'}  Do all unformatted I/O in big_endian mode.
729 @item @code{'little_endian;native:10-20,25'}  Do all unformatted I/O 
730 in little_endian mode, except for units 10 to 20 and 25, which are in
731 native format.
732 @item @code{'10-20'}  Units 10 to 20 are big-endian, the rest is native.
733 @end itemize
735 Setting the environment variables should be done on the command
736 line or via the @command{export}
737 command for @command{sh}-compatible shells and via @command{setenv}
738 for @command{csh}-compatible shells.
740 Example for @command{sh}:
741 @smallexample
742 $ gfortran foo.f90
743 $ GFORTRAN_CONVERT_UNIT='big_endian;native:10-20' ./a.out
744 @end smallexample
746 Example code for @command{csh}:
747 @smallexample
748 % gfortran foo.f90
749 % setenv GFORTRAN_CONVERT_UNIT 'big_endian;native:10-20'
750 % ./a.out
751 @end smallexample
753 Using anything but the native representation for unformatted data
754 carries a significant speed overhead.  If speed in this area matters
755 to you, it is best if you use this only for data that needs to be
756 portable.
758 @xref{CONVERT specifier}, for an alternative way to specify the
759 data representation for unformatted files.  @xref{Runtime Options}, for
760 setting a default data representation for the whole program.  The
761 @code{CONVERT} specifier overrides the @option{-fconvert} compile options.
763 @emph{Note that the values specified via the GFORTRAN_CONVERT_UNIT
764 environment variable will override the CONVERT specifier in the
765 open statement}.  This is to give control over data formats to
766 users who do not have the source code of their program available.
768 @node GFORTRAN_ERROR_BACKTRACE
769 @section @env{GFORTRAN_ERROR_BACKTRACE}---Show backtrace on run-time errors
771 If the @env{GFORTRAN_ERROR_BACKTRACE} variable is set to @samp{y},
772 @samp{Y} or @samp{1} (only the first letter is relevant) then a
773 backtrace is printed when a serious run-time error occurs.  To disable
774 the backtracing, set the variable to @samp{n}, @samp{N}, @samp{0}.
775 Default is to print a backtrace unless the @option{-fno-backtrace}
776 compile option was used.
778 @c =====================================================================
779 @c PART II: LANGUAGE REFERENCE
780 @c =====================================================================
782 @tex
783 \part{II}{Language Reference}
784 @end tex
786 @c ---------------------------------------------------------------------
787 @c Fortran standards status
788 @c ---------------------------------------------------------------------
790 @node Fortran standards status
791 @chapter Fortran standards status
793 @menu
794 * Fortran 2003 status::
795 * Fortran 2008 status::
796 * TS 29113 status::
797 * TS 18508 status::
798 * Fortran 2018 status::
799 @end menu
801 @node Fortran 2003 status
802 @section Fortran 2003 status
804 GNU Fortran supports several Fortran 2003 features; an incomplete
805 list can be found below.  See also the
806 @uref{https://gcc.gnu.org/wiki/Fortran2003, wiki page} about Fortran 2003.
808 @itemize
809 @item Procedure pointers including procedure-pointer components with
810 @code{PASS} attribute.
812 @item Procedures which are bound to a derived type (type-bound procedures)
813 including @code{PASS}, @code{PROCEDURE} and @code{GENERIC}, and
814 operators bound to a type.
816 @item Abstract interfaces and type extension with the possibility to
817 override type-bound procedures or to have deferred binding.
819 @item Polymorphic entities (``@code{CLASS}'') for derived types and unlimited
820 polymorphism (``@code{CLASS(*)}'') -- including @code{SAME_TYPE_AS},
821 @code{EXTENDS_TYPE_OF} and @code{SELECT TYPE} for scalars and arrays and
822 finalization.
824 @item Generic interface names, which have the same name as derived types,
825 are now supported. This allows one to write constructor functions.  Note
826 that Fortran does not support static constructor functions.  For static
827 variables, only default initialization or structure-constructor
828 initialization are available.
830 @item The @code{ASSOCIATE} construct.
832 @item Interoperability with C including enumerations, 
834 @item In structure constructors the components with default values may be
835 omitted.
837 @item Extensions to the @code{ALLOCATE} statement, allowing for a
838 type-specification with type parameter and for allocation and initialization
839 from a @code{SOURCE=} expression; @code{ALLOCATE} and @code{DEALLOCATE}
840 optionally return an error message string via @code{ERRMSG=}.
842 @item Reallocation on assignment: If an intrinsic assignment is
843 used, an allocatable variable on the left-hand side is automatically allocated
844 (if unallocated) or reallocated (if the shape is different). Currently, scalar
845 deferred character length left-hand sides are correctly handled but arrays
846 are not yet fully implemented.
848 @item Deferred-length character variables and scalar deferred-length character
849 components of derived types are supported. (Note that array-valued compoents
850 are not yet implemented.)
852 @item Transferring of allocations via @code{MOVE_ALLOC}.
854 @item The @code{PRIVATE} and @code{PUBLIC} attributes may be given individually
855 to derived-type components.
857 @item In pointer assignments, the lower bound may be specified and
858 the remapping of elements is supported.
860 @item For pointers an @code{INTENT} may be specified which affect the
861 association status not the value of the pointer target.
863 @item Intrinsics @code{command_argument_count}, @code{get_command},
864 @code{get_command_argument}, and @code{get_environment_variable}.
866 @item Support for Unicode characters (ISO 10646) and UTF-8, including
867 the @code{SELECTED_CHAR_KIND} and @code{NEW_LINE} intrinsic functions.
869 @item Support for binary, octal and hexadecimal (BOZ) constants in the
870 intrinsic functions @code{INT}, @code{REAL}, @code{CMPLX} and @code{DBLE}.
872 @item Support for namelist variables with allocatable and pointer
873 attribute and nonconstant length type parameter.
875 @item
876 @cindex array, constructors
877 @cindex @code{[...]}
878 Array constructors using square brackets.  That is, @code{[...]} rather
879 than @code{(/.../)}.  Type-specification for array constructors like
880 @code{(/ some-type :: ... /)}.
882 @item Extensions to the specification and initialization expressions,
883 including the support for intrinsics with real and complex arguments.
885 @item Support for the asynchronous input/output syntax; however, the
886 data transfer is currently always synchronously performed. 
888 @item
889 @cindex @code{FLUSH} statement
890 @cindex statement, @code{FLUSH}
891 @code{FLUSH} statement.
893 @item
894 @cindex @code{IOMSG=} specifier
895 @code{IOMSG=} specifier for I/O statements.
897 @item
898 @cindex @code{ENUM} statement
899 @cindex @code{ENUMERATOR} statement
900 @cindex statement, @code{ENUM}
901 @cindex statement, @code{ENUMERATOR}
902 @opindex @code{fshort-enums}
903 Support for the declaration of enumeration constants via the
904 @code{ENUM} and @code{ENUMERATOR} statements.  Interoperability with
905 @command{gcc} is guaranteed also for the case where the
906 @command{-fshort-enums} command line option is given.
908 @item
909 @cindex TR 15581
910 TR 15581:
911 @itemize
912 @item
913 @cindex @code{ALLOCATABLE} dummy arguments
914 @code{ALLOCATABLE} dummy arguments.
915 @item
916 @cindex @code{ALLOCATABLE} function results
917 @code{ALLOCATABLE} function results
918 @item
919 @cindex @code{ALLOCATABLE} components of derived types
920 @code{ALLOCATABLE} components of derived types
921 @end itemize
923 @item
924 @cindex @code{STREAM} I/O
925 @cindex @code{ACCESS='STREAM'} I/O
926 The @code{OPEN} statement supports the @code{ACCESS='STREAM'} specifier,
927 allowing I/O without any record structure.
929 @item
930 Namelist input/output for internal files.
932 @item Minor I/O features: Rounding during formatted output, using of
933 a decimal comma instead of a decimal point, setting whether a plus sign
934 should appear for positive numbers. On systems where @code{strtod} honours
935 the rounding mode, the rounding mode is also supported for input.
937 @item
938 @cindex @code{PROTECTED} statement
939 @cindex statement, @code{PROTECTED}
940 The @code{PROTECTED} statement and attribute.
942 @item
943 @cindex @code{VALUE} statement
944 @cindex statement, @code{VALUE}
945 The @code{VALUE} statement and attribute.
947 @item
948 @cindex @code{VOLATILE} statement
949 @cindex statement, @code{VOLATILE}
950 The @code{VOLATILE} statement and attribute.
952 @item
953 @cindex @code{IMPORT} statement
954 @cindex statement, @code{IMPORT}
955 The @code{IMPORT} statement, allowing to import
956 host-associated derived types.
958 @item The intrinsic modules @code{ISO_FORTRAN_ENVIRONMENT} is supported,
959 which contains parameters of the I/O units, storage sizes. Additionally,
960 procedures for C interoperability are available in the @code{ISO_C_BINDING}
961 module.
963 @item
964 @cindex @code{USE, INTRINSIC} statement
965 @cindex statement, @code{USE, INTRINSIC}
966 @cindex @code{ISO_FORTRAN_ENV} statement
967 @cindex statement, @code{ISO_FORTRAN_ENV}
968 @code{USE} statement with @code{INTRINSIC} and @code{NON_INTRINSIC}
969 attribute; supported intrinsic modules: @code{ISO_FORTRAN_ENV},
970 @code{ISO_C_BINDING}, @code{OMP_LIB} and @code{OMP_LIB_KINDS},
971 and @code{OPENACC}.
973 @item
974 Renaming of operators in the @code{USE} statement.
976 @end itemize
979 @node Fortran 2008 status
980 @section Fortran 2008 status
982 The latest version of the Fortran standard is ISO/IEC 1539-1:2010, informally
983 known as Fortran 2008.  The official version is available from International
984 Organization for Standardization (ISO) or its national member organizations.
985 The the final draft (FDIS) can be downloaded free of charge from
986 @url{http://www.nag.co.uk/@/sc22wg5/@/links.html}.  Fortran is developed by the
987 Working Group 5 of Sub-Committee 22 of the Joint Technical Committee 1 of the
988 International Organization for Standardization and the International
989 Electrotechnical Commission (IEC).  This group is known as
990 @uref{http://www.nag.co.uk/sc22wg5/, WG5}.
992 The GNU Fortran compiler supports several of the new features of Fortran 2008;
993 the @uref{https://gcc.gnu.org/wiki/Fortran2008Status, wiki} has some information
994 about the current Fortran 2008 implementation status.  In particular, the
995 following is implemented.
997 @itemize
998 @item The @option{-std=f2008} option and support for the file extensions 
999 @file{.f08} and @file{.F08}.
1001 @item The @code{OPEN} statement now supports the @code{NEWUNIT=} option,
1002 which returns a unique file unit, thus preventing inadvertent use of the
1003 same unit in different parts of the program.
1005 @item The @code{g0} format descriptor and unlimited format items.
1007 @item The mathematical intrinsics @code{ASINH}, @code{ACOSH}, @code{ATANH},
1008 @code{ERF}, @code{ERFC}, @code{GAMMA}, @code{LOG_GAMMA}, @code{BESSEL_J0},
1009 @code{BESSEL_J1}, @code{BESSEL_JN}, @code{BESSEL_Y0}, @code{BESSEL_Y1},
1010 @code{BESSEL_YN}, @code{HYPOT}, @code{NORM2}, and @code{ERFC_SCALED}.
1012 @item Using complex arguments with @code{TAN}, @code{SINH}, @code{COSH},
1013 @code{TANH}, @code{ASIN}, @code{ACOS}, and @code{ATAN} is now possible;
1014 @code{ATAN}(@var{Y},@var{X}) is now an alias for @code{ATAN2}(@var{Y},@var{X}).
1016 @item Support of the @code{PARITY} intrinsic functions.
1018 @item The following bit intrinsics: @code{LEADZ} and @code{TRAILZ} for
1019 counting the number of leading and trailing zero bits, @code{POPCNT} and
1020 @code{POPPAR} for counting the number of one bits and returning the parity;
1021 @code{BGE}, @code{BGT}, @code{BLE}, and @code{BLT} for bitwise comparisons;
1022 @code{DSHIFTL} and @code{DSHIFTR} for combined left and right shifts,
1023 @code{MASKL} and @code{MASKR} for simple left and right justified masks,
1024 @code{MERGE_BITS} for a bitwise merge using a mask, @code{SHIFTA},
1025 @code{SHIFTL} and @code{SHIFTR} for shift operations, and the
1026 transformational bit intrinsics @code{IALL}, @code{IANY} and @code{IPARITY}.
1028 @item Support of the @code{EXECUTE_COMMAND_LINE} intrinsic subroutine.
1030 @item Support for the @code{STORAGE_SIZE} intrinsic inquiry function.
1032 @item The @code{INT@{8,16,32@}} and @code{REAL@{32,64,128@}} kind type
1033 parameters and the array-valued named constants @code{INTEGER_KINDS},
1034 @code{LOGICAL_KINDS}, @code{REAL_KINDS} and @code{CHARACTER_KINDS} of
1035 the intrinsic module @code{ISO_FORTRAN_ENV}.
1037 @item The module procedures @code{C_SIZEOF} of the intrinsic module
1038 @code{ISO_C_BINDINGS} and @code{COMPILER_VERSION} and @code{COMPILER_OPTIONS}
1039 of @code{ISO_FORTRAN_ENV}.
1041 @item Coarray support for serial programs with @option{-fcoarray=single} flag
1042 and experimental support for multiple images with the @option{-fcoarray=lib}
1043 flag.
1045 @item Submodules are supported. It should noted that @code{MODULEs} do not
1046 produce the smod file needed by the descendent @code{SUBMODULEs} unless they
1047 contain at least one @code{MODULE PROCEDURE} interface. The reason for this is
1048 that @code{SUBMODULEs} are useless without @code{MODULE PROCEDUREs}. See
1049 http://j3-fortran.org/doc/meeting/207/15-209.txt for a discussion and a draft
1050 interpretation. Adopting this interpretation has the advantage that code that
1051 does not use submodules does not generate smod files.
1053 @item The @code{DO CONCURRENT} construct is supported.
1055 @item The @code{BLOCK} construct is supported.
1057 @item The @code{STOP} and the new @code{ERROR STOP} statements now
1058 support all constant expressions. Both show the signals which were signaling
1059 at termination.
1061 @item Support for the @code{CONTIGUOUS} attribute.
1063 @item Support for @code{ALLOCATE} with @code{MOLD}.
1065 @item Support for the @code{IMPURE} attribute for procedures, which
1066 allows for @code{ELEMENTAL} procedures without the restrictions of
1067 @code{PURE}.
1069 @item Null pointers (including @code{NULL()}) and not-allocated variables
1070 can be used as actual argument to optional non-pointer, non-allocatable
1071 dummy arguments, denoting an absent argument.
1073 @item Non-pointer variables with @code{TARGET} attribute can be used as
1074 actual argument to @code{POINTER} dummies with @code{INTENT(IN)}.
1076 @item Pointers including procedure pointers and those in a derived
1077 type (pointer components) can now be initialized by a target instead
1078 of only by @code{NULL}.
1080 @item The @code{EXIT} statement (with construct-name) can be now be
1081 used to leave not only the @code{DO} but also the @code{ASSOCIATE},
1082 @code{BLOCK}, @code{IF}, @code{SELECT CASE} and @code{SELECT TYPE}
1083 constructs.
1085 @item Internal procedures can now be used as actual argument.
1087 @item Minor features: obsolesce diagnostics for @code{ENTRY} with
1088 @option{-std=f2008}; a line may start with a semicolon; for internal
1089 and module procedures @code{END} can be used instead of
1090 @code{END SUBROUTINE} and @code{END FUNCTION}; @code{SELECTED_REAL_KIND}
1091 now also takes a @code{RADIX} argument; intrinsic types are supported
1092 for @code{TYPE}(@var{intrinsic-type-spec}); multiple type-bound procedures
1093 can be declared in a single @code{PROCEDURE} statement; implied-shape
1094 arrays are supported for named constants (@code{PARAMETER}).
1095 @end itemize
1099 @node TS 29113 status
1100 @section Technical Specification 29113 Status
1102 GNU Fortran supports some of the new features of the Technical
1103 Specification (TS) 29113 on Further Interoperability of Fortran with C.
1104 The @uref{https://gcc.gnu.org/wiki/TS29113Status, wiki} has some information
1105 about the current TS 29113 implementation status.  In particular, the
1106 following is implemented.
1108 See also @ref{Further Interoperability of Fortran with C}.
1110 @itemize
1111 @item The @option{-std=f2008ts} option.
1113 @item The @code{OPTIONAL} attribute is allowed for dummy arguments
1114 of @code{BIND(C) procedures.}
1116 @item The @code{RANK} intrinsic is supported.
1118 @item GNU Fortran's implementation for variables with @code{ASYNCHRONOUS}
1119 attribute is compatible with TS 29113.
1121 @item Assumed types (@code{TYPE(*)}).
1123 @item Assumed-rank (@code{DIMENSION(..)}). However, the array descriptor
1124 of the TS is not yet supported.
1125 @end itemize
1128 @node TS 18508 status
1129 @section Technical Specification 18508 Status
1131 GNU Fortran supports the following new features of the Technical
1132 Specification 18508 on Additional Parallel Features in Fortran:
1134 @itemize
1135 @item The new atomic ADD, CAS, FETCH and ADD/OR/XOR, OR and XOR intrinsics.
1137 @item The @code{CO_MIN} and @code{CO_MAX} and @code{SUM} reduction intrinsics.
1138 And the @code{CO_BROADCAST} and @code{CO_REDUCE} intrinsic, except that those
1139 do not support polymorphic types or types with allocatable, pointer or
1140 polymorphic components.
1142 @item Events (@code{EVENT POST}, @code{EVENT WAIT}, @code{EVENT_QUERY})
1144 @item Failed images (@code{FAIL IMAGE}, @code{IMAGE_STATUS},
1145 @code{FAILED_IMAGES}, @code{STOPPED_IMAGES})
1147 @end itemize
1150 @node Fortran 2018 status
1151 @section Status of Fortran 2018 support
1153 So far very little work has been done to support Fortran 2018.
1155 @itemize
1156 @item ERROR STOP in a PURE procedure
1157 An @code{ERROR STOP} statement is permitted in a @code{PURE}
1158 procedure.
1160 @item IMPLICIT NONE with a spec-list
1161 Support the @code{IMPLICIT NONE} statement with an
1162 @code{implicit-none-spec-list}.
1164 @item Behavior of INQUIRE with the RECL= specifier
1166 The behavior of the @code{INQUIRE} statement with the @code{RECL=}
1167 specifier now conforms to Fortran 2018.
1169 @end itemize
1171 @c ---------------------------------------------------------------------
1172 @c Compiler Characteristics
1173 @c ---------------------------------------------------------------------
1175 @node Compiler Characteristics
1176 @chapter Compiler Characteristics
1178 This chapter describes certain characteristics of the GNU Fortran
1179 compiler, that are not specified by the Fortran standard, but which
1180 might in some way or another become visible to the programmer.
1182 @menu
1183 * KIND Type Parameters::
1184 * Internal representation of LOGICAL variables::
1185 * Thread-safety of the runtime library::
1186 * Data consistency and durability::
1187 * Files opened without an explicit ACTION= specifier::
1188 * File operations on symbolic links::
1189 * File format of unformatted sequential files::
1190 @end menu
1193 @node KIND Type Parameters
1194 @section KIND Type Parameters
1195 @cindex kind
1197 The @code{KIND} type parameters supported by GNU Fortran for the primitive
1198 data types are:
1200 @table @code
1202 @item INTEGER
1203 1, 2, 4, 8*, 16*, default: 4**
1205 @item LOGICAL
1206 1, 2, 4, 8*, 16*, default: 4**
1208 @item REAL
1209 4, 8, 10*, 16*, default: 4***
1211 @item COMPLEX
1212 4, 8, 10*, 16*, default: 4***
1214 @item DOUBLE PRECISION
1215 4, 8, 10*, 16*, default: 8***
1217 @item CHARACTER
1218 1, 4, default: 1
1220 @end table
1222 @noindent
1223 * not available on all systems @*
1224 ** unless @option{-fdefault-integer-8} is used @*
1225 *** unless @option{-fdefault-real-8} is used (see @ref{Fortran Dialect Options})
1227 @noindent
1228 The @code{KIND} value matches the storage size in bytes, except for
1229 @code{COMPLEX} where the storage size is twice as much (or both real and
1230 imaginary part are a real value of the given size).  It is recommended to use
1231 the @ref{SELECTED_CHAR_KIND}, @ref{SELECTED_INT_KIND} and
1232 @ref{SELECTED_REAL_KIND} intrinsics or the @code{INT8}, @code{INT16},
1233 @code{INT32}, @code{INT64}, @code{REAL32}, @code{REAL64}, and @code{REAL128}
1234 parameters of the @code{ISO_FORTRAN_ENV} module instead of the concrete values.
1235 The available kind parameters can be found in the constant arrays
1236 @code{CHARACTER_KINDS}, @code{INTEGER_KINDS}, @code{LOGICAL_KINDS} and
1237 @code{REAL_KINDS} in the @ref{ISO_FORTRAN_ENV} module.  For C interoperability,
1238 the kind parameters of the @ref{ISO_C_BINDING} module should be used.
1241 @node Internal representation of LOGICAL variables
1242 @section Internal representation of LOGICAL variables
1243 @cindex logical, variable representation
1245 The Fortran standard does not specify how variables of @code{LOGICAL}
1246 type are represented, beyond requiring that @code{LOGICAL} variables
1247 of default kind have the same storage size as default @code{INTEGER}
1248 and @code{REAL} variables.  The GNU Fortran internal representation is
1249 as follows.
1251 A @code{LOGICAL(KIND=N)} variable is represented as an
1252 @code{INTEGER(KIND=N)} variable, however, with only two permissible
1253 values: @code{1} for @code{.TRUE.} and @code{0} for
1254 @code{.FALSE.}.  Any other integer value results in undefined behavior.
1256 See also @ref{Argument passing conventions} and @ref{Interoperability with C}.
1259 @node Thread-safety of the runtime library
1260 @section Thread-safety of the runtime library
1261 @cindex thread-safety, threads
1263 GNU Fortran can be used in programs with multiple threads, e.g.@: by
1264 using OpenMP, by calling OS thread handling functions via the
1265 @code{ISO_C_BINDING} facility, or by GNU Fortran compiled library code
1266 being called from a multi-threaded program.
1268 The GNU Fortran runtime library, (@code{libgfortran}), supports being
1269 called concurrently from multiple threads with the following
1270 exceptions. 
1272 During library initialization, the C @code{getenv} function is used,
1273 which need not be thread-safe.  Similarly, the @code{getenv}
1274 function is used to implement the @code{GET_ENVIRONMENT_VARIABLE} and
1275 @code{GETENV} intrinsics.  It is the responsibility of the user to
1276 ensure that the environment is not being updated concurrently when any
1277 of these actions are taking place.
1279 The @code{EXECUTE_COMMAND_LINE} and @code{SYSTEM} intrinsics are
1280 implemented with the @code{system} function, which need not be
1281 thread-safe.  It is the responsibility of the user to ensure that
1282 @code{system} is not called concurrently.
1284 For platforms not supporting thread-safe POSIX functions, further
1285 functionality might not be thread-safe.  For details, please consult
1286 the documentation for your operating system.
1288 The GNU Fortran runtime library uses various C library functions that
1289 depend on the locale, such as @code{strtod} and @code{snprintf}.  In
1290 order to work correctly in locale-aware programs that set the locale
1291 using @code{setlocale}, the locale is reset to the default ``C''
1292 locale while executing a formatted @code{READ} or @code{WRITE}
1293 statement.  On targets supporting the POSIX 2008 per-thread locale
1294 functions (e.g. @code{newlocale}, @code{uselocale},
1295 @code{freelocale}), these are used and thus the global locale set
1296 using @code{setlocale} or the per-thread locales in other threads are
1297 not affected.  However, on targets lacking this functionality, the
1298 global LC_NUMERIC locale is set to ``C'' during the formatted I/O.
1299 Thus, on such targets it's not safe to call @code{setlocale}
1300 concurrently from another thread while a Fortran formatted I/O
1301 operation is in progress.  Also, other threads doing something
1302 dependent on the LC_NUMERIC locale might not work correctly if a
1303 formatted I/O operation is in progress in another thread.
1305 @node Data consistency and durability
1306 @section Data consistency and durability
1307 @cindex consistency, durability
1309 This section contains a brief overview of data and metadata
1310 consistency and durability issues when doing I/O.
1312 With respect to durability, GNU Fortran makes no effort to ensure that
1313 data is committed to stable storage. If this is required, the GNU
1314 Fortran programmer can use the intrinsic @code{FNUM} to retrieve the
1315 low level file descriptor corresponding to an open Fortran unit. Then,
1316 using e.g. the @code{ISO_C_BINDING} feature, one can call the
1317 underlying system call to flush dirty data to stable storage, such as
1318 @code{fsync} on POSIX, @code{_commit} on MingW, or @code{fcntl(fd,
1319 F_FULLSYNC, 0)} on Mac OS X. The following example shows how to call
1320 fsync:
1322 @smallexample
1323   ! Declare the interface for POSIX fsync function
1324   interface
1325     function fsync (fd) bind(c,name="fsync")
1326     use iso_c_binding, only: c_int
1327       integer(c_int), value :: fd
1328       integer(c_int) :: fsync
1329     end function fsync
1330   end interface
1332   ! Variable declaration
1333   integer :: ret
1335   ! Opening unit 10
1336   open (10,file="foo")
1338   ! ...
1339   ! Perform I/O on unit 10
1340   ! ...
1342   ! Flush and sync
1343   flush(10)
1344   ret = fsync(fnum(10))
1346   ! Handle possible error
1347   if (ret /= 0) stop "Error calling FSYNC"
1348 @end smallexample
1350 With respect to consistency, for regular files GNU Fortran uses
1351 buffered I/O in order to improve performance. This buffer is flushed
1352 automatically when full and in some other situations, e.g. when
1353 closing a unit. It can also be explicitly flushed with the
1354 @code{FLUSH} statement. Also, the buffering can be turned off with the
1355 @code{GFORTRAN_UNBUFFERED_ALL} and
1356 @code{GFORTRAN_UNBUFFERED_PRECONNECTED} environment variables. Special
1357 files, such as terminals and pipes, are always unbuffered. Sometimes,
1358 however, further things may need to be done in order to allow other
1359 processes to see data that GNU Fortran has written, as follows.
1361 The Windows platform supports a relaxed metadata consistency model,
1362 where file metadata is written to the directory lazily. This means
1363 that, for instance, the @code{dir} command can show a stale size for a
1364 file. One can force a directory metadata update by closing the unit,
1365 or by calling @code{_commit} on the file descriptor. Note, though,
1366 that @code{_commit} will force all dirty data to stable storage, which
1367 is often a very slow operation.
1369 The Network File System (NFS) implements a relaxed consistency model
1370 called open-to-close consistency. Closing a file forces dirty data and
1371 metadata to be flushed to the server, and opening a file forces the
1372 client to contact the server in order to revalidate cached
1373 data. @code{fsync} will also force a flush of dirty data and metadata
1374 to the server. Similar to @code{open} and @code{close}, acquiring and
1375 releasing @code{fcntl} file locks, if the server supports them, will
1376 also force cache validation and flushing dirty data and metadata.
1379 @node Files opened without an explicit ACTION= specifier
1380 @section Files opened without an explicit ACTION= specifier
1381 @cindex open, action
1383 The Fortran standard says that if an @code{OPEN} statement is executed
1384 without an explicit @code{ACTION=} specifier, the default value is
1385 processor dependent.  GNU Fortran behaves as follows:
1387 @enumerate
1388 @item Attempt to open the file with @code{ACTION='READWRITE'}
1389 @item If that fails, try to open with @code{ACTION='READ'}
1390 @item If that fails, try to open with @code{ACTION='WRITE'}
1391 @item If that fails, generate an error
1392 @end enumerate
1395 @node File operations on symbolic links
1396 @section File operations on symbolic links
1397 @cindex file, symbolic link
1399 This section documents the behavior of GNU Fortran for file operations on
1400 symbolic links, on systems that support them. 
1402 @itemize
1404 @item Results of INQUIRE statements of the ``inquire by file'' form will
1405 relate to the target of the symbolic link. For example,
1406 @code{INQUIRE(FILE="foo",EXIST=ex)} will set @var{ex} to @var{.true.} if
1407 @var{foo} is a symbolic link pointing to an existing file, and @var{.false.}
1408 if @var{foo} points to an non-existing file (``dangling'' symbolic link).
1410 @item Using the @code{OPEN} statement with a @code{STATUS="NEW"} specifier
1411 on a symbolic link will result in an error condition, whether the symbolic
1412 link points to an existing target or is dangling.
1414 @item If a symbolic link was connected, using the @code{CLOSE} statement
1415 with a @code{STATUS="DELETE"} specifier will cause the symbolic link itself
1416 to be deleted, not its target.
1418 @end itemize
1420 @node File format of unformatted sequential files
1421 @section File format of unformatted sequential files
1422 @cindex file, unformatted sequential
1423 @cindex unformatted sequential
1424 @cindex sequential, unformatted
1425 @cindex record marker
1426 @cindex subrecord
1428 Unformatted sequential files are stored as logical records using
1429 record markers.  Each logical record consists of one of more
1430 subrecords.
1432 Each subrecord consists of a leading record marker, the data written
1433 by the user program, and a trailing record marker.  The record markers
1434 are four-byte integers by default, and eight-byte integers if the
1435 @option{-fmax-subrecord-length=8} option (which exists for backwards
1436 compability only) is in effect.
1438 The representation of the record markers is that of unformatted files
1439 given with the @option{-fconvert} option, the @xref{CONVERT specifier}
1440 on the open statement or the @xref{GFORTRAN_CONVERT_UNIT} environment
1441 variable.
1443 The maximum number of bytes of user data in a subrecord is 2147483639
1444 (2 GiB - 9) for a four-byte record marker.  This limit can be lowered
1445 with the @option{-fmax-subrecord-length} option, altough this is
1446 rarely useful. If the length of a logical record exceeds this limit,
1447 the data is distributed among several subrecords.
1449 The absolute of the number stored in the record markers is the number
1450 of bytes of user data in the corresponding subrecord.  If the leading
1451 record marker of a subrecord contains a negative number, another
1452 subrecord follows the current one.  If the trailing record marker
1453 contains a negative number, then there is a preceding subrecord.
1455 In the most simple case, with only one subrecord per logical record,
1456 both record markers contain the number of bytes of user data in the
1457 record,
1459 The format for unformatted sequential data can be duplicated using
1460 unformatted stream, as shown in the example program for an unformatted
1461 record containing a single subrecord:
1463 @smallexample
1464 program main
1465   use iso_fortran_env, only: int32
1466   implicit none
1467   integer(int32) :: i 
1468   real, dimension(10) :: a, b
1469   call random_number(a)
1470   open (10,file='test.dat',form='unformatted',access='stream')
1471   inquire (iolength=i) a
1472   write (10) i, a, i
1473   close (10)
1474   open (10,file='test.dat',form='unformatted')
1475   read (10) b
1476   if (all (a == b)) print *,'success!'
1477 end program main
1478 @end smallexample
1480 @c ---------------------------------------------------------------------
1481 @c Extensions
1482 @c ---------------------------------------------------------------------
1484 @c Maybe this chapter should be merged with the 'Standards' section,
1485 @c whenever that is written :-)
1487 @node Extensions
1488 @chapter Extensions
1489 @cindex extensions
1491 The two sections below detail the extensions to standard Fortran that are
1492 implemented in GNU Fortran, as well as some of the popular or
1493 historically important extensions that are not (or not yet) implemented.
1494 For the latter case, we explain the alternatives available to GNU Fortran
1495 users, including replacement by standard-conforming code or GNU
1496 extensions.
1498 @menu
1499 * Extensions implemented in GNU Fortran::
1500 * Extensions not implemented in GNU Fortran::
1501 @end menu
1504 @node Extensions implemented in GNU Fortran
1505 @section Extensions implemented in GNU Fortran
1506 @cindex extensions, implemented
1508 GNU Fortran implements a number of extensions over standard Fortran.
1509 This chapter contains information on their syntax and meaning.  There
1510 are currently two categories of GNU Fortran extensions, those that
1511 provide functionality beyond that provided by any standard, and those
1512 that are supported by GNU Fortran purely for backward compatibility
1513 with legacy compilers.  By default, @option{-std=gnu} allows the
1514 compiler to accept both types of extensions, but to warn about the use
1515 of the latter.  Specifying either @option{-std=f95},
1516 @option{-std=f2003}, @option{-std=f2008}, or @option{-std=f2018}
1517 disables both types of extensions, and @option{-std=legacy} allows
1518 both without warning.  The special compile flag @option{-fdec} enables
1519 additional compatibility extensions along with those enabled by
1520 @option{-std=legacy}.
1522 @menu
1523 * Old-style kind specifications::
1524 * Old-style variable initialization::
1525 * Extensions to namelist::
1526 * X format descriptor without count field::
1527 * Commas in FORMAT specifications::
1528 * Missing period in FORMAT specifications::
1529 * I/O item lists::
1530 * @code{Q} exponent-letter::
1531 * BOZ literal constants::
1532 * Real array indices::
1533 * Unary operators::
1534 * Implicitly convert LOGICAL and INTEGER values::
1535 * Hollerith constants support::
1536 * Cray pointers::
1537 * CONVERT specifier::
1538 * OpenMP::
1539 * OpenACC::
1540 * Argument list functions::
1541 * Read/Write after EOF marker::
1542 * STRUCTURE and RECORD::
1543 * UNION and MAP::
1544 * Type variants for integer intrinsics::
1545 * AUTOMATIC and STATIC attributes::
1546 * Extended math intrinsics::
1547 * Form feed as whitespace::
1548 * TYPE as an alias for PRINT::
1549 * %LOC as an rvalue::
1550 * .XOR. operator::
1551 * Bitwise logical operators::
1552 * Extended I/O specifiers::
1553 * Legacy PARAMETER statements::
1554 * Default exponents::
1555 @end menu
1557 @node Old-style kind specifications
1558 @subsection Old-style kind specifications
1559 @cindex kind, old-style
1561 GNU Fortran allows old-style kind specifications in declarations.  These
1562 look like:
1563 @smallexample
1564       TYPESPEC*size x,y,z
1565 @end smallexample
1566 @noindent
1567 where @code{TYPESPEC} is a basic type (@code{INTEGER}, @code{REAL},
1568 etc.), and where @code{size} is a byte count corresponding to the
1569 storage size of a valid kind for that type.  (For @code{COMPLEX}
1570 variables, @code{size} is the total size of the real and imaginary
1571 parts.)  The statement then declares @code{x}, @code{y} and @code{z} to
1572 be of type @code{TYPESPEC} with the appropriate kind.  This is
1573 equivalent to the standard-conforming declaration
1574 @smallexample
1575       TYPESPEC(k) x,y,z
1576 @end smallexample
1577 @noindent
1578 where @code{k} is the kind parameter suitable for the intended precision.  As
1579 kind parameters are implementation-dependent, use the @code{KIND},
1580 @code{SELECTED_INT_KIND} and @code{SELECTED_REAL_KIND} intrinsics to retrieve
1581 the correct value, for instance @code{REAL*8 x} can be replaced by:
1582 @smallexample
1583 INTEGER, PARAMETER :: dbl = KIND(1.0d0)
1584 REAL(KIND=dbl) :: x
1585 @end smallexample
1587 @node Old-style variable initialization
1588 @subsection Old-style variable initialization
1590 GNU Fortran allows old-style initialization of variables of the
1591 form:
1592 @smallexample
1593       INTEGER i/1/,j/2/
1594       REAL x(2,2) /3*0.,1./
1595 @end smallexample
1596 The syntax for the initializers is as for the @code{DATA} statement, but
1597 unlike in a @code{DATA} statement, an initializer only applies to the
1598 variable immediately preceding the initialization.  In other words,
1599 something like @code{INTEGER I,J/2,3/} is not valid.  This style of
1600 initialization is only allowed in declarations without double colons
1601 (@code{::}); the double colons were introduced in Fortran 90, which also
1602 introduced a standard syntax for initializing variables in type
1603 declarations.
1605 Examples of standard-conforming code equivalent to the above example
1606 are:
1607 @smallexample
1608 ! Fortran 90
1609       INTEGER :: i = 1, j = 2
1610       REAL :: x(2,2) = RESHAPE((/0.,0.,0.,1./),SHAPE(x))
1611 ! Fortran 77
1612       INTEGER i, j
1613       REAL x(2,2)
1614       DATA i/1/, j/2/, x/3*0.,1./
1615 @end smallexample
1617 Note that variables which are explicitly initialized in declarations
1618 or in @code{DATA} statements automatically acquire the @code{SAVE}
1619 attribute.
1621 @node Extensions to namelist
1622 @subsection Extensions to namelist
1623 @cindex Namelist
1625 GNU Fortran fully supports the Fortran 95 standard for namelist I/O
1626 including array qualifiers, substrings and fully qualified derived types.
1627 The output from a namelist write is compatible with namelist read.  The
1628 output has all names in upper case and indentation to column 1 after the
1629 namelist name.  Two extensions are permitted:
1631 Old-style use of @samp{$} instead of @samp{&}
1632 @smallexample
1633 $MYNML
1634  X(:)%Y(2) = 1.0 2.0 3.0
1635  CH(1:4) = "abcd"
1636 $END
1637 @end smallexample
1639 It should be noted that the default terminator is @samp{/} rather than
1640 @samp{&END}.
1642 Querying of the namelist when inputting from stdin.  After at least
1643 one space, entering @samp{?} sends to stdout the namelist name and the names of
1644 the variables in the namelist:
1645 @smallexample
1648 &mynml
1650  x%y
1651  ch
1652 &end
1653 @end smallexample
1655 Entering @samp{=?} outputs the namelist to stdout, as if
1656 @code{WRITE(*,NML = mynml)} had been called:
1657 @smallexample
1660 &MYNML
1661  X(1)%Y=  0.000000    ,  1.000000    ,  0.000000    ,
1662  X(2)%Y=  0.000000    ,  2.000000    ,  0.000000    ,
1663  X(3)%Y=  0.000000    ,  3.000000    ,  0.000000    ,
1664  CH=abcd,  /
1665 @end smallexample
1667 To aid this dialog, when input is from stdin, errors send their
1668 messages to stderr and execution continues, even if @code{IOSTAT} is set.
1670 @code{PRINT} namelist is permitted.  This causes an error if
1671 @option{-std=f95} is used.
1672 @smallexample
1673 PROGRAM test_print
1674   REAL, dimension (4)  ::  x = (/1.0, 2.0, 3.0, 4.0/)
1675   NAMELIST /mynml/ x
1676   PRINT mynml
1677 END PROGRAM test_print
1678 @end smallexample
1680 Expanded namelist reads are permitted.  This causes an error if 
1681 @option{-std=f95} is used.  In the following example, the first element
1682 of the array will be given the value 0.00 and the two succeeding
1683 elements will be given the values 1.00 and 2.00.
1684 @smallexample
1685 &MYNML
1686   X(1,1) = 0.00 , 1.00 , 2.00
1688 @end smallexample
1690 When writing a namelist, if no @code{DELIM=} is specified, by default a
1691 double quote is used to delimit character strings. If -std=F95, F2003,
1692 or F2008, etc, the delim status is set to 'none'.  Defaulting to
1693 quotes ensures that namelists with character strings can be subsequently
1694 read back in accurately.
1696 @node X format descriptor without count field
1697 @subsection @code{X} format descriptor without count field
1699 To support legacy codes, GNU Fortran permits the count field of the
1700 @code{X} edit descriptor in @code{FORMAT} statements to be omitted.
1701 When omitted, the count is implicitly assumed to be one.
1703 @smallexample
1704        PRINT 10, 2, 3
1705 10     FORMAT (I1, X, I1)
1706 @end smallexample
1708 @node Commas in FORMAT specifications
1709 @subsection Commas in @code{FORMAT} specifications
1711 To support legacy codes, GNU Fortran allows the comma separator
1712 to be omitted immediately before and after character string edit
1713 descriptors in @code{FORMAT} statements.
1715 @smallexample
1716        PRINT 10, 2, 3
1717 10     FORMAT ('FOO='I1' BAR='I2)
1718 @end smallexample
1721 @node Missing period in FORMAT specifications
1722 @subsection Missing period in @code{FORMAT} specifications
1724 To support legacy codes, GNU Fortran allows missing periods in format
1725 specifications if and only if @option{-std=legacy} is given on the
1726 command line.  This is considered non-conforming code and is
1727 discouraged.
1729 @smallexample
1730        REAL :: value
1731        READ(*,10) value
1732 10     FORMAT ('F4')
1733 @end smallexample
1735 @node I/O item lists
1736 @subsection I/O item lists
1737 @cindex I/O item lists
1739 To support legacy codes, GNU Fortran allows the input item list
1740 of the @code{READ} statement, and the output item lists of the
1741 @code{WRITE} and @code{PRINT} statements, to start with a comma.
1743 @node @code{Q} exponent-letter
1744 @subsection @code{Q} exponent-letter
1745 @cindex @code{Q} exponent-letter
1747 GNU Fortran accepts real literal constants with an exponent-letter
1748 of @code{Q}, for example, @code{1.23Q45}.  The constant is interpreted
1749 as a @code{REAL(16)} entity on targets that support this type.  If
1750 the target does not support @code{REAL(16)} but has a @code{REAL(10)}
1751 type, then the real-literal-constant will be interpreted as a
1752 @code{REAL(10)} entity.  In the absence of @code{REAL(16)} and
1753 @code{REAL(10)}, an error will occur.
1755 @node BOZ literal constants
1756 @subsection BOZ literal constants
1757 @cindex BOZ literal constants
1759 Besides decimal constants, Fortran also supports binary (@code{b}),
1760 octal (@code{o}) and hexadecimal (@code{z}) integer constants.  The
1761 syntax is: @samp{prefix quote digits quote}, were the prefix is
1762 either @code{b}, @code{o} or @code{z}, quote is either @code{'} or
1763 @code{"} and the digits are for binary @code{0} or @code{1}, for
1764 octal between @code{0} and @code{7}, and for hexadecimal between
1765 @code{0} and @code{F}.  (Example: @code{b'01011101'}.)
1767 Up to Fortran 95, BOZ literals were only allowed to initialize
1768 integer variables in DATA statements.  Since Fortran 2003 BOZ literals
1769 are also allowed as argument of @code{REAL}, @code{DBLE}, @code{INT}
1770 and @code{CMPLX}; the result is the same as if the integer BOZ
1771 literal had been converted by @code{TRANSFER} to, respectively,
1772 @code{real}, @code{double precision}, @code{integer} or @code{complex}.
1773 As GNU Fortran extension the intrinsic procedures @code{FLOAT},
1774 @code{DFLOAT}, @code{COMPLEX} and @code{DCMPLX} are treated alike.
1776 As an extension, GNU Fortran allows hexadecimal BOZ literal constants to
1777 be specified using the @code{X} prefix, in addition to the standard
1778 @code{Z} prefix.  The BOZ literal can also be specified by adding a
1779 suffix to the string, for example, @code{Z'ABC'} and @code{'ABC'Z} are
1780 equivalent.
1782 Furthermore, GNU Fortran allows using BOZ literal constants outside
1783 DATA statements and the four intrinsic functions allowed by Fortran 2003.
1784 In DATA statements, in direct assignments, where the right-hand side
1785 only contains a BOZ literal constant, and for old-style initializers of
1786 the form @code{integer i /o'0173'/}, the constant is transferred
1787 as if @code{TRANSFER} had been used; for @code{COMPLEX} numbers, only
1788 the real part is initialized unless @code{CMPLX} is used.  In all other
1789 cases, the BOZ literal constant is converted to an @code{INTEGER} value with
1790 the largest decimal representation.  This value is then converted
1791 numerically to the type and kind of the variable in question.
1792 (For instance, @code{real :: r = b'0000001' + 1} initializes @code{r}
1793 with @code{2.0}.) As different compilers implement the extension
1794 differently, one should be careful when doing bitwise initialization
1795 of non-integer variables.
1797 Note that initializing an @code{INTEGER} variable with a statement such
1798 as @code{DATA i/Z'FFFFFFFF'/} will give an integer overflow error rather
1799 than the desired result of @math{-1} when @code{i} is a 32-bit integer
1800 on a system that supports 64-bit integers.  The @samp{-fno-range-check}
1801 option can be used as a workaround for legacy code that initializes
1802 integers in this manner.
1804 @node Real array indices
1805 @subsection Real array indices
1806 @cindex array, indices of type real
1808 As an extension, GNU Fortran allows the use of @code{REAL} expressions
1809 or variables as array indices.
1811 @node Unary operators
1812 @subsection Unary operators
1813 @cindex operators, unary
1815 As an extension, GNU Fortran allows unary plus and unary minus operators
1816 to appear as the second operand of binary arithmetic operators without
1817 the need for parenthesis.
1819 @smallexample
1820        X = Y * -Z
1821 @end smallexample
1823 @node Implicitly convert LOGICAL and INTEGER values
1824 @subsection Implicitly convert @code{LOGICAL} and @code{INTEGER} values
1825 @cindex conversion, to integer
1826 @cindex conversion, to logical
1828 As an extension for backwards compatibility with other compilers, GNU
1829 Fortran allows the implicit conversion of @code{LOGICAL} values to
1830 @code{INTEGER} values and vice versa.  When converting from a
1831 @code{LOGICAL} to an @code{INTEGER}, @code{.FALSE.} is interpreted as
1832 zero, and @code{.TRUE.} is interpreted as one.  When converting from
1833 @code{INTEGER} to @code{LOGICAL}, the value zero is interpreted as
1834 @code{.FALSE.} and any nonzero value is interpreted as @code{.TRUE.}.
1836 @smallexample
1837         LOGICAL :: l
1838         l = 1
1839 @end smallexample
1840 @smallexample
1841         INTEGER :: i
1842         i = .TRUE.
1843 @end smallexample
1845 However, there is no implicit conversion of @code{INTEGER} values in
1846 @code{if}-statements, nor of @code{LOGICAL} or @code{INTEGER} values
1847 in I/O operations.
1849 @node Hollerith constants support
1850 @subsection Hollerith constants support
1851 @cindex Hollerith constants
1853 GNU Fortran supports Hollerith constants in assignments, function
1854 arguments, and @code{DATA} and @code{ASSIGN} statements.  A Hollerith
1855 constant is written as a string of characters preceded by an integer
1856 constant indicating the character count, and the letter @code{H} or
1857 @code{h}, and stored in bytewise fashion in a numeric (@code{INTEGER},
1858 @code{REAL}, or @code{complex}) or @code{LOGICAL} variable.  The
1859 constant will be padded or truncated to fit the size of the variable in
1860 which it is stored.
1862 Examples of valid uses of Hollerith constants:
1863 @smallexample
1864       complex*16 x(2)
1865       data x /16Habcdefghijklmnop, 16Hqrstuvwxyz012345/
1866       x(1) = 16HABCDEFGHIJKLMNOP
1867       call foo (4h abc)
1868 @end smallexample
1870 Invalid Hollerith constants examples:
1871 @smallexample
1872       integer*4 a
1873       a = 8H12345678 ! Valid, but the Hollerith constant will be truncated.
1874       a = 0H         ! At least one character is needed.
1875 @end smallexample
1877 In general, Hollerith constants were used to provide a rudimentary
1878 facility for handling character strings in early Fortran compilers,
1879 prior to the introduction of @code{CHARACTER} variables in Fortran 77;
1880 in those cases, the standard-compliant equivalent is to convert the
1881 program to use proper character strings.  On occasion, there may be a
1882 case where the intent is specifically to initialize a numeric variable
1883 with a given byte sequence.  In these cases, the same result can be
1884 obtained by using the @code{TRANSFER} statement, as in this example.
1885 @smallexample
1886       INTEGER(KIND=4) :: a
1887       a = TRANSFER ("abcd", a)     ! equivalent to: a = 4Habcd
1888 @end smallexample
1891 @node Cray pointers
1892 @subsection Cray pointers
1893 @cindex pointer, Cray
1895 Cray pointers are part of a non-standard extension that provides a
1896 C-like pointer in Fortran.  This is accomplished through a pair of
1897 variables: an integer "pointer" that holds a memory address, and a
1898 "pointee" that is used to dereference the pointer.
1900 Pointer/pointee pairs are declared in statements of the form:
1901 @smallexample
1902         pointer ( <pointer> , <pointee> )
1903 @end smallexample
1905 @smallexample
1906         pointer ( <pointer1> , <pointee1> ), ( <pointer2> , <pointee2> ), ...
1907 @end smallexample
1908 The pointer is an integer that is intended to hold a memory address.
1909 The pointee may be an array or scalar.  A pointee can be an assumed
1910 size array---that is, the last dimension may be left unspecified by
1911 using a @code{*} in place of a value---but a pointee cannot be an
1912 assumed shape array.  No space is allocated for the pointee.
1914 The pointee may have its type declared before or after the pointer
1915 statement, and its array specification (if any) may be declared
1916 before, during, or after the pointer statement.  The pointer may be
1917 declared as an integer prior to the pointer statement.  However, some
1918 machines have default integer sizes that are different than the size
1919 of a pointer, and so the following code is not portable:
1920 @smallexample
1921         integer ipt
1922         pointer (ipt, iarr)
1923 @end smallexample
1924 If a pointer is declared with a kind that is too small, the compiler
1925 will issue a warning; the resulting binary will probably not work
1926 correctly, because the memory addresses stored in the pointers may be
1927 truncated.  It is safer to omit the first line of the above example;
1928 if explicit declaration of ipt's type is omitted, then the compiler
1929 will ensure that ipt is an integer variable large enough to hold a
1930 pointer.
1932 Pointer arithmetic is valid with Cray pointers, but it is not the same
1933 as C pointer arithmetic.  Cray pointers are just ordinary integers, so
1934 the user is responsible for determining how many bytes to add to a
1935 pointer in order to increment it.  Consider the following example:
1936 @smallexample
1937         real target(10)
1938         real pointee(10)
1939         pointer (ipt, pointee)
1940         ipt = loc (target)
1941         ipt = ipt + 1       
1942 @end smallexample
1943 The last statement does not set @code{ipt} to the address of
1944 @code{target(1)}, as it would in C pointer arithmetic.  Adding @code{1}
1945 to @code{ipt} just adds one byte to the address stored in @code{ipt}.
1947 Any expression involving the pointee will be translated to use the
1948 value stored in the pointer as the base address.
1950 To get the address of elements, this extension provides an intrinsic
1951 function @code{LOC()}.  The @code{LOC()} function is equivalent to the
1952 @code{&} operator in C, except the address is cast to an integer type:
1953 @smallexample
1954         real ar(10)
1955         pointer(ipt, arpte(10))
1956         real arpte
1957         ipt = loc(ar)  ! Makes arpte is an alias for ar
1958         arpte(1) = 1.0 ! Sets ar(1) to 1.0
1959 @end smallexample
1960 The pointer can also be set by a call to the @code{MALLOC} intrinsic
1961 (see @ref{MALLOC}).
1963 Cray pointees often are used to alias an existing variable.  For
1964 example:
1965 @smallexample
1966         integer target(10)
1967         integer iarr(10)
1968         pointer (ipt, iarr)
1969         ipt = loc(target)
1970 @end smallexample
1971 As long as @code{ipt} remains unchanged, @code{iarr} is now an alias for
1972 @code{target}.  The optimizer, however, will not detect this aliasing, so
1973 it is unsafe to use @code{iarr} and @code{target} simultaneously.  Using
1974 a pointee in any way that violates the Fortran aliasing rules or
1975 assumptions is illegal.  It is the user's responsibility to avoid doing
1976 this; the compiler works under the assumption that no such aliasing
1977 occurs.
1979 Cray pointers will work correctly when there is no aliasing (i.e., when
1980 they are used to access a dynamically allocated block of memory), and
1981 also in any routine where a pointee is used, but any variable with which
1982 it shares storage is not used.  Code that violates these rules may not
1983 run as the user intends.  This is not a bug in the optimizer; any code
1984 that violates the aliasing rules is illegal.  (Note that this is not
1985 unique to GNU Fortran; any Fortran compiler that supports Cray pointers
1986 will ``incorrectly'' optimize code with illegal aliasing.)
1988 There are a number of restrictions on the attributes that can be applied
1989 to Cray pointers and pointees.  Pointees may not have the
1990 @code{ALLOCATABLE}, @code{INTENT}, @code{OPTIONAL}, @code{DUMMY},
1991 @code{TARGET}, @code{INTRINSIC}, or @code{POINTER} attributes.  Pointers
1992 may not have the @code{DIMENSION}, @code{POINTER}, @code{TARGET},
1993 @code{ALLOCATABLE}, @code{EXTERNAL}, or @code{INTRINSIC} attributes, nor
1994 may they be function results.  Pointees may not occur in more than one
1995 pointer statement.  A pointee cannot be a pointer.  Pointees cannot occur
1996 in equivalence, common, or data statements.
1998 A Cray pointer may also point to a function or a subroutine.  For
1999 example, the following excerpt is valid:
2000 @smallexample
2001   implicit none
2002   external sub
2003   pointer (subptr,subpte)
2004   external subpte
2005   subptr = loc(sub)
2006   call subpte()
2007   [...]
2008   subroutine sub
2009   [...]
2010   end subroutine sub
2011 @end smallexample
2013 A pointer may be modified during the course of a program, and this
2014 will change the location to which the pointee refers.  However, when
2015 pointees are passed as arguments, they are treated as ordinary
2016 variables in the invoked function.  Subsequent changes to the pointer
2017 will not change the base address of the array that was passed.
2019 @node CONVERT specifier
2020 @subsection @code{CONVERT} specifier
2021 @cindex @code{CONVERT} specifier
2023 GNU Fortran allows the conversion of unformatted data between little-
2024 and big-endian representation to facilitate moving of data
2025 between different systems.  The conversion can be indicated with
2026 the @code{CONVERT} specifier on the @code{OPEN} statement.
2027 @xref{GFORTRAN_CONVERT_UNIT}, for an alternative way of specifying
2028 the data format via an environment variable.
2030 Valid values for @code{CONVERT} are:
2031 @itemize @w{}
2032 @item @code{CONVERT='NATIVE'} Use the native format.  This is the default.
2033 @item @code{CONVERT='SWAP'} Swap between little- and big-endian.
2034 @item @code{CONVERT='LITTLE_ENDIAN'} Use the little-endian representation
2035 for unformatted files.
2036 @item @code{CONVERT='BIG_ENDIAN'} Use the big-endian representation for
2037 unformatted files.
2038 @end itemize
2040 Using the option could look like this:
2041 @smallexample
2042   open(file='big.dat',form='unformatted',access='sequential', &
2043        convert='big_endian')
2044 @end smallexample
2046 The value of the conversion can be queried by using
2047 @code{INQUIRE(CONVERT=ch)}.  The values returned are
2048 @code{'BIG_ENDIAN'} and @code{'LITTLE_ENDIAN'}.
2050 @code{CONVERT} works between big- and little-endian for
2051 @code{INTEGER} values of all supported kinds and for @code{REAL}
2052 on IEEE systems of kinds 4 and 8.  Conversion between different
2053 ``extended double'' types on different architectures such as
2054 m68k and x86_64, which GNU Fortran
2055 supports as @code{REAL(KIND=10)} and @code{REAL(KIND=16)}, will
2056 probably not work.
2058 @emph{Note that the values specified via the GFORTRAN_CONVERT_UNIT
2059 environment variable will override the CONVERT specifier in the
2060 open statement}.  This is to give control over data formats to
2061 users who do not have the source code of their program available.
2063 Using anything but the native representation for unformatted data
2064 carries a significant speed overhead.  If speed in this area matters
2065 to you, it is best if you use this only for data that needs to be
2066 portable.
2068 @node OpenMP
2069 @subsection OpenMP
2070 @cindex OpenMP
2072 OpenMP (Open Multi-Processing) is an application programming
2073 interface (API) that supports multi-platform shared memory 
2074 multiprocessing programming in C/C++ and Fortran on many 
2075 architectures, including Unix and Microsoft Windows platforms.
2076 It consists of a set of compiler directives, library routines,
2077 and environment variables that influence run-time behavior.
2079 GNU Fortran strives to be compatible to the 
2080 @uref{http://openmp.org/wp/openmp-specifications/,
2081 OpenMP Application Program Interface v4.5}.
2083 To enable the processing of the OpenMP directive @code{!$omp} in
2084 free-form source code; the @code{c$omp}, @code{*$omp} and @code{!$omp}
2085 directives in fixed form; the @code{!$} conditional compilation sentinels
2086 in free form; and the @code{c$}, @code{*$} and @code{!$} sentinels
2087 in fixed form, @command{gfortran} needs to be invoked with the
2088 @option{-fopenmp}.  This also arranges for automatic linking of the
2089 GNU Offloading and Multi Processing Runtime Library
2090 @ref{Top,,libgomp,libgomp,GNU Offloading and Multi Processing Runtime
2091 Library}.
2093 The OpenMP Fortran runtime library routines are provided both in a
2094 form of a Fortran 90 module named @code{omp_lib} and in a form of
2095 a Fortran @code{include} file named @file{omp_lib.h}.
2097 An example of a parallelized loop taken from Appendix A.1 of
2098 the OpenMP Application Program Interface v2.5:
2099 @smallexample
2100 SUBROUTINE A1(N, A, B)
2101   INTEGER I, N
2102   REAL B(N), A(N)
2103 !$OMP PARALLEL DO !I is private by default
2104   DO I=2,N
2105     B(I) = (A(I) + A(I-1)) / 2.0
2106   ENDDO
2107 !$OMP END PARALLEL DO
2108 END SUBROUTINE A1
2109 @end smallexample
2111 Please note:
2112 @itemize
2113 @item
2114 @option{-fopenmp} implies @option{-frecursive}, i.e., all local arrays
2115 will be allocated on the stack.  When porting existing code to OpenMP,
2116 this may lead to surprising results, especially to segmentation faults
2117 if the stacksize is limited.
2119 @item
2120 On glibc-based systems, OpenMP enabled applications cannot be statically
2121 linked due to limitations of the underlying pthreads-implementation.  It
2122 might be possible to get a working solution if 
2123 @command{-Wl,--whole-archive -lpthread -Wl,--no-whole-archive} is added
2124 to the command line.  However, this is not supported by @command{gcc} and
2125 thus not recommended.
2126 @end itemize
2128 @node OpenACC
2129 @subsection OpenACC
2130 @cindex OpenACC
2132 OpenACC is an application programming interface (API) that supports
2133 offloading of code to accelerator devices.  It consists of a set of
2134 compiler directives, library routines, and environment variables that
2135 influence run-time behavior.
2137 GNU Fortran strives to be compatible to the
2138 @uref{http://www.openacc.org/, OpenACC Application Programming
2139 Interface v2.0}.
2141 To enable the processing of the OpenACC directive @code{!$acc} in
2142 free-form source code; the @code{c$acc}, @code{*$acc} and @code{!$acc}
2143 directives in fixed form; the @code{!$} conditional compilation
2144 sentinels in free form; and the @code{c$}, @code{*$} and @code{!$}
2145 sentinels in fixed form, @command{gfortran} needs to be invoked with
2146 the @option{-fopenacc}.  This also arranges for automatic linking of
2147 the GNU Offloading and Multi Processing Runtime Library
2148 @ref{Top,,libgomp,libgomp,GNU Offloading and Multi Processing Runtime
2149 Library}.
2151 The OpenACC Fortran runtime library routines are provided both in a
2152 form of a Fortran 90 module named @code{openacc} and in a form of a
2153 Fortran @code{include} file named @file{openacc_lib.h}.
2155 Note that this is an experimental feature, incomplete, and subject to
2156 change in future versions of GCC.  See
2157 @uref{https://gcc.gnu.org/wiki/OpenACC} for more information.
2159 @node Argument list functions
2160 @subsection Argument list functions @code{%VAL}, @code{%REF} and @code{%LOC}
2161 @cindex argument list functions
2162 @cindex @code{%VAL}
2163 @cindex @code{%REF}
2164 @cindex @code{%LOC}
2166 GNU Fortran supports argument list functions @code{%VAL}, @code{%REF} 
2167 and @code{%LOC} statements, for backward compatibility with g77. 
2168 It is recommended that these should be used only for code that is 
2169 accessing facilities outside of GNU Fortran, such as operating system 
2170 or windowing facilities.  It is best to constrain such uses to isolated 
2171 portions of a program--portions that deal specifically and exclusively 
2172 with low-level, system-dependent facilities.  Such portions might well 
2173 provide a portable interface for use by the program as a whole, but are 
2174 themselves not portable, and should be thoroughly tested each time they 
2175 are rebuilt using a new compiler or version of a compiler.
2177 @code{%VAL} passes a scalar argument by value, @code{%REF} passes it by 
2178 reference and @code{%LOC} passes its memory location.  Since gfortran 
2179 already passes scalar arguments by reference, @code{%REF} is in effect 
2180 a do-nothing.  @code{%LOC} has the same effect as a Fortran pointer.
2182 An example of passing an argument by value to a C subroutine foo.:
2183 @smallexample
2185 C prototype      void foo_ (float x);
2187       external foo
2188       real*4 x
2189       x = 3.14159
2190       call foo (%VAL (x))
2191       end
2192 @end smallexample
2194 For details refer to the g77 manual
2195 @uref{https://gcc.gnu.org/@/onlinedocs/@/gcc-3.4.6/@/g77/@/index.html#Top}.
2197 Also, @code{c_by_val.f} and its partner @code{c_by_val.c} of the
2198 GNU Fortran testsuite are worth a look.
2200 @node Read/Write after EOF marker
2201 @subsection Read/Write after EOF marker
2202 @cindex @code{EOF}
2203 @cindex @code{BACKSPACE}
2204 @cindex @code{REWIND}
2206 Some legacy codes rely on allowing @code{READ} or @code{WRITE} after the
2207 EOF file marker in order to find the end of a file. GNU Fortran normally
2208 rejects these codes with a run-time error message and suggests the user
2209 consider @code{BACKSPACE} or @code{REWIND} to properly position
2210 the file before the EOF marker.  As an extension, the run-time error may
2211 be disabled using -std=legacy.
2214 @node STRUCTURE and RECORD
2215 @subsection @code{STRUCTURE} and @code{RECORD}
2216 @cindex @code{STRUCTURE}
2217 @cindex @code{RECORD}
2219 Record structures are a pre-Fortran-90 vendor extension to create
2220 user-defined aggregate data types.  Support for record structures in GNU
2221 Fortran can be enabled with the @option{-fdec-structure} compile flag.
2222 If you have a choice, you should instead use Fortran 90's ``derived types'',
2223 which have a different syntax.
2225 In many cases, record structures can easily be converted to derived types.
2226 To convert, replace @code{STRUCTURE /}@var{structure-name}@code{/}
2227 by @code{TYPE} @var{type-name}.  Additionally, replace
2228 @code{RECORD /}@var{structure-name}@code{/} by
2229 @code{TYPE(}@var{type-name}@code{)}. Finally, in the component access,
2230 replace the period (@code{.}) by the percent sign (@code{%}).
2232 Here is an example of code using the non portable record structure syntax:
2234 @example
2235 ! Declaring a structure named ``item'' and containing three fields:
2236 ! an integer ID, an description string and a floating-point price.
2237 STRUCTURE /item/
2238   INTEGER id
2239   CHARACTER(LEN=200) description
2240   REAL price
2241 END STRUCTURE
2243 ! Define two variables, an single record of type ``item''
2244 ! named ``pear'', and an array of items named ``store_catalog''
2245 RECORD /item/ pear, store_catalog(100)
2247 ! We can directly access the fields of both variables
2248 pear.id = 92316
2249 pear.description = "juicy D'Anjou pear"
2250 pear.price = 0.15
2251 store_catalog(7).id = 7831
2252 store_catalog(7).description = "milk bottle"
2253 store_catalog(7).price = 1.2
2255 ! We can also manipulate the whole structure
2256 store_catalog(12) = pear
2257 print *, store_catalog(12)
2258 @end example
2260 @noindent
2261 This code can easily be rewritten in the Fortran 90 syntax as following:
2263 @example
2264 ! ``STRUCTURE /name/ ... END STRUCTURE'' becomes
2265 ! ``TYPE name ... END TYPE''
2266 TYPE item
2267   INTEGER id
2268   CHARACTER(LEN=200) description
2269   REAL price
2270 END TYPE
2272 ! ``RECORD /name/ variable'' becomes ``TYPE(name) variable''
2273 TYPE(item) pear, store_catalog(100)
2275 ! Instead of using a dot (.) to access fields of a record, the
2276 ! standard syntax uses a percent sign (%)
2277 pear%id = 92316
2278 pear%description = "juicy D'Anjou pear"
2279 pear%price = 0.15
2280 store_catalog(7)%id = 7831
2281 store_catalog(7)%description = "milk bottle"
2282 store_catalog(7)%price = 1.2
2284 ! Assignments of a whole variable do not change
2285 store_catalog(12) = pear
2286 print *, store_catalog(12)
2287 @end example
2289 @noindent
2290 GNU Fortran implements STRUCTURES like derived types with the following
2291 rules and exceptions:
2293 @itemize @bullet
2294 @item Structures act like derived types with the @code{SEQUENCE} attribute.
2295 Otherwise they may contain no specifiers.
2297 @item Structures may contain a special field with the name @code{%FILL}.
2298 This will create an anonymous component which cannot be accessed but occupies
2299 space just as if a component of the same type was declared in its place, useful
2300 for alignment purposes.  As an example, the following structure will consist
2301 of at least sixteen bytes:
2303 @smallexample
2304 structure /padded/
2305   character(4) start
2306   character(8) %FILL
2307   character(4) end
2308 end structure
2309 @end smallexample
2311 @item Structures may share names with other symbols. For example, the following
2312 is invalid for derived types, but valid for structures:
2314 @smallexample
2315 structure /header/
2316   ! ...
2317 end structure
2318 record /header/ header
2319 @end smallexample
2321 @item Structure types may be declared nested within another parent structure.
2322 The syntax is:
2323 @smallexample
2324 structure /type-name/
2325     ...
2326     structure [/<type-name>/] <field-list>
2328 @end smallexample
2330 The type name may be ommitted, in which case the structure type itself is
2331 anonymous, and other structures of the same type cannot be instantiated. The
2332 following shows some examples:
2334 @example
2335 structure /appointment/
2336   ! nested structure definition: app_time is an array of two 'time'
2337   structure /time/ app_time (2) 
2338     integer(1) hour, minute
2339   end structure
2340   character(10) memo
2341 end structure
2343 ! The 'time' structure is still usable
2344 record /time/ now
2345 now = time(5, 30)
2349 structure /appointment/
2350   ! anonymous nested structure definition
2351   structure start, end
2352     integer(1) hour, minute
2353   end structure
2354   character(10) memo
2355 end structure
2356 @end example
2358 @item Structures may contain @code{UNION} blocks. For more detail see the
2359 section on @ref{UNION and MAP}.
2361 @item Structures support old-style initialization of components, like
2362 those described in @ref{Old-style variable initialization}. For array
2363 initializers, an initializer may contain a repeat specification of the form
2364 @code{<literal-integer> * <constant-initializer>}. The value of the integer
2365 indicates the number of times to repeat the constant initializer when expanding
2366 the initializer list.
2367 @end itemize
2369 @node UNION and MAP
2370 @subsection @code{UNION} and @code{MAP}
2371 @cindex @code{UNION}
2372 @cindex @code{MAP}
2374 Unions are an old vendor extension which were commonly used with the
2375 non-standard @ref{STRUCTURE and RECORD} extensions. Use of @code{UNION} and
2376 @code{MAP} is automatically enabled with @option{-fdec-structure}.
2378 A @code{UNION} declaration occurs within a structure; within the definition of
2379 each union is a number of @code{MAP} blocks. Each @code{MAP} shares storage
2380 with its sibling maps (in the same union), and the size of the union is the
2381 size of the largest map within it, just as with unions in C. The major
2382 difference is that component references do not indicate which union or map the
2383 component is in (the compiler gets to figure that out).
2385 Here is a small example:
2386 @smallexample
2387 structure /myunion/
2388 union
2389   map
2390     character(2) w0, w1, w2
2391   end map
2392   map
2393     character(6) long
2394   end map
2395 end union
2396 end structure
2398 record /myunion/ rec
2399 ! After this assignment...
2400 rec.long = 'hello!'
2402 ! The following is true:
2403 ! rec.w0 === 'he'
2404 ! rec.w1 === 'll'
2405 ! rec.w2 === 'o!'
2406 @end smallexample
2408 The two maps share memory, and the size of the union is ultimately six bytes:
2410 @example
2411 0    1    2    3    4   5   6     Byte offset
2412 -------------------------------
2413 |    |    |    |    |    |    |
2414 -------------------------------
2416 ^    W0   ^    W1   ^    W2   ^
2417  \-------/ \-------/ \-------/
2419 ^             LONG            ^
2420  \---------------------------/
2421 @end example
2423 Following is an example mirroring the layout of an Intel x86_64 register:
2425 @example
2426 structure /reg/
2427   union ! U0                ! rax
2428     map
2429       character(16) rx
2430     end map
2431     map
2432       character(8) rh         ! rah
2433       union ! U1
2434         map
2435           character(8) rl     ! ral
2436         end map
2437         map
2438           character(8) ex     ! eax
2439         end map
2440         map
2441           character(4) eh     ! eah
2442           union ! U2
2443             map
2444               character(4) el ! eal
2445             end map
2446             map
2447               character(4) x  ! ax
2448             end map
2449             map
2450               character(2) h  ! ah
2451               character(2) l  ! al
2452             end map
2453           end union
2454         end map
2455       end union
2456     end map
2457   end union
2458 end structure
2459 record /reg/ a
2461 ! After this assignment...
2462 a.rx     =     'AAAAAAAA.BBB.C.D'
2464 ! The following is true:
2465 a.rx === 'AAAAAAAA.BBB.C.D'
2466 a.rh === 'AAAAAAAA'
2467 a.rl ===         '.BBB.C.D'
2468 a.ex ===         '.BBB.C.D'
2469 a.eh ===         '.BBB'
2470 a.el ===             '.C.D'
2471 a.x  ===             '.C.D'
2472 a.h  ===             '.C'
2473 a.l  ===               '.D'
2474 @end example
2476 @node Type variants for integer intrinsics
2477 @subsection Type variants for integer intrinsics
2478 @cindex intrinsics, integer
2480 Similar to the D/C prefixes to real functions to specify the input/output
2481 types, GNU Fortran offers B/I/J/K prefixes to integer functions for
2482 compatibility with DEC programs. The types implied by each are:
2484 @example
2485 @code{B} - @code{INTEGER(kind=1)}
2486 @code{I} - @code{INTEGER(kind=2)}
2487 @code{J} - @code{INTEGER(kind=4)}
2488 @code{K} - @code{INTEGER(kind=8)}
2489 @end example
2491 GNU Fortran supports these with the flag @option{-fdec-intrinsic-ints}.
2492 Intrinsics for which prefixed versions are available and in what form are noted
2493 in @ref{Intrinsic Procedures}. The complete list of supported intrinsics is
2494 here:
2496 @multitable @columnfractions .2 .2 .2 .2 .2
2498 @headitem Intrinsic @tab B @tab I @tab J @tab K
2500 @item @code{@ref{ABS}}
2501   @tab @code{BABS} @tab @code{IIABS} @tab @code{JIABS} @tab @code{KIABS}
2502 @item @code{@ref{BTEST}}
2503   @tab @code{BBTEST} @tab @code{BITEST} @tab @code{BJTEST} @tab @code{BKTEST}
2504 @item @code{@ref{IAND}}
2505   @tab @code{BIAND} @tab @code{IIAND} @tab @code{JIAND} @tab @code{KIAND}
2506 @item @code{@ref{IBCLR}}
2507   @tab @code{BBCLR} @tab @code{IIBCLR} @tab @code{JIBCLR} @tab @code{KIBCLR}
2508 @item @code{@ref{IBITS}}
2509   @tab @code{BBITS} @tab @code{IIBITS} @tab @code{JIBITS} @tab @code{KIBITS}
2510 @item @code{@ref{IBSET}}
2511   @tab @code{BBSET} @tab @code{IIBSET} @tab @code{JIBSET} @tab @code{KIBSET}
2512 @item @code{@ref{IEOR}}
2513   @tab @code{BIEOR} @tab @code{IIEOR} @tab @code{JIEOR} @tab @code{KIEOR}
2514 @item @code{@ref{IOR}}
2515   @tab @code{BIOR} @tab @code{IIOR} @tab @code{JIOR} @tab @code{KIOR}
2516 @item @code{@ref{ISHFT}}
2517   @tab @code{BSHFT} @tab @code{IISHFT} @tab @code{JISHFT} @tab @code{KISHFT}
2518 @item @code{@ref{ISHFTC}}
2519   @tab @code{BSHFTC} @tab @code{IISHFTC} @tab @code{JISHFTC} @tab @code{KISHFTC}
2520 @item @code{@ref{MOD}}
2521   @tab @code{BMOD} @tab @code{IMOD} @tab @code{JMOD} @tab @code{KMOD}
2522 @item @code{@ref{NOT}}
2523   @tab @code{BNOT} @tab @code{INOT} @tab @code{JNOT} @tab @code{KNOT}
2524 @item @code{@ref{REAL}}
2525   @tab @code{--} @tab @code{FLOATI} @tab @code{FLOATJ} @tab @code{FLOATK}
2526 @end multitable
2528 @node AUTOMATIC and STATIC attributes
2529 @subsection @code{AUTOMATIC} and @code{STATIC} attributes
2530 @cindex variable attributes
2531 @cindex @code{AUTOMATIC}
2532 @cindex @code{STATIC}
2534 With @option{-fdec-static} GNU Fortran supports the DEC extended attributes
2535 @code{STATIC} and @code{AUTOMATIC} to provide explicit specification of entity
2536 storage.  These follow the syntax of the Fortran standard @code{SAVE} attribute.
2538 @code{STATIC} is exactly equivalent to @code{SAVE}, and specifies that
2539 an entity should be allocated in static memory.  As an example, @code{STATIC}
2540 local variables will retain their values across multiple calls to a function.
2542 Entities marked @code{AUTOMATIC} will be stack automatic whenever possible.
2543 @code{AUTOMATIC} is the default for local variables smaller than
2544 @option{-fmax-stack-var-size}, unless @option{-fno-automatic} is given.  This
2545 attribute overrides @option{-fno-automatic}, @option{-fmax-stack-var-size}, and
2546 blanket @code{SAVE} statements.
2549 Examples:
2551 @example
2552 subroutine f
2553   integer, automatic :: i  ! automatic variable
2554   integer x, y             ! static variables
2555   save
2556   ...
2557 endsubroutine
2558 @end example
2559 @example
2560 subroutine f
2561   integer a, b, c, x, y, z
2562   static :: x
2563   save y
2564   automatic z, c
2565   ! a, b, c, and z are automatic
2566   ! x and y are static
2567 endsubroutine
2568 @end example
2569 @example
2570 ! Compiled with -fno-automatic
2571 subroutine f
2572   integer a, b, c, d
2573   automatic :: a
2574   ! a is automatic; b, c, and d are static
2575 endsubroutine
2576 @end example
2578 @node Extended math intrinsics
2579 @subsection Extended math intrinsics
2580 @cindex intrinsics, math
2581 @cindex intrinsics, trigonometric functions
2583 GNU Fortran supports an extended list of mathematical intrinsics with the
2584 compile flag @option{-fdec-math} for compatability with legacy code.
2585 These intrinsics are described fully in @ref{Intrinsic Procedures} where it is
2586 noted that they are extensions and should be avoided whenever possible.
2588 Specifically, @option{-fdec-math} enables the @ref{COTAN} intrinsic, and
2589 trigonometric intrinsics which accept or produce values in degrees instead of
2590 radians.  Here is a summary of the new intrinsics:
2592 @multitable @columnfractions .5 .5
2593 @headitem Radians @tab Degrees
2594 @item @code{@ref{ACOS}}   @tab @code{@ref{ACOSD}}*
2595 @item @code{@ref{ASIN}}   @tab @code{@ref{ASIND}}*
2596 @item @code{@ref{ATAN}}   @tab @code{@ref{ATAND}}*
2597 @item @code{@ref{ATAN2}}  @tab @code{@ref{ATAN2D}}*
2598 @item @code{@ref{COS}}    @tab @code{@ref{COSD}}*
2599 @item @code{@ref{COTAN}}* @tab @code{@ref{COTAND}}*
2600 @item @code{@ref{SIN}}    @tab @code{@ref{SIND}}*
2601 @item @code{@ref{TAN}}    @tab @code{@ref{TAND}}*
2602 @end multitable
2604 * Enabled with @option{-fdec-math}.
2606 For advanced users, it may be important to know the implementation of these
2607 functions. They are simply wrappers around the standard radian functions, which
2608 have more accurate builtin versions. These functions convert their arguments
2609 (or results) to degrees (or radians) by taking the value modulus 360 (or 2*pi)
2610 and then multiplying it by a constant radian-to-degree (or degree-to-radian)
2611 factor, as appropriate. The factor is computed at compile-time as 180/pi (or
2612 pi/180).
2614 @node Form feed as whitespace
2615 @subsection Form feed as whitespace
2616 @cindex form feed whitespace
2618 Historically, legacy compilers allowed insertion of form feed characters ('\f',
2619 ASCII 0xC) at the beginning of lines for formatted output to line printers,
2620 though the Fortran standard does not mention this. GNU Fortran supports the
2621 interpretation of form feed characters in source as whitespace for
2622 compatibility.
2624 @node TYPE as an alias for PRINT
2625 @subsection TYPE as an alias for PRINT
2626 @cindex type alias print
2627 For compatibility, GNU Fortran will interpret @code{TYPE} statements as
2628 @code{PRINT} statements with the flag @option{-fdec}.  With this flag asserted,
2629 the following two examples are equivalent:
2631 @smallexample
2632 TYPE *, 'hello world'
2633 @end smallexample
2635 @smallexample
2636 PRINT *, 'hello world'
2637 @end smallexample
2639 @node %LOC as an rvalue
2640 @subsection %LOC as an rvalue
2641 @cindex LOC
2642 Normally @code{%LOC} is allowed only in parameter lists.  However the intrinsic
2643 function @code{LOC} does the same thing, and is usable as the right-hand-side of
2644 assignments. For compatibility, GNU Fortran supports the use of @code{%LOC} as
2645 an alias for the builtin @code{LOC} with @option{-std=legacy}.  With this
2646 feature enabled the following two examples are equivalent:
2648 @smallexample
2649 integer :: i, l
2650 l = %loc(i)
2651 call sub(l)
2652 @end smallexample
2654 @smallexample
2655 integer :: i
2656 call sub(%loc(i))
2657 @end smallexample
2659 @node .XOR. operator
2660 @subsection .XOR. operator
2661 @cindex operators, xor
2663 GNU Fortran supports @code{.XOR.} as a logical operator with @code{-std=legacy}
2664 for compatibility with legacy code. @code{.XOR.} is equivalent to
2665 @code{.NEQV.}. That is, the output is true if and only if the inputs differ.
2667 @node Bitwise logical operators
2668 @subsection Bitwise logical operators
2669 @cindex logical, bitwise
2671 With @option{-fdec}, GNU Fortran relaxes the type constraints on
2672 logical operators to allow integer operands, and performs the corresponding
2673 bitwise operation instead.  This flag is for compatibility only, and should be
2674 avoided in new code.  Consider:
2676 @smallexample
2677   INTEGER :: i, j
2678   i = z'33'
2679   j = z'cc'
2680   print *, i .AND. j
2681 @end smallexample
2683 In this example, compiled with @option{-fdec}, GNU Fortran will
2684 replace the @code{.AND.} operation with a call to the intrinsic
2685 @code{@ref{IAND}} function, yielding the bitwise-and of @code{i} and @code{j}.
2687 Note that this conversion will occur if at least one operand is of integral
2688 type.  As a result, a logical operand will be converted to an integer when the
2689 other operand is an integer in a logical operation.  In this case,
2690 @code{.TRUE.} is converted to @code{1} and @code{.FALSE.} to @code{0}.
2692 Here is the mapping of logical operator to bitwise intrinsic used with
2693 @option{-fdec}:
2695 @multitable @columnfractions .25 .25 .5
2696 @headitem Operator @tab Intrinsic @tab Bitwise operation
2697 @item @code{.NOT.} @tab @code{@ref{NOT}} @tab complement
2698 @item @code{.AND.} @tab @code{@ref{IAND}} @tab intersection
2699 @item @code{.OR.} @tab @code{@ref{IOR}} @tab union
2700 @item @code{.NEQV.} @tab @code{@ref{IEOR}} @tab exclusive or
2701 @item @code{.EQV.} @tab @code{@ref{NOT}(@ref{IEOR})} @tab complement of exclusive or
2702 @end multitable
2704 @node Extended I/O specifiers
2705 @subsection Extended I/O specifiers
2706 @cindex @code{CARRIAGECONTROL}
2707 @cindex @code{READONLY}
2708 @cindex @code{SHARE}
2709 @cindex @code{SHARED}
2710 @cindex @code{NOSHARED}
2711 @cindex I/O specifiers
2713 GNU Fortran supports the additional legacy I/O specifiers
2714 @code{CARRIAGECONTROL}, @code{READONLY}, and @code{SHARE} with the
2715 compile flag @option{-fdec}, for compatibility.
2717 @table @code
2718 @item CARRIAGECONTROL
2719 The @code{CARRIAGECONTROL} specifier allows a user to control line
2720 termination settings between output records for an I/O unit. The specifier has
2721 no meaning for readonly files. When @code{CARRAIGECONTROL} is specified upon
2722 opening a unit for formatted writing, the exact @code{CARRIAGECONTROL} setting
2723 determines what characters to write between output records. The syntax is:
2725 @smallexample
2726 OPEN(..., CARRIAGECONTROL=cc)
2727 @end smallexample
2729 Where @emph{cc} is a character expression that evaluates to one of the
2730 following values:
2732 @multitable @columnfractions .2 .8
2733 @item @code{'LIST'} @tab One line feed between records (default)
2734 @item @code{'FORTRAN'} @tab Legacy interpretation of the first character (see below)
2735 @item @code{'NONE'} @tab No separator between records
2736 @end multitable
2738 With @code{CARRIAGECONTROL='FORTRAN'}, when a record is written, the first
2739 character of the input record is not written, and instead determines the output
2740 record separator as follows:
2742 @multitable @columnfractions .3 .3 .4
2743 @headitem Leading character @tab Meaning @tab Output separating character(s)
2744 @item @code{'+'} @tab Overprinting @tab Carriage return only
2745 @item @code{'-'} @tab New line @tab Line feed and carriage return
2746 @item @code{'0'} @tab Skip line @tab Two line feeds and carriage return
2747 @item @code{'1'} @tab New page @tab Form feed and carriage return
2748 @item @code{'$'} @tab Prompting @tab Line feed (no carriage return)
2749 @item @code{CHAR(0)} @tab Overprinting (no advance) @tab None
2750 @end multitable
2752 @item READONLY
2753 The @code{READONLY} specifier may be given upon opening a unit, and is
2754 equivalent to specifying @code{ACTION='READ'}, except that the file may not be
2755 deleted on close (i.e. @code{CLOSE} with @code{STATUS="DELETE"}). The syntax
2758 @smallexample
2759 @code{OPEN(..., READONLY)}
2760 @end smallexample
2762 @item SHARE
2763 The @code{SHARE} specifier allows system-level locking on a unit upon opening
2764 it for controlled access from multiple processes/threads. The @code{SHARE}
2765 specifier has several forms:
2767 @smallexample
2768 OPEN(..., SHARE=sh)
2769 OPEN(..., SHARED)
2770 OPEN(..., NOSHARED)
2771 @end smallexample
2773 Where @emph{sh} in the first form is a character expression that evaluates to
2774 a value as seen in the table below. The latter two forms are aliases
2775 for particular values of @emph{sh}:
2777 @multitable @columnfractions .3 .3 .4
2778 @headitem Explicit form @tab Short form @tab Meaning
2779 @item @code{SHARE='DENYRW'} @tab @code{NOSHARED} @tab Exclusive (write) lock
2780 @item @code{SHARE='DENYNONE'} @tab @code{SHARED} @tab Shared (read) lock
2781 @end multitable
2783 In general only one process may hold an exclusive (write) lock for a given file
2784 at a time, whereas many processes may hold shared (read) locks for the same
2785 file.
2787 The behavior of locking may vary with your operating system. On POSIX systems,
2788 locking is implemented with @code{fcntl}. Consult your corresponding operating
2789 system's manual pages for further details. Locking via @code{SHARE=} is not
2790 supported on other systems.
2792 @end table
2794 @node Legacy PARAMETER statements
2795 @subsection Legacy PARAMETER statements
2796 @cindex PARAMETER
2798 For compatibility, GNU Fortran supports legacy PARAMETER statements without
2799 parentheses with @option{-std=legacy}.  A warning is emitted if used with
2800 @option{-std=gnu}, and an error is acknowledged with a real Fortran standard
2801 flag (@option{-std=f95}, etc...).  These statements take the following form:
2803 @smallexample
2804 implicit real (E)
2805 parameter e = 2.718282
2806 real c
2807 parameter c = 3.0e8
2808 @end smallexample
2810 @node Default exponents
2811 @subsection Default exponents
2812 @cindex exponent
2814 For compatibility, GNU Fortran supports a default exponent of zero in real
2815 constants with @option{-fdec}.  For example, @code{9e} would be
2816 interpreted as @code{9e0}, rather than an error.
2819 @node Extensions not implemented in GNU Fortran
2820 @section Extensions not implemented in GNU Fortran
2821 @cindex extensions, not implemented
2823 The long history of the Fortran language, its wide use and broad
2824 userbase, the large number of different compiler vendors and the lack of
2825 some features crucial to users in the first standards have lead to the
2826 existence of a number of important extensions to the language.  While
2827 some of the most useful or popular extensions are supported by the GNU
2828 Fortran compiler, not all existing extensions are supported.  This section
2829 aims at listing these extensions and offering advice on how best make
2830 code that uses them running with the GNU Fortran compiler.
2832 @c More can be found here:
2833 @c   -- https://gcc.gnu.org/onlinedocs/gcc-3.4.6/g77/Missing-Features.html
2834 @c   -- the list of Fortran and libgfortran bugs closed as WONTFIX:
2835 @c      http://tinyurl.com/2u4h5y
2837 @menu
2838 * ENCODE and DECODE statements::
2839 * Variable FORMAT expressions::
2840 @c * Q edit descriptor::
2841 @c * TYPE and ACCEPT I/O Statements::
2842 @c * DEFAULTFILE, DISPOSE and RECORDTYPE I/O specifiers::
2843 @c * Omitted arguments in procedure call::
2844 * Alternate complex function syntax::
2845 * Volatile COMMON blocks::
2846 * OPEN( ... NAME=)::
2847 @end menu
2849 @node ENCODE and DECODE statements
2850 @subsection @code{ENCODE} and @code{DECODE} statements
2851 @cindex @code{ENCODE}
2852 @cindex @code{DECODE}
2854 GNU Fortran does not support the @code{ENCODE} and @code{DECODE}
2855 statements.  These statements are best replaced by @code{READ} and
2856 @code{WRITE} statements involving internal files (@code{CHARACTER}
2857 variables and arrays), which have been part of the Fortran standard since
2858 Fortran 77.  For example, replace a code fragment like
2860 @smallexample
2861       INTEGER*1 LINE(80)
2862       REAL A, B, C
2863 c     ... Code that sets LINE
2864       DECODE (80, 9000, LINE) A, B, C
2865  9000 FORMAT (1X, 3(F10.5))
2866 @end smallexample
2868 @noindent
2869 with the following:
2871 @smallexample
2872       CHARACTER(LEN=80) LINE
2873       REAL A, B, C
2874 c     ... Code that sets LINE
2875       READ (UNIT=LINE, FMT=9000) A, B, C
2876  9000 FORMAT (1X, 3(F10.5))
2877 @end smallexample
2879 Similarly, replace a code fragment like
2881 @smallexample
2882       INTEGER*1 LINE(80)
2883       REAL A, B, C
2884 c     ... Code that sets A, B and C
2885       ENCODE (80, 9000, LINE) A, B, C
2886  9000 FORMAT (1X, 'OUTPUT IS ', 3(F10.5))
2887 @end smallexample
2889 @noindent
2890 with the following:
2892 @smallexample
2893       CHARACTER(LEN=80) LINE
2894       REAL A, B, C
2895 c     ... Code that sets A, B and C
2896       WRITE (UNIT=LINE, FMT=9000) A, B, C
2897  9000 FORMAT (1X, 'OUTPUT IS ', 3(F10.5))
2898 @end smallexample
2901 @node Variable FORMAT expressions
2902 @subsection Variable @code{FORMAT} expressions
2903 @cindex @code{FORMAT}
2905 A variable @code{FORMAT} expression is format statement which includes
2906 angle brackets enclosing a Fortran expression: @code{FORMAT(I<N>)}.  GNU
2907 Fortran does not support this legacy extension.  The effect of variable
2908 format expressions can be reproduced by using the more powerful (and
2909 standard) combination of internal output and string formats.  For example,
2910 replace a code fragment like this:
2912 @smallexample
2913       WRITE(6,20) INT1
2914  20   FORMAT(I<N+1>)
2915 @end smallexample
2917 @noindent
2918 with the following:
2920 @smallexample
2921 c     Variable declaration
2922       CHARACTER(LEN=20) FMT
2923 c     
2924 c     Other code here...
2926       WRITE(FMT,'("(I", I0, ")")') N+1
2927       WRITE(6,FMT) INT1
2928 @end smallexample
2930 @noindent
2931 or with:
2933 @smallexample
2934 c     Variable declaration
2935       CHARACTER(LEN=20) FMT
2936 c     
2937 c     Other code here...
2939       WRITE(FMT,*) N+1
2940       WRITE(6,"(I" // ADJUSTL(FMT) // ")") INT1
2941 @end smallexample
2944 @node Alternate complex function syntax
2945 @subsection Alternate complex function syntax
2946 @cindex Complex function
2948 Some Fortran compilers, including @command{g77}, let the user declare
2949 complex functions with the syntax @code{COMPLEX FUNCTION name*16()}, as
2950 well as @code{COMPLEX*16 FUNCTION name()}.  Both are non-standard, legacy
2951 extensions.  @command{gfortran} accepts the latter form, which is more
2952 common, but not the former.
2955 @node Volatile COMMON blocks
2956 @subsection Volatile @code{COMMON} blocks
2957 @cindex @code{VOLATILE}
2958 @cindex @code{COMMON}
2960 Some Fortran compilers, including @command{g77}, let the user declare
2961 @code{COMMON} with the @code{VOLATILE} attribute. This is
2962 invalid standard Fortran syntax and is not supported by
2963 @command{gfortran}.  Note that @command{gfortran} accepts
2964 @code{VOLATILE} variables in @code{COMMON} blocks since revision 4.3.
2967 @node OPEN( ... NAME=)
2968 @subsection @code{OPEN( ... NAME=)}
2969 @cindex @code{NAM}
2971 Some Fortran compilers, including @command{g77}, let the user declare
2972 @code{OPEN( ... NAME=)}. This is
2973 invalid standard Fortran syntax and is not supported by
2974 @command{gfortran}.  @code{OPEN( ... NAME=)} should be replaced
2975 with @code{OPEN( ... FILE=)}.
2979 @c ---------------------------------------------------------------------
2980 @c ---------------------------------------------------------------------
2981 @c Mixed-Language Programming
2982 @c ---------------------------------------------------------------------
2984 @node Mixed-Language Programming
2985 @chapter Mixed-Language Programming
2986 @cindex Interoperability
2987 @cindex Mixed-language programming
2989 @menu
2990 * Interoperability with C::
2991 * GNU Fortran Compiler Directives::
2992 * Non-Fortran Main Program::
2993 * Naming and argument-passing conventions::
2994 @end menu
2996 This chapter is about mixed-language interoperability, but also applies
2997 if one links Fortran code compiled by different compilers.  In most cases,
2998 use of the C Binding features of the Fortran 2003 standard is sufficient,
2999 and their use is highly recommended.
3002 @node Interoperability with C
3003 @section Interoperability with C
3005 @menu
3006 * Intrinsic Types::
3007 * Derived Types and struct::
3008 * Interoperable Global Variables::
3009 * Interoperable Subroutines and Functions::
3010 * Working with Pointers::
3011 * Further Interoperability of Fortran with C::
3012 @end menu
3014 Since Fortran 2003 (ISO/IEC 1539-1:2004(E)) there is a
3015 standardized way to generate procedure and derived-type
3016 declarations and global variables which are interoperable with C
3017 (ISO/IEC 9899:1999).  The @code{bind(C)} attribute has been added
3018 to inform the compiler that a symbol shall be interoperable with C;
3019 also, some constraints are added.  Note, however, that not
3020 all C features have a Fortran equivalent or vice versa.  For instance,
3021 neither C's unsigned integers nor C's functions with variable number
3022 of arguments have an equivalent in Fortran.
3024 Note that array dimensions are reversely ordered in C and that arrays in
3025 C always start with index 0 while in Fortran they start by default with
3026 1.  Thus, an array declaration @code{A(n,m)} in Fortran matches
3027 @code{A[m][n]} in C and accessing the element @code{A(i,j)} matches
3028 @code{A[j-1][i-1]}.  The element following @code{A(i,j)} (C: @code{A[j-1][i-1]};
3029 assuming @math{i < n}) in memory is @code{A(i+1,j)} (C: @code{A[j-1][i]}).
3031 @node Intrinsic Types
3032 @subsection Intrinsic Types
3034 In order to ensure that exactly the same variable type and kind is used
3035 in C and Fortran, the named constants shall be used which are defined in the
3036 @code{ISO_C_BINDING} intrinsic module.  That module contains named constants
3037 for kind parameters and character named constants for the escape sequences
3038 in C.  For a list of the constants, see @ref{ISO_C_BINDING}.
3040 For logical types, please note that the Fortran standard only guarantees
3041 interoperability between C99's @code{_Bool} and Fortran's @code{C_Bool}-kind
3042 logicals and C99 defines that @code{true} has the value 1 and @code{false}
3043 the value 0.  Using any other integer value with GNU Fortran's @code{LOGICAL}
3044 (with any kind parameter) gives an undefined result.  (Passing other integer
3045 values than 0 and 1 to GCC's @code{_Bool} is also undefined, unless the
3046 integer is explicitly or implicitly casted to @code{_Bool}.)
3050 @node Derived Types and struct
3051 @subsection Derived Types and struct
3053 For compatibility of derived types with @code{struct}, one needs to use
3054 the @code{BIND(C)} attribute in the type declaration.  For instance, the
3055 following type declaration
3057 @smallexample
3058  USE ISO_C_BINDING
3059  TYPE, BIND(C) :: myType
3060    INTEGER(C_INT) :: i1, i2
3061    INTEGER(C_SIGNED_CHAR) :: i3
3062    REAL(C_DOUBLE) :: d1
3063    COMPLEX(C_FLOAT_COMPLEX) :: c1
3064    CHARACTER(KIND=C_CHAR) :: str(5)
3065  END TYPE
3066 @end smallexample
3068 matches the following @code{struct} declaration in C
3070 @smallexample
3071  struct @{
3072    int i1, i2;
3073    /* Note: "char" might be signed or unsigned.  */
3074    signed char i3;
3075    double d1;
3076    float _Complex c1;
3077    char str[5];
3078  @} myType;
3079 @end smallexample
3081 Derived types with the C binding attribute shall not have the @code{sequence}
3082 attribute, type parameters, the @code{extends} attribute, nor type-bound
3083 procedures.  Every component must be of interoperable type and kind and may not
3084 have the @code{pointer} or @code{allocatable} attribute.  The names of the
3085 components are irrelevant for interoperability.
3087 As there exist no direct Fortran equivalents, neither unions nor structs
3088 with bit field or variable-length array members are interoperable.
3090 @node Interoperable Global Variables
3091 @subsection Interoperable Global Variables
3093 Variables can be made accessible from C using the C binding attribute,
3094 optionally together with specifying a binding name.  Those variables
3095 have to be declared in the declaration part of a @code{MODULE},
3096 be of interoperable type, and have neither the @code{pointer} nor
3097 the @code{allocatable} attribute.
3099 @smallexample
3100   MODULE m
3101     USE myType_module
3102     USE ISO_C_BINDING
3103     integer(C_INT), bind(C, name="_MyProject_flags") :: global_flag
3104     type(myType), bind(C) :: tp
3105   END MODULE
3106 @end smallexample
3108 Here, @code{_MyProject_flags} is the case-sensitive name of the variable
3109 as seen from C programs while @code{global_flag} is the case-insensitive
3110 name as seen from Fortran.  If no binding name is specified, as for
3111 @var{tp}, the C binding name is the (lowercase) Fortran binding name.
3112 If a binding name is specified, only a single variable may be after the
3113 double colon.  Note of warning: You cannot use a global variable to
3114 access @var{errno} of the C library as the C standard allows it to be
3115 a macro.  Use the @code{IERRNO} intrinsic (GNU extension) instead.
3117 @node Interoperable Subroutines and Functions
3118 @subsection Interoperable Subroutines and Functions
3120 Subroutines and functions have to have the @code{BIND(C)} attribute to
3121 be compatible with C.  The dummy argument declaration is relatively
3122 straightforward.  However, one needs to be careful because C uses
3123 call-by-value by default while Fortran behaves usually similar to
3124 call-by-reference.  Furthermore, strings and pointers are handled
3125 differently.  Note that in Fortran 2003 and 2008 only explicit size
3126 and assumed-size arrays are supported but not assumed-shape or
3127 deferred-shape (i.e. allocatable or pointer) arrays.  However, those
3128 are allowed since the Technical Specification 29113, see
3129 @ref{Further Interoperability of Fortran with C}
3131 To pass a variable by value, use the @code{VALUE} attribute.
3132 Thus, the following C prototype
3134 @smallexample
3135 @code{int func(int i, int *j)}
3136 @end smallexample
3138 matches the Fortran declaration
3140 @smallexample
3141   integer(c_int) function func(i,j)
3142     use iso_c_binding, only: c_int
3143     integer(c_int), VALUE :: i
3144     integer(c_int) :: j
3145 @end smallexample
3147 Note that pointer arguments also frequently need the @code{VALUE} attribute,
3148 see @ref{Working with Pointers}.
3150 Strings are handled quite differently in C and Fortran.  In C a string
3151 is a @code{NUL}-terminated array of characters while in Fortran each string
3152 has a length associated with it and is thus not terminated (by e.g.
3153 @code{NUL}).  For example, if one wants to use the following C function,
3155 @smallexample
3156   #include <stdio.h>
3157   void print_C(char *string) /* equivalent: char string[]  */
3158   @{
3159      printf("%s\n", string);
3160   @}
3161 @end smallexample
3163 to print ``Hello World'' from Fortran, one can call it using
3165 @smallexample
3166   use iso_c_binding, only: C_CHAR, C_NULL_CHAR
3167   interface
3168     subroutine print_c(string) bind(C, name="print_C")
3169       use iso_c_binding, only: c_char
3170       character(kind=c_char) :: string(*)
3171     end subroutine print_c
3172   end interface
3173   call print_c(C_CHAR_"Hello World"//C_NULL_CHAR)
3174 @end smallexample
3176 As the example shows, one needs to ensure that the
3177 string is @code{NUL} terminated.  Additionally, the dummy argument
3178 @var{string} of @code{print_C} is a length-one assumed-size
3179 array; using @code{character(len=*)} is not allowed.  The example
3180 above uses @code{c_char_"Hello World"} to ensure the string
3181 literal has the right type; typically the default character
3182 kind and @code{c_char} are the same and thus @code{"Hello World"}
3183 is equivalent.  However, the standard does not guarantee this.
3185 The use of strings is now further illustrated using the C library
3186 function @code{strncpy}, whose prototype is
3188 @smallexample
3189   char *strncpy(char *restrict s1, const char *restrict s2, size_t n);
3190 @end smallexample
3192 The function @code{strncpy} copies at most @var{n} characters from
3193 string @var{s2} to @var{s1} and returns @var{s1}.  In the following
3194 example, we ignore the return value:
3196 @smallexample
3197   use iso_c_binding
3198   implicit none
3199   character(len=30) :: str,str2
3200   interface
3201     ! Ignore the return value of strncpy -> subroutine
3202     ! "restrict" is always assumed if we do not pass a pointer
3203     subroutine strncpy(dest, src, n) bind(C)
3204       import
3205       character(kind=c_char),  intent(out) :: dest(*)
3206       character(kind=c_char),  intent(in)  :: src(*)
3207       integer(c_size_t), value, intent(in) :: n
3208     end subroutine strncpy
3209   end interface
3210   str = repeat('X',30) ! Initialize whole string with 'X'
3211   call strncpy(str, c_char_"Hello World"//C_NULL_CHAR, &
3212                len(c_char_"Hello World",kind=c_size_t))
3213   print '(a)', str ! prints: "Hello WorldXXXXXXXXXXXXXXXXXXX"
3214   end
3215 @end smallexample
3217 The intrinsic procedures are described in @ref{Intrinsic Procedures}.
3219 @node Working with Pointers
3220 @subsection Working with Pointers
3222 C pointers are represented in Fortran via the special opaque derived type
3223 @code{type(c_ptr)} (with private components).  Thus one needs to
3224 use intrinsic conversion procedures to convert from or to C pointers.
3226 For some applications, using an assumed type (@code{TYPE(*)}) can be an
3227 alternative to a C pointer; see
3228 @ref{Further Interoperability of Fortran with C}.
3230 For example,
3232 @smallexample
3233   use iso_c_binding
3234   type(c_ptr) :: cptr1, cptr2
3235   integer, target :: array(7), scalar
3236   integer, pointer :: pa(:), ps
3237   cptr1 = c_loc(array(1)) ! The programmer needs to ensure that the
3238                           ! array is contiguous if required by the C
3239                           ! procedure
3240   cptr2 = c_loc(scalar)
3241   call c_f_pointer(cptr2, ps)
3242   call c_f_pointer(cptr2, pa, shape=[7])
3243 @end smallexample
3245 When converting C to Fortran arrays, the one-dimensional @code{SHAPE} argument
3246 has to be passed.
3248 If a pointer is a dummy-argument of an interoperable procedure, it usually
3249 has to be declared using the @code{VALUE} attribute.  @code{void*}
3250 matches @code{TYPE(C_PTR), VALUE}, while @code{TYPE(C_PTR)} alone
3251 matches @code{void**}.
3253 Procedure pointers are handled analogously to pointers; the C type is
3254 @code{TYPE(C_FUNPTR)} and the intrinsic conversion procedures are
3255 @code{C_F_PROCPOINTER} and @code{C_FUNLOC}.
3257 Let us consider two examples of actually passing a procedure pointer from
3258 C to Fortran and vice versa.  Note that these examples are also very
3259 similar to passing ordinary pointers between both languages. First,
3260 consider this code in C:
3262 @smallexample
3263 /* Procedure implemented in Fortran.  */
3264 void get_values (void (*)(double));
3266 /* Call-back routine we want called from Fortran.  */
3267 void
3268 print_it (double x)
3270   printf ("Number is %f.\n", x);
3273 /* Call Fortran routine and pass call-back to it.  */
3274 void
3275 foobar ()
3277   get_values (&print_it);
3279 @end smallexample
3281 A matching implementation for @code{get_values} in Fortran, that correctly
3282 receives the procedure pointer from C and is able to call it, is given
3283 in the following @code{MODULE}:
3285 @smallexample
3286 MODULE m
3287   IMPLICIT NONE
3289   ! Define interface of call-back routine.
3290   ABSTRACT INTERFACE
3291     SUBROUTINE callback (x)
3292       USE, INTRINSIC :: ISO_C_BINDING
3293       REAL(KIND=C_DOUBLE), INTENT(IN), VALUE :: x
3294     END SUBROUTINE callback
3295   END INTERFACE
3297 CONTAINS
3299   ! Define C-bound procedure.
3300   SUBROUTINE get_values (cproc) BIND(C)
3301     USE, INTRINSIC :: ISO_C_BINDING
3302     TYPE(C_FUNPTR), INTENT(IN), VALUE :: cproc
3304     PROCEDURE(callback), POINTER :: proc
3306     ! Convert C to Fortran procedure pointer.
3307     CALL C_F_PROCPOINTER (cproc, proc)
3309     ! Call it.
3310     CALL proc (1.0_C_DOUBLE)
3311     CALL proc (-42.0_C_DOUBLE)
3312     CALL proc (18.12_C_DOUBLE)
3313   END SUBROUTINE get_values
3315 END MODULE m
3316 @end smallexample
3318 Next, we want to call a C routine that expects a procedure pointer argument
3319 and pass it a Fortran procedure (which clearly must be interoperable!).
3320 Again, the C function may be:
3322 @smallexample
3324 call_it (int (*func)(int), int arg)
3326   return func (arg);
3328 @end smallexample
3330 It can be used as in the following Fortran code:
3332 @smallexample
3333 MODULE m
3334   USE, INTRINSIC :: ISO_C_BINDING
3335   IMPLICIT NONE
3337   ! Define interface of C function.
3338   INTERFACE
3339     INTEGER(KIND=C_INT) FUNCTION call_it (func, arg) BIND(C)
3340       USE, INTRINSIC :: ISO_C_BINDING
3341       TYPE(C_FUNPTR), INTENT(IN), VALUE :: func
3342       INTEGER(KIND=C_INT), INTENT(IN), VALUE :: arg
3343     END FUNCTION call_it
3344   END INTERFACE
3346 CONTAINS
3348   ! Define procedure passed to C function.
3349   ! It must be interoperable!
3350   INTEGER(KIND=C_INT) FUNCTION double_it (arg) BIND(C)
3351     INTEGER(KIND=C_INT), INTENT(IN), VALUE :: arg
3352     double_it = arg + arg
3353   END FUNCTION double_it
3355   ! Call C function.
3356   SUBROUTINE foobar ()
3357     TYPE(C_FUNPTR) :: cproc
3358     INTEGER(KIND=C_INT) :: i
3360     ! Get C procedure pointer.
3361     cproc = C_FUNLOC (double_it)
3363     ! Use it.
3364     DO i = 1_C_INT, 10_C_INT
3365       PRINT *, call_it (cproc, i)
3366     END DO
3367   END SUBROUTINE foobar
3369 END MODULE m
3370 @end smallexample
3372 @node Further Interoperability of Fortran with C
3373 @subsection Further Interoperability of Fortran with C
3375 The Technical Specification ISO/IEC TS 29113:2012 on further
3376 interoperability of Fortran with C extends the interoperability support
3377 of Fortran 2003 and Fortran 2008. Besides removing some restrictions
3378 and constraints, it adds assumed-type (@code{TYPE(*)}) and assumed-rank
3379 (@code{dimension}) variables and allows for interoperability of
3380 assumed-shape, assumed-rank and deferred-shape arrays, including
3381 allocatables and pointers.
3383 Note: Currently, GNU Fortran does not support the array descriptor
3384 (dope vector) as specified in the Technical Specification, but uses
3385 an array descriptor with different fields. The Chasm Language
3386 Interoperability Tools, @url{http://chasm-interop.sourceforge.net/},
3387 provide an interface to GNU Fortran's array descriptor.
3389 The Technical Specification adds the following new features, which
3390 are supported by GNU Fortran:
3392 @itemize @bullet
3394 @item The @code{ASYNCHRONOUS} attribute has been clarified and
3395 extended to allow its use with asynchronous communication in
3396 user-provided libraries such as in implementations of the
3397 Message Passing Interface specification.
3399 @item Many constraints have been relaxed, in particular for
3400 the @code{C_LOC} and @code{C_F_POINTER} intrinsics.
3402 @item The @code{OPTIONAL} attribute is now allowed for dummy
3403 arguments; an absent argument matches a @code{NULL} pointer.
3405 @item Assumed types (@code{TYPE(*)}) have been added, which may
3406 only be used for dummy arguments.  They are unlimited polymorphic
3407 but contrary to @code{CLASS(*)} they do not contain any type
3408 information, similar to C's @code{void *} pointers.  Expressions
3409 of any type and kind can be passed; thus, it can be used as
3410 replacement for @code{TYPE(C_PTR)}, avoiding the use of
3411 @code{C_LOC} in the caller.
3413 Note, however, that @code{TYPE(*)} only accepts scalar arguments,
3414 unless the @code{DIMENSION} is explicitly specified.  As
3415 @code{DIMENSION(*)} only supports array (including array elements) but
3416 no scalars, it is not a full replacement for @code{C_LOC}.  On the
3417 other hand, assumed-type assumed-rank dummy arguments
3418 (@code{TYPE(*), DIMENSION(..)}) allow for both scalars and arrays, but
3419 require special code on the callee side to handle the array descriptor.
3421 @item Assumed-rank arrays (@code{DIMENSION(..)}) as dummy argument
3422 allow that scalars and arrays of any rank can be passed as actual
3423 argument. As the Technical Specification does not provide for direct
3424 means to operate with them, they have to be used either from the C side
3425 or be converted using @code{C_LOC} and @code{C_F_POINTER} to scalars
3426 or arrays of a specific rank. The rank can be determined using the
3427 @code{RANK} intrinisic.
3428 @end itemize
3431 Currently unimplemented:
3433 @itemize @bullet
3435 @item GNU Fortran always uses an array descriptor, which does not
3436 match the one of the Technical Specification. The
3437 @code{ISO_Fortran_binding.h} header file and the C functions it
3438 specifies are not available.
3440 @item Using assumed-shape, assumed-rank and deferred-shape arrays in
3441 @code{BIND(C)} procedures is not fully supported. In particular,
3442 C interoperable strings of other length than one are not supported
3443 as this requires the new array descriptor.
3444 @end itemize
3447 @node GNU Fortran Compiler Directives
3448 @section GNU Fortran Compiler Directives
3450 @menu
3451 * ATTRIBUTES directive::
3452 * UNROLL directive::
3453 @end menu
3455 @node ATTRIBUTES directive
3456 @subsection ATTRIBUTES directive
3458 The Fortran standard describes how a conforming program shall
3459 behave; however, the exact implementation is not standardized.  In order
3460 to allow the user to choose specific implementation details, compiler
3461 directives can be used to set attributes of variables and procedures
3462 which are not part of the standard.  Whether a given attribute is
3463 supported and its exact effects depend on both the operating system and
3464 on the processor; see
3465 @ref{Top,,C Extensions,gcc,Using the GNU Compiler Collection (GCC)}
3466 for details.
3468 For procedures and procedure pointers, the following attributes can
3469 be used to change the calling convention:
3471 @itemize
3472 @item @code{CDECL} -- standard C calling convention
3473 @item @code{STDCALL} -- convention where the called procedure pops the stack
3474 @item @code{FASTCALL} -- part of the arguments are passed via registers
3475 instead using the stack
3476 @end itemize
3478 Besides changing the calling convention, the attributes also influence
3479 the decoration of the symbol name, e.g., by a leading underscore or by
3480 a trailing at-sign followed by the number of bytes on the stack.  When
3481 assigning a procedure to a procedure pointer, both should use the same
3482 calling convention.
3484 On some systems, procedures and global variables (module variables and
3485 @code{COMMON} blocks) need special handling to be accessible when they
3486 are in a shared library.  The following attributes are available:
3488 @itemize
3489 @item @code{DLLEXPORT} -- provide a global pointer to a pointer in the DLL
3490 @item @code{DLLIMPORT} -- reference the function or variable using a
3491 global pointer
3492 @end itemize
3494 For dummy arguments, the @code{NO_ARG_CHECK} attribute can be used; in
3495 other compilers, it is also known as @code{IGNORE_TKR}.  For dummy arguments
3496 with this attribute actual arguments of any type and kind (similar to
3497 @code{TYPE(*)}), scalars and arrays of any rank (no equivalent
3498 in Fortran standard) are accepted.  As with @code{TYPE(*)}, the argument
3499 is unlimited polymorphic and no type information is available.
3500 Additionally, the argument may only be passed to dummy arguments
3501 with the @code{NO_ARG_CHECK} attribute and as argument to the
3502 @code{PRESENT} intrinsic function and to @code{C_LOC} of the
3503 @code{ISO_C_BINDING} module.
3505 Variables with @code{NO_ARG_CHECK} attribute shall be of assumed-type
3506 (@code{TYPE(*)}; recommended) or of type @code{INTEGER}, @code{LOGICAL},
3507 @code{REAL} or @code{COMPLEX}. They shall not have the @code{ALLOCATE},
3508 @code{CODIMENSION}, @code{INTENT(OUT)}, @code{POINTER} or @code{VALUE}
3509 attribute; furthermore, they shall be either scalar or of assumed-size
3510 (@code{dimension(*)}). As @code{TYPE(*)}, the @code{NO_ARG_CHECK} attribute
3511 requires an explicit interface.
3513 @itemize
3514 @item @code{NO_ARG_CHECK} -- disable the type, kind and rank checking
3515 @end itemize
3518 The attributes are specified using the syntax
3520 @code{!GCC$ ATTRIBUTES} @var{attribute-list} @code{::} @var{variable-list}
3522 where in free-form source code only whitespace is allowed before @code{!GCC$}
3523 and in fixed-form source code @code{!GCC$}, @code{cGCC$} or @code{*GCC$} shall
3524 start in the first column.
3526 For procedures, the compiler directives shall be placed into the body
3527 of the procedure; for variables and procedure pointers, they shall be in
3528 the same declaration part as the variable or procedure pointer.
3531 @node UNROLL directive
3532 @subsection UNROLL directive
3534 The syntax of the directive is
3536 @code{!GCC$ unroll N}
3538 You can use this directive to control how many times a loop should be unrolled.
3539 It must be placed immediately before a @code{DO} loop and applies only to the
3540 loop that follows.  N is an integer constant specifying the unrolling factor.
3541 The values of 0 and 1 block any unrolling of the loop.
3545 @node Non-Fortran Main Program
3546 @section Non-Fortran Main Program
3548 @menu
3549 * _gfortran_set_args:: Save command-line arguments
3550 * _gfortran_set_options:: Set library option flags
3551 * _gfortran_set_convert:: Set endian conversion
3552 * _gfortran_set_record_marker:: Set length of record markers
3553 * _gfortran_set_fpe:: Set when a Floating Point Exception should be raised
3554 * _gfortran_set_max_subrecord_length:: Set subrecord length
3555 @end menu
3557 Even if you are doing mixed-language programming, it is very
3558 likely that you do not need to know or use the information in this
3559 section.  Since it is about the internal structure of GNU Fortran,
3560 it may also change in GCC minor releases.
3562 When you compile a @code{PROGRAM} with GNU Fortran, a function
3563 with the name @code{main} (in the symbol table of the object file)
3564 is generated, which initializes the libgfortran library and then
3565 calls the actual program which uses the name @code{MAIN__}, for
3566 historic reasons.  If you link GNU Fortran compiled procedures
3567 to, e.g., a C or C++ program or to a Fortran program compiled by
3568 a different compiler, the libgfortran library is not initialized
3569 and thus a few intrinsic procedures do not work properly, e.g.
3570 those for obtaining the command-line arguments.
3572 Therefore, if your @code{PROGRAM} is not compiled with
3573 GNU Fortran and the GNU Fortran compiled procedures require
3574 intrinsics relying on the library initialization, you need to
3575 initialize the library yourself.  Using the default options,
3576 gfortran calls @code{_gfortran_set_args} and
3577 @code{_gfortran_set_options}.  The initialization of the former
3578 is needed if the called procedures access the command line
3579 (and for backtracing); the latter sets some flags based on the
3580 standard chosen or to enable backtracing.  In typical programs,
3581 it is not necessary to call any initialization function.
3583 If your @code{PROGRAM} is compiled with GNU Fortran, you shall
3584 not call any of the following functions.  The libgfortran
3585 initialization functions are shown in C syntax but using C
3586 bindings they are also accessible from Fortran.
3589 @node _gfortran_set_args
3590 @subsection @code{_gfortran_set_args} --- Save command-line arguments
3591 @fnindex _gfortran_set_args
3592 @cindex libgfortran initialization, set_args
3594 @table @asis
3595 @item @emph{Description}:
3596 @code{_gfortran_set_args} saves the command-line arguments; this
3597 initialization is required if any of the command-line intrinsics
3598 is called.  Additionally, it shall be called if backtracing is
3599 enabled (see @code{_gfortran_set_options}).
3601 @item @emph{Syntax}:
3602 @code{void _gfortran_set_args (int argc, char *argv[])}
3604 @item @emph{Arguments}:
3605 @multitable @columnfractions .15 .70
3606 @item @var{argc} @tab number of command line argument strings
3607 @item @var{argv} @tab the command-line argument strings; argv[0]
3608 is the pathname of the executable itself.
3609 @end multitable
3611 @item @emph{Example}:
3612 @smallexample
3613 int main (int argc, char *argv[])
3615   /* Initialize libgfortran.  */
3616   _gfortran_set_args (argc, argv);
3617   return 0;
3619 @end smallexample
3620 @end table
3623 @node _gfortran_set_options
3624 @subsection @code{_gfortran_set_options} --- Set library option flags
3625 @fnindex _gfortran_set_options
3626 @cindex libgfortran initialization, set_options
3628 @table @asis
3629 @item @emph{Description}:
3630 @code{_gfortran_set_options} sets several flags related to the Fortran
3631 standard to be used, whether backtracing should be enabled
3632 and whether range checks should be performed.  The syntax allows for
3633 upward compatibility since the number of passed flags is specified; for
3634 non-passed flags, the default value is used.  See also
3635 @pxref{Code Gen Options}.  Please note that not all flags are actually
3636 used.
3638 @item @emph{Syntax}:
3639 @code{void _gfortran_set_options (int num, int options[])}
3641 @item @emph{Arguments}:
3642 @multitable @columnfractions .15 .70
3643 @item @var{num} @tab number of options passed
3644 @item @var{argv} @tab The list of flag values
3645 @end multitable
3647 @item @emph{option flag list}:
3648 @multitable @columnfractions .15 .70
3649 @item @var{option}[0] @tab Allowed standard; can give run-time errors
3650 if e.g. an input-output edit descriptor is invalid in a given
3651 standard.  Possible values are (bitwise or-ed) @code{GFC_STD_F77} (1),
3652 @code{GFC_STD_F95_OBS} (2), @code{GFC_STD_F95_DEL} (4),
3653 @code{GFC_STD_F95} (8), @code{GFC_STD_F2003} (16), @code{GFC_STD_GNU}
3654 (32), @code{GFC_STD_LEGACY} (64), @code{GFC_STD_F2008} (128),
3655 @code{GFC_STD_F2008_OBS} (256), @code{GFC_STD_F2008_TS} (512),
3656 @code{GFC_STD_F2018} (1024), @code{GFC_STD_F2018_OBS} (2048), and
3657 @code{GFC_STD=F2018_DEL} (4096). Default: @code{GFC_STD_F95_OBS |
3658 GFC_STD_F95_DEL | GFC_STD_F95 | GFC_STD_F2003 | GFC_STD_F2008 |
3659 GFC_STD_F2008_TS | GFC_STD_F2008_OBS | GFC_STD_F77 | GFC_STD_F2018 |
3660 GFC_STD_F2018_OBS | GFC_STD_F2018_DEL | GFC_STD_GNU | GFC_STD_LEGACY}.
3661 @item @var{option}[1] @tab Standard-warning flag; prints a warning to
3662 standard error.  Default: @code{GFC_STD_F95_DEL | GFC_STD_LEGACY}.
3663 @item @var{option}[2] @tab If non zero, enable pedantic checking.
3664 Default: off.
3665 @item @var{option}[3] @tab Unused.
3666 @item @var{option}[4] @tab If non zero, enable backtracing on run-time
3667 errors.  Default: off. (Default in the compiler: on.)
3668 Note: Installs a signal handler and requires command-line
3669 initialization using @code{_gfortran_set_args}.
3670 @item @var{option}[5] @tab If non zero, supports signed zeros.
3671 Default: enabled.
3672 @item @var{option}[6] @tab Enables run-time checking.  Possible values
3673 are (bitwise or-ed): GFC_RTCHECK_BOUNDS (1), GFC_RTCHECK_ARRAY_TEMPS (2),
3674 GFC_RTCHECK_RECURSION (4), GFC_RTCHECK_DO (16), GFC_RTCHECK_POINTER (32).
3675 Default: disabled.
3676 @item @var{option}[7] @tab Unused.
3677 @item @var{option}[8] @tab Show a warning when invoking @code{STOP} and
3678 @code{ERROR STOP} if a floating-point exception occurred. Possible values
3679 are (bitwise or-ed) @code{GFC_FPE_INVALID} (1), @code{GFC_FPE_DENORMAL} (2),
3680 @code{GFC_FPE_ZERO} (4), @code{GFC_FPE_OVERFLOW} (8),
3681 @code{GFC_FPE_UNDERFLOW} (16), @code{GFC_FPE_INEXACT} (32). Default: None (0).
3682 (Default in the compiler: @code{GFC_FPE_INVALID | GFC_FPE_DENORMAL |
3683 GFC_FPE_ZERO | GFC_FPE_OVERFLOW | GFC_FPE_UNDERFLOW}.)
3684 @end multitable
3686 @item @emph{Example}:
3687 @smallexample
3688   /* Use gfortran 4.9 default options.  */
3689   static int options[] = @{68, 511, 0, 0, 1, 1, 0, 0, 31@};
3690   _gfortran_set_options (9, &options);
3691 @end smallexample
3692 @end table
3695 @node _gfortran_set_convert
3696 @subsection @code{_gfortran_set_convert} --- Set endian conversion
3697 @fnindex _gfortran_set_convert
3698 @cindex libgfortran initialization, set_convert
3700 @table @asis
3701 @item @emph{Description}:
3702 @code{_gfortran_set_convert} set the representation of data for
3703 unformatted files.
3705 @item @emph{Syntax}:
3706 @code{void _gfortran_set_convert (int conv)}
3708 @item @emph{Arguments}:
3709 @multitable @columnfractions .15 .70
3710 @item @var{conv} @tab Endian conversion, possible values:
3711 GFC_CONVERT_NATIVE (0, default), GFC_CONVERT_SWAP (1),
3712 GFC_CONVERT_BIG (2), GFC_CONVERT_LITTLE (3).
3713 @end multitable
3715 @item @emph{Example}:
3716 @smallexample
3717 int main (int argc, char *argv[])
3719   /* Initialize libgfortran.  */
3720   _gfortran_set_args (argc, argv);
3721   _gfortran_set_convert (1);
3722   return 0;
3724 @end smallexample
3725 @end table
3728 @node _gfortran_set_record_marker
3729 @subsection @code{_gfortran_set_record_marker} --- Set length of record markers
3730 @fnindex _gfortran_set_record_marker
3731 @cindex libgfortran initialization, set_record_marker
3733 @table @asis
3734 @item @emph{Description}:
3735 @code{_gfortran_set_record_marker} sets the length of record markers
3736 for unformatted files.
3738 @item @emph{Syntax}:
3739 @code{void _gfortran_set_record_marker (int val)}
3741 @item @emph{Arguments}:
3742 @multitable @columnfractions .15 .70
3743 @item @var{val} @tab Length of the record marker; valid values
3744 are 4 and 8.  Default is 4.
3745 @end multitable
3747 @item @emph{Example}:
3748 @smallexample
3749 int main (int argc, char *argv[])
3751   /* Initialize libgfortran.  */
3752   _gfortran_set_args (argc, argv);
3753   _gfortran_set_record_marker (8);
3754   return 0;
3756 @end smallexample
3757 @end table
3760 @node _gfortran_set_fpe
3761 @subsection @code{_gfortran_set_fpe} --- Enable floating point exception traps
3762 @fnindex _gfortran_set_fpe
3763 @cindex libgfortran initialization, set_fpe
3765 @table @asis
3766 @item @emph{Description}:
3767 @code{_gfortran_set_fpe} enables floating point exception traps for
3768 the specified exceptions.  On most systems, this will result in a
3769 SIGFPE signal being sent and the program being aborted.
3771 @item @emph{Syntax}:
3772 @code{void _gfortran_set_fpe (int val)}
3774 @item @emph{Arguments}:
3775 @multitable @columnfractions .15 .70
3776 @item @var{option}[0] @tab IEEE exceptions.  Possible values are
3777 (bitwise or-ed) zero (0, default) no trapping,
3778 @code{GFC_FPE_INVALID} (1), @code{GFC_FPE_DENORMAL} (2),
3779 @code{GFC_FPE_ZERO} (4), @code{GFC_FPE_OVERFLOW} (8),
3780 @code{GFC_FPE_UNDERFLOW} (16), and @code{GFC_FPE_INEXACT} (32).
3781 @end multitable
3783 @item @emph{Example}:
3784 @smallexample
3785 int main (int argc, char *argv[])
3787   /* Initialize libgfortran.  */
3788   _gfortran_set_args (argc, argv);
3789   /* FPE for invalid operations such as SQRT(-1.0).  */
3790   _gfortran_set_fpe (1);
3791   return 0;
3793 @end smallexample
3794 @end table
3797 @node _gfortran_set_max_subrecord_length
3798 @subsection @code{_gfortran_set_max_subrecord_length} --- Set subrecord length
3799 @fnindex _gfortran_set_max_subrecord_length
3800 @cindex libgfortran initialization, set_max_subrecord_length
3802 @table @asis
3803 @item @emph{Description}:
3804 @code{_gfortran_set_max_subrecord_length} set the maximum length
3805 for a subrecord.  This option only makes sense for testing and
3806 debugging of unformatted I/O.
3808 @item @emph{Syntax}:
3809 @code{void _gfortran_set_max_subrecord_length (int val)}
3811 @item @emph{Arguments}:
3812 @multitable @columnfractions .15 .70
3813 @item @var{val} @tab the maximum length for a subrecord;
3814 the maximum permitted value is 2147483639, which is also
3815 the default.
3816 @end multitable
3818 @item @emph{Example}:
3819 @smallexample
3820 int main (int argc, char *argv[])
3822   /* Initialize libgfortran.  */
3823   _gfortran_set_args (argc, argv);
3824   _gfortran_set_max_subrecord_length (8);
3825   return 0;
3827 @end smallexample
3828 @end table
3831 @node Naming and argument-passing conventions
3832 @section Naming and argument-passing conventions
3834 This section gives an overview about the naming convention of procedures
3835 and global variables and about the argument passing conventions used by
3836 GNU Fortran.  If a C binding has been specified, the naming convention
3837 and some of the argument-passing conventions change.  If possible,
3838 mixed-language and mixed-compiler projects should use the better defined
3839 C binding for interoperability.  See @pxref{Interoperability with C}.
3841 @menu
3842 * Naming conventions::
3843 * Argument passing conventions::
3844 @end menu
3847 @node Naming conventions
3848 @subsection Naming conventions
3850 According the Fortran standard, valid Fortran names consist of a letter
3851 between @code{A} to @code{Z}, @code{a} to @code{z}, digits @code{0},
3852 @code{1} to @code{9} and underscores (@code{_}) with the restriction
3853 that names may only start with a letter.  As vendor extension, the
3854 dollar sign (@code{$}) is additionally permitted with the option
3855 @option{-fdollar-ok}, but not as first character and only if the
3856 target system supports it.
3858 By default, the procedure name is the lower-cased Fortran name with an
3859 appended underscore (@code{_}); using @option{-fno-underscoring} no
3860 underscore is appended while @code{-fsecond-underscore} appends two
3861 underscores.  Depending on the target system and the calling convention,
3862 the procedure might be additionally dressed; for instance, on 32bit
3863 Windows with @code{stdcall}, an at-sign @code{@@} followed by an integer
3864 number is appended.  For the changing the calling convention, see
3865 @pxref{GNU Fortran Compiler Directives}.
3867 For common blocks, the same convention is used, i.e. by default an
3868 underscore is appended to the lower-cased Fortran name.  Blank commons
3869 have the name @code{__BLNK__}.
3871 For procedures and variables declared in the specification space of a
3872 module, the name is formed by @code{__}, followed by the lower-cased
3873 module name, @code{_MOD_}, and the lower-cased Fortran name.  Note that
3874 no underscore is appended.
3877 @node Argument passing conventions
3878 @subsection Argument passing conventions
3880 Subroutines do not return a value (matching C99's @code{void}) while
3881 functions either return a value as specified in the platform ABI or
3882 the result variable is passed as hidden argument to the function and
3883 no result is returned.  A hidden result variable is used when the
3884 result variable is an array or of type @code{CHARACTER}.
3886 Arguments are passed according to the platform ABI. In particular,
3887 complex arguments might not be compatible to a struct with two real
3888 components for the real and imaginary part. The argument passing
3889 matches the one of C99's @code{_Complex}.  Functions with scalar
3890 complex result variables return their value and do not use a
3891 by-reference argument.  Note that with the @option{-ff2c} option,
3892 the argument passing is modified and no longer completely matches
3893 the platform ABI.  Some other Fortran compilers use @code{f2c}
3894 semantic by default; this might cause problems with
3895 interoperablility.
3897 GNU Fortran passes most arguments by reference, i.e. by passing a
3898 pointer to the data.  Note that the compiler might use a temporary
3899 variable into which the actual argument has been copied, if required
3900 semantically (copy-in/copy-out).
3902 For arguments with @code{ALLOCATABLE} and @code{POINTER}
3903 attribute (including procedure pointers), a pointer to the pointer
3904 is passed such that the pointer address can be modified in the
3905 procedure.
3907 For dummy arguments with the @code{VALUE} attribute: Scalar arguments
3908 of the type @code{INTEGER}, @code{LOGICAL}, @code{REAL} and
3909 @code{COMPLEX} are passed by value according to the platform ABI.
3910 (As vendor extension and not recommended, using @code{%VAL()} in the
3911 call to a procedure has the same effect.) For @code{TYPE(C_PTR)} and
3912 procedure pointers, the pointer itself is passed such that it can be
3913 modified without affecting the caller.
3914 @c FIXME: Document how VALUE is handled for CHARACTER, TYPE,
3915 @c CLASS and arrays, i.e. whether the copy-in is done in the caller
3916 @c or in the callee.
3918 For Boolean (@code{LOGICAL}) arguments, please note that GCC expects
3919 only the integer value 0 and 1.  If a GNU Fortran @code{LOGICAL}
3920 variable contains another integer value, the result is undefined.
3921 As some other Fortran compilers use @math{-1} for @code{.TRUE.},
3922 extra care has to be taken -- such as passing the value as
3923 @code{INTEGER}.  (The same value restriction also applies to other
3924 front ends of GCC, e.g. to GCC's C99 compiler for @code{_Bool}
3925 or GCC's Ada compiler for @code{Boolean}.)
3927 For arguments of @code{CHARACTER} type, the character length is passed
3928 as a hidden argument at the end of the argument list.  For
3929 deferred-length strings, the value is passed by reference, otherwise
3930 by value.  The character length has the C type @code{size_t} (or
3931 @code{INTEGER(kind=C_SIZE_T)} in Fortran).  Note that this is
3932 different to older versions of the GNU Fortran compiler, where the
3933 type of the hidden character length argument was a C @code{int}.  In
3934 order to retain compatibility with older versions, one can e.g. for
3935 the following Fortran procedure
3937 @smallexample
3938 subroutine fstrlen (s, a)
3939    character(len=*) :: s
3940    integer :: a
3941    print*, len(s)
3942 end subroutine fstrlen
3943 @end smallexample
3945 define the corresponding C prototype as follows:
3947 @smallexample
3948 #if __GNUC__ > 7
3949 typedef size_t fortran_charlen_t;
3950 #else
3951 typedef int fortran_charlen_t;
3952 #endif
3954 void fstrlen_ (char*, int*, fortran_charlen_t);
3955 @end smallexample
3957 In order to avoid such compiler-specific details, for new code it is
3958 instead recommended to use the ISO_C_BINDING feature.
3960 Note with C binding, @code{CHARACTER(len=1)} result variables are
3961 returned according to the platform ABI and no hidden length argument
3962 is used for dummy arguments; with @code{VALUE}, those variables are
3963 passed by value.
3965 For @code{OPTIONAL} dummy arguments, an absent argument is denoted
3966 by a NULL pointer, except for scalar dummy arguments of type
3967 @code{INTEGER}, @code{LOGICAL}, @code{REAL} and @code{COMPLEX}
3968 which have the @code{VALUE} attribute.  For those, a hidden Boolean
3969 argument (@code{logical(kind=C_bool),value}) is used to indicate
3970 whether the argument is present.
3972 Arguments which are assumed-shape, assumed-rank or deferred-rank
3973 arrays or, with @option{-fcoarray=lib}, allocatable scalar coarrays use
3974 an array descriptor.  All other arrays pass the address of the
3975 first element of the array.  With @option{-fcoarray=lib}, the token
3976 and the offset belonging to nonallocatable coarrays dummy arguments
3977 are passed as hidden argument along the character length hidden
3978 arguments.  The token is an oparque pointer identifying the coarray
3979 and the offset is a passed-by-value integer of kind @code{C_PTRDIFF_T},
3980 denoting the byte offset between the base address of the coarray and
3981 the passed scalar or first element of the passed array.
3983 The arguments are passed in the following order
3984 @itemize @bullet
3985 @item Result variable, when the function result is passed by reference
3986 @item Character length of the function result, if it is a of type
3987 @code{CHARACTER} and no C binding is used
3988 @item The arguments in the order in which they appear in the Fortran
3989 declaration
3990 @item The the present status for optional arguments with value attribute,
3991 which are internally passed by value
3992 @item The character length and/or coarray token and offset for the first
3993 argument which is a @code{CHARACTER} or a nonallocatable coarray dummy
3994 argument, followed by the hidden arguments of the next dummy argument
3995 of such a type
3996 @end itemize
3999 @c ---------------------------------------------------------------------
4000 @c Coarray Programming
4001 @c ---------------------------------------------------------------------
4003 @node Coarray Programming
4004 @chapter Coarray Programming
4005 @cindex Coarrays
4007 @menu
4008 * Type and enum ABI Documentation::
4009 * Function ABI Documentation::
4010 @end menu
4013 @node Type and enum ABI Documentation
4014 @section Type and enum ABI Documentation
4016 @menu
4017 * caf_token_t::
4018 * caf_register_t::
4019 * caf_deregister_t::
4020 * caf_reference_t::
4021 * caf_team_t::
4022 @end menu
4024 @node caf_token_t
4025 @subsection @code{caf_token_t}
4027 Typedef of type @code{void *} on the compiler side. Can be any data
4028 type on the library side.
4030 @node caf_register_t
4031 @subsection @code{caf_register_t}
4033 Indicates which kind of coarray variable should be registered.
4035 @verbatim
4036 typedef enum caf_register_t {
4037   CAF_REGTYPE_COARRAY_STATIC,
4038   CAF_REGTYPE_COARRAY_ALLOC,
4039   CAF_REGTYPE_LOCK_STATIC,
4040   CAF_REGTYPE_LOCK_ALLOC,
4041   CAF_REGTYPE_CRITICAL,
4042   CAF_REGTYPE_EVENT_STATIC,
4043   CAF_REGTYPE_EVENT_ALLOC,
4044   CAF_REGTYPE_COARRAY_ALLOC_REGISTER_ONLY,
4045   CAF_REGTYPE_COARRAY_ALLOC_ALLOCATE_ONLY
4047 caf_register_t;
4048 @end verbatim
4050 The values @code{CAF_REGTYPE_COARRAY_ALLOC_REGISTER_ONLY} and
4051 @code{CAF_REGTYPE_COARRAY_ALLOC_ALLOCATE_ONLY} are for allocatable components
4052 in derived type coarrays only.  The first one sets up the token without
4053 allocating memory for allocatable component.  The latter one only allocates the
4054 memory for an allocatable component in a derived type coarray.  The token
4055 needs to be setup previously by the REGISTER_ONLY.  This allows to have
4056 allocatable components un-allocated on some images.  The status whether an
4057 allocatable component is allocated on a remote image can be queried by
4058 @code{_caf_is_present} which used internally by the @code{ALLOCATED}
4059 intrinsic.
4061 @node caf_deregister_t
4062 @subsection @code{caf_deregister_t}
4064 @verbatim
4065 typedef enum caf_deregister_t {
4066   CAF_DEREGTYPE_COARRAY_DEREGISTER,
4067   CAF_DEREGTYPE_COARRAY_DEALLOCATE_ONLY
4069 caf_deregister_t;
4070 @end verbatim
4072 Allows to specifiy the type of deregistration of a coarray object.  The
4073 @code{CAF_DEREGTYPE_COARRAY_DEALLOCATE_ONLY} flag is only allowed for
4074 allocatable components in derived type coarrays.
4076 @node caf_reference_t
4077 @subsection @code{caf_reference_t}
4079 The structure used for implementing arbitrary reference chains.
4080 A @code{CAF_REFERENCE_T} allows to specify a component reference or any kind
4081 of array reference of any rank supported by gfortran.  For array references all
4082 kinds as known by the compiler/Fortran standard are supported indicated by
4083 a @code{MODE}.
4085 @verbatim
4086 typedef enum caf_ref_type_t {
4087   /* Reference a component of a derived type, either regular one or an
4088      allocatable or pointer type.  For regular ones idx in caf_reference_t is
4089      set to -1.  */
4090   CAF_REF_COMPONENT,
4091   /* Reference an allocatable array.  */
4092   CAF_REF_ARRAY,
4093   /* Reference a non-allocatable/non-pointer array.  I.e., the coarray object
4094      has no array descriptor associated and the addressing is done
4095      completely using the ref.  */
4096   CAF_REF_STATIC_ARRAY
4097 } caf_ref_type_t;
4098 @end verbatim
4100 @verbatim
4101 typedef enum caf_array_ref_t {
4102   /* No array ref.  This terminates the array ref.  */
4103   CAF_ARR_REF_NONE = 0,
4104   /* Reference array elements given by a vector.  Only for this mode
4105      caf_reference_t.u.a.dim[i].v is valid.  */
4106   CAF_ARR_REF_VECTOR,
4107   /* A full array ref (:).  */
4108   CAF_ARR_REF_FULL,
4109   /* Reference a range on elements given by start, end and stride.  */
4110   CAF_ARR_REF_RANGE,
4111   /* Only a single item is referenced given in the start member.  */
4112   CAF_ARR_REF_SINGLE,
4113   /* An array ref of the kind (i:), where i is an arbitrary valid index in the
4114      array.  The index i is given in the start member.  */
4115   CAF_ARR_REF_OPEN_END,
4116   /* An array ref of the kind (:i), where the lower bound of the array ref
4117      is given by the remote side.  The index i is given in the end member.  */
4118   CAF_ARR_REF_OPEN_START
4119 } caf_array_ref_t;
4120 @end verbatim
4122 @verbatim
4123 /* References to remote components of a derived type.  */
4124 typedef struct caf_reference_t {
4125   /* A pointer to the next ref or NULL.  */
4126   struct caf_reference_t *next;
4127   /* The type of the reference.  */
4128   /* caf_ref_type_t, replaced by int to allow specification in fortran FE.  */
4129   int type;
4130   /* The size of an item referenced in bytes.  I.e. in an array ref this is
4131      the factor to advance the array pointer with to get to the next item.
4132      For component refs this gives just the size of the element referenced.  */
4133   size_t item_size;
4134   union {
4135     struct {
4136       /* The offset (in bytes) of the component in the derived type.
4137          Unused for allocatable or pointer components.  */
4138       ptrdiff_t offset;
4139       /* The offset (in bytes) to the caf_token associated with this
4140          component.  NULL, when not allocatable/pointer ref.  */
4141       ptrdiff_t caf_token_offset;
4142     } c;
4143     struct {
4144       /* The mode of the array ref.  See CAF_ARR_REF_*.  */
4145       /* caf_array_ref_t, replaced by unsigend char to allow specification in
4146          fortran FE.  */
4147      unsigned char mode[GFC_MAX_DIMENSIONS];
4148       /* The type of a static array.  Unset for array's with descriptors.  */
4149       int static_array_type;
4150       /* Subscript refs (s) or vector refs (v).  */
4151       union {
4152         struct {
4153           /* The start and end boundary of the ref and the stride.  */
4154           index_type start, end, stride;
4155         } s;
4156         struct {
4157           /* nvec entries of kind giving the elements to reference.  */
4158           void *vector;
4159           /* The number of entries in vector.  */
4160           size_t nvec;
4161           /* The integer kind used for the elements in vector.  */
4162           int kind;
4163         } v;
4164       } dim[GFC_MAX_DIMENSIONS];
4165     } a;
4166   } u;
4167 } caf_reference_t;
4168 @end verbatim
4170 The references make up a single linked list of reference operations.  The
4171 @code{NEXT} member links to the next reference or NULL to indicate the end of
4172 the chain.  Component and array refs can be arbitrarly mixed as long as they
4173 comply to the Fortran standard.
4175 @emph{NOTES}
4176 The member @code{STATIC_ARRAY_TYPE} is used only when the @code{TYPE} is
4177 @code{CAF_REF_STATIC_ARRAY}.  The member gives the type of the data referenced.
4178 Because no array descriptor is available for a descriptor-less array and
4179 type conversion still needs to take place the type is transported here.
4181 At the moment @code{CAF_ARR_REF_VECTOR} is not implemented in the front end for
4182 descriptor-less arrays.  The library caf_single has untested support for it.
4184 @node caf_team_t
4185 @subsection @code{caf_team_t}
4187 Opaque pointer to represent a team-handle.  This type is a stand-in for the
4188 future implementation of teams.  It is about to change without further notice.
4190 @node Function ABI Documentation
4191 @section Function ABI Documentation
4193 @menu
4194 * _gfortran_caf_init:: Initialiation function
4195 * _gfortran_caf_finish:: Finalization function
4196 * _gfortran_caf_this_image:: Querying the image number
4197 * _gfortran_caf_num_images:: Querying the maximal number of images
4198 * _gfortran_caf_image_status :: Query the status of an image
4199 * _gfortran_caf_failed_images :: Get an array of the indexes of the failed images
4200 * _gfortran_caf_stopped_images :: Get an array of the indexes of the stopped images
4201 * _gfortran_caf_register:: Registering coarrays
4202 * _gfortran_caf_deregister:: Deregistering coarrays
4203 * _gfortran_caf_is_present:: Query whether an allocatable or pointer component in a derived type coarray is allocated
4204 * _gfortran_caf_send:: Sending data from a local image to a remote image
4205 * _gfortran_caf_get:: Getting data from a remote image
4206 * _gfortran_caf_sendget:: Sending data between remote images
4207 * _gfortran_caf_send_by_ref:: Sending data from a local image to a remote image using enhanced references
4208 * _gfortran_caf_get_by_ref:: Getting data from a remote image using enhanced references
4209 * _gfortran_caf_sendget_by_ref:: Sending data between remote images using enhanced references
4210 * _gfortran_caf_lock:: Locking a lock variable
4211 * _gfortran_caf_unlock:: Unlocking a lock variable
4212 * _gfortran_caf_event_post:: Post an event
4213 * _gfortran_caf_event_wait:: Wait that an event occurred
4214 * _gfortran_caf_event_query:: Query event count
4215 * _gfortran_caf_sync_all:: All-image barrier
4216 * _gfortran_caf_sync_images:: Barrier for selected images
4217 * _gfortran_caf_sync_memory:: Wait for completion of segment-memory operations
4218 * _gfortran_caf_error_stop:: Error termination with exit code
4219 * _gfortran_caf_error_stop_str:: Error termination with string
4220 * _gfortran_caf_fail_image :: Mark the image failed and end its execution
4221 * _gfortran_caf_atomic_define:: Atomic variable assignment
4222 * _gfortran_caf_atomic_ref:: Atomic variable reference
4223 * _gfortran_caf_atomic_cas:: Atomic compare and swap
4224 * _gfortran_caf_atomic_op:: Atomic operation
4225 * _gfortran_caf_co_broadcast:: Sending data to all images
4226 * _gfortran_caf_co_max:: Collective maximum reduction
4227 * _gfortran_caf_co_min:: Collective minimum reduction
4228 * _gfortran_caf_co_sum:: Collective summing reduction
4229 * _gfortran_caf_co_reduce:: Generic collective reduction
4230 @end menu
4233 @node _gfortran_caf_init
4234 @subsection @code{_gfortran_caf_init} --- Initialiation function
4235 @cindex Coarray, _gfortran_caf_init
4237 @table @asis
4238 @item @emph{Description}:
4239 This function is called at startup of the program before the Fortran main
4240 program, if the latter has been compiled with @option{-fcoarray=lib}.
4241 It takes as arguments the command-line arguments of the program.  It is
4242 permitted to pass two @code{NULL} pointers as argument; if non-@code{NULL},
4243 the library is permitted to modify the arguments.
4245 @item @emph{Syntax}:
4246 @code{void _gfortran_caf_init (int *argc, char ***argv)}
4248 @item @emph{Arguments}:
4249 @multitable @columnfractions .15 .70
4250 @item @var{argc} @tab intent(inout) An integer pointer with the number of
4251 arguments passed to the program or @code{NULL}.
4252 @item @var{argv} @tab intent(inout) A pointer to an array of strings with the
4253 command-line arguments or @code{NULL}.
4254 @end multitable
4256 @item @emph{NOTES}
4257 The function is modelled after the initialization function of the Message
4258 Passing Interface (MPI) specification.  Due to the way coarray registration
4259 works, it might not be the first call to the library.  If the main program is
4260 not written in Fortran and only a library uses coarrays, it can happen that
4261 this function is never called.  Therefore, it is recommended that the library
4262 does not rely on the passed arguments and whether the call has been done.
4263 @end table
4266 @node _gfortran_caf_finish
4267 @subsection @code{_gfortran_caf_finish} --- Finalization function
4268 @cindex Coarray, _gfortran_caf_finish
4270 @table @asis
4271 @item @emph{Description}:
4272 This function is called at the end of the Fortran main program, if it has
4273 been compiled with the @option{-fcoarray=lib} option.
4275 @item @emph{Syntax}:
4276 @code{void _gfortran_caf_finish (void)}
4278 @item @emph{NOTES}
4279 For non-Fortran programs, it is recommended to call the function at the end
4280 of the main program.  To ensure that the shutdown is also performed for
4281 programs where this function is not explicitly invoked, for instance
4282 non-Fortran programs or calls to the system's exit() function, the library
4283 can use a destructor function.  Note that programs can also be terminated
4284 using the STOP and ERROR STOP statements; those use different library calls.
4285 @end table
4288 @node _gfortran_caf_this_image
4289 @subsection @code{_gfortran_caf_this_image} --- Querying the image number
4290 @cindex Coarray, _gfortran_caf_this_image
4292 @table @asis
4293 @item @emph{Description}:
4294 This function returns the current image number, which is a positive number.
4296 @item @emph{Syntax}:
4297 @code{int _gfortran_caf_this_image (int distance)}
4299 @item @emph{Arguments}:
4300 @multitable @columnfractions .15 .70
4301 @item @var{distance} @tab As specified for the @code{this_image} intrinsic
4302 in TS18508.  Shall be a non-negative number.
4303 @end multitable
4305 @item @emph{NOTES}
4306 If the Fortran intrinsic @code{this_image} is invoked without an argument, which
4307 is the only permitted form in Fortran 2008, GCC passes @code{0} as
4308 first argument.
4309 @end table
4312 @node _gfortran_caf_num_images
4313 @subsection @code{_gfortran_caf_num_images} --- Querying the maximal number of images
4314 @cindex Coarray, _gfortran_caf_num_images
4316 @table @asis
4317 @item @emph{Description}:
4318 This function returns the number of images in the current team, if
4319 @var{distance} is 0 or the number of images in the parent team at the specified
4320 distance. If failed is -1, the function returns the number of all images at
4321 the specified distance; if it is 0, the function returns the number of
4322 nonfailed images, and if it is 1, it returns the number of failed images.
4324 @item @emph{Syntax}:
4325 @code{int _gfortran_caf_num_images(int distance, int failed)}
4327 @item @emph{Arguments}:
4328 @multitable @columnfractions .15 .70
4329 @item @var{distance} @tab the distance from this image to the ancestor.
4330 Shall be positive.
4331 @item @var{failed} @tab shall be -1, 0, or 1
4332 @end multitable
4334 @item @emph{NOTES}
4335 This function follows TS18508. If the num_image intrinsic has no arguments,
4336 then the compiler passes @code{distance=0} and @code{failed=-1} to the function.
4337 @end table
4340 @node _gfortran_caf_image_status
4341 @subsection @code{_gfortran_caf_image_status} --- Query the status of an image
4342 @cindex Coarray, _gfortran_caf_image_status
4344 @table @asis
4345 @item @emph{Description}:
4346 Get the status of the image given by the id @var{image} of the team given by
4347 @var{team}.  Valid results are zero, for image is ok, @code{STAT_STOPPED_IMAGE}
4348 from the ISO_FORTRAN_ENV module to indicate that the image has been stopped and
4349 @code{STAT_FAILED_IMAGE} also from ISO_FORTRAN_ENV to indicate that the image
4350 has executed a @code{FAIL IMAGE} statement.
4352 @item @emph{Syntax}:
4353 @code{int _gfortran_caf_image_status (int image, caf_team_t * team)}
4355 @item @emph{Arguments}:
4356 @multitable @columnfractions .15 .70
4357 @item @var{image} @tab the positive scalar id of the image in the current TEAM.
4358 @item @var{team} @tab optional; team on the which the inquiry is to be
4359 performed.
4360 @end multitable
4362 @item @emph{NOTES}
4363 This function follows TS18508.  Because team-functionality is not yet
4364 implemented a null-pointer is passed for the @var{team} argument at the moment.
4365 @end table
4368 @node _gfortran_caf_failed_images
4369 @subsection @code{_gfortran_caf_failed_images} --- Get an array of the indexes of the failed images
4370 @cindex Coarray, _gfortran_caf_failed_images
4372 @table @asis
4373 @item @emph{Description}:
4374 Get an array of image indexes in the current @var{team} that have failed.  The
4375 array is sorted ascendingly.  When @var{team} is not provided the current team
4376 is to be used.  When @var{kind} is provided then the resulting array is of that
4377 integer kind else it is of default integer kind.  The returns an unallocated
4378 size zero array when no images have failed.
4380 @item @emph{Syntax}:
4381 @code{int _gfortran_caf_failed_images (caf_team_t * team, int * kind)}
4383 @item @emph{Arguments}:
4384 @multitable @columnfractions .15 .70
4385 @item @var{team} @tab optional; team on the which the inquiry is to be
4386 performed.
4387 @item @var{image} @tab optional; the kind of the resulting integer array.
4388 @end multitable
4390 @item @emph{NOTES}
4391 This function follows TS18508.  Because team-functionality is not yet
4392 implemented a null-pointer is passed for the @var{team} argument at the moment.
4393 @end table
4396 @node _gfortran_caf_stopped_images
4397 @subsection @code{_gfortran_caf_stopped_images} --- Get an array of the indexes of the stopped images
4398 @cindex Coarray, _gfortran_caf_stopped_images
4400 @table @asis
4401 @item @emph{Description}:
4402 Get an array of image indexes in the current @var{team} that have stopped.  The
4403 array is sorted ascendingly.  When @var{team} is not provided the current team
4404 is to be used.  When @var{kind} is provided then the resulting array is of that
4405 integer kind else it is of default integer kind.  The returns an unallocated
4406 size zero array when no images have failed.
4408 @item @emph{Syntax}:
4409 @code{int _gfortran_caf_stopped_images (caf_team_t * team, int * kind)}
4411 @item @emph{Arguments}:
4412 @multitable @columnfractions .15 .70
4413 @item @var{team} @tab optional; team on the which the inquiry is to be
4414 performed.
4415 @item @var{image} @tab optional; the kind of the resulting integer array.
4416 @end multitable
4418 @item @emph{NOTES}
4419 This function follows TS18508.  Because team-functionality is not yet
4420 implemented a null-pointer is passed for the @var{team} argument at the moment.
4421 @end table
4424 @node _gfortran_caf_register
4425 @subsection @code{_gfortran_caf_register} --- Registering coarrays
4426 @cindex Coarray, _gfortran_caf_register
4428 @table @asis
4429 @item @emph{Description}:
4430 Registers memory for a coarray and creates a token to identify the coarray.  The
4431 routine is called for both coarrays with @code{SAVE} attribute and using an
4432 explicit @code{ALLOCATE} statement.  If an error occurs and @var{STAT} is a
4433 @code{NULL} pointer, the function shall abort with printing an error message
4434 and starting the error termination.  If no error occurs and @var{STAT} is
4435 present, it shall be set to zero.  Otherwise, it shall be set to a positive
4436 value and, if not-@code{NULL}, @var{ERRMSG} shall be set to a string describing
4437 the failure.  The routine shall register the memory provided in the
4438 @code{DATA}-component of the array descriptor @var{DESC}, when that component
4439 is non-@code{NULL}, else it shall allocate sufficient memory and provide a
4440 pointer to it in the @code{DATA}-component of @var{DESC}.  The array descriptor
4441 has rank zero, when a scalar object is to be registered and the array
4442 descriptor may be invalid after the call to @code{_gfortran_caf_register}.
4443 When an array is to be allocated the descriptor persists.
4445 For @code{CAF_REGTYPE_COARRAY_STATIC} and @code{CAF_REGTYPE_COARRAY_ALLOC},
4446 the passed size is the byte size requested.  For @code{CAF_REGTYPE_LOCK_STATIC},
4447 @code{CAF_REGTYPE_LOCK_ALLOC} and @code{CAF_REGTYPE_CRITICAL} it is the array
4448 size or one for a scalar.
4450 When @code{CAF_REGTYPE_COARRAY_ALLOC_REGISTER_ONLY} is used, then only a token
4451 for an allocatable or pointer component is created.  The @code{SIZE} parameter
4452 is not used then.  On the contrary when
4453 @code{CAF_REGTYPE_COARRAY_ALLOC_ALLOCATE_ONLY} is specified, then the
4454 @var{token} needs to be registered by a previous call with regtype
4455 @code{CAF_REGTYPE_COARRAY_ALLOC_REGISTER_ONLY} and either the memory specified
4456 in the @var{DESC}'s data-ptr is registered or allocate when the data-ptr is
4457 @code{NULL}.
4459 @item @emph{Syntax}:
4460 @code{void caf_register (size_t size, caf_register_t type, caf_token_t *token,
4461 gfc_descriptor_t *desc, int *stat, char *errmsg, size_t errmsg_len)}
4463 @item @emph{Arguments}:
4464 @multitable @columnfractions .15 .70
4465 @item @var{size} @tab For normal coarrays, the byte size of the coarray to be
4466 allocated; for lock types and event types, the number of elements.
4467 @item @var{type} @tab one of the caf_register_t types.
4468 @item @var{token} @tab intent(out) An opaque pointer identifying the coarray.
4469 @item @var{desc} @tab intent(inout) The (pseudo) array descriptor.
4470 @item @var{stat} @tab intent(out) For allocatable coarrays, stores the STAT=;
4471 may be @code{NULL}
4472 @item @var{errmsg} @tab intent(out) When an error occurs, this will be set to
4473 an error message; may be @code{NULL}
4474 @item @var{errmsg_len} @tab the buffer size of errmsg.
4475 @end multitable
4477 @item @emph{NOTES}
4478 Nonallocatable coarrays have to be registered prior use from remote images.
4479 In order to guarantee this, they have to be registered before the main
4480 program. This can be achieved by creating constructor functions. That is what
4481 GCC does such that also for nonallocatable coarrays the memory is allocated and
4482 no static memory is used.  The token permits to identify the coarray; to the
4483 processor, the token is a nonaliasing pointer. The library can, for instance,
4484 store the base address of the coarray in the token, some handle or a more
4485 complicated struct.  The library may also store the array descriptor
4486 @var{DESC} when its rank is non-zero.
4488 For lock types, the value shall only be used for checking the allocation
4489 status. Note that for critical blocks, the locking is only required on one
4490 image; in the locking statement, the processor shall always pass an
4491 image index of one for critical-block lock variables
4492 (@code{CAF_REGTYPE_CRITICAL}). For lock types and critical-block variables,
4493 the initial value shall be unlocked (or, respecitively, not in critical
4494 section) such as the value false; for event types, the initial state should
4495 be no event, e.g. zero.
4496 @end table
4499 @node _gfortran_caf_deregister
4500 @subsection @code{_gfortran_caf_deregister} --- Deregistering coarrays
4501 @cindex Coarray, _gfortran_caf_deregister
4503 @table @asis
4504 @item @emph{Description}:
4505 Called to free or deregister the memory of a coarray; the processor calls this
4506 function for automatic and explicit deallocation.  In case of an error, this
4507 function shall fail with an error message, unless the @var{STAT} variable is
4508 not null.  The library is only expected to free memory it allocated itself
4509 during a call to @code{_gfortran_caf_register}.
4511 @item @emph{Syntax}:
4512 @code{void caf_deregister (caf_token_t *token, caf_deregister_t type,
4513 int *stat, char *errmsg, size_t errmsg_len)}
4515 @item @emph{Arguments}:
4516 @multitable @columnfractions .15 .70
4517 @item @var{token} @tab the token to free.
4518 @item @var{type} @tab the type of action to take for the coarray.  A
4519 @code{CAF_DEREGTYPE_COARRAY_DEALLOCATE_ONLY} is allowed only for allocatable or
4520 pointer components of derived type coarrays.  The action only deallocates the
4521 local memory without deleting the token.
4522 @item @var{stat} @tab intent(out) Stores the STAT=; may be NULL
4523 @item @var{errmsg} @tab intent(out) When an error occurs, this will be set
4524 to an error message; may be NULL
4525 @item @var{errmsg_len} @tab the buffer size of errmsg.
4526 @end multitable
4528 @item @emph{NOTES}
4529 For nonalloatable coarrays this function is never called.  If a cleanup is
4530 required, it has to be handled via the finish, stop and error stop functions,
4531 and via destructors.
4532 @end table
4535 @node _gfortran_caf_is_present
4536 @subsection @code{_gfortran_caf_is_present} --- Query whether an allocatable or pointer component in a derived type coarray is allocated
4537 @cindex Coarray, _gfortran_caf_is_present
4539 @table @asis
4540 @item @emph{Description}:
4541 Used to query the coarray library whether an allocatable component in a derived
4542 type coarray is allocated on a remote image.
4544 @item @emph{Syntax}:
4545 @code{void _gfortran_caf_is_present (caf_token_t token, int image_index,
4546 gfc_reference_t *ref)}
4548 @item @emph{Arguments}:
4549 @multitable @columnfractions .15 .70
4550 @item @var{token} @tab An opaque pointer identifying the coarray.
4551 @item @var{image_index} @tab The ID of the remote image; must be a positive
4552 number.
4553 @item @var{ref} @tab A chain of references to address the allocatable or
4554 pointer component in the derived type coarray.  The object reference needs to be
4555 a scalar or a full array reference, respectively.
4556 @end multitable
4558 @end table
4560 @node _gfortran_caf_send
4561 @subsection @code{_gfortran_caf_send} --- Sending data from a local image to a remote image
4562 @cindex Coarray, _gfortran_caf_send
4564 @table @asis
4565 @item @emph{Description}:
4566 Called to send a scalar, an array section or a whole array from a local
4567 to a remote image identified by the image_index.
4569 @item @emph{Syntax}:
4570 @code{void _gfortran_caf_send (caf_token_t token, size_t offset,
4571 int image_index, gfc_descriptor_t *dest, caf_vector_t *dst_vector,
4572 gfc_descriptor_t *src, int dst_kind, int src_kind, bool may_require_tmp,
4573 int *stat)}
4575 @item @emph{Arguments}:
4576 @multitable @columnfractions .15 .70
4577 @item @var{token} @tab intent(in)  An opaque pointer identifying the coarray.
4578 @item @var{offset} @tab intent(in)  By which amount of bytes the actual data is
4579 shifted compared to the base address of the coarray.
4580 @item @var{image_index} @tab intent(in)  The ID of the remote image; must be a
4581 positive number.
4582 @item @var{dest} @tab intent(in)  Array descriptor for the remote image for the
4583 bounds and the size.  The @code{base_addr} shall not be accessed.
4584 @item @var{dst_vector} @tab intent(in)  If not NULL, it contains the vector
4585 subscript of the destination array; the values are relative to the dimension
4586 triplet of the dest argument.
4587 @item @var{src} @tab intent(in)  Array descriptor of the local array to be
4588 transferred to the remote image
4589 @item @var{dst_kind} @tab intent(in)  Kind of the destination argument
4590 @item @var{src_kind} @tab intent(in)  Kind of the source argument
4591 @item @var{may_require_tmp} @tab intent(in)  The variable is @code{false} when
4592 it is known at compile time that the @var{dest} and @var{src} either cannot
4593 overlap or overlap (fully or partially) such that walking @var{src} and
4594 @var{dest} in element wise element order (honoring the stride value) will not
4595 lead to wrong results.  Otherwise, the value is @code{true}.
4596 @item @var{stat} @tab intent(out) when non-NULL give the result of the
4597 operation, i.e., zero on success and non-zero on error.  When NULL and an error
4598 occurs, then an error message is printed and the program is terminated.
4599 @end multitable
4601 @item @emph{NOTES}
4602 It is permitted to have @var{image_index} equal the current image; the memory
4603 of the send-to and the send-from might (partially) overlap in that case.  The
4604 implementation has to take care that it handles this case, e.g. using
4605 @code{memmove} which handles (partially) overlapping memory. If
4606 @var{may_require_tmp} is true, the library might additionally create a
4607 temporary variable, unless additional checks show that this is not required
4608 (e.g. because walking backward is possible or because both arrays are
4609 contiguous and @code{memmove} takes care of overlap issues).
4611 Note that the assignment of a scalar to an array is permitted. In addition,
4612 the library has to handle numeric-type conversion and for strings, padding
4613 and different character kinds.
4614 @end table
4617 @node _gfortran_caf_get
4618 @subsection @code{_gfortran_caf_get} --- Getting data from a remote image
4619 @cindex Coarray, _gfortran_caf_get
4621 @table @asis
4622 @item @emph{Description}:
4623 Called to get an array section or a whole array from a remote,
4624 image identified by the image_index.
4626 @item @emph{Syntax}:
4627 @code{void _gfortran_caf_get (caf_token_t token, size_t offset,
4628 int image_index, gfc_descriptor_t *src, caf_vector_t *src_vector,
4629 gfc_descriptor_t *dest, int src_kind, int dst_kind, bool may_require_tmp,
4630 int *stat)}
4632 @item @emph{Arguments}:
4633 @multitable @columnfractions .15 .70
4634 @item @var{token} @tab intent(in)  An opaque pointer identifying the coarray.
4635 @item @var{offset} @tab intent(in)  By which amount of bytes the actual data is
4636 shifted compared to the base address of the coarray.
4637 @item @var{image_index} @tab intent(in)  The ID of the remote image; must be a
4638 positive number.
4639 @item @var{dest} @tab intent(out) Array descriptor of the local array to store
4640 the data retrieved from the remote image
4641 @item @var{src} @tab intent(in) Array descriptor for the remote image for the
4642 bounds and the size.  The @code{base_addr} shall not be accessed.
4643 @item @var{src_vector} @tab intent(in)  If not NULL, it contains the vector
4644 subscript of the source array; the values are relative to the dimension
4645 triplet of the @var{src} argument.
4646 @item @var{dst_kind} @tab intent(in)  Kind of the destination argument
4647 @item @var{src_kind} @tab intent(in)  Kind of the source argument
4648 @item @var{may_require_tmp} @tab intent(in)  The variable is @code{false} when
4649 it is known at compile time that the @var{dest} and @var{src} either cannot
4650 overlap or overlap (fully or partially) such that walking @var{src} and
4651 @var{dest} in element wise element order (honoring the stride value) will not
4652 lead to wrong results.  Otherwise, the value is @code{true}.
4653 @item @var{stat} @tab intent(out) When non-NULL give the result of the
4654 operation, i.e., zero on success and non-zero on error.  When NULL and an error
4655 occurs, then an error message is printed and the program is terminated.
4656 @end multitable
4658 @item @emph{NOTES}
4659 It is permitted to have @var{image_index} equal the current image; the memory of
4660 the send-to and the send-from might (partially) overlap in that case.  The
4661 implementation has to take care that it handles this case, e.g. using
4662 @code{memmove} which handles (partially) overlapping memory. If
4663 @var{may_require_tmp} is true, the library might additionally create a
4664 temporary variable, unless additional checks show that this is not required
4665 (e.g. because walking backward is possible or because both arrays are
4666 contiguous and @code{memmove} takes care of overlap issues).
4668 Note that the library has to handle numeric-type conversion and for strings,
4669 padding and different character kinds.
4670 @end table
4673 @node _gfortran_caf_sendget
4674 @subsection @code{_gfortran_caf_sendget} --- Sending data between remote images
4675 @cindex Coarray, _gfortran_caf_sendget
4677 @table @asis
4678 @item @emph{Description}:
4679 Called to send a scalar, an array section or a whole array from a remote image
4680 identified by the @var{src_image_index} to a remote image identified by the
4681 @var{dst_image_index}.
4683 @item @emph{Syntax}:
4684 @code{void _gfortran_caf_sendget (caf_token_t dst_token, size_t dst_offset,
4685 int dst_image_index, gfc_descriptor_t *dest, caf_vector_t *dst_vector,
4686 caf_token_t src_token, size_t src_offset, int src_image_index,
4687 gfc_descriptor_t *src, caf_vector_t *src_vector, int dst_kind, int src_kind,
4688 bool may_require_tmp, int *stat)}
4690 @item @emph{Arguments}:
4691 @multitable @columnfractions .15 .70
4692 @item @var{dst_token} @tab intent(in)  An opaque pointer identifying the
4693 destination coarray.
4694 @item @var{dst_offset} @tab intent(in)  By which amount of bytes the actual data
4695 is shifted compared to the base address of the destination coarray.
4696 @item @var{dst_image_index} @tab intent(in)  The ID of the destination remote
4697 image; must be a positive number.
4698 @item @var{dest} @tab intent(in) Array descriptor for the destination
4699 remote image for the bounds and the size.  The @code{base_addr} shall not be
4700 accessed.
4701 @item @var{dst_vector} @tab intent(int)  If not NULL, it contains the vector
4702 subscript of the destination array; the values are relative to the dimension
4703 triplet of the @var{dest} argument.
4704 @item @var{src_token} @tab intent(in)  An opaque pointer identifying the source
4705 coarray.
4706 @item @var{src_offset} @tab intent(in)  By which amount of bytes the actual data
4707 is shifted compared to the base address of the source coarray.
4708 @item @var{src_image_index} @tab intent(in)  The ID of the source remote image;
4709 must be a positive number.
4710 @item @var{src} @tab intent(in) Array descriptor of the local array to be
4711 transferred to the remote image.
4712 @item @var{src_vector} @tab intent(in) Array descriptor of the local array to
4713 be transferred to the remote image
4714 @item @var{dst_kind} @tab intent(in)  Kind of the destination argument
4715 @item @var{src_kind} @tab intent(in)  Kind of the source argument
4716 @item @var{may_require_tmp} @tab intent(in)  The variable is @code{false} when
4717 it is known at compile time that the @var{dest} and @var{src} either cannot
4718 overlap or overlap (fully or partially) such that walking @var{src} and
4719 @var{dest} in element wise element order (honoring the stride value) will not
4720 lead to wrong results.  Otherwise, the value is @code{true}.
4721 @item @var{stat} @tab intent(out) when non-NULL give the result of the
4722 operation, i.e., zero on success and non-zero on error.  When NULL and an error
4723 occurs, then an error message is printed and the program is terminated.
4724 @end multitable
4726 @item @emph{NOTES}
4727 It is permitted to have the same image index for both @var{src_image_index} and
4728 @var{dst_image_index}; the memory of the send-to and the send-from might
4729 (partially) overlap in that case.  The implementation has to take care that it
4730 handles this case, e.g. using @code{memmove} which handles (partially)
4731 overlapping memory.  If @var{may_require_tmp} is true, the library
4732 might additionally create a temporary variable, unless additional checks show
4733 that this is not required (e.g. because walking backward is possible or because
4734 both arrays are contiguous and @code{memmove} takes care of overlap issues).
4736 Note that the assignment of a scalar to an array is permitted. In addition,
4737 the library has to handle numeric-type conversion and for strings, padding and
4738 different character kinds.
4739 @end table
4741 @node _gfortran_caf_send_by_ref
4742 @subsection @code{_gfortran_caf_send_by_ref} --- Sending data from a local image to a remote image with enhanced referencing options
4743 @cindex Coarray, _gfortran_caf_send_by_ref
4745 @table @asis
4746 @item @emph{Description}:
4747 Called to send a scalar, an array section or a whole array from a local to a
4748 remote image identified by the @var{image_index}.
4750 @item @emph{Syntax}:
4751 @code{void _gfortran_caf_send_by_ref (caf_token_t token, int image_index,
4752 gfc_descriptor_t *src, caf_reference_t *refs, int dst_kind, int src_kind,
4753 bool may_require_tmp, bool dst_reallocatable, int *stat, int dst_type)}
4755 @item @emph{Arguments}:
4756 @multitable @columnfractions .15 .70
4757 @item @var{token} @tab intent(in)  An opaque pointer identifying the coarray.
4758 @item @var{image_index} @tab intent(in)  The ID of the remote image; must be a
4759 positive number.
4760 @item @var{src} @tab intent(in) Array descriptor of the local array to be
4761 transferred to the remote image
4762 @item @var{refs} @tab intent(in) The references on the remote array to store
4763 the data given by src.  Guaranteed to have at least one entry.
4764 @item @var{dst_kind} @tab intent(in)  Kind of the destination argument
4765 @item @var{src_kind} @tab intent(in)  Kind of the source argument
4766 @item @var{may_require_tmp} @tab intent(in)  The variable is @code{false} when
4767 it is known at compile time that the @var{dest} and @var{src} either cannot
4768 overlap or overlap (fully or partially) such that walking @var{src} and
4769 @var{dest} in element wise element order (honoring the stride value) will not
4770 lead to wrong results.  Otherwise, the value is @code{true}.
4771 @item @var{dst_reallocatable} @tab intent(in)  Set when the destination is of
4772 allocatable or pointer type and the refs will allow reallocation, i.e., the ref
4773 is a full array or component ref.
4774 @item @var{stat} @tab intent(out) When non-@code{NULL} give the result of the
4775 operation, i.e., zero on success and non-zero on error.  When @code{NULL} and
4776 an error occurs, then an error message is printed and the program is terminated.
4777 @item @var{dst_type} @tab intent(in)  Give the type of the destination.  When
4778 the destination is not an array, than the precise type, e.g. of a component in
4779 a derived type, is not known, but provided here.
4780 @end multitable
4782 @item @emph{NOTES}
4783 It is permitted to have @var{image_index} equal the current image; the memory of
4784 the send-to and the send-from might (partially) overlap in that case.  The
4785 implementation has to take care that it handles this case, e.g. using
4786 @code{memmove} which handles (partially) overlapping memory.  If
4787 @var{may_require_tmp} is true, the library might additionally create a
4788 temporary variable, unless additional checks show that this is not required
4789 (e.g. because walking backward is possible or because both arrays are
4790 contiguous and @code{memmove} takes care of overlap issues).
4792 Note that the assignment of a scalar to an array is permitted.  In addition,
4793 the library has to handle numeric-type conversion and for strings, padding
4794 and different character kinds.
4796 Because of the more complicated references possible some operations may be
4797 unsupported by certain libraries.  The library is expected to issue a precise
4798 error message why the operation is not permitted.
4799 @end table
4802 @node _gfortran_caf_get_by_ref
4803 @subsection @code{_gfortran_caf_get_by_ref} --- Getting data from a remote image using enhanced references
4804 @cindex Coarray, _gfortran_caf_get_by_ref
4806 @table @asis
4807 @item @emph{Description}:
4808 Called to get a scalar, an array section or a whole array from a remote image
4809 identified by the @var{image_index}.
4811 @item @emph{Syntax}:
4812 @code{void _gfortran_caf_get_by_ref (caf_token_t token, int image_index,
4813 caf_reference_t *refs, gfc_descriptor_t *dst, int dst_kind, int src_kind,
4814 bool may_require_tmp, bool dst_reallocatable, int *stat, int src_type)}
4816 @item @emph{Arguments}:
4817 @multitable @columnfractions .15 .70
4818 @item @var{token} @tab intent(in)  An opaque pointer identifying the coarray.
4819 @item @var{image_index} @tab intent(in)  The ID of the remote image; must be a
4820 positive number.
4821 @item @var{refs} @tab intent(in) The references to apply to the remote structure
4822 to get the data.
4823 @item @var{dst} @tab intent(in) Array descriptor of the local array to store
4824 the data transferred from the remote image.  May be reallocated where needed
4825 and when @var{DST_REALLOCATABLE} allows it.
4826 @item @var{dst_kind} @tab intent(in)  Kind of the destination argument
4827 @item @var{src_kind} @tab intent(in)  Kind of the source argument
4828 @item @var{may_require_tmp} @tab intent(in)  The variable is @code{false} when
4829 it is known at compile time that the @var{dest} and @var{src} either cannot
4830 overlap or overlap (fully or partially) such that walking @var{src} and
4831 @var{dest} in element wise element order (honoring the stride value) will not
4832 lead to wrong results.  Otherwise, the value is @code{true}.
4833 @item @var{dst_reallocatable} @tab intent(in)  Set when @var{DST} is of
4834 allocatable or pointer type and its refs allow reallocation, i.e., the full
4835 array or a component is referenced.
4836 @item @var{stat} @tab intent(out) When non-@code{NULL} give the result of the
4837 operation, i.e., zero on success and non-zero on error.  When @code{NULL} and an
4838 error occurs, then an error message is printed and the program is terminated.
4839 @item @var{src_type} @tab intent(in)  Give the type of the source.  When the
4840 source is not an array, than the precise type, e.g. of a component in a
4841 derived type, is not known, but provided here.
4842 @end multitable
4844 @item @emph{NOTES}
4845 It is permitted to have @code{image_index} equal the current image; the memory
4846 of the send-to and the send-from might (partially) overlap in that case.  The
4847 implementation has to take care that it handles this case, e.g. using
4848 @code{memmove} which handles (partially) overlapping memory.  If
4849 @var{may_require_tmp} is true, the library might additionally create a
4850 temporary variable, unless additional checks show that this is not required
4851 (e.g. because walking backward is possible or because both arrays are
4852 contiguous and @code{memmove} takes care of overlap issues).
4854 Note that the library has to handle numeric-type conversion and for strings,
4855 padding and different character kinds.
4857 Because of the more complicated references possible some operations may be
4858 unsupported by certain libraries.  The library is expected to issue a precise
4859 error message why the operation is not permitted.
4860 @end table
4863 @node _gfortran_caf_sendget_by_ref
4864 @subsection @code{_gfortran_caf_sendget_by_ref} --- Sending data between remote images using enhanced references on both sides
4865 @cindex Coarray, _gfortran_caf_sendget_by_ref
4867 @table @asis
4868 @item @emph{Description}:
4869 Called to send a scalar, an array section or a whole array from a remote image
4870 identified by the @var{src_image_index} to a remote image identified by the
4871 @var{dst_image_index}.
4873 @item @emph{Syntax}:
4874 @code{void _gfortran_caf_sendget_by_ref (caf_token_t dst_token,
4875 int dst_image_index, caf_reference_t *dst_refs,
4876 caf_token_t src_token, int src_image_index, caf_reference_t *src_refs,
4877 int dst_kind, int src_kind, bool may_require_tmp, int *dst_stat,
4878 int *src_stat, int dst_type, int src_type)}
4880 @item @emph{Arguments}:
4881 @multitable @columnfractions .15 .70
4882 @item @var{dst_token} @tab intent(in)  An opaque pointer identifying the
4883 destination coarray.
4884 @item @var{dst_image_index} @tab intent(in)  The ID of the destination remote
4885 image; must be a positive number.
4886 @item @var{dst_refs} @tab intent(in) The references on the remote array to store
4887 the data given by the source.  Guaranteed to have at least one entry.
4888 @item @var{src_token} @tab intent(in)  An opaque pointer identifying the source
4889 coarray.
4890 @item @var{src_image_index} @tab intent(in)  The ID of the source remote image;
4891 must be a positive number.
4892 @item @var{src_refs} @tab intent(in) The references to apply to the remote
4893 structure to get the data.
4894 @item @var{dst_kind} @tab intent(in)  Kind of the destination argument
4895 @item @var{src_kind} @tab intent(in)  Kind of the source argument
4896 @item @var{may_require_tmp} @tab intent(in)  The variable is @code{false} when
4897 it is known at compile time that the @var{dest} and @var{src} either cannot
4898 overlap or overlap (fully or partially) such that walking @var{src} and
4899 @var{dest} in element wise element order (honoring the stride value) will not
4900 lead to wrong results.  Otherwise, the value is @code{true}.
4901 @item @var{dst_stat} @tab intent(out) when non-@code{NULL} give the result of
4902 the send-operation, i.e., zero on success and non-zero on error.  When
4903 @code{NULL} and an error occurs, then an error message is printed and the
4904 program is terminated.
4905 @item @var{src_stat} @tab intent(out) When non-@code{NULL} give the result of
4906 the get-operation, i.e., zero on success and non-zero on error.  When
4907 @code{NULL} and an error occurs, then an error message is printed and the
4908 program is terminated.
4909 @item @var{dst_type} @tab intent(in)  Give the type of the destination.  When
4910 the destination is not an array, than the precise type, e.g. of a component in
4911 a derived type, is not known, but provided here.
4912 @item @var{src_type} @tab intent(in)  Give the type of the source.  When the
4913 source is not an array, than the precise type, e.g. of a component in a
4914 derived type, is not known, but provided here.
4915 @end multitable
4917 @item @emph{NOTES}
4918 It is permitted to have the same image index for both @var{src_image_index} and
4919 @var{dst_image_index}; the memory of the send-to and the send-from might
4920 (partially) overlap in that case.  The implementation has to take care that it
4921 handles this case, e.g. using @code{memmove} which handles (partially)
4922 overlapping memory.  If @var{may_require_tmp} is true, the library
4923 might additionally create a temporary variable, unless additional checks show
4924 that this is not required (e.g. because walking backward is possible or because
4925 both arrays are contiguous and @code{memmove} takes care of overlap issues).
4927 Note that the assignment of a scalar to an array is permitted.  In addition,
4928 the library has to handle numeric-type conversion and for strings, padding and
4929 different character kinds.
4931 Because of the more complicated references possible some operations may be
4932 unsupported by certain libraries.  The library is expected to issue a precise
4933 error message why the operation is not permitted.
4934 @end table
4937 @node _gfortran_caf_lock
4938 @subsection @code{_gfortran_caf_lock} --- Locking a lock variable
4939 @cindex Coarray, _gfortran_caf_lock
4941 @table @asis
4942 @item @emph{Description}:
4943 Acquire a lock on the given image on a scalar locking variable or for the
4944 given array element for an array-valued variable.  If the @var{aquired_lock}
4945 is @code{NULL}, the function returns after having obtained the lock.  If it is
4946 non-@code{NULL}, then @var{acquired_lock} is assigned the value true (one) when
4947 the lock could be obtained and false (zero) otherwise.  Locking a lock variable
4948 which has already been locked by the same image is an error.
4950 @item @emph{Syntax}:
4951 @code{void _gfortran_caf_lock (caf_token_t token, size_t index, int image_index,
4952 int *aquired_lock, int *stat, char *errmsg, size_t errmsg_len)}
4954 @item @emph{Arguments}:
4955 @multitable @columnfractions .15 .70
4956 @item @var{token} @tab intent(in)  An opaque pointer identifying the coarray.
4957 @item @var{index} @tab intent(in)  Array index; first array index is 0.  For
4958 scalars, it is always 0.
4959 @item @var{image_index} @tab intent(in)  The ID of the remote image; must be a
4960 positive number.
4961 @item @var{aquired_lock} @tab intent(out) If not NULL, it returns whether lock
4962 could be obtained.
4963 @item @var{stat} @tab intent(out) Stores the STAT=; may be NULL.
4964 @item @var{errmsg} @tab intent(out) When an error occurs, this will be set to
4965 an error message; may be NULL.
4966 @item @var{errmsg_len} @tab intent(in)  the buffer size of errmsg
4967 @end multitable
4969 @item @emph{NOTES}
4970 This function is also called for critical blocks; for those, the array index
4971 is always zero and the image index is one.  Libraries are permitted to use other
4972 images for critical-block locking variables.
4973 @end table
4975 @node _gfortran_caf_unlock
4976 @subsection @code{_gfortran_caf_lock} --- Unlocking a lock variable
4977 @cindex Coarray, _gfortran_caf_unlock
4979 @table @asis
4980 @item @emph{Description}:
4981 Release a lock on the given image on a scalar locking variable or for the
4982 given array element for an array-valued variable. Unlocking a lock variable
4983 which is unlocked or has been locked by a different image is an error.
4985 @item @emph{Syntax}:
4986 @code{void _gfortran_caf_unlock (caf_token_t token, size_t index, int image_index,
4987 int *stat, char *errmsg, size_t errmsg_len)}
4989 @item @emph{Arguments}:
4990 @multitable @columnfractions .15 .70
4991 @item @var{token} @tab intent(in)  An opaque pointer identifying the coarray.
4992 @item @var{index} @tab intent(in)  Array index; first array index is 0.  For
4993 scalars, it is always 0.
4994 @item @var{image_index} @tab intent(in)  The ID of the remote image; must be a
4995 positive number.
4996 @item @var{stat} @tab intent(out) For allocatable coarrays, stores the STAT=;
4997 may be NULL.
4998 @item @var{errmsg} @tab intent(out) When an error occurs, this will be set to
4999 an error message; may be NULL.
5000 @item @var{errmsg_len} @tab intent(in)  the buffer size of errmsg
5001 @end multitable
5003 @item @emph{NOTES}
5004 This function is also called for critical block; for those, the array index
5005 is always zero and the image index is one.  Libraries are permitted to use other
5006 images for critical-block locking variables.
5007 @end table
5009 @node _gfortran_caf_event_post
5010 @subsection @code{_gfortran_caf_event_post} --- Post an event
5011 @cindex Coarray, _gfortran_caf_event_post
5013 @table @asis
5014 @item @emph{Description}:
5015 Increment the event count of the specified event variable.
5017 @item @emph{Syntax}:
5018 @code{void _gfortran_caf_event_post (caf_token_t token, size_t index,
5019 int image_index, int *stat, char *errmsg, size_t errmsg_len)}
5021 @item @emph{Arguments}:
5022 @multitable @columnfractions .15 .70
5023 @item @var{token} @tab intent(in)  An opaque pointer identifying the coarray.
5024 @item @var{index} @tab intent(in)  Array index; first array index is 0.  For
5025 scalars, it is always 0.
5026 @item @var{image_index} @tab intent(in)  The ID of the remote image; must be a
5027 positive number; zero indicates the current image, when accessed noncoindexed.
5028 @item @var{stat} @tab intent(out)  Stores the STAT=; may be NULL.
5029 @item @var{errmsg} @tab intent(out)  When an error occurs, this will be set to
5030 an error message; may be NULL.
5031 @item @var{errmsg_len} @tab intent(in)  the buffer size of errmsg
5032 @end multitable
5034 @item @emph{NOTES}
5035 This acts like an atomic add of one to the remote image's event variable.
5036 The statement is an image-control statement but does not imply sync memory.
5037 Still, all preceeding push communications of this image to the specified
5038 remote image have to be completed before @code{event_wait} on the remote
5039 image returns.
5040 @end table
5044 @node _gfortran_caf_event_wait
5045 @subsection @code{_gfortran_caf_event_wait} --- Wait that an event occurred
5046 @cindex Coarray, _gfortran_caf_event_wait
5048 @table @asis
5049 @item @emph{Description}:
5050 Wait until the event count has reached at least the specified
5051 @var{until_count}; if so, atomically decrement the event variable by this
5052 amount and return.
5054 @item @emph{Syntax}:
5055 @code{void _gfortran_caf_event_wait (caf_token_t token, size_t index,
5056 int until_count, int *stat, char *errmsg, size_t errmsg_len)}
5058 @item @emph{Arguments}:
5059 @multitable @columnfractions .15 .70
5060 @item @var{token} @tab intent(in)  An opaque pointer identifying the coarray.
5061 @item @var{index} @tab intent(in)  Array index; first array index is 0.  For
5062 scalars, it is always 0.
5063 @item @var{until_count} @tab intent(in)  The number of events which have to be
5064 available before the function returns.
5065 @item @var{stat} @tab intent(out)  Stores the STAT=; may be NULL.
5066 @item @var{errmsg} @tab intent(out)  When an error occurs, this will be set to
5067 an error message; may be NULL.
5068 @item @var{errmsg_len} @tab intent(in)  the buffer size of errmsg
5069 @end multitable
5071 @item @emph{NOTES}
5072 This function only operates on a local coarray. It acts like a loop checking
5073 atomically the value of the event variable, breaking if the value is greater
5074 or equal the requested number of counts. Before the function returns, the
5075 event variable has to be decremented by the requested @var{until_count} value.
5076 A possible implementation would be a busy loop for a certain number of spins
5077 (possibly depending on the number of threads relative to the number of available
5078 cores) followed by another waiting strategy such as a sleeping wait (possibly
5079 with an increasing number of sleep time) or, if possible, a futex wait.
5081 The statement is an image-control statement but does not imply sync memory.
5082 Still, all preceeding push communications of this image to the specified
5083 remote image have to be completed before @code{event_wait} on the remote
5084 image returns.
5085 @end table
5089 @node _gfortran_caf_event_query
5090 @subsection @code{_gfortran_caf_event_query} --- Query event count
5091 @cindex Coarray, _gfortran_caf_event_query
5093 @table @asis
5094 @item @emph{Description}:
5095 Return the event count of the specified event variable.
5097 @item @emph{Syntax}:
5098 @code{void _gfortran_caf_event_query (caf_token_t token, size_t index,
5099 int image_index, int *count, int *stat)}
5101 @item @emph{Arguments}:
5102 @multitable @columnfractions .15 .70
5103 @item @var{token} @tab intent(in)  An opaque pointer identifying the coarray.
5104 @item @var{index} @tab intent(in)  Array index; first array index is 0.  For
5105 scalars, it is always 0.
5106 @item @var{image_index} @tab intent(in)  The ID of the remote image; must be a
5107 positive number; zero indicates the current image when accessed noncoindexed.
5108 @item @var{count} @tab intent(out)  The number of events currently posted to
5109 the event variable.
5110 @item @var{stat} @tab intent(out)  Stores the STAT=; may be NULL.
5111 @end multitable
5113 @item @emph{NOTES}
5114 The typical use is to check the local event variable to only call
5115 @code{event_wait} when the data is available. However, a coindexed variable
5116 is permitted; there is no ordering or synchronization implied.  It acts like
5117 an atomic fetch of the value of the event variable.
5118 @end table
5122 @node _gfortran_caf_sync_all
5123 @subsection @code{_gfortran_caf_sync_all} --- All-image barrier
5124 @cindex Coarray, _gfortran_caf_sync_all
5126 @table @asis
5127 @item @emph{Description}:
5128 Synchronization of all images in the current team; the program only continues
5129 on a given image after this function has been called on all images of the
5130 current team.  Additionally, it ensures that all pending data transfers of
5131 previous segment have completed.
5133 @item @emph{Syntax}:
5134 @code{void _gfortran_caf_sync_all (int *stat, char *errmsg, size_t errmsg_len)}
5136 @item @emph{Arguments}:
5137 @multitable @columnfractions .15 .70
5138 @item @var{stat} @tab intent(out)  Stores the status STAT= and may be NULL.
5139 @item @var{errmsg} @tab intent(out)  When an error occurs, this will be set to
5140 an error message; may be NULL.
5141 @item @var{errmsg_len} @tab intent(in)  the buffer size of errmsg
5142 @end multitable
5143 @end table
5147 @node _gfortran_caf_sync_images
5148 @subsection @code{_gfortran_caf_sync_images} --- Barrier for selected images
5149 @cindex Coarray, _gfortran_caf_sync_images
5151 @table @asis
5152 @item @emph{Description}:
5153 Synchronization between the specified images; the program only continues on a
5154 given image after this function has been called on all images specified for
5155 that image. Note that one image can wait for all other images in the current
5156 team (e.g. via @code{sync images(*)}) while those only wait for that specific
5157 image.  Additionally, @code{sync images} ensures that all pending data
5158 transfers of previous segments have completed.
5160 @item @emph{Syntax}:
5161 @code{void _gfortran_caf_sync_images (int count, int images[], int *stat,
5162 char *errmsg, size_t errmsg_len)}
5164 @item @emph{Arguments}:
5165 @multitable @columnfractions .15 .70
5166 @item @var{count} @tab intent(in)  The number of images which are provided in
5167 the next argument.  For a zero-sized array, the value is zero.  For
5168 @code{sync images (*)}, the value is @math{-1}.
5169 @item @var{images} @tab intent(in)  An array with the images provided by the
5170 user.  If @var{count} is zero, a NULL pointer is passed.
5171 @item @var{stat} @tab intent(out)  Stores the status STAT= and may be NULL.
5172 @item @var{errmsg} @tab intent(out)  When an error occurs, this will be set to
5173 an error message; may be NULL.
5174 @item @var{errmsg_len} @tab intent(in)  the buffer size of errmsg
5175 @end multitable
5176 @end table
5180 @node _gfortran_caf_sync_memory
5181 @subsection @code{_gfortran_caf_sync_memory} --- Wait for completion of segment-memory operations
5182 @cindex Coarray, _gfortran_caf_sync_memory
5184 @table @asis
5185 @item @emph{Description}:
5186 Acts as optimization barrier between different segments. It also ensures that
5187 all pending memory operations of this image have been completed.
5189 @item @emph{Syntax}:
5190 @code{void _gfortran_caf_sync_memory (int *stat, char *errmsg, size_t errmsg_len)}
5192 @item @emph{Arguments}:
5193 @multitable @columnfractions .15 .70
5194 @item @var{stat} @tab intent(out)  Stores the status STAT= and may be NULL.
5195 @item @var{errmsg} @tab intent(out)  When an error occurs, this will be set to
5196 an error message; may be NULL.
5197 @item @var{errmsg_len} @tab intent(in)  the buffer size of errmsg
5198 @end multitable
5200 @item @emph{NOTE} A simple implementation could be
5201 @code{__asm__ __volatile__ ("":::"memory")} to prevent code movements.
5202 @end table
5206 @node _gfortran_caf_error_stop
5207 @subsection @code{_gfortran_caf_error_stop} --- Error termination with exit code
5208 @cindex Coarray, _gfortran_caf_error_stop
5210 @table @asis
5211 @item @emph{Description}:
5212 Invoked for an @code{ERROR STOP} statement which has an integer argument.  The
5213 function should terminate the program with the specified exit code.
5216 @item @emph{Syntax}:
5217 @code{void _gfortran_caf_error_stop (int error)}
5219 @item @emph{Arguments}:
5220 @multitable @columnfractions .15 .70
5221 @item @var{error} @tab intent(in)  The exit status to be used.
5222 @end multitable
5223 @end table
5227 @node _gfortran_caf_error_stop_str
5228 @subsection @code{_gfortran_caf_error_stop_str} --- Error termination with string
5229 @cindex Coarray, _gfortran_caf_error_stop_str
5231 @table @asis
5232 @item @emph{Description}:
5233 Invoked for an @code{ERROR STOP} statement which has a string as argument.  The
5234 function should terminate the program with a nonzero-exit code.
5236 @item @emph{Syntax}:
5237 @code{void _gfortran_caf_error_stop (const char *string, size_t len)}
5239 @item @emph{Arguments}:
5240 @multitable @columnfractions .15 .70
5241 @item @var{string} @tab intent(in)  the error message (not zero terminated)
5242 @item @var{len} @tab intent(in)  the length of the string
5243 @end multitable
5244 @end table
5248 @node _gfortran_caf_fail_image
5249 @subsection @code{_gfortran_caf_fail_image} --- Mark the image failed and end its execution
5250 @cindex Coarray, _gfortran_caf_fail_image
5252 @table @asis
5253 @item @emph{Description}:
5254 Invoked for an @code{FAIL IMAGE} statement.  The function should terminate the
5255 current image.
5257 @item @emph{Syntax}:
5258 @code{void _gfortran_caf_fail_image ()}
5260 @item @emph{NOTES}
5261 This function follows TS18508.
5262 @end table
5266 @node _gfortran_caf_atomic_define
5267 @subsection @code{_gfortran_caf_atomic_define} --- Atomic variable assignment
5268 @cindex Coarray, _gfortran_caf_atomic_define
5270 @table @asis
5271 @item @emph{Description}:
5272 Assign atomically a value to an integer or logical variable.
5274 @item @emph{Syntax}:
5275 @code{void _gfortran_caf_atomic_define (caf_token_t token, size_t offset,
5276 int image_index, void *value, int *stat, int type, int kind)}
5278 @item @emph{Arguments}:
5279 @multitable @columnfractions .15 .70
5280 @item @var{token} @tab intent(in)  An opaque pointer identifying the coarray.
5281 @item @var{offset} @tab intent(in)  By which amount of bytes the actual data is
5282 shifted compared to the base address of the coarray.
5283 @item @var{image_index} @tab intent(in)  The ID of the remote image; must be a
5284 positive number; zero indicates the current image when used noncoindexed.
5285 @item @var{value} @tab intent(in)  the value to be assigned, passed by reference
5286 @item @var{stat} @tab intent(out)  Stores the status STAT= and may be NULL.
5287 @item @var{type} @tab intent(in)  The data type, i.e. @code{BT_INTEGER} (1) or
5288 @code{BT_LOGICAL} (2).
5289 @item @var{kind} @tab intent(in)  The kind value (only 4; always @code{int})
5290 @end multitable
5291 @end table
5295 @node _gfortran_caf_atomic_ref
5296 @subsection @code{_gfortran_caf_atomic_ref} --- Atomic variable reference
5297 @cindex Coarray, _gfortran_caf_atomic_ref
5299 @table @asis
5300 @item @emph{Description}:
5301 Reference atomically a value of a kind-4 integer or logical variable.
5303 @item @emph{Syntax}:
5304 @code{void _gfortran_caf_atomic_ref (caf_token_t token, size_t offset,
5305 int image_index, void *value, int *stat, int type, int kind)}
5307 @item @emph{Arguments}:
5308 @multitable @columnfractions .15 .70
5309 @item @var{token} @tab intent(in)  An opaque pointer identifying the coarray.
5310 @item @var{offset} @tab intent(in)  By which amount of bytes the actual data is
5311 shifted compared to the base address of the coarray.
5312 @item @var{image_index} @tab intent(in)  The ID of the remote image; must be a
5313 positive number; zero indicates the current image when used noncoindexed.
5314 @item @var{value} @tab intent(out)  The variable assigned the atomically
5315 referenced variable.
5316 @item @var{stat} @tab intent(out) Stores the status STAT= and may be NULL.
5317 @item @var{type} @tab the data type, i.e. @code{BT_INTEGER} (1) or
5318 @code{BT_LOGICAL} (2).
5319 @item @var{kind} @tab The kind value (only 4; always @code{int})
5320 @end multitable
5321 @end table
5325 @node _gfortran_caf_atomic_cas
5326 @subsection @code{_gfortran_caf_atomic_cas} --- Atomic compare and swap
5327 @cindex Coarray, _gfortran_caf_atomic_cas
5329 @table @asis
5330 @item @emph{Description}:
5331 Atomic compare and swap of a kind-4 integer or logical variable. Assigns
5332 atomically the specified value to the atomic variable, if the latter has
5333 the value specified by the passed condition value.
5335 @item @emph{Syntax}:
5336 @code{void _gfortran_caf_atomic_cas (caf_token_t token, size_t offset,
5337 int image_index, void *old, void *compare, void *new_val, int *stat,
5338 int type, int kind)}
5340 @item @emph{Arguments}:
5341 @multitable @columnfractions .15 .70
5342 @item @var{token} @tab intent(in)  An opaque pointer identifying the coarray.
5343 @item @var{offset} @tab intent(in)  By which amount of bytes the actual data is
5344 shifted compared to the base address of the coarray.
5345 @item @var{image_index} @tab intent(in)  The ID of the remote image; must be a
5346 positive number; zero indicates the current image when used noncoindexed.
5347 @item @var{old} @tab intent(out)  The value which the atomic variable had
5348 just before the cas operation.
5349 @item @var{compare} @tab intent(in)  The value used for comparision.
5350 @item @var{new_val} @tab intent(in)  The new value for the atomic variable,
5351 assigned to the atomic variable, if @code{compare} equals the value of the
5352 atomic variable.
5353 @item @var{stat} @tab intent(out)  Stores the status STAT= and may be NULL.
5354 @item @var{type} @tab intent(in)  the data type, i.e. @code{BT_INTEGER} (1) or
5355 @code{BT_LOGICAL} (2).
5356 @item @var{kind} @tab intent(in)  The kind value (only 4; always @code{int})
5357 @end multitable
5358 @end table
5362 @node _gfortran_caf_atomic_op
5363 @subsection @code{_gfortran_caf_atomic_op} --- Atomic operation
5364 @cindex Coarray, _gfortran_caf_atomic_op
5366 @table @asis
5367 @item @emph{Description}:
5368 Apply an operation atomically to an atomic integer or logical variable.
5369 After the operation, @var{old} contains the value just before the operation,
5370 which, respectively, adds (GFC_CAF_ATOMIC_ADD) atomically the @code{value} to
5371 the atomic integer variable or does a bitwise AND, OR or exclusive OR
5372 between the atomic variable and @var{value}; the result is then stored in the
5373 atomic variable.
5375 @item @emph{Syntax}:
5376 @code{void _gfortran_caf_atomic_op (int op, caf_token_t token, size_t offset,
5377 int image_index, void *value, void *old, int *stat, int type, int kind)}
5379 @item @emph{Arguments}:
5380 @multitable @columnfractions .15 .70
5381 @item @var{op} @tab intent(in)  the operation to be performed; possible values
5382 @code{GFC_CAF_ATOMIC_ADD} (1), @code{GFC_CAF_ATOMIC_AND} (2),
5383 @code{GFC_CAF_ATOMIC_OR} (3), @code{GFC_CAF_ATOMIC_XOR} (4).
5384 @item @var{token} @tab intent(in)  An opaque pointer identifying the coarray.
5385 @item @var{offset} @tab intent(in)  By which amount of bytes the actual data is
5386 shifted compared to the base address of the coarray.
5387 @item @var{image_index} @tab intent(in)  The ID of the remote image; must be a
5388 positive number; zero indicates the current image when used noncoindexed.
5389 @item @var{old} @tab intent(out)  The value which the atomic variable had
5390 just before the atomic operation.
5391 @item @var{val} @tab intent(in)  The new value for the atomic variable,
5392 assigned to the atomic variable, if @code{compare} equals the value of the
5393 atomic variable.
5394 @item @var{stat} @tab intent(out)  Stores the status STAT= and may be NULL.
5395 @item @var{type} @tab intent(in)  the data type, i.e. @code{BT_INTEGER} (1) or
5396 @code{BT_LOGICAL} (2)
5397 @item @var{kind} @tab intent(in)  the kind value (only 4; always @code{int})
5398 @end multitable
5399 @end table
5404 @node _gfortran_caf_co_broadcast
5405 @subsection @code{_gfortran_caf_co_broadcast} --- Sending data to all images
5406 @cindex Coarray, _gfortran_caf_co_broadcast
5408 @table @asis
5409 @item @emph{Description}:
5410 Distribute a value from a given image to all other images in the team. Has to
5411 be called collectively.
5413 @item @emph{Syntax}:
5414 @code{void _gfortran_caf_co_broadcast (gfc_descriptor_t *a,
5415 int source_image, int *stat, char *errmsg, size_t errmsg_len)}
5417 @item @emph{Arguments}:
5418 @multitable @columnfractions .15 .70
5419 @item @var{a} @tab intent(inout)  An array descriptor with the data to be
5420 broadcasted (on @var{source_image}) or to be received (other images).
5421 @item @var{source_image} @tab intent(in)  The ID of the image from which the
5422 data should be broadcasted.
5423 @item @var{stat} @tab intent(out)  Stores the status STAT= and may be NULL.
5424 @item @var{errmsg} @tab intent(out)  When an error occurs, this will be set to
5425 an error message; may be NULL.
5426 @item @var{errmsg_len} @tab intent(in)  the buffer size of errmsg.
5427 @end multitable
5428 @end table
5432 @node _gfortran_caf_co_max
5433 @subsection @code{_gfortran_caf_co_max} --- Collective maximum reduction
5434 @cindex Coarray, _gfortran_caf_co_max
5436 @table @asis
5437 @item @emph{Description}:
5438 Calculates for each array element of the variable @var{a} the maximum
5439 value for that element in the current team; if @var{result_image} has the
5440 value 0, the result shall be stored on all images, otherwise, only on the
5441 specified image. This function operates on numeric values and character
5442 strings.
5444 @item @emph{Syntax}:
5445 @code{void _gfortran_caf_co_max (gfc_descriptor_t *a, int result_image,
5446 int *stat, char *errmsg, int a_len, size_t errmsg_len)}
5448 @item @emph{Arguments}:
5449 @multitable @columnfractions .15 .70
5450 @item @var{a} @tab intent(inout)  An array descriptor for the data to be
5451 processed.  On the destination image(s) the result overwrites the old content.
5452 @item @var{result_image} @tab intent(in)  The ID of the image to which the
5453 reduced value should be copied to; if zero, it has to be copied to all images.
5454 @item @var{stat} @tab intent(out)  Stores the status STAT= and may be NULL.
5455 @item @var{errmsg} @tab intent(out)  When an error occurs, this will be set to
5456 an error message; may be NULL.
5457 @item @var{a_len} @tab intent(in)  the string length of argument @var{a}
5458 @item @var{errmsg_len} @tab intent(in)  the buffer size of errmsg
5459 @end multitable
5461 @item @emph{NOTES}
5462 If @var{result_image} is nonzero, the data in the array descriptor @var{a} on
5463 all images except of the specified one become undefined; hence, the library may
5464 make use of this.
5465 @end table
5469 @node _gfortran_caf_co_min
5470 @subsection @code{_gfortran_caf_co_min} --- Collective minimum reduction
5471 @cindex Coarray, _gfortran_caf_co_min
5473 @table @asis
5474 @item @emph{Description}:
5475 Calculates for each array element of the variable @var{a} the minimum
5476 value for that element in the current team; if @var{result_image} has the
5477 value 0, the result shall be stored on all images, otherwise, only on the
5478 specified image. This function operates on numeric values and character
5479 strings.
5481 @item @emph{Syntax}:
5482 @code{void _gfortran_caf_co_min (gfc_descriptor_t *a, int result_image,
5483 int *stat, char *errmsg, int a_len, size_t errmsg_len)}
5485 @item @emph{Arguments}:
5486 @multitable @columnfractions .15 .70
5487 @item @var{a} @tab intent(inout)  An array descriptor for the data to be
5488 processed.  On the destination image(s) the result overwrites the old content.
5489 @item @var{result_image} @tab intent(in)  The ID of the image to which the
5490 reduced value should be copied to; if zero, it has to be copied to all images.
5491 @item @var{stat} @tab intent(out)  Stores the status STAT= and may be NULL.
5492 @item @var{errmsg} @tab intent(out)  When an error occurs, this will be set to
5493 an error message; may be NULL.
5494 @item @var{a_len} @tab intent(in)  the string length of argument @var{a}
5495 @item @var{errmsg_len} @tab intent(in)  the buffer size of errmsg
5496 @end multitable
5498 @item @emph{NOTES}
5499 If @var{result_image} is nonzero, the data in the array descriptor @var{a} on
5500 all images except of the specified one become undefined; hence, the library may
5501 make use of this.
5502 @end table
5506 @node _gfortran_caf_co_sum
5507 @subsection @code{_gfortran_caf_co_sum} --- Collective summing reduction
5508 @cindex Coarray, _gfortran_caf_co_sum
5510 @table @asis
5511 @item @emph{Description}:
5512 Calculates for each array element of the variable @var{a} the sum of all
5513 values for that element in the current team; if @var{result_image} has the
5514 value 0, the result shall be stored on all images, otherwise, only on the
5515 specified image.  This function operates on numeric values only.
5517 @item @emph{Syntax}:
5518 @code{void _gfortran_caf_co_sum (gfc_descriptor_t *a, int result_image,
5519 int *stat, char *errmsg, size_t errmsg_len)}
5521 @item @emph{Arguments}:
5522 @multitable @columnfractions .15 .70
5523 @item @var{a} @tab intent(inout)  An array descriptor with the data to be
5524 processed.  On the destination image(s) the result overwrites the old content.
5525 @item @var{result_image} @tab intent(in)  The ID of the image to which the
5526 reduced value should be copied to; if zero, it has to be copied to all images.
5527 @item @var{stat} @tab intent(out)  Stores the status STAT= and may be NULL.
5528 @item @var{errmsg} @tab intent(out)  When an error occurs, this will be set to
5529 an error message; may be NULL.
5530 @item @var{errmsg_len} @tab intent(in)  the buffer size of errmsg
5531 @end multitable
5533 @item @emph{NOTES}
5534 If @var{result_image} is nonzero, the data in the array descriptor @var{a} on
5535 all images except of the specified one become undefined; hence, the library may
5536 make use of this.
5537 @end table
5541 @node _gfortran_caf_co_reduce
5542 @subsection @code{_gfortran_caf_co_reduce} --- Generic collective reduction
5543 @cindex Coarray, _gfortran_caf_co_reduce
5545 @table @asis
5546 @item @emph{Description}:
5547 Calculates for each array element of the variable @var{a} the reduction
5548 value for that element in the current team; if @var{result_image} has the
5549 value 0, the result shall be stored on all images, otherwise, only on the
5550 specified image.  The @var{opr} is a pure function doing a mathematically
5551 commutative and associative operation.
5553 The @var{opr_flags} denote the following; the values are bitwise ored.
5554 @code{GFC_CAF_BYREF} (1) if the result should be returned
5555 by reference; @code{GFC_CAF_HIDDENLEN} (2) whether the result and argument
5556 string lengths shall be specified as hidden arguments;
5557 @code{GFC_CAF_ARG_VALUE} (4) whether the arguments shall be passed by value,
5558 @code{GFC_CAF_ARG_DESC} (8) whether the arguments shall be passed by descriptor.
5561 @item @emph{Syntax}:
5562 @code{void _gfortran_caf_co_reduce (gfc_descriptor_t *a,
5563 void * (*opr) (void *, void *), int opr_flags, int result_image,
5564 int *stat, char *errmsg, int a_len, size_t errmsg_len)}
5566 @item @emph{Arguments}:
5567 @multitable @columnfractions .15 .70
5568 @item @var{a} @tab intent(inout)  An array descriptor with the data to be
5569 processed.  On the destination image(s) the result overwrites the old content.
5570 @item @var{opr} @tab intent(in)  Function pointer to the reduction function
5571 @item @var{opr_flags} @tab intent(in)  Flags regarding the reduction function
5572 @item @var{result_image} @tab intent(in)  The ID of the image to which the
5573 reduced value should be copied to; if zero, it has to be copied to all images.
5574 @item @var{stat} @tab intent(out)  Stores the status STAT= and may be NULL.
5575 @item @var{errmsg} @tab intent(out)  When an error occurs, this will be set to
5576 an error message; may be NULL.
5577 @item @var{a_len} @tab intent(in)  the string length of argument @var{a}
5578 @item @var{errmsg_len} @tab intent(in)  the buffer size of errmsg
5579 @end multitable
5581 @item @emph{NOTES}
5582 If @var{result_image} is nonzero, the data in the array descriptor @var{a} on
5583 all images except of the specified one become undefined; hence, the library may
5584 make use of this.
5586 For character arguments, the result is passed as first argument, followed
5587 by the result string length, next come the two string arguments, followed
5588 by the two hidden string length arguments.  With C binding, there are no hidden
5589 arguments and by-reference passing and either only a single character is passed
5590 or an array descriptor.
5591 @end table
5594 @c Intrinsic Procedures
5595 @c ---------------------------------------------------------------------
5597 @include intrinsic.texi
5600 @tex
5601 \blankpart
5602 @end tex
5604 @c ---------------------------------------------------------------------
5605 @c Contributing
5606 @c ---------------------------------------------------------------------
5608 @node Contributing
5609 @unnumbered Contributing
5610 @cindex Contributing
5612 Free software is only possible if people contribute to efforts
5613 to create it.
5614 We're always in need of more people helping out with ideas
5615 and comments, writing documentation and contributing code.
5617 If you want to contribute to GNU Fortran,
5618 have a look at the long lists of projects you can take on.
5619 Some of these projects are small,
5620 some of them are large;
5621 some are completely orthogonal to the rest of what is
5622 happening on GNU Fortran,
5623 but others are ``mainstream'' projects in need of enthusiastic hackers.
5624 All of these projects are important!
5625 We will eventually get around to the things here,
5626 but they are also things doable by someone who is willing and able.
5628 @menu
5629 * Contributors::
5630 * Projects::
5631 * Proposed Extensions::
5632 @end menu
5635 @node Contributors
5636 @section Contributors to GNU Fortran
5637 @cindex Contributors
5638 @cindex Credits
5639 @cindex Authors
5641 Most of the parser was hand-crafted by @emph{Andy Vaught}, who is
5642 also the initiator of the whole project.  Thanks Andy!
5643 Most of the interface with GCC was written by @emph{Paul Brook}.
5645 The following individuals have contributed code and/or
5646 ideas and significant help to the GNU Fortran project
5647 (in alphabetical order):
5649 @itemize @minus
5650 @item Janne Blomqvist
5651 @item Steven Bosscher
5652 @item Paul Brook
5653 @item Tobias Burnus
5654 @item Fran@,{c}ois-Xavier Coudert
5655 @item Bud Davis
5656 @item Jerry DeLisle
5657 @item Erik Edelmann
5658 @item Bernhard Fischer
5659 @item Daniel Franke
5660 @item Richard Guenther
5661 @item Richard Henderson
5662 @item Katherine Holcomb
5663 @item Jakub Jelinek
5664 @item Niels Kristian Bech Jensen
5665 @item Steven Johnson
5666 @item Steven G. Kargl
5667 @item Thomas Koenig
5668 @item Asher Langton
5669 @item H. J. Lu
5670 @item Toon Moene
5671 @item Brooks Moses
5672 @item Andrew Pinski
5673 @item Tim Prince
5674 @item Christopher D. Rickett
5675 @item Richard Sandiford
5676 @item Tobias Schl@"uter
5677 @item Roger Sayle
5678 @item Paul Thomas
5679 @item Andy Vaught
5680 @item Feng Wang
5681 @item Janus Weil
5682 @item Daniel Kraft
5683 @end itemize
5685 The following people have contributed bug reports,
5686 smaller or larger patches,
5687 and much needed feedback and encouragement for the
5688 GNU Fortran project: 
5690 @itemize @minus
5691 @item Bill Clodius
5692 @item Dominique d'Humi@`eres
5693 @item Kate Hedstrom
5694 @item Erik Schnetter
5695 @item Joost VandeVondele
5696 @end itemize
5698 Many other individuals have helped debug,
5699 test and improve the GNU Fortran compiler over the past few years,
5700 and we welcome you to do the same!
5701 If you already have done so,
5702 and you would like to see your name listed in the
5703 list above, please contact us.
5706 @node Projects
5707 @section Projects
5709 @table @emph
5711 @item Help build the test suite
5712 Solicit more code for donation to the test suite: the more extensive the
5713 testsuite, the smaller the risk of breaking things in the future! We can
5714 keep code private on request.
5716 @item Bug hunting/squishing
5717 Find bugs and write more test cases! Test cases are especially very
5718 welcome, because it allows us to concentrate on fixing bugs instead of
5719 isolating them.  Going through the bugzilla database at
5720 @url{https://gcc.gnu.org/@/bugzilla/} to reduce testcases posted there and
5721 add more information (for example, for which version does the testcase
5722 work, for which versions does it fail?) is also very helpful.
5724 @end table
5727 @node Proposed Extensions
5728 @section Proposed Extensions
5730 Here's a list of proposed extensions for the GNU Fortran compiler, in no particular
5731 order.  Most of these are necessary to be fully compatible with
5732 existing Fortran compilers, but they are not part of the official
5733 J3 Fortran 95 standard.
5735 @subsection Compiler extensions:
5736 @itemize @bullet
5737 @item
5738 User-specified alignment rules for structures.
5740 @item
5741 Automatically extend single precision constants to double.
5743 @item
5744 Compile code that conserves memory by dynamically allocating common and
5745 module storage either on stack or heap.
5747 @item
5748 Compile flag to generate code for array conformance checking (suggest -CC).
5750 @item
5751 User control of symbol names (underscores, etc).
5753 @item
5754 Compile setting for maximum size of stack frame size before spilling
5755 parts to static or heap.
5757 @item
5758 Flag to force local variables into static space.
5760 @item
5761 Flag to force local variables onto stack.
5762 @end itemize
5765 @subsection Environment Options
5766 @itemize @bullet
5767 @item
5768 Pluggable library modules for random numbers, linear algebra.
5769 LA should use BLAS calling conventions.
5771 @item
5772 Environment variables controlling actions on arithmetic exceptions like
5773 overflow, underflow, precision loss---Generate NaN, abort, default.
5774 action.
5776 @item
5777 Set precision for fp units that support it (i387).
5779 @item
5780 Variable for setting fp rounding mode.
5782 @item
5783 Variable to fill uninitialized variables with a user-defined bit
5784 pattern.
5786 @item
5787 Environment variable controlling filename that is opened for that unit
5788 number.
5790 @item
5791 Environment variable to clear/trash memory being freed.
5793 @item
5794 Environment variable to control tracing of allocations and frees.
5796 @item
5797 Environment variable to display allocated memory at normal program end.
5799 @item
5800 Environment variable for filename for * IO-unit.
5802 @item
5803 Environment variable for temporary file directory.
5805 @item
5806 Environment variable forcing standard output to be line buffered (Unix).
5808 @end itemize
5811 @c ---------------------------------------------------------------------
5812 @c GNU General Public License
5813 @c ---------------------------------------------------------------------
5815 @include gpl_v3.texi
5819 @c ---------------------------------------------------------------------
5820 @c GNU Free Documentation License
5821 @c ---------------------------------------------------------------------
5823 @include fdl.texi
5827 @c ---------------------------------------------------------------------
5828 @c Funding Free Software
5829 @c ---------------------------------------------------------------------
5831 @include funding.texi
5833 @c ---------------------------------------------------------------------
5834 @c Indices
5835 @c ---------------------------------------------------------------------
5837 @node Option Index
5838 @unnumbered Option Index
5839 @command{gfortran}'s command line options are indexed here without any
5840 initial @samp{-} or @samp{--}.  Where an option has both positive and
5841 negative forms (such as -foption and -fno-option), relevant entries in
5842 the manual are indexed under the most appropriate form; it may sometimes
5843 be useful to look up both forms.
5844 @printindex op
5846 @node Keyword Index
5847 @unnumbered Keyword Index
5848 @printindex cp
5850 @bye