1\input texinfo  @c -*-texinfo-*-
2@c %**start of header
3@setfilename gfortran.info
4@set copyrights-gfortran 1999-2015
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 2003 and 2008 status::  Fortran 2003 and 2008 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 and Fortran 2008 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,
253stored in a file and containing instructions written
254in Fortran 77, Fortran 90, Fortran 95, Fortran 2003 or Fortran 2008.
255This file contains @dfn{source code}.
256
257@item
258Translate the user's program into instructions a computer
259can carry out more quickly than it takes to translate the
260instructions in the first
261place.  The result after compilation of a program is
262@dfn{machine code},
263code designed to be efficiently translated and processed
264by a machine such as your computer.
265Humans usually are not as good writing machine code
266as they are at writing Fortran (or C++, Ada, or Java),
267because it is easy to make tiny mistakes writing machine code.
268
269@item
270Provide the user with information about the reasons why
271the compiler is unable to create a binary from the source code.
272Usually this will be the case if the source code is flawed.
273The Fortran 90 standard requires that the compiler can point out
274mistakes to the user.
275An incorrect usage of the language causes an @dfn{error message}.
276
277The compiler will also attempt to diagnose cases where the
278user's program contains a correct usage of the language,
279but instructs the computer to do something questionable.
280This kind of diagnostics message is called a @dfn{warning message}.
281
282@item
283Provide optional information about the translation passes
284from the source code to machine code.
285This can help a user of the compiler to find the cause of
286certain bugs which may not be obvious in the source code,
287but may be more easily found at a lower level compiler output.
288It also helps developers to find bugs in the compiler itself.
289
290@item
291Provide information in the generated machine code that can
292make it easier to find bugs in the program (using a debugging tool,
293called a @dfn{debugger}, such as the GNU Debugger @command{gdb}).
294
295@item
296Locate and gather machine code already generated to
297perform actions requested by statements in the user's program.
298This machine code is organized into @dfn{modules} and is located
299and @dfn{linked} to the user program.
300@end itemize
301
302The GNU Fortran compiler consists of several components:
303
304@itemize @bullet
305@item
306A version of the @command{gcc} command
307(which also might be installed as the system's @command{cc} command)
308that also understands and accepts Fortran source code.
309The @command{gcc} command is the @dfn{driver} program for
310all the languages in the GNU Compiler Collection (GCC);
311With @command{gcc},
312you can compile the source code of any language for
313which a front end is available in GCC.
314
315@item
316The @command{gfortran} command itself,
317which also might be installed as the
318system's @command{f95} command.
319@command{gfortran} is just another driver program,
320but specifically for the Fortran compiler only.
321The difference with @command{gcc} is that @command{gfortran}
322will automatically link the correct libraries to your program.
323
324@item
325A collection of run-time libraries.
326These libraries contain the machine code needed to support
327capabilities of the Fortran language that are not directly
328provided by the machine code generated by the
329@command{gfortran} compilation phase,
330such as intrinsic functions and subroutines,
331and routines for interaction with files and the operating system.
332@c and mechanisms to spawn,
333@c unleash and pause threads in parallelized code.
334
335@item
336The Fortran compiler itself, (@command{f951}).
337This is the GNU Fortran parser and code generator,
338linked to and interfaced with the GCC backend library.
339@command{f951} ``translates'' the source code to
340assembler code.  You would typically not use this
341program directly;
342instead, the @command{gcc} or @command{gfortran} driver
343programs will call it for you.
344@end itemize
345
346
347@c ---------------------------------------------------------------------
348@c GNU Fortran and GCC
349@c ---------------------------------------------------------------------
350
351@node GNU Fortran and GCC
352@section GNU Fortran and GCC
353@cindex GNU Compiler Collection
354@cindex GCC
355
356GNU Fortran is a part of GCC, the @dfn{GNU Compiler Collection}.  GCC
357consists of a collection of front ends for various languages, which
358translate the source code into a language-independent form called
359@dfn{GENERIC}.  This is then processed by a common middle end which
360provides optimization, and then passed to one of a collection of back
361ends which generate code for different computer architectures and
362operating systems.
363
364Functionally, this is implemented with a driver program (@command{gcc})
365which provides the command-line interface for the compiler.  It calls
366the relevant compiler front-end program (e.g., @command{f951} for
367Fortran) for each file in the source code, and then calls the assembler
368and linker as appropriate to produce the compiled output.  In a copy of
369GCC which has been compiled with Fortran language support enabled,
370@command{gcc} will recognize files with @file{.f}, @file{.for}, @file{.ftn},
371@file{.f90}, @file{.f95}, @file{.f03} and @file{.f08} extensions as
372Fortran source code, and compile it accordingly.  A @command{gfortran}
373driver program is also provided, which is identical to @command{gcc}
374except that it automatically links the Fortran runtime libraries into the
375compiled program.
376
377Source files with @file{.f}, @file{.for}, @file{.fpp}, @file{.ftn}, @file{.F},
378@file{.FOR}, @file{.FPP}, and @file{.FTN} extensions are treated as fixed form.
379Source files with @file{.f90}, @file{.f95}, @file{.f03}, @file{.f08},
380@file{.F90}, @file{.F95}, @file{.F03} and @file{.F08} extensions are
381treated as free form.  The capitalized versions of either form are run
382through preprocessing.  Source files with the lower case @file{.fpp}
383extension are also run through preprocessing.
384
385This manual specifically documents the Fortran front end, which handles
386the programming language's syntax and semantics.  The aspects of GCC
387which relate to the optimization passes and the back-end code generation
388are documented in the GCC manual; see 
389@ref{Top,,Introduction,gcc,Using the GNU Compiler Collection (GCC)}.
390The two manuals together provide a complete reference for the GNU
391Fortran compiler.
392
393
394@c ---------------------------------------------------------------------
395@c Preprocessing and conditional compilation
396@c ---------------------------------------------------------------------
397
398@node Preprocessing and conditional compilation
399@section Preprocessing and conditional compilation
400@cindex CPP
401@cindex FPP
402@cindex Conditional compilation
403@cindex Preprocessing
404@cindex preprocessor, include file handling
405
406Many Fortran compilers including GNU Fortran allow passing the source code
407through a C preprocessor (CPP; sometimes also called the Fortran preprocessor,
408FPP) to allow for conditional compilation.  In the case of GNU Fortran,
409this is the GNU C Preprocessor in the traditional mode.  On systems with
410case-preserving file names, the preprocessor is automatically invoked if the
411filename extension is @file{.F}, @file{.FOR}, @file{.FTN}, @file{.fpp},
412@file{.FPP}, @file{.F90}, @file{.F95}, @file{.F03} or @file{.F08}.  To manually
413invoke the preprocessor on any file, use @option{-cpp}, to disable
414preprocessing on files where the preprocessor is run automatically, use
415@option{-nocpp}.
416
417If a preprocessed file includes another file with the Fortran @code{INCLUDE}
418statement, the included file is not preprocessed.  To preprocess included
419files, use the equivalent preprocessor statement @code{#include}.
420
421If GNU Fortran invokes the preprocessor, @code{__GFORTRAN__}
422is defined and @code{__GNUC__}, @code{__GNUC_MINOR__} and
423@code{__GNUC_PATCHLEVEL__} can be used to determine the version of the
424compiler.  See @ref{Top,,Overview,cpp,The C Preprocessor} for details.
425
426While CPP is the de-facto standard for preprocessing Fortran code,
427Part 3 of the Fortran 95 standard (ISO/IEC 1539-3:1998) defines
428Conditional Compilation, which is not widely used and not directly
429supported by the GNU Fortran compiler.  You can use the program coco
430to preprocess such files (@uref{http://www.daniellnagle.com/coco.html}).
431
432
433@c ---------------------------------------------------------------------
434@c GNU Fortran and G77
435@c ---------------------------------------------------------------------
436
437@node GNU Fortran and G77
438@section GNU Fortran and G77
439@cindex Fortran 77
440@cindex @command{g77}
441
442The GNU Fortran compiler is the successor to @command{g77}, the Fortran 
44377 front end included in GCC prior to version 4.  It is an entirely new 
444program that has been designed to provide Fortran 95 support and 
445extensibility for future Fortran language standards, as well as providing 
446backwards compatibility for Fortran 77 and nearly all of the GNU language 
447extensions supported by @command{g77}.
448
449
450@c ---------------------------------------------------------------------
451@c Project Status
452@c ---------------------------------------------------------------------
453
454@node Project Status
455@section Project Status
456
457@quotation
458As soon as @command{gfortran} can parse all of the statements correctly,
459it will be in the ``larva'' state.
460When we generate code, the ``puppa'' state.
461When @command{gfortran} is done,
462we'll see if it will be a beautiful butterfly,
463or just a big bug....
464
465--Andy Vaught, April 2000
466@end quotation
467
468The start of the GNU Fortran 95 project was announced on
469the GCC homepage in March 18, 2000
470(even though Andy had already been working on it for a while,
471of course).
472
473The GNU Fortran compiler is able to compile nearly all
474standard-compliant Fortran 95, Fortran 90, and Fortran 77 programs,
475including a number of standard and non-standard extensions, and can be
476used on real-world programs.  In particular, the supported extensions
477include OpenMP, Cray-style pointers, and several Fortran 2003 and Fortran
4782008 features, including TR 15581.  However, it is still under
479development and has a few remaining rough edges.
480There also is initial support for OpenACC.
481Note that this is an experimental feature, incomplete, and subject to
482change in future versions of GCC.  See
483@uref{https://gcc.gnu.org/wiki/OpenACC} for more information.
484
485At present, the GNU Fortran compiler passes the
486@uref{http://www.fortran-2000.com/ArnaudRecipes/fcvs21_f95.html, 
487NIST Fortran 77 Test Suite}, and produces acceptable results on the
488@uref{http://www.netlib.org/lapack/faq.html#1.21, LAPACK Test Suite}.
489It also provides respectable performance on 
490the @uref{http://www.polyhedron.com/fortran-compiler-comparisons/polyhedron-benchmark-suite,
491Polyhedron Fortran
492compiler benchmarks} and the
493@uref{http://www.netlib.org/benchmark/livermore,
494Livermore Fortran Kernels test}.  It has been used to compile a number of
495large real-world programs, including
496@uref{http://hirlam.org/, the HARMONIE and HIRLAM weather forecasting code} and
497@uref{http://physical-chemistry.scb.uwa.edu.au/tonto/wiki/index.php/Main_Page,
498the Tonto quantum chemistry package}; see
499@url{https://gcc.gnu.org/@/wiki/@/GfortranApps} for an extended list.
500
501Among other things, the GNU Fortran compiler is intended as a replacement
502for G77.  At this point, nearly all programs that could be compiled with
503G77 can be compiled with GNU Fortran, although there are a few minor known
504regressions.
505
506The primary work remaining to be done on GNU Fortran falls into three
507categories: bug fixing (primarily regarding the treatment of invalid code
508and providing useful error messages), improving the compiler optimizations
509and the performance of compiled code, and extending the compiler to support
510future standards---in particular, Fortran 2003 and Fortran 2008.
511
512
513@c ---------------------------------------------------------------------
514@c Standards
515@c ---------------------------------------------------------------------
516
517@node Standards
518@section Standards
519@cindex Standards
520
521@menu
522* Varying Length Character Strings::
523@end menu
524
525The GNU Fortran compiler implements
526ISO/IEC 1539:1997 (Fortran 95).  As such, it can also compile essentially all
527standard-compliant Fortran 90 and Fortran 77 programs.   It also supports
528the ISO/IEC TR-15581 enhancements to allocatable arrays.
529
530GNU Fortran also have a partial support for ISO/IEC 1539-1:2004 (Fortran
5312003), ISO/IEC 1539-1:2010 (Fortran 2008), the Technical Specification
532@code{Further Interoperability of Fortran with C} (ISO/IEC TS 29113:2012).
533Full support of those standards and future Fortran standards is planned.
534The current status of the support is can be found in the
535@ref{Fortran 2003 status}, @ref{Fortran 2008 status} and
536@ref{TS 29113 status} sections of the documentation.
537
538Additionally, the GNU Fortran compilers supports the OpenMP specification
539(version 4.0, @url{http://openmp.org/@/wp/@/openmp-specifications/}).
540There also is initial support for the OpenACC specification (targeting
541version 2.0, @uref{http://www.openacc.org/}).
542Note that this is an experimental feature, incomplete, and subject to
543change in future versions of GCC.  See
544@uref{https://gcc.gnu.org/wiki/OpenACC} for more information.
545
546@node Varying Length Character Strings
547@subsection Varying Length Character Strings
548@cindex Varying length character strings
549@cindex Varying length strings
550@cindex strings, varying length
551
552The Fortran 95 standard specifies in Part 2 (ISO/IEC 1539-2:2000)
553varying length character strings.  While GNU Fortran currently does not
554support such strings directly, there exist two Fortran implementations
555for them, which work with GNU Fortran.  They can be found at
556@uref{http://www.fortran.com/@/iso_varying_string.f95} and at
557@uref{ftp://ftp.nag.co.uk/@/sc22wg5/@/ISO_VARYING_STRING/}.
558
559Deferred-length character strings of Fortran 2003 supports part of
560the features of @code{ISO_VARYING_STRING} and should be considered as
561replacement. (Namely, allocatable or pointers of the type
562@code{character(len=:)}.)
563
564
565@c =====================================================================
566@c PART I: INVOCATION REFERENCE
567@c =====================================================================
568
569@tex
570\part{I}{Invoking GNU Fortran}
571@end tex
572
573@c ---------------------------------------------------------------------
574@c Compiler Options
575@c ---------------------------------------------------------------------
576
577@include invoke.texi
578
579
580@c ---------------------------------------------------------------------
581@c Runtime
582@c ---------------------------------------------------------------------
583
584@node Runtime
585@chapter Runtime:  Influencing runtime behavior with environment variables
586@cindex environment variable
587
588The behavior of the @command{gfortran} can be influenced by
589environment variables.
590
591Malformed environment variables are silently ignored.
592
593@menu
594* TMPDIR:: Directory for scratch files
595* GFORTRAN_STDIN_UNIT:: Unit number for standard input
596* GFORTRAN_STDOUT_UNIT:: Unit number for standard output
597* GFORTRAN_STDERR_UNIT:: Unit number for standard error
598* GFORTRAN_UNBUFFERED_ALL:: Do not buffer I/O for all units.
599* GFORTRAN_UNBUFFERED_PRECONNECTED:: Do not buffer I/O for preconnected units.
600* GFORTRAN_SHOW_LOCUS::  Show location for runtime errors
601* GFORTRAN_OPTIONAL_PLUS:: Print leading + where permitted
602* GFORTRAN_DEFAULT_RECL:: Default record length for new files
603* GFORTRAN_LIST_SEPARATOR::  Separator for list output
604* GFORTRAN_CONVERT_UNIT::  Set endianness for unformatted I/O
605* GFORTRAN_ERROR_BACKTRACE:: Show backtrace on run-time errors
606@end menu
607
608@node TMPDIR
609@section @env{TMPDIR}---Directory for scratch files
610
611When opening a file with @code{STATUS='SCRATCH'}, GNU Fortran tries to
612create the file in one of the potential directories by testing each
613directory in the order below.
614
615@enumerate
616@item
617The environment variable @env{TMPDIR}, if it exists.
618
619@item
620On the MinGW target, the directory returned by the @code{GetTempPath}
621function. Alternatively, on the Cygwin target, the @env{TMP} and
622@env{TEMP} environment variables, if they exist, in that order.
623
624@item
625The @code{P_tmpdir} macro if it is defined, otherwise the directory
626@file{/tmp}.
627@end enumerate
628
629@node GFORTRAN_STDIN_UNIT
630@section @env{GFORTRAN_STDIN_UNIT}---Unit number for standard input
631
632This environment variable can be used to select the unit number
633preconnected to standard input.  This must be a positive integer.
634The default value is 5.
635
636@node GFORTRAN_STDOUT_UNIT
637@section @env{GFORTRAN_STDOUT_UNIT}---Unit number for standard output
638
639This environment variable can be used to select the unit number
640preconnected to standard output.  This must be a positive integer.
641The default value is 6.
642
643@node GFORTRAN_STDERR_UNIT
644@section @env{GFORTRAN_STDERR_UNIT}---Unit number for standard error
645
646This environment variable can be used to select the unit number
647preconnected to standard error.  This must be a positive integer.
648The default value is 0.
649
650@node GFORTRAN_UNBUFFERED_ALL
651@section @env{GFORTRAN_UNBUFFERED_ALL}---Do not buffer I/O on all units
652
653This environment variable controls whether all I/O is unbuffered.  If
654the first letter is @samp{y}, @samp{Y} or @samp{1}, all I/O is
655unbuffered.  This will slow down small sequential reads and writes.  If
656the first letter is @samp{n}, @samp{N} or @samp{0}, I/O is buffered.
657This is the default.
658
659@node GFORTRAN_UNBUFFERED_PRECONNECTED
660@section @env{GFORTRAN_UNBUFFERED_PRECONNECTED}---Do not buffer I/O on preconnected units
661
662The environment variable named @env{GFORTRAN_UNBUFFERED_PRECONNECTED} controls
663whether I/O on a preconnected unit (i.e.@: STDOUT or STDERR) is unbuffered.  If 
664the first letter is @samp{y}, @samp{Y} or @samp{1}, I/O is unbuffered.  This
665will slow down small sequential reads and writes.  If the first letter
666is @samp{n}, @samp{N} or @samp{0}, I/O is buffered.  This is the default.
667
668@node GFORTRAN_SHOW_LOCUS
669@section @env{GFORTRAN_SHOW_LOCUS}---Show location for runtime errors
670
671If the first letter is @samp{y}, @samp{Y} or @samp{1}, filename and
672line numbers for runtime errors are printed.  If the first letter is
673@samp{n}, @samp{N} or @samp{0}, do not print filename and line numbers
674for runtime errors.  The default is to print the location.
675
676@node GFORTRAN_OPTIONAL_PLUS
677@section @env{GFORTRAN_OPTIONAL_PLUS}---Print leading + where permitted
678
679If the first letter is @samp{y}, @samp{Y} or @samp{1},
680a plus sign is printed
681where permitted by the Fortran standard.  If the first letter
682is @samp{n}, @samp{N} or @samp{0}, a plus sign is not printed
683in most cases.  Default is not to print plus signs.
684
685@node GFORTRAN_DEFAULT_RECL
686@section @env{GFORTRAN_DEFAULT_RECL}---Default record length for new files
687
688This environment variable specifies the default record length, in
689bytes, for files which are opened without a @code{RECL} tag in the
690@code{OPEN} statement.  This must be a positive integer.  The
691default value is 1073741824 bytes (1 GB).
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 2003 and 2008 Status
795@c ---------------------------------------------------------------------
796
797@node Fortran 2003 and 2008 status
798@chapter Fortran 2003 and 2008 Status
799
800@menu
801* Fortran 2003 status::
802* Fortran 2008 status::
803* TS 29113 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 syntax; however, the
891data transfer is currently always synchronously performed. 
892
893@item
894@cindex @code{FLUSH} statement
895@cindex statement, @code{FLUSH}
896@code{FLUSH} statement.
897
898@item
899@cindex @code{IOMSG=} specifier
900@code{IOMSG=} specifier for I/O statements.
901
902@item
903@cindex @code{ENUM} statement
904@cindex @code{ENUMERATOR} statement
905@cindex statement, @code{ENUM}
906@cindex statement, @code{ENUMERATOR}
907@opindex @code{fshort-enums}
908Support for the declaration of enumeration constants via the
909@code{ENUM} and @code{ENUMERATOR} statements.  Interoperability with
910@command{gcc} is guaranteed also for the case where the
911@command{-fshort-enums} command line option is given.
912
913@item
914@cindex TR 15581
915TR 15581:
916@itemize
917@item
918@cindex @code{ALLOCATABLE} dummy arguments
919@code{ALLOCATABLE} dummy arguments.
920@item
921@cindex @code{ALLOCATABLE} function results
922@code{ALLOCATABLE} function results
923@item
924@cindex @code{ALLOCATABLE} components of derived types
925@code{ALLOCATABLE} components of derived types
926@end itemize
927
928@item
929@cindex @code{STREAM} I/O
930@cindex @code{ACCESS='STREAM'} I/O
931The @code{OPEN} statement supports the @code{ACCESS='STREAM'} specifier,
932allowing I/O without any record structure.
933
934@item
935Namelist input/output for internal files.
936
937@item Minor I/O features: Rounding during formatted output, using of
938a decimal comma instead of a decimal point, setting whether a plus sign
939should appear for positive numbers. On systems where @code{strtod} honours
940the rounding mode, the rounding mode is also supported for input.
941
942@item
943@cindex @code{PROTECTED} statement
944@cindex statement, @code{PROTECTED}
945The @code{PROTECTED} statement and attribute.
946
947@item
948@cindex @code{VALUE} statement
949@cindex statement, @code{VALUE}
950The @code{VALUE} statement and attribute.
951
952@item
953@cindex @code{VOLATILE} statement
954@cindex statement, @code{VOLATILE}
955The @code{VOLATILE} statement and attribute.
956
957@item
958@cindex @code{IMPORT} statement
959@cindex statement, @code{IMPORT}
960The @code{IMPORT} statement, allowing to import
961host-associated derived types.
962
963@item The intrinsic modules @code{ISO_FORTRAN_ENVIRONMENT} is supported,
964which contains parameters of the I/O units, storage sizes. Additionally,
965procedures for C interoperability are available in the @code{ISO_C_BINDING}
966module.
967
968@item
969@cindex @code{USE, INTRINSIC} statement
970@cindex statement, @code{USE, INTRINSIC}
971@cindex @code{ISO_FORTRAN_ENV} statement
972@cindex statement, @code{ISO_FORTRAN_ENV}
973@code{USE} statement with @code{INTRINSIC} and @code{NON_INTRINSIC}
974attribute; supported intrinsic modules: @code{ISO_FORTRAN_ENV},
975@code{ISO_C_BINDING}, @code{OMP_LIB} and @code{OMP_LIB_KINDS},
976and @code{OPENACC}.
977
978@item
979Renaming of operators in the @code{USE} statement.
980
981@end itemize
982
983
984@node Fortran 2008 status
985@section Fortran 2008 status
986
987The latest version of the Fortran standard is ISO/IEC 1539-1:2010, informally
988known as Fortran 2008.  The official version is available from International
989Organization for Standardization (ISO) or its national member organizations.
990The the final draft (FDIS) can be downloaded free of charge from
991@url{http://www.nag.co.uk/@/sc22wg5/@/links.html}.  Fortran is developed by the
992Working Group 5 of Sub-Committee 22 of the Joint Technical Committee 1 of the
993International Organization for Standardization and the International
994Electrotechnical Commission (IEC).  This group is known as
995@uref{http://www.nag.co.uk/sc22wg5/, WG5}.
996
997The GNU Fortran compiler supports several of the new features of Fortran 2008;
998the @uref{https://gcc.gnu.org/wiki/Fortran2008Status, wiki} has some information
999about the current Fortran 2008 implementation status.  In particular, the
1000following is implemented.
1001
1002@itemize
1003@item The @option{-std=f2008} option and support for the file extensions 
1004@file{.f08} and @file{.F08}.
1005
1006@item The @code{OPEN} statement now supports the @code{NEWUNIT=} option,
1007which returns a unique file unit, thus preventing inadvertent use of the
1008same unit in different parts of the program.
1009
1010@item The @code{g0} format descriptor and unlimited format items.
1011
1012@item The mathematical intrinsics @code{ASINH}, @code{ACOSH}, @code{ATANH},
1013@code{ERF}, @code{ERFC}, @code{GAMMA}, @code{LOG_GAMMA}, @code{BESSEL_J0},
1014@code{BESSEL_J1}, @code{BESSEL_JN}, @code{BESSEL_Y0}, @code{BESSEL_Y1},
1015@code{BESSEL_YN}, @code{HYPOT}, @code{NORM2}, and @code{ERFC_SCALED}.
1016
1017@item Using complex arguments with @code{TAN}, @code{SINH}, @code{COSH},
1018@code{TANH}, @code{ASIN}, @code{ACOS}, and @code{ATAN} is now possible;
1019@code{ATAN}(@var{Y},@var{X}) is now an alias for @code{ATAN2}(@var{Y},@var{X}).
1020
1021@item Support of the @code{PARITY} intrinsic functions.
1022
1023@item The following bit intrinsics: @code{LEADZ} and @code{TRAILZ} for
1024counting the number of leading and trailing zero bits, @code{POPCNT} and
1025@code{POPPAR} for counting the number of one bits and returning the parity;
1026@code{BGE}, @code{BGT}, @code{BLE}, and @code{BLT} for bitwise comparisons;
1027@code{DSHIFTL} and @code{DSHIFTR} for combined left and right shifts,
1028@code{MASKL} and @code{MASKR} for simple left and right justified masks,
1029@code{MERGE_BITS} for a bitwise merge using a mask, @code{SHIFTA},
1030@code{SHIFTL} and @code{SHIFTR} for shift operations, and the
1031transformational bit intrinsics @code{IALL}, @code{IANY} and @code{IPARITY}.
1032
1033@item Support of the @code{EXECUTE_COMMAND_LINE} intrinsic subroutine.
1034
1035@item Support for the @code{STORAGE_SIZE} intrinsic inquiry function.
1036
1037@item The @code{INT@{8,16,32@}} and @code{REAL@{32,64,128@}} kind type
1038parameters and the array-valued named constants @code{INTEGER_KINDS},
1039@code{LOGICAL_KINDS}, @code{REAL_KINDS} and @code{CHARACTER_KINDS} of
1040the intrinsic module @code{ISO_FORTRAN_ENV}.
1041
1042@item The module procedures @code{C_SIZEOF} of the intrinsic module
1043@code{ISO_C_BINDINGS} and @code{COMPILER_VERSION} and @code{COMPILER_OPTIONS}
1044of @code{ISO_FORTRAN_ENV}.
1045
1046@item Coarray support for serial programs with @option{-fcoarray=single} flag
1047and experimental support for multiple images with the @option{-fcoarray=lib}
1048flag.
1049
1050@item The @code{DO CONCURRENT} construct is supported.
1051
1052@item The @code{BLOCK} construct is supported.
1053
1054@item The @code{STOP} and the new @code{ERROR STOP} statements now
1055support all constant expressions. Both show the signals which were signaling
1056at termination.
1057
1058@item Support for the @code{CONTIGUOUS} attribute.
1059
1060@item Support for @code{ALLOCATE} with @code{MOLD}.
1061
1062@item Support for the @code{IMPURE} attribute for procedures, which
1063allows for @code{ELEMENTAL} procedures without the restrictions of
1064@code{PURE}.
1065
1066@item Null pointers (including @code{NULL()}) and not-allocated variables
1067can be used as actual argument to optional non-pointer, non-allocatable
1068dummy arguments, denoting an absent argument.
1069
1070@item Non-pointer variables with @code{TARGET} attribute can be used as
1071actual argument to @code{POINTER} dummies with @code{INTENT(IN)}.
1072
1073@item Pointers including procedure pointers and those in a derived
1074type (pointer components) can now be initialized by a target instead
1075of only by @code{NULL}.
1076
1077@item The @code{EXIT} statement (with construct-name) can be now be
1078used to leave not only the @code{DO} but also the @code{ASSOCIATE},
1079@code{BLOCK}, @code{IF}, @code{SELECT CASE} and @code{SELECT TYPE}
1080constructs.
1081
1082@item Internal procedures can now be used as actual argument.
1083
1084@item Minor features: obsolesce diagnostics for @code{ENTRY} with
1085@option{-std=f2008}; a line may start with a semicolon; for internal
1086and module procedures @code{END} can be used instead of
1087@code{END SUBROUTINE} and @code{END FUNCTION}; @code{SELECTED_REAL_KIND}
1088now also takes a @code{RADIX} argument; intrinsic types are supported
1089for @code{TYPE}(@var{intrinsic-type-spec}); multiple type-bound procedures
1090can be declared in a single @code{PROCEDURE} statement; implied-shape
1091arrays are supported for named constants (@code{PARAMETER}).
1092@end itemize
1093
1094
1095
1096@node TS 29113 status
1097@section Technical Specification 29113 Status
1098
1099GNU Fortran supports some of the new features of the Technical
1100Specification (TS) 29113 on Further Interoperability of Fortran with C.
1101The @uref{https://gcc.gnu.org/wiki/TS29113Status, wiki} has some information
1102about the current TS 29113 implementation status.  In particular, the
1103following is implemented.
1104
1105See also @ref{Further Interoperability of Fortran with C}.
1106
1107@itemize
1108@item The @option{-std=f2008ts} option.
1109
1110@item The @code{OPTIONAL} attribute is allowed for dummy arguments
1111of @code{BIND(C) procedures.}
1112
1113@item The @code{RANK} intrinsic is supported.
1114
1115@item GNU Fortran's implementation for variables with @code{ASYNCHRONOUS}
1116attribute is compatible with TS 29113.
1117
1118@item Assumed types (@code{TYPE(*)}.
1119
1120@item Assumed-rank (@code{DIMENSION(..)}). However, the array descriptor
1121of the TS is not yet supported.
1122@end itemize
1123
1124
1125
1126@c ---------------------------------------------------------------------
1127@c Compiler Characteristics
1128@c ---------------------------------------------------------------------
1129
1130@node Compiler Characteristics
1131@chapter Compiler Characteristics
1132
1133This chapter describes certain characteristics of the GNU Fortran
1134compiler, that are not specified by the Fortran standard, but which
1135might in some way or another become visible to the programmer.
1136
1137@menu
1138* KIND Type Parameters::
1139* Internal representation of LOGICAL variables::
1140* Thread-safety of the runtime library::
1141* Data consistency and durability::
1142* Files opened without an explicit ACTION= specifier::
1143@end menu
1144
1145
1146@node KIND Type Parameters
1147@section KIND Type Parameters
1148@cindex kind
1149
1150The @code{KIND} type parameters supported by GNU Fortran for the primitive
1151data types are:
1152
1153@table @code
1154
1155@item INTEGER
11561, 2, 4, 8*, 16*, default: 4**
1157
1158@item LOGICAL
11591, 2, 4, 8*, 16*, default: 4**
1160
1161@item REAL
11624, 8, 10*, 16*, default: 4***
1163
1164@item COMPLEX
11654, 8, 10*, 16*, default: 4***
1166
1167@item DOUBLE PRECISION
11684, 8, 10*, 16*, default: 8***
1169
1170@item CHARACTER
11711, 4, default: 1
1172
1173@end table
1174
1175@noindent
1176* not available on all systems @*
1177** unless @option{-fdefault-integer-8} is used @*
1178*** unless @option{-fdefault-real-8} is used (see @ref{Fortran Dialect Options})
1179
1180@noindent
1181The @code{KIND} value matches the storage size in bytes, except for
1182@code{COMPLEX} where the storage size is twice as much (or both real and
1183imaginary part are a real value of the given size).  It is recommended to use
1184the @ref{SELECTED_CHAR_KIND}, @ref{SELECTED_INT_KIND} and
1185@ref{SELECTED_REAL_KIND} intrinsics or the @code{INT8}, @code{INT16},
1186@code{INT32}, @code{INT64}, @code{REAL32}, @code{REAL64}, and @code{REAL128}
1187parameters of the @code{ISO_FORTRAN_ENV} module instead of the concrete values.
1188The available kind parameters can be found in the constant arrays
1189@code{CHARACTER_KINDS}, @code{INTEGER_KINDS}, @code{LOGICAL_KINDS} and
1190@code{REAL_KINDS} in the @ref{ISO_FORTRAN_ENV} module.  For C interoperability,
1191the kind parameters of the @ref{ISO_C_BINDING} module should be used.
1192
1193
1194@node Internal representation of LOGICAL variables
1195@section Internal representation of LOGICAL variables
1196@cindex logical, variable representation
1197
1198The Fortran standard does not specify how variables of @code{LOGICAL}
1199type are represented, beyond requiring that @code{LOGICAL} variables
1200of default kind have the same storage size as default @code{INTEGER}
1201and @code{REAL} variables.  The GNU Fortran internal representation is
1202as follows.
1203
1204A @code{LOGICAL(KIND=N)} variable is represented as an
1205@code{INTEGER(KIND=N)} variable, however, with only two permissible
1206values: @code{1} for @code{.TRUE.} and @code{0} for
1207@code{.FALSE.}.  Any other integer value results in undefined behavior.
1208
1209See also @ref{Argument passing conventions} and @ref{Interoperability with C}.
1210
1211
1212@node Thread-safety of the runtime library
1213@section Thread-safety of the runtime library
1214@cindex thread-safety, threads
1215
1216GNU Fortran can be used in programs with multiple threads, e.g.@: by
1217using OpenMP, by calling OS thread handling functions via the
1218@code{ISO_C_BINDING} facility, or by GNU Fortran compiled library code
1219being called from a multi-threaded program.
1220
1221The GNU Fortran runtime library, (@code{libgfortran}), supports being
1222called concurrently from multiple threads with the following
1223exceptions. 
1224
1225During library initialization, the C @code{getenv} function is used,
1226which need not be thread-safe.  Similarly, the @code{getenv}
1227function is used to implement the @code{GET_ENVIRONMENT_VARIABLE} and
1228@code{GETENV} intrinsics.  It is the responsibility of the user to
1229ensure that the environment is not being updated concurrently when any
1230of these actions are taking place.
1231
1232The @code{EXECUTE_COMMAND_LINE} and @code{SYSTEM} intrinsics are
1233implemented with the @code{system} function, which need not be
1234thread-safe.  It is the responsibility of the user to ensure that
1235@code{system} is not called concurrently.
1236
1237For platforms not supporting thread-safe POSIX functions, further
1238functionality might not be thread-safe.  For details, please consult
1239the documentation for your operating system.
1240
1241The GNU Fortran runtime library uses various C library functions that
1242depend on the locale, such as @code{strtod} and @code{snprintf}.  In
1243order to work correctly in locale-aware programs that set the locale
1244using @code{setlocale}, the locale is reset to the default ``C''
1245locale while executing a formatted @code{READ} or @code{WRITE}
1246statement.  On targets supporting the POSIX 2008 per-thread locale
1247functions (e.g. @code{newlocale}, @code{uselocale},
1248@code{freelocale}), these are used and thus the global locale set
1249using @code{setlocale} or the per-thread locales in other threads are
1250not affected.  However, on targets lacking this functionality, the
1251global LC_NUMERIC locale is set to ``C'' during the formatted I/O.
1252Thus, on such targets it's not safe to call @code{setlocale}
1253concurrently from another thread while a Fortran formatted I/O
1254operation is in progress.  Also, other threads doing something
1255dependent on the LC_NUMERIC locale might not work correctly if a
1256formatted I/O operation is in progress in another thread.
1257
1258@node Data consistency and durability
1259@section Data consistency and durability
1260@cindex consistency, durability
1261
1262This section contains a brief overview of data and metadata
1263consistency and durability issues when doing I/O.
1264
1265With respect to durability, GNU Fortran makes no effort to ensure that
1266data is committed to stable storage. If this is required, the GNU
1267Fortran programmer can use the intrinsic @code{FNUM} to retrieve the
1268low level file descriptor corresponding to an open Fortran unit. Then,
1269using e.g. the @code{ISO_C_BINDING} feature, one can call the
1270underlying system call to flush dirty data to stable storage, such as
1271@code{fsync} on POSIX, @code{_commit} on MingW, or @code{fcntl(fd,
1272F_FULLSYNC, 0)} on Mac OS X. The following example shows how to call
1273fsync:
1274
1275@smallexample
1276  ! Declare the interface for POSIX fsync function
1277  interface
1278    function fsync (fd) bind(c,name="fsync")
1279    use iso_c_binding, only: c_int
1280      integer(c_int), value :: fd
1281      integer(c_int) :: fsync
1282    end function fsync
1283  end interface
1284
1285  ! Variable declaration
1286  integer :: ret
1287
1288  ! Opening unit 10
1289  open (10,file="foo")
1290
1291  ! ...
1292  ! Perform I/O on unit 10
1293  ! ...
1294
1295  ! Flush and sync
1296  flush(10)
1297  ret = fsync(fnum(10))
1298
1299  ! Handle possible error
1300  if (ret /= 0) stop "Error calling FSYNC"
1301@end smallexample
1302
1303With respect to consistency, for regular files GNU Fortran uses
1304buffered I/O in order to improve performance. This buffer is flushed
1305automatically when full and in some other situations, e.g. when
1306closing a unit. It can also be explicitly flushed with the
1307@code{FLUSH} statement. Also, the buffering can be turned off with the
1308@code{GFORTRAN_UNBUFFERED_ALL} and
1309@code{GFORTRAN_UNBUFFERED_PRECONNECTED} environment variables. Special
1310files, such as terminals and pipes, are always unbuffered. Sometimes,
1311however, further things may need to be done in order to allow other
1312processes to see data that GNU Fortran has written, as follows.
1313
1314The Windows platform supports a relaxed metadata consistency model,
1315where file metadata is written to the directory lazily. This means
1316that, for instance, the @code{dir} command can show a stale size for a
1317file. One can force a directory metadata update by closing the unit,
1318or by calling @code{_commit} on the file descriptor. Note, though,
1319that @code{_commit} will force all dirty data to stable storage, which
1320is often a very slow operation.
1321
1322The Network File System (NFS) implements a relaxed consistency model
1323called open-to-close consistency. Closing a file forces dirty data and
1324metadata to be flushed to the server, and opening a file forces the
1325client to contact the server in order to revalidate cached
1326data. @code{fsync} will also force a flush of dirty data and metadata
1327to the server. Similar to @code{open} and @code{close}, acquiring and
1328releasing @code{fcntl} file locks, if the server supports them, will
1329also force cache validation and flushing dirty data and metadata.
1330
1331
1332@node Files opened without an explicit ACTION= specifier
1333@section Files opened without an explicit ACTION= specifier
1334@cindex open, action
1335
1336The Fortran standard says that if an @code{OPEN} statement is executed
1337without an explicit @code{ACTION=} specifier, the default value is
1338processor dependent.  GNU Fortran behaves as follows:
1339
1340@enumerate
1341@item Attempt to open the file with @code{ACTION='READWRITE'}
1342@item If that fails, try to open with @code{ACTION='READ'}
1343@item If that fails, try to open with @code{ACTION='WRITE'}
1344@item If that fails, generate an error
1345@end enumerate
1346
1347
1348@c ---------------------------------------------------------------------
1349@c Extensions
1350@c ---------------------------------------------------------------------
1351
1352@c Maybe this chapter should be merged with the 'Standards' section,
1353@c whenever that is written :-)
1354
1355@node Extensions
1356@chapter Extensions
1357@cindex extensions
1358
1359The two sections below detail the extensions to standard Fortran that are
1360implemented in GNU Fortran, as well as some of the popular or
1361historically important extensions that are not (or not yet) implemented.
1362For the latter case, we explain the alternatives available to GNU Fortran
1363users, including replacement by standard-conforming code or GNU
1364extensions.
1365
1366@menu
1367* Extensions implemented in GNU Fortran::
1368* Extensions not implemented in GNU Fortran::
1369@end menu
1370
1371
1372@node Extensions implemented in GNU Fortran
1373@section Extensions implemented in GNU Fortran
1374@cindex extensions, implemented
1375
1376GNU Fortran implements a number of extensions over standard
1377Fortran.  This chapter contains information on their syntax and
1378meaning.  There are currently two categories of GNU Fortran
1379extensions, those that provide functionality beyond that provided
1380by any standard, and those that are supported by GNU Fortran
1381purely for backward compatibility with legacy compilers.  By default,
1382@option{-std=gnu} allows the compiler to accept both types of
1383extensions, but to warn about the use of the latter.  Specifying
1384either @option{-std=f95}, @option{-std=f2003} or @option{-std=f2008}
1385disables both types of extensions, and @option{-std=legacy} allows both
1386without warning.
1387
1388@menu
1389* Old-style kind specifications::
1390* Old-style variable initialization::
1391* Extensions to namelist::
1392* X format descriptor without count field::
1393* Commas in FORMAT specifications::
1394* Missing period in FORMAT specifications::
1395* I/O item lists::
1396* @code{Q} exponent-letter::
1397* BOZ literal constants::
1398* Real array indices::
1399* Unary operators::
1400* Implicitly convert LOGICAL and INTEGER values::
1401* Hollerith constants support::
1402* Cray pointers::
1403* CONVERT specifier::
1404* OpenMP::
1405* OpenACC::
1406* Argument list functions::
1407* Read/Write after EOF marker::
1408@end menu
1409
1410@node Old-style kind specifications
1411@subsection Old-style kind specifications
1412@cindex kind, old-style
1413
1414GNU Fortran allows old-style kind specifications in declarations.  These
1415look like:
1416@smallexample
1417      TYPESPEC*size x,y,z
1418@end smallexample
1419@noindent
1420where @code{TYPESPEC} is a basic type (@code{INTEGER}, @code{REAL},
1421etc.), and where @code{size} is a byte count corresponding to the
1422storage size of a valid kind for that type.  (For @code{COMPLEX}
1423variables, @code{size} is the total size of the real and imaginary
1424parts.)  The statement then declares @code{x}, @code{y} and @code{z} to
1425be of type @code{TYPESPEC} with the appropriate kind.  This is
1426equivalent to the standard-conforming declaration
1427@smallexample
1428      TYPESPEC(k) x,y,z
1429@end smallexample
1430@noindent
1431where @code{k} is the kind parameter suitable for the intended precision.  As
1432kind parameters are implementation-dependent, use the @code{KIND},
1433@code{SELECTED_INT_KIND} and @code{SELECTED_REAL_KIND} intrinsics to retrieve
1434the correct value, for instance @code{REAL*8 x} can be replaced by:
1435@smallexample
1436INTEGER, PARAMETER :: dbl = KIND(1.0d0)
1437REAL(KIND=dbl) :: x
1438@end smallexample
1439
1440@node Old-style variable initialization
1441@subsection Old-style variable initialization
1442
1443GNU Fortran allows old-style initialization of variables of the
1444form:
1445@smallexample
1446      INTEGER i/1/,j/2/
1447      REAL x(2,2) /3*0.,1./
1448@end smallexample
1449The syntax for the initializers is as for the @code{DATA} statement, but
1450unlike in a @code{DATA} statement, an initializer only applies to the
1451variable immediately preceding the initialization.  In other words,
1452something like @code{INTEGER I,J/2,3/} is not valid.  This style of
1453initialization is only allowed in declarations without double colons
1454(@code{::}); the double colons were introduced in Fortran 90, which also
1455introduced a standard syntax for initializing variables in type
1456declarations.
1457
1458Examples of standard-conforming code equivalent to the above example
1459are:
1460@smallexample
1461! Fortran 90
1462      INTEGER :: i = 1, j = 2
1463      REAL :: x(2,2) = RESHAPE((/0.,0.,0.,1./),SHAPE(x))
1464! Fortran 77
1465      INTEGER i, j
1466      REAL x(2,2)
1467      DATA i/1/, j/2/, x/3*0.,1./
1468@end smallexample
1469
1470Note that variables which are explicitly initialized in declarations
1471or in @code{DATA} statements automatically acquire the @code{SAVE}
1472attribute.
1473
1474@node Extensions to namelist
1475@subsection Extensions to namelist
1476@cindex Namelist
1477
1478GNU Fortran fully supports the Fortran 95 standard for namelist I/O
1479including array qualifiers, substrings and fully qualified derived types.
1480The output from a namelist write is compatible with namelist read.  The
1481output has all names in upper case and indentation to column 1 after the
1482namelist name.  Two extensions are permitted:
1483
1484Old-style use of @samp{$} instead of @samp{&}
1485@smallexample
1486$MYNML
1487 X(:)%Y(2) = 1.0 2.0 3.0
1488 CH(1:4) = "abcd"
1489$END
1490@end smallexample
1491
1492It should be noted that the default terminator is @samp{/} rather than
1493@samp{&END}.
1494
1495Querying of the namelist when inputting from stdin.  After at least
1496one space, entering @samp{?} sends to stdout the namelist name and the names of
1497the variables in the namelist:
1498@smallexample
1499 ?
1500
1501&mynml
1502 x
1503 x%y
1504 ch
1505&end
1506@end smallexample
1507
1508Entering @samp{=?} outputs the namelist to stdout, as if
1509@code{WRITE(*,NML = mynml)} had been called:
1510@smallexample
1511=?
1512
1513&MYNML
1514 X(1)%Y=  0.000000    ,  1.000000    ,  0.000000    ,
1515 X(2)%Y=  0.000000    ,  2.000000    ,  0.000000    ,
1516 X(3)%Y=  0.000000    ,  3.000000    ,  0.000000    ,
1517 CH=abcd,  /
1518@end smallexample
1519
1520To aid this dialog, when input is from stdin, errors send their
1521messages to stderr and execution continues, even if @code{IOSTAT} is set.
1522
1523@code{PRINT} namelist is permitted.  This causes an error if
1524@option{-std=f95} is used.
1525@smallexample
1526PROGRAM test_print
1527  REAL, dimension (4)  ::  x = (/1.0, 2.0, 3.0, 4.0/)
1528  NAMELIST /mynml/ x
1529  PRINT mynml
1530END PROGRAM test_print
1531@end smallexample
1532
1533Expanded namelist reads are permitted.  This causes an error if 
1534@option{-std=f95} is used.  In the following example, the first element
1535of the array will be given the value 0.00 and the two succeeding
1536elements will be given the values 1.00 and 2.00.
1537@smallexample
1538&MYNML
1539  X(1,1) = 0.00 , 1.00 , 2.00
1540/
1541@end smallexample
1542
1543When writing a namelist, if no @code{DELIM=} is specified, by default a
1544double quote is used to delimit character strings. If -std=F95, F2003,
1545or F2008, etc, the delim status is set to 'none'.  Defaulting to
1546quotes ensures that namelists with character strings can be subsequently
1547read back in accurately.
1548
1549@node X format descriptor without count field
1550@subsection @code{X} format descriptor without count field
1551
1552To support legacy codes, GNU Fortran permits the count field of the
1553@code{X} edit descriptor in @code{FORMAT} statements to be omitted.
1554When omitted, the count is implicitly assumed to be one.
1555
1556@smallexample
1557       PRINT 10, 2, 3
155810     FORMAT (I1, X, I1)
1559@end smallexample
1560
1561@node Commas in FORMAT specifications
1562@subsection Commas in @code{FORMAT} specifications
1563
1564To support legacy codes, GNU Fortran allows the comma separator
1565to be omitted immediately before and after character string edit
1566descriptors in @code{FORMAT} statements.
1567
1568@smallexample
1569       PRINT 10, 2, 3
157010     FORMAT ('FOO='I1' BAR='I2)
1571@end smallexample
1572
1573
1574@node Missing period in FORMAT specifications
1575@subsection Missing period in @code{FORMAT} specifications
1576
1577To support legacy codes, GNU Fortran allows missing periods in format
1578specifications if and only if @option{-std=legacy} is given on the
1579command line.  This is considered non-conforming code and is
1580discouraged.
1581
1582@smallexample
1583       REAL :: value
1584       READ(*,10) value
158510     FORMAT ('F4')
1586@end smallexample
1587
1588@node I/O item lists
1589@subsection I/O item lists
1590@cindex I/O item lists
1591
1592To support legacy codes, GNU Fortran allows the input item list
1593of the @code{READ} statement, and the output item lists of the
1594@code{WRITE} and @code{PRINT} statements, to start with a comma.
1595
1596@node @code{Q} exponent-letter
1597@subsection @code{Q} exponent-letter
1598@cindex @code{Q} exponent-letter
1599
1600GNU Fortran accepts real literal constants with an exponent-letter
1601of @code{Q}, for example, @code{1.23Q45}.  The constant is interpreted
1602as a @code{REAL(16)} entity on targets that support this type.  If
1603the target does not support @code{REAL(16)} but has a @code{REAL(10)}
1604type, then the real-literal-constant will be interpreted as a
1605@code{REAL(10)} entity.  In the absence of @code{REAL(16)} and
1606@code{REAL(10)}, an error will occur.
1607
1608@node BOZ literal constants
1609@subsection BOZ literal constants
1610@cindex BOZ literal constants
1611
1612Besides decimal constants, Fortran also supports binary (@code{b}),
1613octal (@code{o}) and hexadecimal (@code{z}) integer constants.  The
1614syntax is: @samp{prefix quote digits quote}, were the prefix is
1615either @code{b}, @code{o} or @code{z}, quote is either @code{'} or
1616@code{"} and the digits are for binary @code{0} or @code{1}, for
1617octal between @code{0} and @code{7}, and for hexadecimal between
1618@code{0} and @code{F}.  (Example: @code{b'01011101'}.)
1619
1620Up to Fortran 95, BOZ literals were only allowed to initialize
1621integer variables in DATA statements.  Since Fortran 2003 BOZ literals
1622are also allowed as argument of @code{REAL}, @code{DBLE}, @code{INT}
1623and @code{CMPLX}; the result is the same as if the integer BOZ
1624literal had been converted by @code{TRANSFER} to, respectively,
1625@code{real}, @code{double precision}, @code{integer} or @code{complex}.
1626As GNU Fortran extension the intrinsic procedures @code{FLOAT},
1627@code{DFLOAT}, @code{COMPLEX} and @code{DCMPLX} are treated alike.
1628
1629As an extension, GNU Fortran allows hexadecimal BOZ literal constants to
1630be specified using the @code{X} prefix, in addition to the standard
1631@code{Z} prefix.  The BOZ literal can also be specified by adding a
1632suffix to the string, for example, @code{Z'ABC'} and @code{'ABC'Z} are
1633equivalent.
1634
1635Furthermore, GNU Fortran allows using BOZ literal constants outside
1636DATA statements and the four intrinsic functions allowed by Fortran 2003.
1637In DATA statements, in direct assignments, where the right-hand side
1638only contains a BOZ literal constant, and for old-style initializers of
1639the form @code{integer i /o'0173'/}, the constant is transferred
1640as if @code{TRANSFER} had been used; for @code{COMPLEX} numbers, only
1641the real part is initialized unless @code{CMPLX} is used.  In all other
1642cases, the BOZ literal constant is converted to an @code{INTEGER} value with
1643the largest decimal representation.  This value is then converted
1644numerically to the type and kind of the variable in question.
1645(For instance, @code{real :: r = b'0000001' + 1} initializes @code{r}
1646with @code{2.0}.) As different compilers implement the extension
1647differently, one should be careful when doing bitwise initialization
1648of non-integer variables.
1649
1650Note that initializing an @code{INTEGER} variable with a statement such
1651as @code{DATA i/Z'FFFFFFFF'/} will give an integer overflow error rather
1652than the desired result of @math{-1} when @code{i} is a 32-bit integer
1653on a system that supports 64-bit integers.  The @samp{-fno-range-check}
1654option can be used as a workaround for legacy code that initializes
1655integers in this manner.
1656
1657@node Real array indices
1658@subsection Real array indices
1659@cindex array, indices of type real
1660
1661As an extension, GNU Fortran allows the use of @code{REAL} expressions
1662or variables as array indices.
1663
1664@node Unary operators
1665@subsection Unary operators
1666@cindex operators, unary
1667
1668As an extension, GNU Fortran allows unary plus and unary minus operators
1669to appear as the second operand of binary arithmetic operators without
1670the need for parenthesis.
1671
1672@smallexample
1673       X = Y * -Z
1674@end smallexample
1675
1676@node Implicitly convert LOGICAL and INTEGER values
1677@subsection Implicitly convert @code{LOGICAL} and @code{INTEGER} values
1678@cindex conversion, to integer
1679@cindex conversion, to logical
1680
1681As an extension for backwards compatibility with other compilers, GNU
1682Fortran allows the implicit conversion of @code{LOGICAL} values to
1683@code{INTEGER} values and vice versa.  When converting from a
1684@code{LOGICAL} to an @code{INTEGER}, @code{.FALSE.} is interpreted as
1685zero, and @code{.TRUE.} is interpreted as one.  When converting from
1686@code{INTEGER} to @code{LOGICAL}, the value zero is interpreted as
1687@code{.FALSE.} and any nonzero value is interpreted as @code{.TRUE.}.
1688
1689@smallexample
1690        LOGICAL :: l
1691        l = 1
1692@end smallexample
1693@smallexample
1694        INTEGER :: i
1695        i = .TRUE.
1696@end smallexample
1697
1698However, there is no implicit conversion of @code{INTEGER} values in
1699@code{if}-statements, nor of @code{LOGICAL} or @code{INTEGER} values
1700in I/O operations.
1701
1702@node Hollerith constants support
1703@subsection Hollerith constants support
1704@cindex Hollerith constants
1705
1706GNU Fortran supports Hollerith constants in assignments, function
1707arguments, and @code{DATA} and @code{ASSIGN} statements.  A Hollerith
1708constant is written as a string of characters preceded by an integer
1709constant indicating the character count, and the letter @code{H} or
1710@code{h}, and stored in bytewise fashion in a numeric (@code{INTEGER},
1711@code{REAL}, or @code{complex}) or @code{LOGICAL} variable.  The
1712constant will be padded or truncated to fit the size of the variable in
1713which it is stored.
1714
1715Examples of valid uses of Hollerith constants:
1716@smallexample
1717      complex*16 x(2)
1718      data x /16Habcdefghijklmnop, 16Hqrstuvwxyz012345/
1719      x(1) = 16HABCDEFGHIJKLMNOP
1720      call foo (4h abc)
1721@end smallexample
1722
1723Invalid Hollerith constants examples:
1724@smallexample
1725      integer*4 a
1726      a = 8H12345678 ! Valid, but the Hollerith constant will be truncated.
1727      a = 0H         ! At least one character is needed.
1728@end smallexample
1729
1730In general, Hollerith constants were used to provide a rudimentary
1731facility for handling character strings in early Fortran compilers,
1732prior to the introduction of @code{CHARACTER} variables in Fortran 77;
1733in those cases, the standard-compliant equivalent is to convert the
1734program to use proper character strings.  On occasion, there may be a
1735case where the intent is specifically to initialize a numeric variable
1736with a given byte sequence.  In these cases, the same result can be
1737obtained by using the @code{TRANSFER} statement, as in this example.
1738@smallexample
1739      INTEGER(KIND=4) :: a
1740      a = TRANSFER ("abcd", a)     ! equivalent to: a = 4Habcd
1741@end smallexample
1742
1743
1744@node Cray pointers
1745@subsection Cray pointers
1746@cindex pointer, Cray
1747
1748Cray pointers are part of a non-standard extension that provides a
1749C-like pointer in Fortran.  This is accomplished through a pair of
1750variables: an integer "pointer" that holds a memory address, and a
1751"pointee" that is used to dereference the pointer.
1752
1753Pointer/pointee pairs are declared in statements of the form:
1754@smallexample
1755        pointer ( <pointer> , <pointee> )
1756@end smallexample
1757or,
1758@smallexample
1759        pointer ( <pointer1> , <pointee1> ), ( <pointer2> , <pointee2> ), ...
1760@end smallexample
1761The pointer is an integer that is intended to hold a memory address.
1762The pointee may be an array or scalar.  A pointee can be an assumed
1763size array---that is, the last dimension may be left unspecified by
1764using a @code{*} in place of a value---but a pointee cannot be an
1765assumed shape array.  No space is allocated for the pointee.
1766
1767The pointee may have its type declared before or after the pointer
1768statement, and its array specification (if any) may be declared
1769before, during, or after the pointer statement.  The pointer may be
1770declared as an integer prior to the pointer statement.  However, some
1771machines have default integer sizes that are different than the size
1772of a pointer, and so the following code is not portable:
1773@smallexample
1774        integer ipt
1775        pointer (ipt, iarr)
1776@end smallexample
1777If a pointer is declared with a kind that is too small, the compiler
1778will issue a warning; the resulting binary will probably not work
1779correctly, because the memory addresses stored in the pointers may be
1780truncated.  It is safer to omit the first line of the above example;
1781if explicit declaration of ipt's type is omitted, then the compiler
1782will ensure that ipt is an integer variable large enough to hold a
1783pointer.
1784
1785Pointer arithmetic is valid with Cray pointers, but it is not the same
1786as C pointer arithmetic.  Cray pointers are just ordinary integers, so
1787the user is responsible for determining how many bytes to add to a
1788pointer in order to increment it.  Consider the following example:
1789@smallexample
1790        real target(10)
1791        real pointee(10)
1792        pointer (ipt, pointee)
1793        ipt = loc (target)
1794        ipt = ipt + 1       
1795@end smallexample
1796The last statement does not set @code{ipt} to the address of
1797@code{target(1)}, as it would in C pointer arithmetic.  Adding @code{1}
1798to @code{ipt} just adds one byte to the address stored in @code{ipt}.
1799
1800Any expression involving the pointee will be translated to use the
1801value stored in the pointer as the base address.
1802
1803To get the address of elements, this extension provides an intrinsic
1804function @code{LOC()}.  The @code{LOC()} function is equivalent to the
1805@code{&} operator in C, except the address is cast to an integer type:
1806@smallexample
1807        real ar(10)
1808        pointer(ipt, arpte(10))
1809        real arpte
1810        ipt = loc(ar)  ! Makes arpte is an alias for ar
1811        arpte(1) = 1.0 ! Sets ar(1) to 1.0
1812@end smallexample
1813The pointer can also be set by a call to the @code{MALLOC} intrinsic
1814(see @ref{MALLOC}).
1815
1816Cray pointees often are used to alias an existing variable.  For
1817example:
1818@smallexample
1819        integer target(10)
1820        integer iarr(10)
1821        pointer (ipt, iarr)
1822        ipt = loc(target)
1823@end smallexample
1824As long as @code{ipt} remains unchanged, @code{iarr} is now an alias for
1825@code{target}.  The optimizer, however, will not detect this aliasing, so
1826it is unsafe to use @code{iarr} and @code{target} simultaneously.  Using
1827a pointee in any way that violates the Fortran aliasing rules or
1828assumptions is illegal.  It is the user's responsibility to avoid doing
1829this; the compiler works under the assumption that no such aliasing
1830occurs.
1831
1832Cray pointers will work correctly when there is no aliasing (i.e., when
1833they are used to access a dynamically allocated block of memory), and
1834also in any routine where a pointee is used, but any variable with which
1835it shares storage is not used.  Code that violates these rules may not
1836run as the user intends.  This is not a bug in the optimizer; any code
1837that violates the aliasing rules is illegal.  (Note that this is not
1838unique to GNU Fortran; any Fortran compiler that supports Cray pointers
1839will ``incorrectly'' optimize code with illegal aliasing.)
1840
1841There are a number of restrictions on the attributes that can be applied
1842to Cray pointers and pointees.  Pointees may not have the
1843@code{ALLOCATABLE}, @code{INTENT}, @code{OPTIONAL}, @code{DUMMY},
1844@code{TARGET}, @code{INTRINSIC}, or @code{POINTER} attributes.  Pointers
1845may not have the @code{DIMENSION}, @code{POINTER}, @code{TARGET},
1846@code{ALLOCATABLE}, @code{EXTERNAL}, or @code{INTRINSIC} attributes, nor
1847may they be function results.  Pointees may not occur in more than one
1848pointer statement.  A pointee cannot be a pointer.  Pointees cannot occur
1849in equivalence, common, or data statements.
1850
1851A Cray pointer may also point to a function or a subroutine.  For
1852example, the following excerpt is valid:
1853@smallexample
1854  implicit none
1855  external sub
1856  pointer (subptr,subpte)
1857  external subpte
1858  subptr = loc(sub)
1859  call subpte()
1860  [...]
1861  subroutine sub
1862  [...]
1863  end subroutine sub
1864@end smallexample
1865
1866A pointer may be modified during the course of a program, and this
1867will change the location to which the pointee refers.  However, when
1868pointees are passed as arguments, they are treated as ordinary
1869variables in the invoked function.  Subsequent changes to the pointer
1870will not change the base address of the array that was passed.
1871
1872@node CONVERT specifier
1873@subsection @code{CONVERT} specifier
1874@cindex @code{CONVERT} specifier
1875
1876GNU Fortran allows the conversion of unformatted data between little-
1877and big-endian representation to facilitate moving of data
1878between different systems.  The conversion can be indicated with
1879the @code{CONVERT} specifier on the @code{OPEN} statement.
1880@xref{GFORTRAN_CONVERT_UNIT}, for an alternative way of specifying
1881the data format via an environment variable.
1882
1883Valid values for @code{CONVERT} are:
1884@itemize @w{}
1885@item @code{CONVERT='NATIVE'} Use the native format.  This is the default.
1886@item @code{CONVERT='SWAP'} Swap between little- and big-endian.
1887@item @code{CONVERT='LITTLE_ENDIAN'} Use the little-endian representation
1888for unformatted files.
1889@item @code{CONVERT='BIG_ENDIAN'} Use the big-endian representation for
1890unformatted files.
1891@end itemize
1892
1893Using the option could look like this:
1894@smallexample
1895  open(file='big.dat',form='unformatted',access='sequential', &
1896       convert='big_endian')
1897@end smallexample
1898
1899The value of the conversion can be queried by using
1900@code{INQUIRE(CONVERT=ch)}.  The values returned are
1901@code{'BIG_ENDIAN'} and @code{'LITTLE_ENDIAN'}.
1902
1903@code{CONVERT} works between big- and little-endian for
1904@code{INTEGER} values of all supported kinds and for @code{REAL}
1905on IEEE systems of kinds 4 and 8.  Conversion between different
1906``extended double'' types on different architectures such as
1907m68k and x86_64, which GNU Fortran
1908supports as @code{REAL(KIND=10)} and @code{REAL(KIND=16)}, will
1909probably not work.
1910
1911@emph{Note that the values specified via the GFORTRAN_CONVERT_UNIT
1912environment variable will override the CONVERT specifier in the
1913open statement}.  This is to give control over data formats to
1914users who do not have the source code of their program available.
1915
1916Using anything but the native representation for unformatted data
1917carries a significant speed overhead.  If speed in this area matters
1918to you, it is best if you use this only for data that needs to be
1919portable.
1920
1921@node OpenMP
1922@subsection OpenMP
1923@cindex OpenMP
1924
1925OpenMP (Open Multi-Processing) is an application programming
1926interface (API) that supports multi-platform shared memory 
1927multiprocessing programming in C/C++ and Fortran on many 
1928architectures, including Unix and Microsoft Windows platforms.
1929It consists of a set of compiler directives, library routines,
1930and environment variables that influence run-time behavior.
1931
1932GNU Fortran strives to be compatible to the 
1933@uref{http://openmp.org/wp/openmp-specifications/,
1934OpenMP Application Program Interface v4.0}.
1935
1936To enable the processing of the OpenMP directive @code{!$omp} in
1937free-form source code; the @code{c$omp}, @code{*$omp} and @code{!$omp}
1938directives in fixed form; the @code{!$} conditional compilation sentinels
1939in free form; and the @code{c$}, @code{*$} and @code{!$} sentinels
1940in fixed form, @command{gfortran} needs to be invoked with the
1941@option{-fopenmp}.  This also arranges for automatic linking of the
1942GNU Offloading and Multi Processing Runtime Library
1943@ref{Top,,libgomp,libgomp,GNU Offloading and Multi Processing Runtime
1944Library}.
1945
1946The OpenMP Fortran runtime library routines are provided both in a
1947form of a Fortran 90 module named @code{omp_lib} and in a form of
1948a Fortran @code{include} file named @file{omp_lib.h}.
1949
1950An example of a parallelized loop taken from Appendix A.1 of
1951the OpenMP Application Program Interface v2.5:
1952@smallexample
1953SUBROUTINE A1(N, A, B)
1954  INTEGER I, N
1955  REAL B(N), A(N)
1956!$OMP PARALLEL DO !I is private by default
1957  DO I=2,N
1958    B(I) = (A(I) + A(I-1)) / 2.0
1959  ENDDO
1960!$OMP END PARALLEL DO
1961END SUBROUTINE A1
1962@end smallexample
1963
1964Please note:
1965@itemize
1966@item
1967@option{-fopenmp} implies @option{-frecursive}, i.e., all local arrays
1968will be allocated on the stack.  When porting existing code to OpenMP,
1969this may lead to surprising results, especially to segmentation faults
1970if the stacksize is limited.
1971
1972@item
1973On glibc-based systems, OpenMP enabled applications cannot be statically
1974linked due to limitations of the underlying pthreads-implementation.  It
1975might be possible to get a working solution if 
1976@command{-Wl,--whole-archive -lpthread -Wl,--no-whole-archive} is added
1977to the command line.  However, this is not supported by @command{gcc} and
1978thus not recommended.
1979@end itemize
1980
1981@node OpenACC
1982@subsection OpenACC
1983@cindex OpenACC
1984
1985OpenACC is an application programming interface (API) that supports
1986offloading of code to accelerator devices.  It consists of a set of
1987compiler directives, library routines, and environment variables that
1988influence run-time behavior.
1989
1990GNU Fortran strives to be compatible to the
1991@uref{http://www.openacc.org/, OpenACC Application Programming
1992Interface v2.0}.
1993
1994To enable the processing of the OpenACC directive @code{!$acc} in
1995free-form source code; the @code{c$acc}, @code{*$acc} and @code{!$acc}
1996directives in fixed form; the @code{!$} conditional compilation
1997sentinels in free form; and the @code{c$}, @code{*$} and @code{!$}
1998sentinels in fixed form, @command{gfortran} needs to be invoked with
1999the @option{-fopenacc}.  This also arranges for automatic linking of
2000the GNU Offloading and Multi Processing Runtime Library
2001@ref{Top,,libgomp,libgomp,GNU Offloading and Multi Processing Runtime
2002Library}.
2003
2004The OpenACC Fortran runtime library routines are provided both in a
2005form of a Fortran 90 module named @code{openacc} and in a form of a
2006Fortran @code{include} file named @file{openacc_lib.h}.
2007
2008Note that this is an experimental feature, incomplete, and subject to
2009change in future versions of GCC.  See
2010@uref{https://gcc.gnu.org/wiki/OpenACC} for more information.
2011
2012@node Argument list functions
2013@subsection Argument list functions @code{%VAL}, @code{%REF} and @code{%LOC}
2014@cindex argument list functions
2015@cindex @code{%VAL}
2016@cindex @code{%REF}
2017@cindex @code{%LOC}
2018
2019GNU Fortran supports argument list functions @code{%VAL}, @code{%REF} 
2020and @code{%LOC} statements, for backward compatibility with g77. 
2021It is recommended that these should be used only for code that is 
2022accessing facilities outside of GNU Fortran, such as operating system 
2023or windowing facilities.  It is best to constrain such uses to isolated 
2024portions of a program--portions that deal specifically and exclusively 
2025with low-level, system-dependent facilities.  Such portions might well 
2026provide a portable interface for use by the program as a whole, but are 
2027themselves not portable, and should be thoroughly tested each time they 
2028are rebuilt using a new compiler or version of a compiler.
2029
2030@code{%VAL} passes a scalar argument by value, @code{%REF} passes it by 
2031reference and @code{%LOC} passes its memory location.  Since gfortran 
2032already passes scalar arguments by reference, @code{%REF} is in effect 
2033a do-nothing.  @code{%LOC} has the same effect as a Fortran pointer.
2034
2035An example of passing an argument by value to a C subroutine foo.:
2036@smallexample
2037C
2038C prototype      void foo_ (float x);
2039C
2040      external foo
2041      real*4 x
2042      x = 3.14159
2043      call foo (%VAL (x))
2044      end
2045@end smallexample
2046
2047For details refer to the g77 manual
2048@uref{https://gcc.gnu.org/@/onlinedocs/@/gcc-3.4.6/@/g77/@/index.html#Top}.
2049
2050Also, @code{c_by_val.f} and its partner @code{c_by_val.c} of the
2051GNU Fortran testsuite are worth a look.
2052
2053@node Read/Write after EOF marker
2054@subsection Read/Write after EOF marker
2055@cindex @code{EOF}
2056@cindex @code{BACKSPACE}
2057@cindex @code{REWIND}
2058
2059Some legacy codes rely on allowing @code{READ} or @code{WRITE} after the
2060EOF file marker in order to find the end of a file. GNU Fortran normally
2061rejects these codes with a run-time error message and suggests the user
2062consider @code{BACKSPACE} or @code{REWIND} to properly position
2063the file before the EOF marker.  As an extension, the run-time error may
2064be disabled using -std=legacy.
2065
2066@node Extensions not implemented in GNU Fortran
2067@section Extensions not implemented in GNU Fortran
2068@cindex extensions, not implemented
2069
2070The long history of the Fortran language, its wide use and broad
2071userbase, the large number of different compiler vendors and the lack of
2072some features crucial to users in the first standards have lead to the
2073existence of a number of important extensions to the language.  While
2074some of the most useful or popular extensions are supported by the GNU
2075Fortran compiler, not all existing extensions are supported.  This section
2076aims at listing these extensions and offering advice on how best make
2077code that uses them running with the GNU Fortran compiler.
2078
2079@c More can be found here:
2080@c   -- https://gcc.gnu.org/onlinedocs/gcc-3.4.6/g77/Missing-Features.html
2081@c   -- the list of Fortran and libgfortran bugs closed as WONTFIX:
2082@c      http://tinyurl.com/2u4h5y
2083
2084@menu
2085* STRUCTURE and RECORD::
2086@c * UNION and MAP::
2087* ENCODE and DECODE statements::
2088* Variable FORMAT expressions::
2089@c * Q edit descriptor::
2090@c * AUTOMATIC statement::
2091@c * TYPE and ACCEPT I/O Statements::
2092@c * .XOR. operator::
2093@c * CARRIAGECONTROL, DEFAULTFILE, DISPOSE and RECORDTYPE I/O specifiers::
2094@c * Omitted arguments in procedure call::
2095* Alternate complex function syntax::
2096* Volatile COMMON blocks::
2097@end menu
2098
2099
2100@node STRUCTURE and RECORD
2101@subsection @code{STRUCTURE} and @code{RECORD}
2102@cindex @code{STRUCTURE}
2103@cindex @code{RECORD}
2104
2105Record structures are a pre-Fortran-90 vendor extension to create
2106user-defined aggregate data types.  GNU Fortran does not support
2107record structures, only Fortran 90's ``derived types'', which have
2108a different syntax.
2109
2110In many cases, record structures can easily be converted to derived types.
2111To convert, replace @code{STRUCTURE /}@var{structure-name}@code{/}
2112by @code{TYPE} @var{type-name}.  Additionally, replace
2113@code{RECORD /}@var{structure-name}@code{/} by
2114@code{TYPE(}@var{type-name}@code{)}. Finally, in the component access,
2115replace the period (@code{.}) by the percent sign (@code{%}).
2116
2117Here is an example of code using the non portable record structure syntax:
2118
2119@example
2120! Declaring a structure named ``item'' and containing three fields:
2121! an integer ID, an description string and a floating-point price.
2122STRUCTURE /item/
2123  INTEGER id
2124  CHARACTER(LEN=200) description
2125  REAL price
2126END STRUCTURE
2127
2128! Define two variables, an single record of type ``item''
2129! named ``pear'', and an array of items named ``store_catalog''
2130RECORD /item/ pear, store_catalog(100)
2131
2132! We can directly access the fields of both variables
2133pear.id = 92316
2134pear.description = "juicy D'Anjou pear"
2135pear.price = 0.15
2136store_catalog(7).id = 7831
2137store_catalog(7).description = "milk bottle"
2138store_catalog(7).price = 1.2
2139
2140! We can also manipulate the whole structure
2141store_catalog(12) = pear
2142print *, store_catalog(12)
2143@end example
2144
2145@noindent
2146This code can easily be rewritten in the Fortran 90 syntax as following:
2147
2148@example
2149! ``STRUCTURE /name/ ... END STRUCTURE'' becomes
2150! ``TYPE name ... END TYPE''
2151TYPE item
2152  INTEGER id
2153  CHARACTER(LEN=200) description
2154  REAL price
2155END TYPE
2156
2157! ``RECORD /name/ variable'' becomes ``TYPE(name) variable''
2158TYPE(item) pear, store_catalog(100)
2159
2160! Instead of using a dot (.) to access fields of a record, the
2161! standard syntax uses a percent sign (%)
2162pear%id = 92316
2163pear%description = "juicy D'Anjou pear"
2164pear%price = 0.15
2165store_catalog(7)%id = 7831
2166store_catalog(7)%description = "milk bottle"
2167store_catalog(7)%price = 1.2
2168
2169! Assignments of a whole variable do not change
2170store_catalog(12) = pear
2171print *, store_catalog(12)
2172@end example
2173
2174
2175@c @node UNION and MAP
2176@c @subsection @code{UNION} and @code{MAP}
2177@c @cindex @code{UNION}
2178@c @cindex @code{MAP}
2179@c
2180@c For help writing this one, see
2181@c http://www.eng.umd.edu/~nsw/ench250/fortran1.htm#UNION and
2182@c http://www.tacc.utexas.edu/services/userguides/pgi/pgiws_ug/pgi32u06.htm
2183
2184
2185@node ENCODE and DECODE statements
2186@subsection @code{ENCODE} and @code{DECODE} statements
2187@cindex @code{ENCODE}
2188@cindex @code{DECODE}
2189
2190GNU Fortran does not support the @code{ENCODE} and @code{DECODE}
2191statements.  These statements are best replaced by @code{READ} and
2192@code{WRITE} statements involving internal files (@code{CHARACTER}
2193variables and arrays), which have been part of the Fortran standard since
2194Fortran 77.  For example, replace a code fragment like
2195
2196@smallexample
2197      INTEGER*1 LINE(80)
2198      REAL A, B, C
2199c     ... Code that sets LINE
2200      DECODE (80, 9000, LINE) A, B, C
2201 9000 FORMAT (1X, 3(F10.5))
2202@end smallexample
2203
2204@noindent
2205with the following:
2206
2207@smallexample
2208      CHARACTER(LEN=80) LINE
2209      REAL A, B, C
2210c     ... Code that sets LINE
2211      READ (UNIT=LINE, FMT=9000) A, B, C
2212 9000 FORMAT (1X, 3(F10.5))
2213@end smallexample
2214
2215Similarly, replace a code fragment like
2216
2217@smallexample
2218      INTEGER*1 LINE(80)
2219      REAL A, B, C
2220c     ... Code that sets A, B and C
2221      ENCODE (80, 9000, LINE) A, B, C
2222 9000 FORMAT (1X, 'OUTPUT IS ', 3(F10.5))
2223@end smallexample
2224
2225@noindent
2226with the following:
2227
2228@smallexample
2229      CHARACTER(LEN=80) LINE
2230      REAL A, B, C
2231c     ... Code that sets A, B and C
2232      WRITE (UNIT=LINE, FMT=9000) A, B, C
2233 9000 FORMAT (1X, 'OUTPUT IS ', 3(F10.5))
2234@end smallexample
2235
2236
2237@node Variable FORMAT expressions
2238@subsection Variable @code{FORMAT} expressions
2239@cindex @code{FORMAT}
2240
2241A variable @code{FORMAT} expression is format statement which includes
2242angle brackets enclosing a Fortran expression: @code{FORMAT(I<N>)}.  GNU
2243Fortran does not support this legacy extension.  The effect of variable
2244format expressions can be reproduced by using the more powerful (and
2245standard) combination of internal output and string formats.  For example,
2246replace a code fragment like this:
2247
2248@smallexample
2249      WRITE(6,20) INT1
2250 20   FORMAT(I<N+1>)
2251@end smallexample
2252
2253@noindent
2254with the following:
2255
2256@smallexample
2257c     Variable declaration
2258      CHARACTER(LEN=20) FMT
2259c     
2260c     Other code here...
2261c
2262      WRITE(FMT,'("(I", I0, ")")') N+1
2263      WRITE(6,FMT) INT1
2264@end smallexample
2265
2266@noindent
2267or with:
2268
2269@smallexample
2270c     Variable declaration
2271      CHARACTER(LEN=20) FMT
2272c     
2273c     Other code here...
2274c
2275      WRITE(FMT,*) N+1
2276      WRITE(6,"(I" // ADJUSTL(FMT) // ")") INT1
2277@end smallexample
2278
2279
2280@node Alternate complex function syntax
2281@subsection Alternate complex function syntax
2282@cindex Complex function
2283
2284Some Fortran compilers, including @command{g77}, let the user declare
2285complex functions with the syntax @code{COMPLEX FUNCTION name*16()}, as
2286well as @code{COMPLEX*16 FUNCTION name()}.  Both are non-standard, legacy
2287extensions.  @command{gfortran} accepts the latter form, which is more
2288common, but not the former.
2289
2290
2291@node Volatile COMMON blocks
2292@subsection Volatile @code{COMMON} blocks
2293@cindex @code{VOLATILE}
2294@cindex @code{COMMON}
2295
2296Some Fortran compilers, including @command{g77}, let the user declare
2297@code{COMMON} with the @code{VOLATILE} attribute. This is
2298invalid standard Fortran syntax and is not supported by
2299@command{gfortran}.  Note that @command{gfortran} accepts
2300@code{VOLATILE} variables in @code{COMMON} blocks since revision 4.3.
2301
2302
2303
2304@c ---------------------------------------------------------------------
2305@c Mixed-Language Programming
2306@c ---------------------------------------------------------------------
2307
2308@node Mixed-Language Programming
2309@chapter Mixed-Language Programming
2310@cindex Interoperability
2311@cindex Mixed-language programming
2312
2313@menu
2314* Interoperability with C::
2315* GNU Fortran Compiler Directives::
2316* Non-Fortran Main Program::
2317* Naming and argument-passing conventions::
2318@end menu
2319
2320This chapter is about mixed-language interoperability, but also applies
2321if one links Fortran code compiled by different compilers.  In most cases,
2322use of the C Binding features of the Fortran 2003 standard is sufficient,
2323and their use is highly recommended.
2324
2325
2326@node Interoperability with C
2327@section Interoperability with C
2328
2329@menu
2330* Intrinsic Types::
2331* Derived Types and struct::
2332* Interoperable Global Variables::
2333* Interoperable Subroutines and Functions::
2334* Working with Pointers::
2335* Further Interoperability of Fortran with C::
2336@end menu
2337
2338Since Fortran 2003 (ISO/IEC 1539-1:2004(E)) there is a
2339standardized way to generate procedure and derived-type
2340declarations and global variables which are interoperable with C
2341(ISO/IEC 9899:1999).  The @code{bind(C)} attribute has been added
2342to inform the compiler that a symbol shall be interoperable with C;
2343also, some constraints are added.  Note, however, that not
2344all C features have a Fortran equivalent or vice versa.  For instance,
2345neither C's unsigned integers nor C's functions with variable number
2346of arguments have an equivalent in Fortran.
2347
2348Note that array dimensions are reversely ordered in C and that arrays in
2349C always start with index 0 while in Fortran they start by default with
23501.  Thus, an array declaration @code{A(n,m)} in Fortran matches
2351@code{A[m][n]} in C and accessing the element @code{A(i,j)} matches
2352@code{A[j-1][i-1]}.  The element following @code{A(i,j)} (C: @code{A[j-1][i-1]};
2353assuming @math{i < n}) in memory is @code{A(i+1,j)} (C: @code{A[j-1][i]}).
2354
2355@node Intrinsic Types
2356@subsection Intrinsic Types
2357
2358In order to ensure that exactly the same variable type and kind is used
2359in C and Fortran, the named constants shall be used which are defined in the
2360@code{ISO_C_BINDING} intrinsic module.  That module contains named constants
2361for kind parameters and character named constants for the escape sequences
2362in C.  For a list of the constants, see @ref{ISO_C_BINDING}.
2363
2364For logical types, please note that the Fortran standard only guarantees
2365interoperability between C99's @code{_Bool} and Fortran's @code{C_Bool}-kind
2366logicals and C99 defines that @code{true} has the value 1 and @code{false}
2367the value 0.  Using any other integer value with GNU Fortran's @code{LOGICAL}
2368(with any kind parameter) gives an undefined result.  (Passing other integer
2369values than 0 and 1 to GCC's @code{_Bool} is also undefined, unless the
2370integer is explicitly or implicitly casted to @code{_Bool}.)
2371
2372
2373
2374@node Derived Types and struct
2375@subsection Derived Types and struct
2376
2377For compatibility of derived types with @code{struct}, one needs to use
2378the @code{BIND(C)} attribute in the type declaration.  For instance, the
2379following type declaration
2380
2381@smallexample
2382 USE ISO_C_BINDING
2383 TYPE, BIND(C) :: myType
2384   INTEGER(C_INT) :: i1, i2
2385   INTEGER(C_SIGNED_CHAR) :: i3
2386   REAL(C_DOUBLE) :: d1
2387   COMPLEX(C_FLOAT_COMPLEX) :: c1
2388   CHARACTER(KIND=C_CHAR) :: str(5)
2389 END TYPE
2390@end smallexample
2391
2392matches the following @code{struct} declaration in C
2393
2394@smallexample
2395 struct @{
2396   int i1, i2;
2397   /* Note: "char" might be signed or unsigned.  */
2398   signed char i3;
2399   double d1;
2400   float _Complex c1;
2401   char str[5];
2402 @} myType;
2403@end smallexample
2404
2405Derived types with the C binding attribute shall not have the @code{sequence}
2406attribute, type parameters, the @code{extends} attribute, nor type-bound
2407procedures.  Every component must be of interoperable type and kind and may not
2408have the @code{pointer} or @code{allocatable} attribute.  The names of the
2409components are irrelevant for interoperability.
2410
2411As there exist no direct Fortran equivalents, neither unions nor structs
2412with bit field or variable-length array members are interoperable.
2413
2414@node Interoperable Global Variables
2415@subsection Interoperable Global Variables
2416
2417Variables can be made accessible from C using the C binding attribute,
2418optionally together with specifying a binding name.  Those variables
2419have to be declared in the declaration part of a @code{MODULE},
2420be of interoperable type, and have neither the @code{pointer} nor
2421the @code{allocatable} attribute.
2422
2423@smallexample
2424  MODULE m
2425    USE myType_module
2426    USE ISO_C_BINDING
2427    integer(C_INT), bind(C, name="_MyProject_flags") :: global_flag
2428    type(myType), bind(C) :: tp
2429  END MODULE
2430@end smallexample
2431
2432Here, @code{_MyProject_flags} is the case-sensitive name of the variable
2433as seen from C programs while @code{global_flag} is the case-insensitive
2434name as seen from Fortran.  If no binding name is specified, as for
2435@var{tp}, the C binding name is the (lowercase) Fortran binding name.
2436If a binding name is specified, only a single variable may be after the
2437double colon.  Note of warning: You cannot use a global variable to
2438access @var{errno} of the C library as the C standard allows it to be
2439a macro.  Use the @code{IERRNO} intrinsic (GNU extension) instead.
2440
2441@node Interoperable Subroutines and Functions
2442@subsection Interoperable Subroutines and Functions
2443
2444Subroutines and functions have to have the @code{BIND(C)} attribute to
2445be compatible with C.  The dummy argument declaration is relatively
2446straightforward.  However, one needs to be careful because C uses
2447call-by-value by default while Fortran behaves usually similar to
2448call-by-reference.  Furthermore, strings and pointers are handled
2449differently.  Note that in Fortran 2003 and 2008 only explicit size
2450and assumed-size arrays are supported but not assumed-shape or
2451deferred-shape (i.e. allocatable or pointer) arrays.  However, those
2452are allowed since the Technical Specification 29113, see
2453@ref{Further Interoperability of Fortran with C}
2454
2455To pass a variable by value, use the @code{VALUE} attribute.
2456Thus, the following C prototype
2457
2458@smallexample
2459@code{int func(int i, int *j)}
2460@end smallexample
2461
2462matches the Fortran declaration
2463
2464@smallexample
2465  integer(c_int) function func(i,j)
2466    use iso_c_binding, only: c_int
2467    integer(c_int), VALUE :: i
2468    integer(c_int) :: j
2469@end smallexample
2470
2471Note that pointer arguments also frequently need the @code{VALUE} attribute,
2472see @ref{Working with Pointers}.
2473
2474Strings are handled quite differently in C and Fortran.  In C a string
2475is a @code{NUL}-terminated array of characters while in Fortran each string
2476has a length associated with it and is thus not terminated (by e.g.
2477@code{NUL}).  For example, if one wants to use the following C function,
2478
2479@smallexample
2480  #include <stdio.h>
2481  void print_C(char *string) /* equivalent: char string[]  */
2482  @{
2483     printf("%s\n", string);
2484  @}
2485@end smallexample
2486
2487to print ``Hello World'' from Fortran, one can call it using
2488
2489@smallexample
2490  use iso_c_binding, only: C_CHAR, C_NULL_CHAR
2491  interface
2492    subroutine print_c(string) bind(C, name="print_C")
2493      use iso_c_binding, only: c_char
2494      character(kind=c_char) :: string(*)
2495    end subroutine print_c
2496  end interface
2497  call print_c(C_CHAR_"Hello World"//C_NULL_CHAR)
2498@end smallexample
2499
2500As the example shows, one needs to ensure that the
2501string is @code{NUL} terminated.  Additionally, the dummy argument
2502@var{string} of @code{print_C} is a length-one assumed-size
2503array; using @code{character(len=*)} is not allowed.  The example
2504above uses @code{c_char_"Hello World"} to ensure the string
2505literal has the right type; typically the default character
2506kind and @code{c_char} are the same and thus @code{"Hello World"}
2507is equivalent.  However, the standard does not guarantee this.
2508
2509The use of strings is now further illustrated using the C library
2510function @code{strncpy}, whose prototype is
2511
2512@smallexample
2513  char *strncpy(char *restrict s1, const char *restrict s2, size_t n);
2514@end smallexample
2515
2516The function @code{strncpy} copies at most @var{n} characters from
2517string @var{s2} to @var{s1} and returns @var{s1}.  In the following
2518example, we ignore the return value:
2519
2520@smallexample
2521  use iso_c_binding
2522  implicit none
2523  character(len=30) :: str,str2
2524  interface
2525    ! Ignore the return value of strncpy -> subroutine
2526    ! "restrict" is always assumed if we do not pass a pointer
2527    subroutine strncpy(dest, src, n) bind(C)
2528      import
2529      character(kind=c_char),  intent(out) :: dest(*)
2530      character(kind=c_char),  intent(in)  :: src(*)
2531      integer(c_size_t), value, intent(in) :: n
2532    end subroutine strncpy
2533  end interface
2534  str = repeat('X',30) ! Initialize whole string with 'X'
2535  call strncpy(str, c_char_"Hello World"//C_NULL_CHAR, &
2536               len(c_char_"Hello World",kind=c_size_t))
2537  print '(a)', str ! prints: "Hello WorldXXXXXXXXXXXXXXXXXXX"
2538  end
2539@end smallexample
2540
2541The intrinsic procedures are described in @ref{Intrinsic Procedures}.
2542
2543@node Working with Pointers
2544@subsection Working with Pointers
2545
2546C pointers are represented in Fortran via the special opaque derived type
2547@code{type(c_ptr)} (with private components).  Thus one needs to
2548use intrinsic conversion procedures to convert from or to C pointers.
2549
2550For some applications, using an assumed type (@code{TYPE(*)}) can be an
2551alternative to a C pointer; see
2552@ref{Further Interoperability of Fortran with C}.
2553
2554For example,
2555
2556@smallexample
2557  use iso_c_binding
2558  type(c_ptr) :: cptr1, cptr2
2559  integer, target :: array(7), scalar
2560  integer, pointer :: pa(:), ps
2561  cptr1 = c_loc(array(1)) ! The programmer needs to ensure that the
2562                          ! array is contiguous if required by the C
2563                          ! procedure
2564  cptr2 = c_loc(scalar)
2565  call c_f_pointer(cptr2, ps)
2566  call c_f_pointer(cptr2, pa, shape=[7])
2567@end smallexample
2568
2569When converting C to Fortran arrays, the one-dimensional @code{SHAPE} argument
2570has to be passed.
2571
2572If a pointer is a dummy-argument of an interoperable procedure, it usually
2573has to be declared using the @code{VALUE} attribute.  @code{void*}
2574matches @code{TYPE(C_PTR), VALUE}, while @code{TYPE(C_PTR)} alone
2575matches @code{void**}.
2576
2577Procedure pointers are handled analogously to pointers; the C type is
2578@code{TYPE(C_FUNPTR)} and the intrinsic conversion procedures are
2579@code{C_F_PROCPOINTER} and @code{C_FUNLOC}.
2580
2581Let us consider two examples of actually passing a procedure pointer from
2582C to Fortran and vice versa.  Note that these examples are also very
2583similar to passing ordinary pointers between both languages. First,
2584consider this code in C:
2585
2586@smallexample
2587/* Procedure implemented in Fortran.  */
2588void get_values (void (*)(double));
2589
2590/* Call-back routine we want called from Fortran.  */
2591void
2592print_it (double x)
2593@{
2594  printf ("Number is %f.\n", x);
2595@}
2596
2597/* Call Fortran routine and pass call-back to it.  */
2598void
2599foobar ()
2600@{
2601  get_values (&print_it);
2602@}
2603@end smallexample
2604
2605A matching implementation for @code{get_values} in Fortran, that correctly
2606receives the procedure pointer from C and is able to call it, is given
2607in the following @code{MODULE}:
2608
2609@smallexample
2610MODULE m
2611  IMPLICIT NONE
2612
2613  ! Define interface of call-back routine.
2614  ABSTRACT INTERFACE
2615    SUBROUTINE callback (x)
2616      USE, INTRINSIC :: ISO_C_BINDING
2617      REAL(KIND=C_DOUBLE), INTENT(IN), VALUE :: x
2618    END SUBROUTINE callback
2619  END INTERFACE
2620
2621CONTAINS
2622
2623  ! Define C-bound procedure.
2624  SUBROUTINE get_values (cproc) BIND(C)
2625    USE, INTRINSIC :: ISO_C_BINDING
2626    TYPE(C_FUNPTR), INTENT(IN), VALUE :: cproc
2627
2628    PROCEDURE(callback), POINTER :: proc
2629
2630    ! Convert C to Fortran procedure pointer.
2631    CALL C_F_PROCPOINTER (cproc, proc)
2632
2633    ! Call it.
2634    CALL proc (1.0_C_DOUBLE)
2635    CALL proc (-42.0_C_DOUBLE)
2636    CALL proc (18.12_C_DOUBLE)
2637  END SUBROUTINE get_values
2638
2639END MODULE m
2640@end smallexample
2641
2642Next, we want to call a C routine that expects a procedure pointer argument
2643and pass it a Fortran procedure (which clearly must be interoperable!).
2644Again, the C function may be:
2645
2646@smallexample
2647int
2648call_it (int (*func)(int), int arg)
2649@{
2650  return func (arg);
2651@}
2652@end smallexample
2653
2654It can be used as in the following Fortran code:
2655
2656@smallexample
2657MODULE m
2658  USE, INTRINSIC :: ISO_C_BINDING
2659  IMPLICIT NONE
2660
2661  ! Define interface of C function.
2662  INTERFACE
2663    INTEGER(KIND=C_INT) FUNCTION call_it (func, arg) BIND(C)
2664      USE, INTRINSIC :: ISO_C_BINDING
2665      TYPE(C_FUNPTR), INTENT(IN), VALUE :: func
2666      INTEGER(KIND=C_INT), INTENT(IN), VALUE :: arg
2667    END FUNCTION call_it
2668  END INTERFACE
2669
2670CONTAINS
2671
2672  ! Define procedure passed to C function.
2673  ! It must be interoperable!
2674  INTEGER(KIND=C_INT) FUNCTION double_it (arg) BIND(C)
2675    INTEGER(KIND=C_INT), INTENT(IN), VALUE :: arg
2676    double_it = arg + arg
2677  END FUNCTION double_it
2678
2679  ! Call C function.
2680  SUBROUTINE foobar ()
2681    TYPE(C_FUNPTR) :: cproc
2682    INTEGER(KIND=C_INT) :: i
2683
2684    ! Get C procedure pointer.
2685    cproc = C_FUNLOC (double_it)
2686
2687    ! Use it.
2688    DO i = 1_C_INT, 10_C_INT
2689      PRINT *, call_it (cproc, i)
2690    END DO
2691  END SUBROUTINE foobar
2692
2693END MODULE m
2694@end smallexample
2695
2696@node Further Interoperability of Fortran with C
2697@subsection Further Interoperability of Fortran with C
2698
2699The Technical Specification ISO/IEC TS 29113:2012 on further
2700interoperability of Fortran with C extends the interoperability support
2701of Fortran 2003 and Fortran 2008. Besides removing some restrictions
2702and constraints, it adds assumed-type (@code{TYPE(*)}) and assumed-rank
2703(@code{dimension}) variables and allows for interoperability of
2704assumed-shape, assumed-rank and deferred-shape arrays, including
2705allocatables and pointers.
2706
2707Note: Currently, GNU Fortran does not support the array descriptor
2708(dope vector) as specified in the Technical Specification, but uses
2709an array descriptor with different fields. The Chasm Language
2710Interoperability Tools, @url{http://chasm-interop.sourceforge.net/},
2711provide an interface to GNU Fortran's array descriptor.
2712
2713The Technical Specification adds the following new features, which
2714are supported by GNU Fortran:
2715
2716@itemize @bullet
2717
2718@item The @code{ASYNCHRONOUS} attribute has been clarified and
2719extended to allow its use with asynchronous communication in
2720user-provided libraries such as in implementations of the
2721Message Passing Interface specification.
2722
2723@item Many constraints have been relaxed, in particular for
2724the @code{C_LOC} and @code{C_F_POINTER} intrinsics.
2725
2726@item The @code{OPTIONAL} attribute is now allowed for dummy
2727arguments; an absent argument matches a @code{NULL} pointer.
2728
2729@item Assumed types (@code{TYPE(*)}) have been added, which may
2730only be used for dummy arguments.  They are unlimited polymorphic
2731but contrary to @code{CLASS(*)} they do not contain any type
2732information, similar to C's @code{void *} pointers.  Expressions
2733of any type and kind can be passed; thus, it can be used as
2734replacement for @code{TYPE(C_PTR)}, avoiding the use of
2735@code{C_LOC} in the caller.
2736
2737Note, however, that @code{TYPE(*)} only accepts scalar arguments,
2738unless the @code{DIMENSION} is explicitly specified.  As
2739@code{DIMENSION(*)} only supports array (including array elements) but
2740no scalars, it is not a full replacement for @code{C_LOC}.  On the
2741other hand, assumed-type assumed-rank dummy arguments
2742(@code{TYPE(*), DIMENSION(..)}) allow for both scalars and arrays, but
2743require special code on the callee side to handle the array descriptor.
2744
2745@item Assumed-rank arrays (@code{DIMENSION(..)}) as dummy argument
2746allow that scalars and arrays of any rank can be passed as actual
2747argument. As the Technical Specification does not provide for direct
2748means to operate with them, they have to be used either from the C side
2749or be converted using @code{C_LOC} and @code{C_F_POINTER} to scalars
2750or arrays of a specific rank. The rank can be determined using the
2751@code{RANK} intrinisic.
2752@end itemize
2753
2754
2755Currently unimplemented:
2756
2757@itemize @bullet
2758
2759@item GNU Fortran always uses an array descriptor, which does not
2760match the one of the Technical Specification. The
2761@code{ISO_Fortran_binding.h} header file and the C functions it
2762specifies are not available.
2763
2764@item Using assumed-shape, assumed-rank and deferred-shape arrays in
2765@code{BIND(C)} procedures is not fully supported. In particular,
2766C interoperable strings of other length than one are not supported
2767as this requires the new array descriptor.
2768@end itemize
2769
2770
2771@node GNU Fortran Compiler Directives
2772@section GNU Fortran Compiler Directives
2773
2774The Fortran standard describes how a conforming program shall
2775behave; however, the exact implementation is not standardized.  In order
2776to allow the user to choose specific implementation details, compiler
2777directives can be used to set attributes of variables and procedures
2778which are not part of the standard.  Whether a given attribute is
2779supported and its exact effects depend on both the operating system and
2780on the processor; see
2781@ref{Top,,C Extensions,gcc,Using the GNU Compiler Collection (GCC)}
2782for details.
2783
2784For procedures and procedure pointers, the following attributes can
2785be used to change the calling convention:
2786
2787@itemize
2788@item @code{CDECL} -- standard C calling convention
2789@item @code{STDCALL} -- convention where the called procedure pops the stack
2790@item @code{FASTCALL} -- part of the arguments are passed via registers
2791instead using the stack
2792@end itemize
2793
2794Besides changing the calling convention, the attributes also influence
2795the decoration of the symbol name, e.g., by a leading underscore or by
2796a trailing at-sign followed by the number of bytes on the stack.  When
2797assigning a procedure to a procedure pointer, both should use the same
2798calling convention.
2799
2800On some systems, procedures and global variables (module variables and
2801@code{COMMON} blocks) need special handling to be accessible when they
2802are in a shared library.  The following attributes are available:
2803
2804@itemize
2805@item @code{DLLEXPORT} -- provide a global pointer to a pointer in the DLL
2806@item @code{DLLIMPORT} -- reference the function or variable using a
2807global pointer
2808@end itemize
2809
2810For dummy arguments, the @code{NO_ARG_CHECK} attribute can be used; in
2811other compilers, it is also known as @code{IGNORE_TKR}.  For dummy arguments
2812with this attribute actual arguments of any type and kind (similar to
2813@code{TYPE(*)}), scalars and arrays of any rank (no equivalent
2814in Fortran standard) are accepted.  As with @code{TYPE(*)}, the argument
2815is unlimited polymorphic and no type information is available.
2816Additionally, the argument may only be passed to dummy arguments
2817with the @code{NO_ARG_CHECK} attribute and as argument to the
2818@code{PRESENT} intrinsic function and to @code{C_LOC} of the
2819@code{ISO_C_BINDING} module.
2820
2821Variables with @code{NO_ARG_CHECK} attribute shall be of assumed-type
2822(@code{TYPE(*)}; recommended) or of type @code{INTEGER}, @code{LOGICAL},
2823@code{REAL} or @code{COMPLEX}. They shall not have the @code{ALLOCATE},
2824@code{CODIMENSION}, @code{INTENT(OUT)}, @code{POINTER} or @code{VALUE}
2825attribute; furthermore, they shall be either scalar or of assumed-size
2826(@code{dimension(*)}). As @code{TYPE(*)}, the @code{NO_ARG_CHECK} attribute
2827requires an explicit interface.
2828
2829@itemize
2830@item @code{NO_ARG_CHECK} -- disable the type, kind and rank checking
2831@end itemize
2832
2833
2834The attributes are specified using the syntax
2835
2836@code{!GCC$ ATTRIBUTES} @var{attribute-list} @code{::} @var{variable-list}
2837
2838where in free-form source code only whitespace is allowed before @code{!GCC$}
2839and in fixed-form source code @code{!GCC$}, @code{cGCC$} or @code{*GCC$} shall
2840start in the first column.
2841
2842For procedures, the compiler directives shall be placed into the body
2843of the procedure; for variables and procedure pointers, they shall be in
2844the same declaration part as the variable or procedure pointer.
2845
2846
2847
2848@node Non-Fortran Main Program
2849@section Non-Fortran Main Program
2850
2851@menu
2852* _gfortran_set_args:: Save command-line arguments
2853* _gfortran_set_options:: Set library option flags
2854* _gfortran_set_convert:: Set endian conversion
2855* _gfortran_set_record_marker:: Set length of record markers
2856* _gfortran_set_fpe:: Set when a Floating Point Exception should be raised
2857* _gfortran_set_max_subrecord_length:: Set subrecord length
2858@end menu
2859
2860Even if you are doing mixed-language programming, it is very
2861likely that you do not need to know or use the information in this
2862section.  Since it is about the internal structure of GNU Fortran,
2863it may also change in GCC minor releases.
2864
2865When you compile a @code{PROGRAM} with GNU Fortran, a function
2866with the name @code{main} (in the symbol table of the object file)
2867is generated, which initializes the libgfortran library and then
2868calls the actual program which uses the name @code{MAIN__}, for
2869historic reasons.  If you link GNU Fortran compiled procedures
2870to, e.g., a C or C++ program or to a Fortran program compiled by
2871a different compiler, the libgfortran library is not initialized
2872and thus a few intrinsic procedures do not work properly, e.g.
2873those for obtaining the command-line arguments.
2874
2875Therefore, if your @code{PROGRAM} is not compiled with
2876GNU Fortran and the GNU Fortran compiled procedures require
2877intrinsics relying on the library initialization, you need to
2878initialize the library yourself.  Using the default options,
2879gfortran calls @code{_gfortran_set_args} and
2880@code{_gfortran_set_options}.  The initialization of the former
2881is needed if the called procedures access the command line
2882(and for backtracing); the latter sets some flags based on the
2883standard chosen or to enable backtracing.  In typical programs,
2884it is not necessary to call any initialization function.
2885
2886If your @code{PROGRAM} is compiled with GNU Fortran, you shall
2887not call any of the following functions.  The libgfortran
2888initialization functions are shown in C syntax but using C
2889bindings they are also accessible from Fortran.
2890
2891
2892@node _gfortran_set_args
2893@subsection @code{_gfortran_set_args} --- Save command-line arguments
2894@fnindex _gfortran_set_args
2895@cindex libgfortran initialization, set_args
2896
2897@table @asis
2898@item @emph{Description}:
2899@code{_gfortran_set_args} saves the command-line arguments; this
2900initialization is required if any of the command-line intrinsics
2901is called.  Additionally, it shall be called if backtracing is
2902enabled (see @code{_gfortran_set_options}).
2903
2904@item @emph{Syntax}:
2905@code{void _gfortran_set_args (int argc, char *argv[])}
2906
2907@item @emph{Arguments}:
2908@multitable @columnfractions .15 .70
2909@item @var{argc} @tab number of command line argument strings
2910@item @var{argv} @tab the command-line argument strings; argv[0]
2911is the pathname of the executable itself.
2912@end multitable
2913
2914@item @emph{Example}:
2915@smallexample
2916int main (int argc, char *argv[])
2917@{
2918  /* Initialize libgfortran.  */
2919  _gfortran_set_args (argc, argv);
2920  return 0;
2921@}
2922@end smallexample
2923@end table
2924
2925
2926@node _gfortran_set_options
2927@subsection @code{_gfortran_set_options} --- Set library option flags
2928@fnindex _gfortran_set_options
2929@cindex libgfortran initialization, set_options
2930
2931@table @asis
2932@item @emph{Description}:
2933@code{_gfortran_set_options} sets several flags related to the Fortran
2934standard to be used, whether backtracing should be enabled
2935and whether range checks should be performed.  The syntax allows for
2936upward compatibility since the number of passed flags is specified; for
2937non-passed flags, the default value is used.  See also
2938@pxref{Code Gen Options}.  Please note that not all flags are actually
2939used.
2940
2941@item @emph{Syntax}:
2942@code{void _gfortran_set_options (int num, int options[])}
2943
2944@item @emph{Arguments}:
2945@multitable @columnfractions .15 .70
2946@item @var{num} @tab number of options passed
2947@item @var{argv} @tab The list of flag values
2948@end multitable
2949
2950@item @emph{option flag list}:
2951@multitable @columnfractions .15 .70
2952@item @var{option}[0] @tab Allowed standard; can give run-time errors
2953if e.g. an input-output edit descriptor is invalid in a given standard.
2954Possible values are (bitwise or-ed) @code{GFC_STD_F77} (1),
2955@code{GFC_STD_F95_OBS} (2), @code{GFC_STD_F95_DEL} (4), @code{GFC_STD_F95}
2956(8), @code{GFC_STD_F2003} (16), @code{GFC_STD_GNU} (32),
2957@code{GFC_STD_LEGACY} (64), @code{GFC_STD_F2008} (128),
2958@code{GFC_STD_F2008_OBS} (256) and GFC_STD_F2008_TS (512). Default:
2959@code{GFC_STD_F95_OBS | GFC_STD_F95_DEL | GFC_STD_F95 | GFC_STD_F2003
2960| GFC_STD_F2008 | GFC_STD_F2008_TS | GFC_STD_F2008_OBS | GFC_STD_F77
2961| GFC_STD_GNU | GFC_STD_LEGACY}.
2962@item @var{option}[1] @tab Standard-warning flag; prints a warning to
2963standard error.  Default: @code{GFC_STD_F95_DEL | GFC_STD_LEGACY}.
2964@item @var{option}[2] @tab If non zero, enable pedantic checking.
2965Default: off.
2966@item @var{option}[3] @tab Unused.
2967@item @var{option}[4] @tab If non zero, enable backtracing on run-time
2968errors.  Default: off. (Default in the compiler: on.)
2969Note: Installs a signal handler and requires command-line
2970initialization using @code{_gfortran_set_args}.
2971@item @var{option}[5] @tab If non zero, supports signed zeros.
2972Default: enabled.
2973@item @var{option}[6] @tab Enables run-time checking.  Possible values
2974are (bitwise or-ed): GFC_RTCHECK_BOUNDS (1), GFC_RTCHECK_ARRAY_TEMPS (2),
2975GFC_RTCHECK_RECURSION (4), GFC_RTCHECK_DO (16), GFC_RTCHECK_POINTER (32).
2976Default: disabled.
2977@item @var{option}[7] @tab Unused.
2978@item @var{option}[8] @tab Show a warning when invoking @code{STOP} and
2979@code{ERROR STOP} if a floating-point exception occurred. Possible values
2980are (bitwise or-ed) @code{GFC_FPE_INVALID} (1), @code{GFC_FPE_DENORMAL} (2),
2981@code{GFC_FPE_ZERO} (4), @code{GFC_FPE_OVERFLOW} (8),
2982@code{GFC_FPE_UNDERFLOW} (16), @code{GFC_FPE_INEXACT} (32). Default: None (0).
2983(Default in the compiler: @code{GFC_FPE_INVALID | GFC_FPE_DENORMAL |
2984GFC_FPE_ZERO | GFC_FPE_OVERFLOW | GFC_FPE_UNDERFLOW}.)
2985@end multitable
2986
2987@item @emph{Example}:
2988@smallexample
2989  /* Use gfortran 4.9 default options.  */
2990  static int options[] = @{68, 511, 0, 0, 1, 1, 0, 0, 31@};
2991  _gfortran_set_options (9, &options);
2992@end smallexample
2993@end table
2994
2995
2996@node _gfortran_set_convert
2997@subsection @code{_gfortran_set_convert} --- Set endian conversion
2998@fnindex _gfortran_set_convert
2999@cindex libgfortran initialization, set_convert
3000
3001@table @asis
3002@item @emph{Description}:
3003@code{_gfortran_set_convert} set the representation of data for
3004unformatted files.
3005
3006@item @emph{Syntax}:
3007@code{void _gfortran_set_convert (int conv)}
3008
3009@item @emph{Arguments}:
3010@multitable @columnfractions .15 .70
3011@item @var{conv} @tab Endian conversion, possible values:
3012GFC_CONVERT_NATIVE (0, default), GFC_CONVERT_SWAP (1),
3013GFC_CONVERT_BIG (2), GFC_CONVERT_LITTLE (3).
3014@end multitable
3015
3016@item @emph{Example}:
3017@smallexample
3018int main (int argc, char *argv[])
3019@{
3020  /* Initialize libgfortran.  */
3021  _gfortran_set_args (argc, argv);
3022  _gfortran_set_convert (1);
3023  return 0;
3024@}
3025@end smallexample
3026@end table
3027
3028
3029@node _gfortran_set_record_marker
3030@subsection @code{_gfortran_set_record_marker} --- Set length of record markers
3031@fnindex _gfortran_set_record_marker
3032@cindex libgfortran initialization, set_record_marker
3033
3034@table @asis
3035@item @emph{Description}:
3036@code{_gfortran_set_record_marker} sets the length of record markers
3037for unformatted files.
3038
3039@item @emph{Syntax}:
3040@code{void _gfortran_set_record_marker (int val)}
3041
3042@item @emph{Arguments}:
3043@multitable @columnfractions .15 .70
3044@item @var{val} @tab Length of the record marker; valid values
3045are 4 and 8.  Default is 4.
3046@end multitable
3047
3048@item @emph{Example}:
3049@smallexample
3050int main (int argc, char *argv[])
3051@{
3052  /* Initialize libgfortran.  */
3053  _gfortran_set_args (argc, argv);
3054  _gfortran_set_record_marker (8);
3055  return 0;
3056@}
3057@end smallexample
3058@end table
3059
3060
3061@node _gfortran_set_fpe
3062@subsection @code{_gfortran_set_fpe} --- Enable floating point exception traps
3063@fnindex _gfortran_set_fpe
3064@cindex libgfortran initialization, set_fpe
3065
3066@table @asis
3067@item @emph{Description}:
3068@code{_gfortran_set_fpe} enables floating point exception traps for
3069the specified exceptions.  On most systems, this will result in a
3070SIGFPE signal being sent and the program being aborted.
3071
3072@item @emph{Syntax}:
3073@code{void _gfortran_set_fpe (int val)}
3074
3075@item @emph{Arguments}:
3076@multitable @columnfractions .15 .70
3077@item @var{option}[0] @tab IEEE exceptions.  Possible values are
3078(bitwise or-ed) zero (0, default) no trapping,
3079@code{GFC_FPE_INVALID} (1), @code{GFC_FPE_DENORMAL} (2),
3080@code{GFC_FPE_ZERO} (4), @code{GFC_FPE_OVERFLOW} (8),
3081@code{GFC_FPE_UNDERFLOW} (16), and @code{GFC_FPE_INEXACT} (32).
3082@end multitable
3083
3084@item @emph{Example}:
3085@smallexample
3086int main (int argc, char *argv[])
3087@{
3088  /* Initialize libgfortran.  */
3089  _gfortran_set_args (argc, argv);
3090  /* FPE for invalid operations such as SQRT(-1.0).  */
3091  _gfortran_set_fpe (1);
3092  return 0;
3093@}
3094@end smallexample
3095@end table
3096
3097
3098@node _gfortran_set_max_subrecord_length
3099@subsection @code{_gfortran_set_max_subrecord_length} --- Set subrecord length
3100@fnindex _gfortran_set_max_subrecord_length
3101@cindex libgfortran initialization, set_max_subrecord_length
3102
3103@table @asis
3104@item @emph{Description}:
3105@code{_gfortran_set_max_subrecord_length} set the maximum length
3106for a subrecord.  This option only makes sense for testing and
3107debugging of unformatted I/O.
3108
3109@item @emph{Syntax}:
3110@code{void _gfortran_set_max_subrecord_length (int val)}
3111
3112@item @emph{Arguments}:
3113@multitable @columnfractions .15 .70
3114@item @var{val} @tab the maximum length for a subrecord;
3115the maximum permitted value is 2147483639, which is also
3116the default.
3117@end multitable
3118
3119@item @emph{Example}:
3120@smallexample
3121int main (int argc, char *argv[])
3122@{
3123  /* Initialize libgfortran.  */
3124  _gfortran_set_args (argc, argv);
3125  _gfortran_set_max_subrecord_length (8);
3126  return 0;
3127@}
3128@end smallexample
3129@end table
3130
3131
3132@node Naming and argument-passing conventions
3133@section Naming and argument-passing conventions
3134
3135This section gives an overview about the naming convention of procedures
3136and global variables and about the argument passing conventions used by
3137GNU Fortran.  If a C binding has been specified, the naming convention
3138and some of the argument-passing conventions change.  If possible,
3139mixed-language and mixed-compiler projects should use the better defined
3140C binding for interoperability.  See @pxref{Interoperability with C}.
3141
3142@menu
3143* Naming conventions::
3144* Argument passing conventions::
3145@end menu
3146
3147
3148@node Naming conventions
3149@subsection Naming conventions
3150
3151According the Fortran standard, valid Fortran names consist of a letter
3152between @code{A} to @code{Z}, @code{a} to @code{z}, digits @code{0},
3153@code{1} to @code{9} and underscores (@code{_}) with the restriction
3154that names may only start with a letter.  As vendor extension, the
3155dollar sign (@code{$}) is additionally permitted with the option
3156@option{-fdollar-ok}, but not as first character and only if the
3157target system supports it.
3158
3159By default, the procedure name is the lower-cased Fortran name with an
3160appended underscore (@code{_}); using @option{-fno-underscoring} no
3161underscore is appended while @code{-fsecond-underscore} appends two
3162underscores.  Depending on the target system and the calling convention,
3163the procedure might be additionally dressed; for instance, on 32bit
3164Windows with @code{stdcall}, an at-sign @code{@@} followed by an integer
3165number is appended.  For the changing the calling convention, see
3166@pxref{GNU Fortran Compiler Directives}.
3167
3168For common blocks, the same convention is used, i.e. by default an
3169underscore is appended to the lower-cased Fortran name.  Blank commons
3170have the name @code{__BLNK__}.
3171
3172For procedures and variables declared in the specification space of a
3173module, the name is formed by @code{__}, followed by the lower-cased
3174module name, @code{_MOD_}, and the lower-cased Fortran name.  Note that
3175no underscore is appended.
3176
3177
3178@node Argument passing conventions
3179@subsection Argument passing conventions
3180
3181Subroutines do not return a value (matching C99's @code{void}) while
3182functions either return a value as specified in the platform ABI or
3183the result variable is passed as hidden argument to the function and
3184no result is returned.  A hidden result variable is used when the
3185result variable is an array or of type @code{CHARACTER}.
3186
3187Arguments are passed according to the platform ABI. In particular,
3188complex arguments might not be compatible to a struct with two real
3189components for the real and imaginary part. The argument passing
3190matches the one of C99's @code{_Complex}.  Functions with scalar
3191complex result variables return their value and do not use a
3192by-reference argument.  Note that with the @option{-ff2c} option,
3193the argument passing is modified and no longer completely matches
3194the platform ABI.  Some other Fortran compilers use @code{f2c}
3195semantic by default; this might cause problems with
3196interoperablility.
3197
3198GNU Fortran passes most arguments by reference, i.e. by passing a
3199pointer to the data.  Note that the compiler might use a temporary
3200variable into which the actual argument has been copied, if required
3201semantically (copy-in/copy-out).
3202
3203For arguments with @code{ALLOCATABLE} and @code{POINTER}
3204attribute (including procedure pointers), a pointer to the pointer
3205is passed such that the pointer address can be modified in the
3206procedure.
3207
3208For dummy arguments with the @code{VALUE} attribute: Scalar arguments
3209of the type @code{INTEGER}, @code{LOGICAL}, @code{REAL} and
3210@code{COMPLEX} are passed by value according to the platform ABI.
3211(As vendor extension and not recommended, using @code{%VAL()} in the
3212call to a procedure has the same effect.) For @code{TYPE(C_PTR)} and
3213procedure pointers, the pointer itself is passed such that it can be
3214modified without affecting the caller.
3215@c FIXME: Document how VALUE is handled for CHARACTER, TYPE,
3216@c CLASS and arrays, i.e. whether the copy-in is done in the caller
3217@c or in the callee.
3218
3219For Boolean (@code{LOGICAL}) arguments, please note that GCC expects
3220only the integer value 0 and 1.  If a GNU Fortran @code{LOGICAL}
3221variable contains another integer value, the result is undefined.
3222As some other Fortran compilers use @math{-1} for @code{.TRUE.},
3223extra care has to be taken -- such as passing the value as
3224@code{INTEGER}.  (The same value restriction also applies to other
3225front ends of GCC, e.g. to GCC's C99 compiler for @code{_Bool}
3226or GCC's Ada compiler for @code{Boolean}.)
3227
3228For arguments of @code{CHARACTER} type, the character length is passed
3229as hidden argument.  For deferred-length strings, the value is passed
3230by reference, otherwise by value.  The character length has the type
3231@code{INTEGER(kind=4)}.  Note with C binding, @code{CHARACTER(len=1)}
3232result variables are returned according to the platform ABI and no
3233hidden length argument is used for dummy arguments; with @code{VALUE},
3234those variables are passed by value.
3235
3236For @code{OPTIONAL} dummy arguments, an absent argument is denoted
3237by a NULL pointer, except for scalar dummy arguments of type
3238@code{INTEGER}, @code{LOGICAL}, @code{REAL} and @code{COMPLEX}
3239which have the @code{VALUE} attribute.  For those, a hidden Boolean
3240argument (@code{logical(kind=C_bool),value}) is used to indicate
3241whether the argument is present.
3242
3243Arguments which are assumed-shape, assumed-rank or deferred-rank
3244arrays or, with @option{-fcoarray=lib}, allocatable scalar coarrays use
3245an array descriptor.  All other arrays pass the address of the
3246first element of the array.  With @option{-fcoarray=lib}, the token
3247and the offset belonging to nonallocatable coarrays dummy arguments
3248are passed as hidden argument along the character length hidden
3249arguments.  The token is an oparque pointer identifying the coarray
3250and the offset is a passed-by-value integer of kind @code{C_PTRDIFF_T},
3251denoting the byte offset between the base address of the coarray and
3252the passed scalar or first element of the passed array.
3253
3254The arguments are passed in the following order
3255@itemize @bullet
3256@item Result variable, when the function result is passed by reference
3257@item Character length of the function result, if it is a of type
3258@code{CHARACTER} and no C binding is used
3259@item The arguments in the order in which they appear in the Fortran
3260declaration
3261@item The the present status for optional arguments with value attribute,
3262which are internally passed by value
3263@item The character length and/or coarray token and offset for the first
3264argument which is a @code{CHARACTER} or a nonallocatable coarray dummy
3265argument, followed by the hidden arguments of the next dummy argument
3266of such a type
3267@end itemize
3268
3269
3270@c ---------------------------------------------------------------------
3271@c Coarray Programming
3272@c ---------------------------------------------------------------------
3273
3274@node Coarray Programming
3275@chapter Coarray Programming
3276@cindex Coarrays
3277
3278@menu
3279* Type and enum ABI Documentation::
3280* Function ABI Documentation::
3281@end menu
3282
3283
3284@node Type and enum ABI Documentation
3285@section Type and enum ABI Documentation
3286
3287@menu
3288* caf_token_t::
3289* caf_register_t::
3290@end menu
3291
3292@node caf_token_t
3293@subsection @code{caf_token_t}
3294
3295Typedef of type @code{void *} on the compiler side. Can be any data
3296type on the library side.
3297
3298@node caf_register_t
3299@subsection @code{caf_register_t}
3300
3301Indicates which kind of coarray variable should be registered.
3302
3303@verbatim
3304typedef enum caf_register_t {
3305  CAF_REGTYPE_COARRAY_STATIC,
3306  CAF_REGTYPE_COARRAY_ALLOC,
3307  CAF_REGTYPE_LOCK_STATIC,
3308  CAF_REGTYPE_LOCK_ALLOC,
3309  CAF_REGTYPE_CRITICAL,
3310  CAF_REGTYPE_EVENT_STATIC,
3311  CAF_REGTYPE_EVENT_ALLOC
3312}
3313caf_register_t;
3314@end verbatim
3315
3316
3317@node Function ABI Documentation
3318@section Function ABI Documentation
3319
3320@menu
3321* _gfortran_caf_init:: Initialiation function
3322* _gfortran_caf_finish:: Finalization function
3323* _gfortran_caf_this_image:: Querying the image number
3324* _gfortran_caf_num_images:: Querying the maximal number of images
3325* _gfortran_caf_register:: Registering coarrays
3326* _gfortran_caf_deregister:: Deregistering coarrays
3327* _gfortran_caf_send:: Sending data from a local image to a remote image
3328* _gfortran_caf_get:: Getting data from a remote image
3329* _gfortran_caf_sendget:: Sending data between remote images
3330* _gfortran_caf_lock:: Locking a lock variable
3331* _gfortran_caf_unlock:: Unlocking a lock variable
3332* _gfortran_caf_event_post:: Post an event
3333* _gfortran_caf_event_wait:: Wait that an event occurred
3334* _gfortran_caf_event_query:: Query event count
3335* _gfortran_caf_sync_all:: All-image barrier
3336* _gfortran_caf_sync_images:: Barrier for selected images
3337* _gfortran_caf_sync_memory:: Wait for completion of segment-memory operations
3338* _gfortran_caf_error_stop:: Error termination with exit code
3339* _gfortran_caf_error_stop_str:: Error termination with string
3340* _gfortran_caf_atomic_define:: Atomic variable assignment
3341* _gfortran_caf_atomic_ref:: Atomic variable reference
3342* _gfortran_caf_atomic_cas:: Atomic compare and swap
3343* _gfortran_caf_atomic_op:: Atomic operation
3344* _gfortran_caf_co_broadcast:: Sending data to all images
3345* _gfortran_caf_co_max:: Collective maximum reduction
3346* _gfortran_caf_co_min:: Collective minimum reduction
3347* _gfortran_caf_co_sum:: Collective summing reduction
3348* _gfortran_caf_co_reduce:: Generic collective reduction
3349@end menu
3350
3351
3352@node _gfortran_caf_init
3353@subsection @code{_gfortran_caf_init} --- Initialiation function
3354@cindex Coarray, _gfortran_caf_init
3355
3356@table @asis
3357@item @emph{Description}:
3358This function is called at startup of the program before the Fortran main
3359program, if the latter has been compiled with @option{-fcoarray=lib}.
3360It takes as arguments the command-line arguments of the program.  It is
3361permitted to pass to @code{NULL} pointers as argument; if non-@code{NULL},
3362the library is permitted to modify the arguments.
3363
3364@item @emph{Syntax}:
3365@code{void _gfortran_caf_init (int *argc, char ***argv)}
3366
3367@item @emph{Arguments}:
3368@multitable @columnfractions .15 .70
3369@item @var{argc} @tab intent(inout) An integer pointer with the number of
3370arguments passed to the program or @code{NULL}.
3371@item @var{argv} @tab intent(inout) A pointer to an array of strings with the
3372command-line arguments or @code{NULL}.
3373@end multitable
3374
3375@item @emph{NOTES}
3376The function is modelled after the initialization function of the Message
3377Passing Interface (MPI) specification.  Due to the way coarray registration
3378works, it might not be the first call to the libaray.  If the main program is
3379not written in Fortran and only a library uses coarrays, it can happen that
3380this function is never called.  Therefore, it is recommended that the library
3381does not rely on the passed arguments and whether the call has been done.
3382@end table
3383
3384
3385@node _gfortran_caf_finish
3386@subsection @code{_gfortran_caf_finish} --- Finalization function
3387@cindex Coarray, _gfortran_caf_finish
3388
3389@table @asis
3390@item @emph{Description}:
3391This function is called at the end of the Fortran main program, if it has
3392been compiled with the @option{-fcoarray=lib} option.
3393
3394@item @emph{Syntax}:
3395@code{void _gfortran_caf_finish (void)}
3396
3397@item @emph{NOTES}
3398For non-Fortran programs, it is recommended to call the function at the end
3399of the main program.  To ensure that the shutdown is also performed for
3400programs where this function is not explicitly invoked, for instance
3401non-Fortran programs or calls to the system's exit() function, the library
3402can use a destructor function.  Note that programs can also be terminated
3403using the STOP and ERROR STOP statements; those use different library calls.
3404@end table
3405
3406
3407@node _gfortran_caf_this_image
3408@subsection @code{_gfortran_caf_this_image} --- Querying the image number
3409@cindex Coarray, _gfortran_caf_this_image
3410
3411@table @asis
3412@item @emph{Description}:
3413This function returns the current image number, which is a positive number.
3414
3415@item @emph{Syntax}:
3416@code{int _gfortran_caf_this_image (int distance)}
3417
3418@item @emph{Arguments}:
3419@multitable @columnfractions .15 .70
3420@item @var{distance} @tab As specified for the @code{this_image} intrinsic
3421in TS18508. Shall be a nonnegative number.
3422@end multitable
3423
3424@item @emph{NOTES}
3425If the Fortran intrinsic @code{this_image} is invoked without an argument, which
3426is the only permitted form in Fortran 2008, GCC passes @code{0} as
3427first argument.
3428@end table
3429
3430
3431@node _gfortran_caf_num_images
3432@subsection @code{_gfortran_caf_num_images} --- Querying the maximal number of images
3433@cindex Coarray, _gfortran_caf_num_images
3434
3435@table @asis
3436@item @emph{Description}:
3437This function returns the number of images in the current team, if
3438@var{distance} is 0 or the number of images in the parent team at the specified
3439distance. If failed is -1, the function returns the number of all images at
3440the specified distance; if it is 0, the function returns the number of
3441nonfailed images, and if it is 1, it returns the number of failed images.
3442
3443@item @emph{Syntax}:
3444@code{int _gfortran_caf_num_images(int distance, int failed)}
3445
3446@item @emph{Arguments}:
3447@multitable @columnfractions .15 .70
3448@item @var{distance} @tab the distance from this image to the ancestor.
3449Shall be positive.
3450@item @var{failed} @tab shall be -1, 0, or 1
3451@end multitable
3452
3453@item @emph{NOTES}
3454This function follows TS18508. If the num_image intrinsic has no arguments,
3455the the compiler passes @code{distance=0} and @code{failed=-1} to the function.
3456@end table
3457
3458
3459@node _gfortran_caf_register
3460@subsection @code{_gfortran_caf_register} --- Registering coarrays
3461@cindex Coarray, _gfortran_caf_deregister
3462
3463@table @asis
3464@item @emph{Description}:
3465Allocates memory for a coarray and creates a token to identify the coarray. The
3466function is called for both coarrays with @code{SAVE} attribute and using an
3467explicit @code{ALLOCATE} statement. If an error occurs and @var{STAT} is a
3468@code{NULL} pointer, the function shall abort with printing an error message
3469and starting the error termination.  If no error occurs and @var{STAT} is
3470present, it shall be set to zero. Otherwise, it shall be set to a positive
3471value and, if not-@code{NULL}, @var{ERRMSG} shall be set to a string describing
3472the failure. The function shall return a pointer to the requested memory
3473for the local image as a call to @code{malloc} would do.
3474
3475For @code{CAF_REGTYPE_COARRAY_STATIC} and @code{CAF_REGTYPE_COARRAY_ALLOC},
3476the passed size is the byte size requested.  For @code{CAF_REGTYPE_LOCK_STATIC},
3477@code{CAF_REGTYPE_LOCK_ALLOC} and @code{CAF_REGTYPE_CRITICAL} it is the array
3478size or one for a scalar.
3479
3480
3481@item @emph{Syntax}:
3482@code{void *caf_register (size_t size, caf_register_t type, caf_token_t *token,
3483int *stat, char *errmsg, int errmsg_len)}
3484
3485@item @emph{Arguments}:
3486@multitable @columnfractions .15 .70
3487@item @var{size} @tab For normal coarrays, the byte size of the coarray to be
3488allocated; for lock types and event types, the number of elements.
3489@item @var{type} @tab one of the caf_register_t types.
3490@item @var{token} @tab intent(out) An opaque pointer identifying the coarray.
3491@item @var{stat} @tab intent(out) For allocatable coarrays, stores the STAT=;
3492may be NULL
3493@item @var{errmsg} @tab intent(out) When an error occurs, this will be set to
3494an error message; may be NULL
3495@item @var{errmsg_len} @tab the buffer size of errmsg.
3496@end multitable
3497
3498@item @emph{NOTES}
3499Nonalloatable coarrays have to be registered prior use from remote images.
3500In order to guarantee this, they have to be registered before the main
3501program. This can be achieved by creating constructor functions. That is what
3502GCC does such that also nonallocatable coarrays the memory is allocated and no
3503static memory is used.  The token permits to identify the coarray; to the
3504processor, the token is a nonaliasing pointer. The library can, for instance,
3505store the base address of the coarray in the token, some handle or a more
3506complicated struct.
3507
3508For normal coarrays, the returned pointer is used for accesses on the local
3509image. For lock types, the value shall only used for checking the allocation
3510status. Note that for critical blocks, the locking is only required on one
3511image; in the locking statement, the processor shall always pass always an
3512image index of one for critical-block lock variables
3513(@code{CAF_REGTYPE_CRITICAL}). For lock types and critical-block variables,
3514the initial value shall be unlocked (or, respecitively, not in critical
3515section) such as the value false; for event types, the initial state should
3516be no event, e.g. zero.
3517@end table
3518
3519
3520@node _gfortran_caf_deregister
3521@subsection @code{_gfortran_caf_deregister} --- Deregistering coarrays
3522@cindex Coarray, _gfortran_caf_deregister
3523
3524@table @asis
3525@item @emph{Description}:
3526Called to free the memory of a coarray; the processor calls this function for
3527automatic and explicit deallocation.  In case of an error, this function shall
3528fail with an error message, unless the @var{STAT} variable is not null.
3529
3530@item @emph{Syntax}:
3531@code{void caf_deregister (const caf_token_t *token, int *stat, char *errmsg,
3532int errmsg_len)}
3533
3534@item @emph{Arguments}:
3535@multitable @columnfractions .15 .70
3536@item @var{stat} @tab intent(out) Stores the STAT=; may be NULL
3537@item @var{errmsg} @tab intent(out) When an error occurs, this will be set
3538to an error message; may be NULL
3539@item @var{errmsg_len} @tab the buffer size of errmsg.
3540@end multitable
3541
3542@item @emph{NOTES}
3543For nonalloatable coarrays this function is never called.  If a cleanup is
3544required, it has to be handled via the finish, stop and error stop functions,
3545and via destructors.
3546@end table
3547
3548
3549@node _gfortran_caf_send
3550@subsection @code{_gfortran_caf_send} --- Sending data from a local image to a remote image
3551@cindex Coarray, _gfortran_caf_send
3552
3553@table @asis
3554@item @emph{Description}:
3555Called to send a scalar, an array section or whole array from a local
3556to a remote image identified by the image_index.
3557
3558@item @emph{Syntax}:
3559@code{void _gfortran_caf_send (caf_token_t token, size_t offset,
3560int image_index, gfc_descriptor_t *dest, caf_vector_t *dst_vector,
3561gfc_descriptor_t *src, int dst_kind, int src_kind, bool may_require_tmp)}
3562
3563@item @emph{Arguments}:
3564@multitable @columnfractions .15 .70
3565@item @var{token} @tab intent(in)  An opaque pointer identifying the coarray.
3566@item @var{offset} @tab By which amount of bytes the actual data is shifted
3567compared to the base address of the coarray.
3568@item @var{image_index} @tab The ID of the remote image; must be a positive
3569number.
3570@item @var{dest} @tab intent(in) Array descriptor for the remote image for the
3571bounds and the size. The base_addr shall not be accessed.
3572@item @var{dst_vector} @tab intent(int)  If not NULL, it contains the vector
3573subscript of the destination array; the values are relative to the dimension
3574triplet of the dest argument.
3575@item @var{src} @tab intent(in) Array descriptor of the local array to be
3576transferred to the remote image
3577@item @var{dst_kind} @tab Kind of the destination argument
3578@item @var{src_kind} @tab Kind of the source argument
3579@item @var{may_require_tmp} @tab The variable is false it is known at compile
3580time that the @var{dest} and @var{src} either cannot overlap or overlap (fully
3581or partially) such that walking @var{src} and @var{dest} in element wise
3582element order (honoring the stride value) will not lead to wrong results.
3583Otherwise, the value is true.
3584@end multitable
3585
3586@item @emph{NOTES}
3587It is permitted to have image_id equal the current image; the memory of the
3588send-to and the send-from might (partially) overlap in that case. The
3589implementation has to take care that it handles this case, e.g. using
3590@code{memmove} which handles (partially) overlapping memory. If
3591@var{may_require_tmp} is true, the library might additionally create a
3592temporary variable, unless additional checks show that this is not required
3593(e.g. because walking backward is possible or because both arrays are
3594contiguous and @code{memmove} takes care of overlap issues).
3595
3596Note that the assignment of a scalar to an array is permitted. In addition,
3597the library has to handle numeric-type conversion and for strings, padding
3598and different character kinds.
3599@end table
3600
3601
3602@node _gfortran_caf_get
3603@subsection @code{_gfortran_caf_get} --- Getting data from a remote image
3604@cindex Coarray, _gfortran_caf_get
3605
3606@table @asis
3607@item @emph{Description}:
3608Called to get an array section or whole array from a a remote,
3609image identified by the image_index.
3610
3611@item @emph{Syntax}:
3612@code{void _gfortran_caf_get_desc (caf_token_t token, size_t offset,
3613int image_index, gfc_descriptor_t *src, caf_vector_t *src_vector,
3614gfc_descriptor_t *dest, int src_kind, int dst_kind, bool may_require_tmp)}
3615
3616@item @emph{Arguments}:
3617@multitable @columnfractions .15 .70
3618@item @var{token} @tab intent(in)  An opaque pointer identifying the coarray.
3619@item @var{offset} @tab By which amount of bytes the actual data is shifted
3620compared to the base address of the coarray.
3621@item @var{image_index} @tab The ID of the remote image; must be a positive
3622number.
3623@item @var{dest} @tab intent(in) Array descriptor of the local array to be
3624transferred to the remote image
3625@item @var{src} @tab intent(in) Array descriptor for the remote image for the
3626bounds and the size. The base_addr shall not be accessed.
3627@item @var{src_vector} @tab intent(int)  If not NULL, it contains the vector
3628subscript of the destination array; the values are relative to the dimension
3629triplet of the dest argument.
3630@item @var{dst_kind} @tab Kind of the destination argument
3631@item @var{src_kind} @tab Kind of the source argument
3632@item @var{may_require_tmp} @tab The variable is false it is known at compile
3633time that the @var{dest} and @var{src} either cannot overlap or overlap (fully
3634or partially) such that walking @var{src} and @var{dest} in element wise
3635element order (honoring the stride value) will not lead to wrong results.
3636Otherwise, the value is true.
3637@end multitable
3638
3639@item @emph{NOTES}
3640It is permitted to have image_id equal the current image; the memory of the
3641send-to and the send-from might (partially) overlap in that case. The
3642implementation has to take care that it handles this case, e.g. using
3643@code{memmove} which handles (partially) overlapping memory. If
3644@var{may_require_tmp} is true, the library might additionally create a
3645temporary variable, unless additional checks show that this is not required
3646(e.g. because walking backward is possible or because both arrays are
3647contiguous and @code{memmove} takes care of overlap issues).
3648
3649Note that the library has to handle numeric-type conversion and for strings,
3650padding and different character kinds.
3651@end table
3652
3653
3654@node _gfortran_caf_sendget
3655@subsection @code{_gfortran_caf_sendget} --- Sending data between remote images
3656@cindex Coarray, _gfortran_caf_sendget
3657
3658@table @asis
3659@item @emph{Description}:
3660Called to send a scalar, an array section or whole array from a remote image
3661identified by the src_image_index to a remote image identified by the
3662dst_image_index.
3663
3664@item @emph{Syntax}:
3665@code{void _gfortran_caf_sendget (caf_token_t dst_token, size_t dst_offset,
3666int dst_image_index, gfc_descriptor_t *dest, caf_vector_t *dst_vector,
3667caf_token_t src_token, size_t src_offset, int src_image_index,
3668gfc_descriptor_t *src, caf_vector_t *src_vector, int dst_kind, int src_kind,
3669bool may_require_tmp)}
3670
3671@item @emph{Arguments}:
3672@multitable @columnfractions .15 .70
3673@item @var{dst_token} @tab intent(in)  An opaque pointer identifying the
3674destination coarray.
3675@item @var{dst_offset} @tab  By which amount of bytes the actual data is
3676shifted compared to the base address of the destination coarray.
3677@item @var{dst_image_index} @tab The ID of the destination remote image; must
3678be a positive number.
3679@item @var{dest} @tab intent(in) Array descriptor for the destination
3680remote image for the bounds and the size. The base_addr shall not be accessed.
3681@item @var{dst_vector} @tab intent(int)  If not NULL, it contains the vector
3682subscript of the destination array; the values are relative to the dimension
3683triplet of the dest argument.
3684@item @var{src_token} @tab An opaque pointer identifying the source coarray.
3685@item @var{src_offset} @tab By which amount of bytes the actual data is shifted
3686compared to the base address of the source coarray.
3687@item @var{src_image_index} @tab The ID of the source remote image; must be a
3688positive number.
3689@item @var{src} @tab intent(in) Array descriptor of the local array to be
3690transferred to the remote image.
3691@item @var{src_vector} @tab intent(in) Array descriptor of the local array to
3692be transferred to the remote image
3693@item @var{dst_kind} @tab Kind of the destination argument
3694@item @var{src_kind} @tab Kind of the source argument
3695@item @var{may_require_tmp} @tab The variable is false it is known at compile
3696time that the @var{dest} and @var{src} either cannot overlap or overlap (fully
3697or partially) such that walking @var{src} and @var{dest} in element wise
3698element order (honoring the stride value) will not lead to wrong results.
3699Otherwise, the value is true.
3700@end multitable
3701
3702@item @emph{NOTES}
3703It is permitted to have image_ids equal; the memory of the send-to and the
3704send-from might (partially) overlap in that case. The implementation has to
3705take care that it handles this case, e.g. using @code{memmove} which handles
3706(partially) overlapping memory. If @var{may_require_tmp} is true, the library
3707might additionally create a temporary variable, unless additional checks show
3708that this is not required (e.g. because walking backward is possible or because
3709both arrays are contiguous and @code{memmove} takes care of overlap issues).
3710
3711Note that the assignment of a scalar to an array is permitted. In addition,
3712the library has to handle numeric-type conversion and for strings, padding and
3713different character kinds.
3714@end table
3715
3716
3717@node _gfortran_caf_lock
3718@subsection @code{_gfortran_caf_lock} --- Locking a lock variable
3719@cindex Coarray, _gfortran_caf_lock
3720
3721@table @asis
3722@item @emph{Description}:
3723Acquire a lock on the given image on a scalar locking variable or for the
3724given array element for an array-valued variable. If the @var{aquired_lock}
3725is @code{NULL}, the function return after having obtained the lock. If it is
3726nonnull, the result is is assigned the value true (one) when the lock could be
3727obtained and false (zero) otherwise.  Locking a lock variable which has already
3728been locked by the same image is an error.
3729
3730@item @emph{Syntax}:
3731@code{void _gfortran_caf_lock (caf_token_t token, size_t index, int image_index,
3732int *aquired_lock, int *stat, char *errmsg, int errmsg_len)}
3733
3734@item @emph{Arguments}:
3735@multitable @columnfractions .15 .70
3736@item @var{token} @tab intent(in) An opaque pointer identifying the coarray.
3737@item @var{index} @tab Array index; first array index is 0. For scalars, it is
3738always 0.
3739@item @var{image_index} @tab The ID of the remote image; must be a positive
3740number.
3741@item @var{aquired_lock} @tab intent(out) If not NULL, it returns whether lock
3742could be obtained
3743@item @var{stat} @tab intent(out) Stores the STAT=; may be NULL
3744@item @var{errmsg} @tab intent(out) When an error occurs, this will be set to
3745an error message; may be NULL
3746@item @var{errmsg_len} @tab the buffer size of errmsg.
3747@end multitable
3748
3749@item @emph{NOTES}
3750This function is also called for critical blocks; for those, the array index
3751is always zero and the image index is one.  Libraries are permitted to use other
3752images for critical-block locking variables.
3753@end table
3754
3755@node _gfortran_caf_unlock
3756@subsection @code{_gfortran_caf_lock} --- Unlocking a lock variable
3757@cindex Coarray, _gfortran_caf_unlock
3758
3759@table @asis
3760@item @emph{Description}:
3761Release a lock on the given image on a scalar locking variable or for the
3762given array element for an array-valued variable. Unlocking a lock variable
3763which is unlocked or has been locked by a different image is an error.
3764
3765@item @emph{Syntax}:
3766@code{void _gfortran_caf_unlock (caf_token_t token, size_t index, int image_index,
3767int *stat, char *errmsg, int errmsg_len)}
3768
3769@item @emph{Arguments}:
3770@multitable @columnfractions .15 .70
3771@item @var{token} @tab intent(in) An opaque pointer identifying the coarray.
3772@item @var{index} @tab Array index; first array index is 0. For scalars, it is
3773always 0.
3774@item @var{image_index} @tab The ID of the remote image; must be a positive
3775number.
3776@item @var{stat} @tab intent(out) For allocatable coarrays, stores the STAT=;
3777may be NULL
3778@item @var{errmsg} @tab intent(out) When an error occurs, this will be set to
3779an error message; may be NULL
3780@item @var{errmsg_len} @tab the buffer size of errmsg.
3781@end multitable
3782
3783@item @emph{NOTES}
3784This function is also called for critical block; for those, the array index
3785is always zero and the image index is one.  Libraries are permitted to use other
3786images for critical-block locking variables.
3787@end table
3788
3789@node _gfortran_caf_event_post
3790@subsection @code{_gfortran_caf_event_post} --- Post an event
3791@cindex Coarray, _gfortran_caf_event_post
3792
3793@table @asis
3794@item @emph{Description}:
3795Increment the event count of the specified event variable.
3796
3797@item @emph{Syntax}:
3798@code{void _gfortran_caf_event_post (caf_token_t token, size_t index,
3799int image_index, int *stat, char *errmsg, int errmsg_len)}
3800
3801@item @emph{Arguments}:
3802@multitable @columnfractions .15 .70
3803@item @var{token} @tab intent(in) An opaque pointer identifying the coarray.
3804@item @var{index} @tab Array index; first array index is 0. For scalars, it is
3805always 0.
3806@item @var{image_index} @tab The ID of the remote image; must be a positive
3807number; zero indicates the current image when accessed noncoindexed.
3808@item @var{stat} @tab intent(out) Stores the STAT=; may be NULL
3809@item @var{errmsg} @tab intent(out) When an error occurs, this will be set to
3810an error message; may be NULL
3811@item @var{errmsg_len} @tab the buffer size of errmsg.
3812@end multitable
3813
3814@item @emph{NOTES}
3815This acts like an atomic add of one to the remote image's event variable.
3816The statement is an image-control statement but does not imply sync memory.
3817Still, all preceeding push communications of this image to the specified
3818remote image has to be completed before @code{event_wait} on the remote
3819image returns.
3820@end table
3821
3822
3823
3824@node _gfortran_caf_event_wait
3825@subsection @code{_gfortran_caf_event_wait} --- Wait that an event occurred
3826@cindex Coarray, _gfortran_caf_event_wait
3827
3828@table @asis
3829@item @emph{Description}:
3830Wait until the event count has reached at least the specified
3831@var{until_count}; if so, atomically decrement the event variable by this
3832amount and return.
3833
3834@item @emph{Syntax}:
3835@code{void _gfortran_caf_event_wait (caf_token_t token, size_t index,
3836int until_count, int *stat, char *errmsg, int errmsg_len)}
3837
3838@item @emph{Arguments}:
3839@multitable @columnfractions .15 .70
3840@item @var{token} @tab intent(in) An opaque pointer identifying the coarray.
3841@item @var{index} @tab Array index; first array index is 0. For scalars, it is
3842always 0.
3843@item @var{until_count} @tab The number of events which have to be available
3844before the function returns.
3845@item @var{stat} @tab intent(out) Stores the STAT=; may be NULL
3846@item @var{errmsg} @tab intent(out) When an error occurs, this will be set to
3847an error message; may be NULL
3848@item @var{errmsg_len} @tab the buffer size of errmsg.
3849@end multitable
3850
3851@item @emph{NOTES}
3852This function only operates on a local coarray. It acts like a loop checking
3853atomically the value of the event variable, breaking if the value is greater
3854or equal the requested number of counts. Before the function returns, the
3855event variable has to be decremented by the requested @var{until_count} value.
3856A possible implementation would be a busy loop for a certain number of spins
3857(possibly depending on the number of threads relative to the number of available
3858cores) followed by other waiting strategy such as a sleeping wait (possibly with
3859an increasing number of sleep time) or, if possible, a futex wait.
3860
3861The statement is an image-control statement but does not imply sync memory.
3862Still, all preceeding push communications to this image of images having
3863issued a @code{event_push} have to be completed before this function returns.
3864@end table
3865
3866
3867
3868@node _gfortran_caf_event_query
3869@subsection @code{_gfortran_caf_event_query} --- Query event count
3870@cindex Coarray, _gfortran_caf_event_query
3871
3872@table @asis
3873@item @emph{Description}:
3874Return the event count of the specified event count.
3875
3876@item @emph{Syntax}:
3877@code{void _gfortran_caf_event_query (caf_token_t token, size_t index,
3878int image_index, int *count, int *stat)}
3879
3880@item @emph{Arguments}:
3881@multitable @columnfractions .15 .70
3882@item @var{token} @tab intent(in) An opaque pointer identifying the coarray.
3883@item @var{index} @tab Array index; first array index is 0. For scalars, it is
3884always 0.
3885@item @var{image_index} @tab The ID of the remote image; must be a positive
3886number; zero indicates the current image when accessed noncoindexed.
3887@item @var{count} @tab intent(out) The number of events currently posted to
3888the event variable
3889@item @var{stat} @tab intent(out) Stores the STAT=; may be NULL
3890@end multitable
3891
3892@item @emph{NOTES}
3893The typical use is to check the local even variable to only call
3894@code{event_wait} when the data is available. However, a coindexed variable
3895is permitted; there is no ordering or synchronization implied.  It acts like
3896an atomic fetch of the value of the event variable.
3897@end table
3898
3899@node _gfortran_caf_sync_all
3900@subsection @code{_gfortran_caf_sync_all} --- All-image barrier
3901@cindex Coarray, _gfortran_caf_sync_all
3902
3903@table @asis
3904@item @emph{Description}:
3905Synchronization of all images in the current team; the program only continues
3906on a given image after this function has been called on all images of the
3907current team.  Additionally, it ensures that all pending data transfers of
3908previous segment have completed.
3909
3910@item @emph{Syntax}:
3911@code{void _gfortran_caf_sync_all (int *stat, char *errmsg, int errmsg_len)}
3912
3913@item @emph{Arguments}:
3914@multitable @columnfractions .15 .70
3915@item @var{stat} @tab intent(out) Stores the status STAT= and may be NULL.
3916@item @var{errmsg} @tab intent(out) When an error occurs, this will be set to
3917an error message; may be NULL
3918@item @var{errmsg_len} @tab the buffer size of errmsg.
3919@end multitable
3920@end table
3921
3922
3923
3924@node _gfortran_caf_sync_images
3925@subsection @code{_gfortran_caf_sync_images} --- Barrier for selected images
3926@cindex Coarray, _gfortran_caf_sync_images
3927
3928@table @asis
3929@item @emph{Description}:
3930Synchronization between the specified images; the program only continues on a
3931given image after this function has been called on all images specified for
3932that image. Note that one image can wait for all other images in the current
3933team (e.g. via @code{sync images(*)}) while those only wait for that specific
3934image.  Additionally, @code{sync images} it ensures that all pending data
3935transfers of previous segment have completed.
3936
3937@item @emph{Syntax}:
3938@code{void _gfortran_caf_sync_images (int count, int images[], int *stat,
3939char *errmsg, int errmsg_len)}
3940
3941@item @emph{Arguments}:
3942@multitable @columnfractions .15 .70
3943@item @var{count} @tab the number of images which are provided in the next
3944argument.  For a zero-sized array, the value is zero.  For @code{sync
3945images (*)}, the value is @math{-1}.
3946@item @var{images} @tab intent(in) an array with the images provided by the
3947user. If @var{count} is zero, a NULL pointer is passed.
3948@item @var{stat} @tab intent(out) Stores the status STAT= and may be NULL.
3949@item @var{errmsg} @tab intent(out) When an error occurs, this will be set to
3950an error message; may be NULL
3951@item @var{errmsg_len} @tab the buffer size of errmsg.
3952@end multitable
3953@end table
3954
3955
3956
3957@node _gfortran_caf_sync_memory
3958@subsection @code{_gfortran_caf_sync_memory} --- Wait for completion of segment-memory operations
3959@cindex Coarray, _gfortran_caf_sync_memory
3960
3961@table @asis
3962@item @emph{Description}:
3963Acts as optimization barrier between different segments. It also ensures that
3964all pending memory operations of this image have been completed.
3965
3966@item @emph{Syntax}:
3967@code{void _gfortran_caf_sync_memory (int *stat, char *errmsg, int errmsg_len)}
3968
3969@item @emph{Arguments}:
3970@multitable @columnfractions .15 .70
3971@item @var{stat} @tab intent(out) Stores the status STAT= and may be NULL.
3972@item @var{errmsg} @tab intent(out) When an error occurs, this will be set to
3973an error message; may be NULL
3974@item @var{errmsg_len} @tab the buffer size of errmsg.
3975@end multitable
3976
3977@item @emph{NOTE} A simple implementation could be
3978@code{__asm__ __volatile__ ("":::"memory")} to prevent code movements.
3979@end table
3980
3981
3982
3983@node _gfortran_caf_error_stop
3984@subsection @code{_gfortran_caf_error_stop} --- Error termination with exit code
3985@cindex Coarray, _gfortran_caf_error_stop
3986
3987@table @asis
3988@item @emph{Description}:
3989Invoked for an @code{ERROR STOP} statement which has an integer argument.  The
3990function should terminate the program with the specified exit code.
3991
3992
3993@item @emph{Syntax}:
3994@code{void _gfortran_caf_error_stop (int32_t error)}
3995
3996@item @emph{Arguments}:
3997@multitable @columnfractions .15 .70
3998@item @var{error} @tab the exit status to be used.
3999@end multitable
4000@end table
4001
4002
4003
4004@node _gfortran_caf_error_stop_str
4005@subsection @code{_gfortran_caf_error_stop_str} --- Error termination with string
4006@cindex Coarray, _gfortran_caf_error_stop_str
4007
4008@table @asis
4009@item @emph{Description}:
4010Invoked for an @code{ERROR STOP} statement which has a string as argument.  The
4011function should terminate the program with a nonzero-exit code.
4012
4013@item @emph{Syntax}:
4014@code{void _gfortran_caf_error_stop (const char *string, int32_t len)}
4015
4016@item @emph{Arguments}:
4017@multitable @columnfractions .15 .70
4018@item @var{string} @tab the error message (not zero terminated)
4019@item @var{len} @tab the length of the string
4020@end multitable
4021@end table
4022
4023
4024
4025@node _gfortran_caf_atomic_define
4026@subsection @code{_gfortran_caf_atomic_define} --- Atomic variable assignment
4027@cindex Coarray, _gfortran_caf_atomic_define
4028
4029@table @asis
4030@item @emph{Description}:
4031Assign atomically a value to an integer or logical variable.
4032
4033@item @emph{Syntax}:
4034@code{void _gfortran_caf_atomic_define (caf_token_t token, size_t offset,
4035int image_index, void *value, int *stat, int type, int kind)}
4036
4037@item @emph{Arguments}:
4038@multitable @columnfractions .15 .70
4039@item @var{token} @tab intent(in) An opaque pointer identifying the coarray.
4040@item @var{offset} @tab By which amount of bytes the actual data is shifted
4041compared to the base address of the coarray.
4042@item @var{image_index} @tab The ID of the remote image; must be a positive
4043number; zero indicates the current image when used noncoindexed.
4044@item @var{value} @tab intent(in) the value to be assigned, passed by reference.
4045@item @var{stat} @tab intent(out) Stores the status STAT= and may be NULL.
4046@item @var{type} @tab the data type, i.e. @code{BT_INTEGER} (1) or
4047@code{BT_LOGICAL} (2).
4048@item @var{kind} @tab The kind value (only 4; always @code{int})
4049@end multitable
4050@end table
4051
4052
4053
4054@node _gfortran_caf_atomic_ref
4055@subsection @code{_gfortran_caf_atomic_ref} --- Atomic variable reference
4056@cindex Coarray, _gfortran_caf_atomic_ref
4057
4058@table @asis
4059@item @emph{Description}:
4060Reference atomically a value of a kind-4 integer or logical variable.
4061
4062@item @emph{Syntax}:
4063@code{void _gfortran_caf_atomic_ref (caf_token_t token, size_t offset,
4064int image_index, void *value, int *stat, int type, int kind)}
4065
4066@item @emph{Arguments}:
4067@item @emph{Arguments}:
4068@multitable @columnfractions .15 .70
4069@item @var{token} @tab intent(in) An opaque pointer identifying the coarray.
4070@item @var{offset} @tab By which amount of bytes the actual data is shifted
4071compared to the base address of the coarray.
4072@item @var{image_index} @tab The ID of the remote image; must be a positive
4073number; zero indicates the current image when used noncoindexed.
4074@item @var{value} @tab intent(out) The variable assigned the atomically
4075referenced variable.
4076@item @var{stat} @tab intent(out) Stores the status STAT= and may be NULL.
4077@item @var{type} @tab the data type, i.e. @code{BT_INTEGER} (1) or
4078@code{BT_LOGICAL} (2).
4079@item @var{kind} @tab The kind value (only 4; always @code{int})
4080@end multitable
4081@end table
4082
4083
4084
4085@node _gfortran_caf_atomic_cas
4086@subsection @code{_gfortran_caf_atomic_cas} --- Atomic compare and swap
4087@cindex Coarray, _gfortran_caf_atomic_cas
4088
4089@table @asis
4090@item @emph{Description}:
4091Atomic compare and swap of a kind-4 integer or logical variable. Assigns
4092atomically the specified value to the atomic variable, if the latter has
4093the value specified by the passed condition value.
4094
4095@item @emph{Syntax}:
4096@code{void _gfortran_caf_atomic_cas (caf_token_t token, size_t offset,
4097int image_index, void *old, void *compare, void *new_val, int *stat,
4098int type, int kind)}
4099
4100@item @emph{Arguments}:
4101@multitable @columnfractions .15 .70
4102@item @var{token} @tab intent(in) An opaque pointer identifying the coarray.
4103@item @var{offset} @tab By which amount of bytes the actual data is shifted
4104compared to the base address of the coarray.
4105@item @var{image_index} @tab The ID of the remote image; must be a positive
4106number; zero indicates the current image when used noncoindexed.
4107@item @var{old} @tab intent(out) the value which the atomic variable had
4108just before the cas operation.
4109@item @var{compare} @tab intent(in) The value used for comparision.
4110@item @var{new_val} @tab intent(in) The new value for the atomic variable,
4111assigned to the atomic variable, if @code{compare} equals the value of the
4112atomic variable.
4113@item @var{stat} @tab intent(out) Stores the status STAT= and may be NULL.
4114@item @var{type} @tab the data type, i.e. @code{BT_INTEGER} (1) or
4115@code{BT_LOGICAL} (2).
4116@item @var{kind} @tab The kind value (only 4; always @code{int})
4117@end multitable
4118@end table
4119
4120
4121
4122@node _gfortran_caf_atomic_op
4123@subsection @code{_gfortran_caf_atomic_op} --- Atomic operation
4124@cindex Coarray, _gfortran_caf_atomic_op
4125
4126@table @asis
4127@item @emph{Description}:
4128Apply an operation atomically to an atomic integer or logical variable.
4129After the operation, @var{old} contains the value just before the operation,
4130which, respectively, adds (GFC_CAF_ATOMIC_ADD) atomically the @code{value} to
4131the atomic integer variable or does a bitwise AND, OR or exclusive OR of the
4132between the atomic variable and @var{value}; the result is then stored in the
4133atomic variable.
4134
4135@item @emph{Syntax}:
4136@code{void _gfortran_caf_atomic_op (int op, caf_token_t token, size_t offset,
4137int image_index, void *value, void *old, int *stat, int type, int kind)}
4138
4139@item @emph{Arguments}:
4140@multitable @columnfractions .15 .70
4141@item @var{op} @tab the operation to be performed; possible values
4142@code{GFC_CAF_ATOMIC_ADD} (1), @code{GFC_CAF_ATOMIC_AND} (2),
4143@code{GFC_CAF_ATOMIC_OR} (3), @code{GFC_CAF_ATOMIC_XOR} (4).
4144@item @var{token} @tab intent(in) An opaque pointer identifying the coarray.
4145@item @var{offset} @tab By which amount of bytes the actual data is shifted
4146compared to the base address of the coarray.
4147@item @var{image_index} @tab The ID of the remote image; must be a positive
4148number; zero indicates the current image when used noncoindexed.
4149@item @var{old} @tab intent(out) the value which the atomic variable had
4150just before the atomic operation.
4151@item @var{val} @tab intent(in) The new value for the atomic variable,
4152assigned to the atomic variable, if @code{compare} equals the value of the
4153atomic variable.
4154@item @var{stat} @tab intent(out) Stores the status STAT= and may be NULL.
4155@item @var{type} @tab the data type, i.e. @code{BT_INTEGER} (1) or
4156@code{BT_LOGICAL} (2).
4157@item @var{kind} @tab The kind value (only 4; always @code{int})
4158@end multitable
4159@end table
4160
4161
4162
4163
4164@node _gfortran_caf_co_broadcast
4165@subsection @code{_gfortran_caf_co_broadcast} --- Sending data to all images
4166@cindex Coarray, _gfortran_caf_co_broadcast
4167
4168@table @asis
4169@item @emph{Description}:
4170Distribute a value from a given image to all other images in the team. Has to
4171be called collectively.
4172
4173@item @emph{Syntax}:
4174@code{void _gfortran_caf_co_broadcast (gfc_descriptor_t *a,
4175int source_image, int *stat, char *errmsg, int errmsg_len)}
4176
4177@item @emph{Arguments}:
4178@multitable @columnfractions .15 .70
4179@item @var{a} @tab intent(inout) And array descriptor with the data to be
4180breoadcasted (on @var{source_image}) or to be received (other images).
4181@item @var{source_image} @tab The ID of the image from which the data should
4182be taken.
4183@item @var{stat} @tab intent(out) Stores the status STAT= and may be NULL.
4184@item @var{errmsg} @tab intent(out) When an error occurs, this will be set to
4185an error message; may be NULL
4186@item @var{errmsg_len} @tab the buffer size of errmsg.
4187@end multitable
4188@end table
4189
4190
4191
4192@node _gfortran_caf_co_max
4193@subsection @code{_gfortran_caf_co_max} --- Collective maximum reduction
4194@cindex Coarray, _gfortran_caf_co_max
4195
4196@table @asis
4197@item @emph{Description}:
4198Calculates the for the each array element of the variable @var{a} the maximum
4199value for that element in the current team; if @var{result_image} has the
4200value 0, the result shall be stored on all images, otherwise, only on the
4201specified image. This function operates on numeric values and character
4202strings.
4203
4204@item @emph{Syntax}:
4205@code{void _gfortran_caf_co_max (gfc_descriptor_t *a, int result_image,
4206int *stat, char *errmsg, int a_len, int errmsg_len)}
4207
4208@item @emph{Arguments}:
4209@multitable @columnfractions .15 .70
4210@item @var{a} @tab intent(inout) And array descriptor with the data to be
4211breoadcasted (on @var{source_image}) or to be received (other images).
4212@item @var{result_image} @tab The ID of the image to which the reduced
4213value should be copied to; if zero, it has to be copied to all images.
4214@item @var{stat} @tab intent(out) Stores the status STAT= and may be NULL.
4215@item @var{errmsg} @tab intent(out) When an error occurs, this will be set to
4216an error message; may be NULL
4217@item @var{a_len} @tab The string length of argument @var{a}.
4218@item @var{errmsg_len} @tab the buffer size of errmsg.
4219@end multitable
4220
4221@item @emph{NOTES}
4222If @var{result_image} is nonzero, the value on all images except of the
4223specified one become undefined; hence, the library may make use of this.
4224@end table
4225
4226
4227
4228@node _gfortran_caf_co_min
4229@subsection @code{_gfortran_caf_co_min} --- Collective minimum reduction
4230@cindex Coarray, _gfortran_caf_co_min
4231
4232@table @asis
4233@item @emph{Description}:
4234Calculates the for the each array element of the variable @var{a} the minimum
4235value for that element in the current team; if @var{result_image} has the
4236value 0, the result shall be stored on all images, otherwise, only on the
4237specified image. This function operates on numeric values and character
4238strings.
4239
4240@item @emph{Syntax}:
4241@code{void _gfortran_caf_co_min (gfc_descriptor_t *a, int result_image,
4242int *stat, char *errmsg, int a_len, int errmsg_len)}
4243
4244@item @emph{Arguments}:
4245@multitable @columnfractions .15 .70
4246@item @var{a} @tab intent(inout) And array descriptor with the data to be
4247breoadcasted (on @var{source_image}) or to be received (other images).
4248@item @var{result_image} @tab The ID of the image to which the reduced
4249value should be copied to; if zero, it has to be copied to all images.
4250@item @var{stat} @tab intent(out) Stores the status STAT= and may be NULL.
4251@item @var{errmsg} @tab intent(out) When an error occurs, this will be set to
4252an error message; may be NULL
4253@item @var{a_len} @tab The string length of argument @var{a}.
4254@item @var{errmsg_len} @tab the buffer size of errmsg.
4255@end multitable
4256
4257@item @emph{NOTES}
4258If @var{result_image} is nonzero, the value on all images except of the
4259specified one become undefined; hence, the library may make use of this.
4260@end table
4261
4262
4263
4264@node _gfortran_caf_co_sum
4265@subsection @code{_gfortran_caf_co_sum} --- Collective summing reduction
4266@cindex Coarray, _gfortran_caf_co_sum
4267
4268@table @asis
4269@item @emph{Description}:
4270Calculates the for the each array element of the variable @var{a} the sum
4271value for that element in the current team; if @var{result_image} has the
4272value 0, the result shall be stored on all images, otherwise, only on the
4273specified image. This function operates on numeric values.
4274
4275@item @emph{Syntax}:
4276@code{void _gfortran_caf_co_sum (gfc_descriptor_t *a, int result_image,
4277int *stat, char *errmsg, int errmsg_len)}
4278
4279@item @emph{Arguments}:
4280@multitable @columnfractions .15 .70
4281@item @var{a} @tab intent(inout) And array descriptor with the data to be
4282breoadcasted (on @var{source_image}) or to be received (other images).
4283@item @var{result_image} @tab The ID of the image to which the reduced
4284value should be copied to; if zero, it has to be copied to all images.
4285@item @var{stat} @tab intent(out) Stores the status STAT= and may be NULL.
4286@item @var{errmsg} @tab intent(out) When an error occurs, this will be set to
4287an error message; may be NULL
4288@item @var{errmsg_len} @tab the buffer size of errmsg.
4289@end multitable
4290
4291@item @emph{NOTES}
4292If @var{result_image} is nonzero, the value on all images except of the
4293specified one become undefined; hence, the library may make use of this.
4294@end table
4295
4296
4297
4298@node _gfortran_caf_co_reduce
4299@subsection @code{_gfortran_caf_co_reduce} --- Generic collective reduction
4300@cindex Coarray, _gfortran_caf_co_reduce
4301
4302@table @asis
4303@item @emph{Description}:
4304Calculates the for the each array element of the variable @var{a} the reduction
4305value for that element in the current team; if @var{result_image} has the
4306value 0, the result shall be stored on all images, otherwise, only on the
4307specified image. The @var{opr} is a pure function doing a mathematically
4308commutative and associative operation.
4309
4310The @var{opr_flags} denote the following; the values are bitwise ored.
4311@code{GFC_CAF_BYREF} (1) if the result should be returned
4312by value; @code{GFC_CAF_HIDDENLEN} (2) whether the result and argument
4313string lengths shall be specified as hidden argument;
4314@code{GFC_CAF_ARG_VALUE} (4) whether the arguments shall be passed by value,
4315@code{GFC_CAF_ARG_DESC} (8) whether the arguments shall be passed by descriptor.
4316
4317
4318@item @emph{Syntax}:
4319@code{void _gfortran_caf_co_reduce (gfc_descriptor_t *a,
4320void * (*opr) (void *, void *), int opr_flags, int result_image,
4321int *stat, char *errmsg, int a_len, int errmsg_len)}
4322
4323@item @emph{Arguments}:
4324@multitable @columnfractions .15 .70
4325@item @var{opr} @tab Function pointer to the reduction function.
4326@item @var{opr_flags} @tab Flags regarding the reduction function
4327@item @var{a} @tab intent(inout) And array descriptor with the data to be
4328breoadcasted (on @var{source_image}) or to be received (other images).
4329@item @var{result_image} @tab The ID of the image to which the reduced
4330value should be copied to; if zero, it has to be copied to all images.
4331@item @var{stat} @tab intent(out) Stores the status STAT= and may be NULL.
4332@item @var{errmsg} @tab intent(out) When an error occurs, this will be set to
4333an error message; may be NULL
4334@item @var{a_len} @tab The string length of argument @var{a}.
4335@item @var{errmsg_len} @tab the buffer size of errmsg.
4336@end multitable
4337
4338@item @emph{NOTES}
4339If @var{result_image} is nonzero, the value on all images except of the
4340specified one become undefined; hence, the library may make use of this.
4341For character arguments, the result is passed as first argument, followed
4342by the result string length, next come the two string arguments, followed
4343by the two hidden arguments. With C binding, there are no hidden arguments
4344and by-reference passing and either only a single character is passed or
4345an array descriptor.
4346@end table
4347
4348
4349@c Intrinsic Procedures
4350@c ---------------------------------------------------------------------
4351
4352@include intrinsic.texi
4353
4354
4355@tex
4356\blankpart
4357@end tex
4358
4359@c ---------------------------------------------------------------------
4360@c Contributing
4361@c ---------------------------------------------------------------------
4362
4363@node Contributing
4364@unnumbered Contributing
4365@cindex Contributing
4366
4367Free software is only possible if people contribute to efforts
4368to create it.
4369We're always in need of more people helping out with ideas
4370and comments, writing documentation and contributing code.
4371
4372If you want to contribute to GNU Fortran,
4373have a look at the long lists of projects you can take on.
4374Some of these projects are small,
4375some of them are large;
4376some are completely orthogonal to the rest of what is
4377happening on GNU Fortran,
4378but others are ``mainstream'' projects in need of enthusiastic hackers.
4379All of these projects are important!
4380We will eventually get around to the things here,
4381but they are also things doable by someone who is willing and able.
4382
4383@menu
4384* Contributors::
4385* Projects::
4386* Proposed Extensions::
4387@end menu
4388
4389
4390@node Contributors
4391@section Contributors to GNU Fortran
4392@cindex Contributors
4393@cindex Credits
4394@cindex Authors
4395
4396Most of the parser was hand-crafted by @emph{Andy Vaught}, who is
4397also the initiator of the whole project.  Thanks Andy!
4398Most of the interface with GCC was written by @emph{Paul Brook}.
4399
4400The following individuals have contributed code and/or
4401ideas and significant help to the GNU Fortran project
4402(in alphabetical order):
4403
4404@itemize @minus
4405@item Janne Blomqvist
4406@item Steven Bosscher
4407@item Paul Brook
4408@item Tobias Burnus
4409@item Fran@,{c}ois-Xavier Coudert
4410@item Bud Davis
4411@item Jerry DeLisle
4412@item Erik Edelmann
4413@item Bernhard Fischer
4414@item Daniel Franke
4415@item Richard Guenther
4416@item Richard Henderson
4417@item Katherine Holcomb
4418@item Jakub Jelinek
4419@item Niels Kristian Bech Jensen
4420@item Steven Johnson
4421@item Steven G. Kargl
4422@item Thomas Koenig
4423@item Asher Langton
4424@item H. J. Lu
4425@item Toon Moene
4426@item Brooks Moses
4427@item Andrew Pinski
4428@item Tim Prince
4429@item Christopher D. Rickett
4430@item Richard Sandiford
4431@item Tobias Schl@"uter
4432@item Roger Sayle
4433@item Paul Thomas
4434@item Andy Vaught
4435@item Feng Wang
4436@item Janus Weil
4437@item Daniel Kraft
4438@end itemize
4439
4440The following people have contributed bug reports,
4441smaller or larger patches,
4442and much needed feedback and encouragement for the
4443GNU Fortran project: 
4444
4445@itemize @minus
4446@item Bill Clodius
4447@item Dominique d'Humi@`eres
4448@item Kate Hedstrom
4449@item Erik Schnetter
4450@item Joost VandeVondele
4451@end itemize
4452
4453Many other individuals have helped debug,
4454test and improve the GNU Fortran compiler over the past few years,
4455and we welcome you to do the same!
4456If you already have done so,
4457and you would like to see your name listed in the
4458list above, please contact us.
4459
4460
4461@node Projects
4462@section Projects
4463
4464@table @emph
4465
4466@item Help build the test suite
4467Solicit more code for donation to the test suite: the more extensive the
4468testsuite, the smaller the risk of breaking things in the future! We can
4469keep code private on request.
4470
4471@item Bug hunting/squishing
4472Find bugs and write more test cases! Test cases are especially very
4473welcome, because it allows us to concentrate on fixing bugs instead of
4474isolating them.  Going through the bugzilla database at
4475@url{https://gcc.gnu.org/@/bugzilla/} to reduce testcases posted there and
4476add more information (for example, for which version does the testcase
4477work, for which versions does it fail?) is also very helpful.
4478
4479@end table
4480
4481
4482@node Proposed Extensions
4483@section Proposed Extensions
4484
4485Here's a list of proposed extensions for the GNU Fortran compiler, in no particular
4486order.  Most of these are necessary to be fully compatible with
4487existing Fortran compilers, but they are not part of the official
4488J3 Fortran 95 standard.
4489
4490@subsection Compiler extensions:
4491@itemize @bullet
4492@item
4493User-specified alignment rules for structures.
4494
4495@item
4496Automatically extend single precision constants to double.
4497
4498@item
4499Compile code that conserves memory by dynamically allocating common and
4500module storage either on stack or heap.
4501
4502@item
4503Compile flag to generate code for array conformance checking (suggest -CC).
4504
4505@item
4506User control of symbol names (underscores, etc).
4507
4508@item
4509Compile setting for maximum size of stack frame size before spilling
4510parts to static or heap.
4511
4512@item
4513Flag to force local variables into static space.
4514
4515@item
4516Flag to force local variables onto stack.
4517@end itemize
4518
4519
4520@subsection Environment Options
4521@itemize @bullet
4522@item
4523Pluggable library modules for random numbers, linear algebra.
4524LA should use BLAS calling conventions.
4525
4526@item
4527Environment variables controlling actions on arithmetic exceptions like
4528overflow, underflow, precision loss---Generate NaN, abort, default.
4529action.
4530
4531@item
4532Set precision for fp units that support it (i387).
4533
4534@item
4535Variable for setting fp rounding mode.
4536
4537@item
4538Variable to fill uninitialized variables with a user-defined bit
4539pattern.
4540
4541@item
4542Environment variable controlling filename that is opened for that unit
4543number.
4544
4545@item
4546Environment variable to clear/trash memory being freed.
4547
4548@item
4549Environment variable to control tracing of allocations and frees.
4550
4551@item
4552Environment variable to display allocated memory at normal program end.
4553
4554@item
4555Environment variable for filename for * IO-unit.
4556
4557@item
4558Environment variable for temporary file directory.
4559
4560@item
4561Environment variable forcing standard output to be line buffered (Unix).
4562
4563@end itemize
4564
4565
4566@c ---------------------------------------------------------------------
4567@c GNU General Public License
4568@c ---------------------------------------------------------------------
4569
4570@include gpl_v3.texi
4571
4572
4573
4574@c ---------------------------------------------------------------------
4575@c GNU Free Documentation License
4576@c ---------------------------------------------------------------------
4577
4578@include fdl.texi
4579
4580
4581
4582@c ---------------------------------------------------------------------
4583@c Funding Free Software
4584@c ---------------------------------------------------------------------
4585
4586@include funding.texi
4587
4588@c ---------------------------------------------------------------------
4589@c Indices
4590@c ---------------------------------------------------------------------
4591
4592@node Option Index
4593@unnumbered Option Index
4594@command{gfortran}'s command line options are indexed here without any
4595initial @samp{-} or @samp{--}.  Where an option has both positive and
4596negative forms (such as -foption and -fno-option), relevant entries in
4597the manual are indexed under the most appropriate form; it may sometimes
4598be useful to look up both forms.
4599@printindex op
4600
4601@node Keyword Index
4602@unnumbered Keyword Index
4603@printindex cp
4604
4605@bye
4606