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