gcc/
[official-gcc.git] / gcc / fortran / gfortran.texi
blob4d288bafac37c585b4b8f9f931989cab723848b0
1 \input texinfo  @c -*-texinfo-*-
2 @c %**start of header
3 @setfilename gfortran.info
4 @set copyrights-gfortran 1999-2016
6 @include gcc-common.texi
8 @settitle The GNU Fortran Compiler
10 @c Create a separate index for command line options
11 @defcodeindex op
12 @c Merge the standard indexes into a single one.
13 @syncodeindex fn cp
14 @syncodeindex vr cp
15 @syncodeindex ky cp
16 @syncodeindex pg cp
17 @syncodeindex tp cp
19 @c TODO: The following "Part" definitions are included here temporarily
20 @c until they are incorporated into the official Texinfo distribution.
21 @c They borrow heavily from Texinfo's \unnchapentry definitions.
23 @tex
24 \gdef\part#1#2{%
25   \pchapsepmacro
26   \gdef\thischapter{}
27   \begingroup
28     \vglue\titlepagetopglue
29     \titlefonts \rm
30     \leftline{Part #1:@* #2}
31     \vskip4pt \hrule height 4pt width \hsize \vskip4pt
32   \endgroup
33   \writetocentry{part}{#2}{#1}
35 \gdef\blankpart{%
36   \writetocentry{blankpart}{}{}
38 % Part TOC-entry definition for summary contents.
39 \gdef\dosmallpartentry#1#2#3#4{%
40   \vskip .5\baselineskip plus.2\baselineskip
41   \begingroup
42     \let\rm=\bf \rm
43     \tocentry{Part #2: #1}{\doshortpageno\bgroup#4\egroup}
44   \endgroup
46 \gdef\dosmallblankpartentry#1#2#3#4{%
47   \vskip .5\baselineskip plus.2\baselineskip
49 % Part TOC-entry definition for regular contents.  This has to be
50 % equated to an existing entry to not cause problems when the PDF
51 % outline is created.
52 \gdef\dopartentry#1#2#3#4{%
53   \unnchapentry{Part #2: #1}{}{#3}{#4}
55 \gdef\doblankpartentry#1#2#3#4{}
56 @end tex
58 @c %**end of header
60 @c Use with @@smallbook.
62 @c %** start of document
64 @c Cause even numbered pages to be printed on the left hand side of
65 @c the page and odd numbered pages to be printed on the right hand
66 @c side of the page.  Using this, you can print on both sides of a
67 @c sheet of paper and have the text on the same part of the sheet.
69 @c The text on right hand pages is pushed towards the right hand
70 @c margin and the text on left hand pages is pushed toward the left
71 @c hand margin.
72 @c (To provide the reverse effect, set bindingoffset to -0.75in.)
74 @c @tex
75 @c \global\bindingoffset=0.75in
76 @c \global\normaloffset =0.75in
77 @c @end tex
79 @copying
80 Copyright @copyright{} @value{copyrights-gfortran} Free Software Foundation, Inc.
82 Permission is granted to copy, distribute and/or modify this document
83 under the terms of the GNU Free Documentation License, Version 1.3 or
84 any later version published by the Free Software Foundation; with the
85 Invariant Sections being ``Funding Free Software'', the Front-Cover
86 Texts being (a) (see below), and with the Back-Cover Texts being (b)
87 (see below).  A copy of the license is included in the section entitled
88 ``GNU Free Documentation License''.
90 (a) The FSF's Front-Cover Text is:
92      A GNU Manual
94 (b) The FSF's Back-Cover Text is:
96      You have freedom to copy and modify this GNU Manual, like GNU
97      software.  Copies published by the Free Software Foundation raise
98      funds for GNU development.
99 @end copying
101 @ifinfo
102 @dircategory Software development
103 @direntry
104 * gfortran: (gfortran).                  The GNU Fortran Compiler.
105 @end direntry
106 This file documents the use and the internals of
107 the GNU Fortran compiler, (@command{gfortran}).
109 Published by the Free Software Foundation
110 51 Franklin Street, Fifth Floor
111 Boston, MA 02110-1301 USA
113 @insertcopying
114 @end ifinfo
117 @setchapternewpage odd
118 @titlepage
119 @title Using GNU Fortran
120 @versionsubtitle
121 @author The @t{gfortran} team
122 @page
123 @vskip 0pt plus 1filll
124 Published by the Free Software Foundation@*
125 51 Franklin Street, Fifth Floor@*
126 Boston, MA 02110-1301, USA@*
127 @c Last printed ??ber, 19??.@*
128 @c Printed copies are available for $? each.@*
129 @c ISBN ???
130 @sp 1
131 @insertcopying
132 @end titlepage
134 @c TODO: The following "Part" definitions are included here temporarily
135 @c until they are incorporated into the official Texinfo distribution.
137 @tex
138 \global\let\partentry=\dosmallpartentry
139 \global\let\blankpartentry=\dosmallblankpartentry
140 @end tex
141 @summarycontents
143 @tex
144 \global\let\partentry=\dopartentry
145 \global\let\blankpartentry=\doblankpartentry
146 @end tex
147 @contents
149 @page
151 @c ---------------------------------------------------------------------
152 @c TexInfo table of contents.
153 @c ---------------------------------------------------------------------
155 @ifnottex
156 @node Top
157 @top Introduction
158 @cindex Introduction
160 This manual documents the use of @command{gfortran},
161 the GNU Fortran compiler.  You can find in this manual how to invoke
162 @command{gfortran}, as well as its features and incompatibilities.
164 @ifset DEVELOPMENT
165 @emph{Warning:} This document, and the compiler it describes, are still
166 under development.  While efforts are made to keep it up-to-date, it might
167 not accurately reflect the status of the most recent GNU Fortran compiler.
168 @end ifset
170 @comment
171 @comment  When you add a new menu item, please keep the right hand
172 @comment  aligned to the same column.  Do not use tabs.  This provides
173 @comment  better formatting.
174 @comment
175 @menu
176 * Introduction::
178 Part I: Invoking GNU Fortran
179 * Invoking GNU Fortran:: Command options supported by @command{gfortran}.
180 * Runtime::              Influencing runtime behavior with environment variables.
182 Part II: Language Reference
183 * Fortran 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.
191 * Contributing::         How you can help.
192 * Copying::              GNU General Public License says
193                          how you can copy and share GNU Fortran.
194 * GNU Free Documentation License::
195                          How you can copy and share this manual.
196 * Funding::              How to help assure continued work for free software.
197 * Option Index::         Index of command line options
198 * Keyword Index::        Index of concepts
199 @end menu
200 @end ifnottex
202 @c ---------------------------------------------------------------------
203 @c Introduction
204 @c ---------------------------------------------------------------------
206 @node Introduction
207 @chapter Introduction
209 @c The following duplicates the text on the TexInfo table of contents.
210 @iftex
211 This manual documents the use of @command{gfortran}, the GNU Fortran
212 compiler.  You can find in this manual how to invoke @command{gfortran},
213 as well as its features and incompatibilities.
215 @ifset DEVELOPMENT
216 @emph{Warning:} This document, and the compiler it describes, are still
217 under development.  While efforts are made to keep it up-to-date, it
218 might not accurately reflect the status of the most recent GNU Fortran
219 compiler.
220 @end ifset
221 @end iftex
223 The GNU Fortran compiler front end was
224 designed initially as a free replacement for,
225 or alternative to, the Unix @command{f95} command;
226 @command{gfortran} is the command you will use to invoke the compiler.
228 @menu
229 * About GNU Fortran::    What you should know about the GNU Fortran compiler.
230 * GNU Fortran and GCC::  You can compile Fortran, C, or other programs.
231 * Preprocessing and conditional compilation:: The Fortran preprocessor
232 * GNU Fortran and G77::  Why we chose to start from scratch.
233 * Project Status::       Status of GNU Fortran, roadmap, proposed extensions.
234 * Standards::            Standards supported by GNU Fortran.
235 @end menu
238 @c ---------------------------------------------------------------------
239 @c About GNU Fortran
240 @c ---------------------------------------------------------------------
242 @node About GNU Fortran
243 @section About GNU Fortran
245 The GNU Fortran compiler supports the Fortran 77, 90 and 95 standards
246 completely, parts of the Fortran 2003 and Fortran 2008 standards, and
247 several vendor extensions.  The development goal is to provide the
248 following features:
250 @itemize @bullet
251 @item
252 Read a user's program,
253 stored in a file and containing instructions written
254 in Fortran 77, Fortran 90, Fortran 95, Fortran 2003 or Fortran 2008.
255 This file contains @dfn{source code}.
257 @item
258 Translate the user's program into instructions a computer
259 can carry out more quickly than it takes to translate the
260 instructions in the first
261 place.  The result after compilation of a program is
262 @dfn{machine code},
263 code designed to be efficiently translated and processed
264 by a machine such as your computer.
265 Humans usually are not as good writing machine code
266 as they are at writing Fortran (or C++, Ada, or Java),
267 because it is easy to make tiny mistakes writing machine code.
269 @item
270 Provide the user with information about the reasons why
271 the compiler is unable to create a binary from the source code.
272 Usually this will be the case if the source code is flawed.
273 The Fortran 90 standard requires that the compiler can point out
274 mistakes to the user.
275 An incorrect usage of the language causes an @dfn{error message}.
277 The compiler will also attempt to diagnose cases where the
278 user's program contains a correct usage of the language,
279 but instructs the computer to do something questionable.
280 This kind of diagnostics message is called a @dfn{warning message}.
282 @item
283 Provide optional information about the translation passes
284 from the source code to machine code.
285 This can help a user of the compiler to find the cause of
286 certain bugs which may not be obvious in the source code,
287 but may be more easily found at a lower level compiler output.
288 It also helps developers to find bugs in the compiler itself.
290 @item
291 Provide information in the generated machine code that can
292 make it easier to find bugs in the program (using a debugging tool,
293 called a @dfn{debugger}, such as the GNU Debugger @command{gdb}).
295 @item
296 Locate and gather machine code already generated to
297 perform actions requested by statements in the user's program.
298 This machine code is organized into @dfn{modules} and is located
299 and @dfn{linked} to the user program.
300 @end itemize
302 The GNU Fortran compiler consists of several components:
304 @itemize @bullet
305 @item
306 A version of the @command{gcc} command
307 (which also might be installed as the system's @command{cc} command)
308 that also understands and accepts Fortran source code.
309 The @command{gcc} command is the @dfn{driver} program for
310 all the languages in the GNU Compiler Collection (GCC);
311 With @command{gcc},
312 you can compile the source code of any language for
313 which a front end is available in GCC.
315 @item
316 The @command{gfortran} command itself,
317 which also might be installed as the
318 system's @command{f95} command.
319 @command{gfortran} is just another driver program,
320 but specifically for the Fortran compiler only.
321 The difference with @command{gcc} is that @command{gfortran}
322 will automatically link the correct libraries to your program.
324 @item
325 A collection of run-time libraries.
326 These libraries contain the machine code needed to support
327 capabilities of the Fortran language that are not directly
328 provided by the machine code generated by the
329 @command{gfortran} compilation phase,
330 such as intrinsic functions and subroutines,
331 and routines for interaction with files and the operating system.
332 @c and mechanisms to spawn,
333 @c unleash and pause threads in parallelized code.
335 @item
336 The Fortran compiler itself, (@command{f951}).
337 This is the GNU Fortran parser and code generator,
338 linked to and interfaced with the GCC backend library.
339 @command{f951} ``translates'' the source code to
340 assembler code.  You would typically not use this
341 program directly;
342 instead, the @command{gcc} or @command{gfortran} driver
343 programs will call it for you.
344 @end itemize
347 @c ---------------------------------------------------------------------
348 @c GNU Fortran and GCC
349 @c ---------------------------------------------------------------------
351 @node GNU Fortran and GCC
352 @section GNU Fortran and GCC
353 @cindex GNU Compiler Collection
354 @cindex GCC
356 GNU Fortran is a part of GCC, the @dfn{GNU Compiler Collection}.  GCC
357 consists of a collection of front ends for various languages, which
358 translate the source code into a language-independent form called
359 @dfn{GENERIC}.  This is then processed by a common middle end which
360 provides optimization, and then passed to one of a collection of back
361 ends which generate code for different computer architectures and
362 operating systems.
364 Functionally, this is implemented with a driver program (@command{gcc})
365 which provides the command-line interface for the compiler.  It calls
366 the relevant compiler front-end program (e.g., @command{f951} for
367 Fortran) for each file in the source code, and then calls the assembler
368 and linker as appropriate to produce the compiled output.  In a copy of
369 GCC 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
372 Fortran source code, and compile it accordingly.  A @command{gfortran}
373 driver program is also provided, which is identical to @command{gcc}
374 except that it automatically links the Fortran runtime libraries into the
375 compiled program.
377 Source 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.
379 Source files with @file{.f90}, @file{.f95}, @file{.f03}, @file{.f08},
380 @file{.F90}, @file{.F95}, @file{.F03} and @file{.F08} extensions are
381 treated as free form.  The capitalized versions of either form are run
382 through preprocessing.  Source files with the lower case @file{.fpp}
383 extension are also run through preprocessing.
385 This manual specifically documents the Fortran front end, which handles
386 the programming language's syntax and semantics.  The aspects of GCC
387 which relate to the optimization passes and the back-end code generation
388 are documented in the GCC manual; see 
389 @ref{Top,,Introduction,gcc,Using the GNU Compiler Collection (GCC)}.
390 The two manuals together provide a complete reference for the GNU
391 Fortran compiler.
394 @c ---------------------------------------------------------------------
395 @c Preprocessing and conditional compilation
396 @c ---------------------------------------------------------------------
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
406 Many Fortran compilers including GNU Fortran allow passing the source code
407 through a C preprocessor (CPP; sometimes also called the Fortran preprocessor,
408 FPP) to allow for conditional compilation.  In the case of GNU Fortran,
409 this is the GNU C Preprocessor in the traditional mode.  On systems with
410 case-preserving file names, the preprocessor is automatically invoked if the
411 filename extension is @file{.F}, @file{.FOR}, @file{.FTN}, @file{.fpp},
412 @file{.FPP}, @file{.F90}, @file{.F95}, @file{.F03} or @file{.F08}.  To manually
413 invoke the preprocessor on any file, use @option{-cpp}, to disable
414 preprocessing on files where the preprocessor is run automatically, use
415 @option{-nocpp}.
417 If a preprocessed file includes another file with the Fortran @code{INCLUDE}
418 statement, the included file is not preprocessed.  To preprocess included
419 files, use the equivalent preprocessor statement @code{#include}.
421 If GNU Fortran invokes the preprocessor, @code{__GFORTRAN__}
422 is defined and @code{__GNUC__}, @code{__GNUC_MINOR__} and
423 @code{__GNUC_PATCHLEVEL__} can be used to determine the version of the
424 compiler.  See @ref{Top,,Overview,cpp,The C Preprocessor} for details.
426 While CPP is the de-facto standard for preprocessing Fortran code,
427 Part 3 of the Fortran 95 standard (ISO/IEC 1539-3:1998) defines
428 Conditional Compilation, which is not widely used and not directly
429 supported by the GNU Fortran compiler.  You can use the program coco
430 to preprocess such files (@uref{http://www.daniellnagle.com/coco.html}).
433 @c ---------------------------------------------------------------------
434 @c GNU Fortran and G77
435 @c ---------------------------------------------------------------------
437 @node GNU Fortran and G77
438 @section GNU Fortran and G77
439 @cindex Fortran 77
440 @cindex @command{g77}
442 The GNU Fortran compiler is the successor to @command{g77}, the Fortran 
443 77 front end included in GCC prior to version 4.  It is an entirely new 
444 program that has been designed to provide Fortran 95 support and 
445 extensibility for future Fortran language standards, as well as providing 
446 backwards compatibility for Fortran 77 and nearly all of the GNU language 
447 extensions supported by @command{g77}.
450 @c ---------------------------------------------------------------------
451 @c Project Status
452 @c ---------------------------------------------------------------------
454 @node Project Status
455 @section Project Status
457 @quotation
458 As soon as @command{gfortran} can parse all of the statements correctly,
459 it will be in the ``larva'' state.
460 When we generate code, the ``puppa'' state.
461 When @command{gfortran} is done,
462 we'll see if it will be a beautiful butterfly,
463 or just a big bug....
465 --Andy Vaught, April 2000
466 @end quotation
468 The start of the GNU Fortran 95 project was announced on
469 the GCC homepage in March 18, 2000
470 (even though Andy had already been working on it for a while,
471 of course).
473 The GNU Fortran compiler is able to compile nearly all
474 standard-compliant Fortran 95, Fortran 90, and Fortran 77 programs,
475 including a number of standard and non-standard extensions, and can be
476 used on real-world programs.  In particular, the supported extensions
477 include OpenMP, Cray-style pointers, some old vendor extensions, and several
478 Fortran 2003 and Fortran 2008 features, including TR 15581.  However, it is
479 still under development and has a few remaining rough edges.
480 There also is initial support for OpenACC.
481 Note that this is an experimental feature, incomplete, and subject to
482 change in future versions of GCC.  See
483 @uref{https://gcc.gnu.org/wiki/OpenACC} for more information.
485 At present, the GNU Fortran compiler passes the
486 @uref{http://www.fortran-2000.com/ArnaudRecipes/fcvs21_f95.html, 
487 NIST Fortran 77 Test Suite}, and produces acceptable results on the
488 @uref{http://www.netlib.org/lapack/faq.html#1.21, LAPACK Test Suite}.
489 It also provides respectable performance on 
490 the @uref{http://www.polyhedron.com/fortran-compiler-comparisons/polyhedron-benchmark-suite,
491 Polyhedron Fortran
492 compiler benchmarks} and the
493 @uref{http://www.netlib.org/benchmark/livermore,
494 Livermore Fortran Kernels test}.  It has been used to compile a number of
495 large 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,
498 the Tonto quantum chemistry package}; see
499 @url{https://gcc.gnu.org/@/wiki/@/GfortranApps} for an extended list.
501 Among other things, the GNU Fortran compiler is intended as a replacement
502 for G77.  At this point, nearly all programs that could be compiled with
503 G77 can be compiled with GNU Fortran, although there are a few minor known
504 regressions.
506 The primary work remaining to be done on GNU Fortran falls into three
507 categories: bug fixing (primarily regarding the treatment of invalid code
508 and providing useful error messages), improving the compiler optimizations
509 and the performance of compiled code, and extending the compiler to support
510 future standards---in particular, Fortran 2003 and Fortran 2008.
513 @c ---------------------------------------------------------------------
514 @c Standards
515 @c ---------------------------------------------------------------------
517 @node Standards
518 @section Standards
519 @cindex Standards
521 @menu
522 * Varying Length Character Strings::
523 @end menu
525 The GNU Fortran compiler implements
526 ISO/IEC 1539:1997 (Fortran 95).  As such, it can also compile essentially all
527 standard-compliant Fortran 90 and Fortran 77 programs.   It also supports
528 the ISO/IEC TR-15581 enhancements to allocatable arrays.
530 GNU Fortran also have a partial support for ISO/IEC 1539-1:2004 (Fortran
531 2003), ISO/IEC 1539-1:2010 (Fortran 2008), the Technical Specification
532 @code{Further Interoperability of Fortran with C} (ISO/IEC TS 29113:2012).
533 Full support of those standards and future Fortran standards is planned.
534 The current status of the support is can be found in the
535 @ref{Fortran 2003 status}, @ref{Fortran 2008 status}, @ref{TS 29113 status}
536 and @ref{TS 18508 status} sections of the documentation.
538 Additionally, the GNU Fortran compilers supports the OpenMP specification
539 (version 4.0, @url{http://openmp.org/@/wp/@/openmp-specifications/}).
540 There also is initial support for the OpenACC specification (targeting
541 version 2.0, @uref{http://www.openacc.org/}).
542 Note that this is an experimental feature, incomplete, and subject to
543 change in future versions of GCC.  See
544 @uref{https://gcc.gnu.org/wiki/OpenACC} for more information.
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
552 The Fortran 95 standard specifies in Part 2 (ISO/IEC 1539-2:2000)
553 varying length character strings.  While GNU Fortran currently does not
554 support such strings directly, there exist two Fortran implementations
555 for 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/}.
559 Deferred-length character strings of Fortran 2003 supports part of
560 the features of @code{ISO_VARYING_STRING} and should be considered as
561 replacement. (Namely, allocatable or pointers of the type
562 @code{character(len=:)}.)
565 @c =====================================================================
566 @c PART I: INVOCATION REFERENCE
567 @c =====================================================================
569 @tex
570 \part{I}{Invoking GNU Fortran}
571 @end tex
573 @c ---------------------------------------------------------------------
574 @c Compiler Options
575 @c ---------------------------------------------------------------------
577 @include invoke.texi
580 @c ---------------------------------------------------------------------
581 @c Runtime
582 @c ---------------------------------------------------------------------
584 @node Runtime
585 @chapter Runtime:  Influencing runtime behavior with environment variables
586 @cindex environment variable
588 The behavior of the @command{gfortran} can be influenced by
589 environment variables.
591 Malformed environment variables are silently ignored.
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
608 @node TMPDIR
609 @section @env{TMPDIR}---Directory for scratch files
611 When opening a file with @code{STATUS='SCRATCH'}, GNU Fortran tries to
612 create the file in one of the potential directories by testing each
613 directory in the order below.
615 @enumerate
616 @item
617 The environment variable @env{TMPDIR}, if it exists.
619 @item
620 On the MinGW target, the directory returned by the @code{GetTempPath}
621 function. Alternatively, on the Cygwin target, the @env{TMP} and
622 @env{TEMP} environment variables, if they exist, in that order.
624 @item
625 The @code{P_tmpdir} macro if it is defined, otherwise the directory
626 @file{/tmp}.
627 @end enumerate
629 @node GFORTRAN_STDIN_UNIT
630 @section @env{GFORTRAN_STDIN_UNIT}---Unit number for standard input
632 This environment variable can be used to select the unit number
633 preconnected to standard input.  This must be a positive integer.
634 The default value is 5.
636 @node GFORTRAN_STDOUT_UNIT
637 @section @env{GFORTRAN_STDOUT_UNIT}---Unit number for standard output
639 This environment variable can be used to select the unit number
640 preconnected to standard output.  This must be a positive integer.
641 The default value is 6.
643 @node GFORTRAN_STDERR_UNIT
644 @section @env{GFORTRAN_STDERR_UNIT}---Unit number for standard error
646 This environment variable can be used to select the unit number
647 preconnected to standard error.  This must be a positive integer.
648 The default value is 0.
650 @node GFORTRAN_UNBUFFERED_ALL
651 @section @env{GFORTRAN_UNBUFFERED_ALL}---Do not buffer I/O on all units
653 This environment variable controls whether all I/O is unbuffered.  If
654 the first letter is @samp{y}, @samp{Y} or @samp{1}, all I/O is
655 unbuffered.  This will slow down small sequential reads and writes.  If
656 the first letter is @samp{n}, @samp{N} or @samp{0}, I/O is buffered.
657 This is the default.
659 @node GFORTRAN_UNBUFFERED_PRECONNECTED
660 @section @env{GFORTRAN_UNBUFFERED_PRECONNECTED}---Do not buffer I/O on preconnected units
662 The environment variable named @env{GFORTRAN_UNBUFFERED_PRECONNECTED} controls
663 whether I/O on a preconnected unit (i.e.@: STDOUT or STDERR) is unbuffered.  If 
664 the first letter is @samp{y}, @samp{Y} or @samp{1}, I/O is unbuffered.  This
665 will slow down small sequential reads and writes.  If the first letter
666 is @samp{n}, @samp{N} or @samp{0}, I/O is buffered.  This is the default.
668 @node GFORTRAN_SHOW_LOCUS
669 @section @env{GFORTRAN_SHOW_LOCUS}---Show location for runtime errors
671 If the first letter is @samp{y}, @samp{Y} or @samp{1}, filename and
672 line numbers for runtime errors are printed.  If the first letter is
673 @samp{n}, @samp{N} or @samp{0}, do not print filename and line numbers
674 for runtime errors.  The default is to print the location.
676 @node GFORTRAN_OPTIONAL_PLUS
677 @section @env{GFORTRAN_OPTIONAL_PLUS}---Print leading + where permitted
679 If the first letter is @samp{y}, @samp{Y} or @samp{1},
680 a plus sign is printed
681 where permitted by the Fortran standard.  If the first letter
682 is @samp{n}, @samp{N} or @samp{0}, a plus sign is not printed
683 in most cases.  Default is not to print plus signs.
685 @node GFORTRAN_DEFAULT_RECL
686 @section @env{GFORTRAN_DEFAULT_RECL}---Default record length for new files
688 This environment variable specifies the default record length, in
689 bytes, for files which are opened without a @code{RECL} tag in the
690 @code{OPEN} statement.  This must be a positive integer.  The
691 default value is 1073741824 bytes (1 GB).
693 @node GFORTRAN_LIST_SEPARATOR
694 @section @env{GFORTRAN_LIST_SEPARATOR}---Separator for list output
696 This environment variable specifies the separator when writing
697 list-directed output.  It may contain any number of spaces and
698 at most one comma.  If you specify this on the command line,
699 be sure to quote spaces, as in
700 @smallexample
701 $ GFORTRAN_LIST_SEPARATOR='  ,  ' ./a.out
702 @end smallexample
703 when @command{a.out} is the compiled Fortran program that you want to run.
704 Default is a single space.
706 @node GFORTRAN_CONVERT_UNIT
707 @section @env{GFORTRAN_CONVERT_UNIT}---Set endianness for unformatted I/O
709 By setting the @env{GFORTRAN_CONVERT_UNIT} variable, it is possible
710 to change the representation of data for unformatted files.
711 The syntax for the @env{GFORTRAN_CONVERT_UNIT} variable is:
712 @smallexample
713 GFORTRAN_CONVERT_UNIT: mode | mode ';' exception | exception ;
714 mode: 'native' | 'swap' | 'big_endian' | 'little_endian' ;
715 exception: mode ':' unit_list | unit_list ;
716 unit_list: unit_spec | unit_list unit_spec ;
717 unit_spec: INTEGER | INTEGER '-' INTEGER ;
718 @end smallexample
719 The variable consists of an optional default mode, followed by
720 a list of optional exceptions, which are separated by semicolons
721 from the preceding default and each other.  Each exception consists
722 of a format and a comma-separated list of units.  Valid values for
723 the modes are the same as for the @code{CONVERT} specifier:
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
729 for unformatted files.
730 @item @code{BIG_ENDIAN} Use the big-endian format for unformatted files.
731 @end itemize
732 A missing mode for an exception is taken to mean @code{BIG_ENDIAN}.
733 Examples 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 
737 in little_endian mode, except for units 10 to 20 and 25, which are in
738 native format.
739 @item @code{'10-20'}  Units 10 to 20 are big-endian, the rest is native.
740 @end itemize
742 Setting the environment variables should be done on the command
743 line or via the @command{export}
744 command for @command{sh}-compatible shells and via @command{setenv}
745 for @command{csh}-compatible shells.
747 Example for @command{sh}:
748 @smallexample
749 $ gfortran foo.f90
750 $ GFORTRAN_CONVERT_UNIT='big_endian;native:10-20' ./a.out
751 @end smallexample
753 Example 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
760 Using anything but the native representation for unformatted data
761 carries a significant speed overhead.  If speed in this area matters
762 to you, it is best if you use this only for data that needs to be
763 portable.
765 @xref{CONVERT specifier}, for an alternative way to specify the
766 data representation for unformatted files.  @xref{Runtime Options}, for
767 setting a default data representation for the whole program.  The
768 @code{CONVERT} specifier overrides the @option{-fconvert} compile options.
770 @emph{Note that the values specified via the GFORTRAN_CONVERT_UNIT
771 environment variable will override the CONVERT specifier in the
772 open statement}.  This is to give control over data formats to
773 users who do not have the source code of their program available.
775 @node GFORTRAN_ERROR_BACKTRACE
776 @section @env{GFORTRAN_ERROR_BACKTRACE}---Show backtrace on run-time errors
778 If 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
780 backtrace is printed when a serious run-time error occurs.  To disable
781 the backtracing, set the variable to @samp{n}, @samp{N}, @samp{0}.
782 Default is to print a backtrace unless the @option{-fno-backtrace}
783 compile option was used.
785 @c =====================================================================
786 @c PART II: LANGUAGE REFERENCE
787 @c =====================================================================
789 @tex
790 \part{II}{Language Reference}
791 @end tex
793 @c ---------------------------------------------------------------------
794 @c Fortran 2003 and 2008 Status
795 @c ---------------------------------------------------------------------
797 @node Fortran 2003 and 2008 status
798 @chapter Fortran 2003 and 2008 Status
800 @menu
801 * Fortran 2003 status::
802 * Fortran 2008 status::
803 * TS 29113 status::
804 * TS 18508 status::
805 @end menu
807 @node Fortran 2003 status
808 @section Fortran 2003 status
810 GNU Fortran supports several Fortran 2003 features; an incomplete
811 list can be found below.  See also the
812 @uref{https://gcc.gnu.org/wiki/Fortran2003, wiki page} about Fortran 2003.
814 @itemize
815 @item Procedure pointers including procedure-pointer components with
816 @code{PASS} attribute.
818 @item Procedures which are bound to a derived type (type-bound procedures)
819 including @code{PASS}, @code{PROCEDURE} and @code{GENERIC}, and
820 operators bound to a type.
822 @item Abstract interfaces and type extension with the possibility to
823 override type-bound procedures or to have deferred binding.
825 @item Polymorphic entities (``@code{CLASS}'') for derived types and unlimited
826 polymorphism (``@code{CLASS(*)}'') -- including @code{SAME_TYPE_AS},
827 @code{EXTENDS_TYPE_OF} and @code{SELECT TYPE} for scalars and arrays and
828 finalization.
830 @item Generic interface names, which have the same name as derived types,
831 are now supported. This allows one to write constructor functions.  Note
832 that Fortran does not support static constructor functions.  For static
833 variables, only default initialization or structure-constructor
834 initialization are available.
836 @item The @code{ASSOCIATE} construct.
838 @item Interoperability with C including enumerations, 
840 @item In structure constructors the components with default values may be
841 omitted.
843 @item Extensions to the @code{ALLOCATE} statement, allowing for a
844 type-specification with type parameter and for allocation and initialization
845 from a @code{SOURCE=} expression; @code{ALLOCATE} and @code{DEALLOCATE}
846 optionally return an error message string via @code{ERRMSG=}.
848 @item Reallocation on assignment: If an intrinsic assignment is
849 used, an allocatable variable on the left-hand side is automatically allocated
850 (if unallocated) or reallocated (if the shape is different). Currently, scalar
851 deferred character length left-hand sides are correctly handled but arrays
852 are not yet fully implemented.
854 @item Deferred-length character variables and scalar deferred-length character
855 components of derived types are supported. (Note that array-valued compoents
856 are not yet implemented.)
858 @item Transferring of allocations via @code{MOVE_ALLOC}.
860 @item The @code{PRIVATE} and @code{PUBLIC} attributes may be given individually
861 to derived-type components.
863 @item In pointer assignments, the lower bound may be specified and
864 the remapping of elements is supported.
866 @item For pointers an @code{INTENT} may be specified which affect the
867 association status not the value of the pointer target.
869 @item Intrinsics @code{command_argument_count}, @code{get_command},
870 @code{get_command_argument}, and @code{get_environment_variable}.
872 @item Support for Unicode characters (ISO 10646) and UTF-8, including
873 the @code{SELECTED_CHAR_KIND} and @code{NEW_LINE} intrinsic functions.
875 @item Support for binary, octal and hexadecimal (BOZ) constants in the
876 intrinsic functions @code{INT}, @code{REAL}, @code{CMPLX} and @code{DBLE}.
878 @item Support for namelist variables with allocatable and pointer
879 attribute and nonconstant length type parameter.
881 @item
882 @cindex array, constructors
883 @cindex @code{[...]}
884 Array constructors using square brackets.  That is, @code{[...]} rather
885 than @code{(/.../)}.  Type-specification for array constructors like
886 @code{(/ some-type :: ... /)}.
888 @item Extensions to the specification and initialization expressions,
889 including the support for intrinsics with real and complex arguments.
891 @item Support for the asynchronous input/output syntax; however, the
892 data transfer is currently always synchronously performed. 
894 @item
895 @cindex @code{FLUSH} statement
896 @cindex statement, @code{FLUSH}
897 @code{FLUSH} statement.
899 @item
900 @cindex @code{IOMSG=} specifier
901 @code{IOMSG=} specifier for I/O statements.
903 @item
904 @cindex @code{ENUM} statement
905 @cindex @code{ENUMERATOR} statement
906 @cindex statement, @code{ENUM}
907 @cindex statement, @code{ENUMERATOR}
908 @opindex @code{fshort-enums}
909 Support for the declaration of enumeration constants via the
910 @code{ENUM} and @code{ENUMERATOR} statements.  Interoperability with
911 @command{gcc} is guaranteed also for the case where the
912 @command{-fshort-enums} command line option is given.
914 @item
915 @cindex TR 15581
916 TR 15581:
917 @itemize
918 @item
919 @cindex @code{ALLOCATABLE} dummy arguments
920 @code{ALLOCATABLE} dummy arguments.
921 @item
922 @cindex @code{ALLOCATABLE} function results
923 @code{ALLOCATABLE} function results
924 @item
925 @cindex @code{ALLOCATABLE} components of derived types
926 @code{ALLOCATABLE} components of derived types
927 @end itemize
929 @item
930 @cindex @code{STREAM} I/O
931 @cindex @code{ACCESS='STREAM'} I/O
932 The @code{OPEN} statement supports the @code{ACCESS='STREAM'} specifier,
933 allowing I/O without any record structure.
935 @item
936 Namelist input/output for internal files.
938 @item Minor I/O features: Rounding during formatted output, using of
939 a decimal comma instead of a decimal point, setting whether a plus sign
940 should appear for positive numbers. On systems where @code{strtod} honours
941 the rounding mode, the rounding mode is also supported for input.
943 @item
944 @cindex @code{PROTECTED} statement
945 @cindex statement, @code{PROTECTED}
946 The @code{PROTECTED} statement and attribute.
948 @item
949 @cindex @code{VALUE} statement
950 @cindex statement, @code{VALUE}
951 The @code{VALUE} statement and attribute.
953 @item
954 @cindex @code{VOLATILE} statement
955 @cindex statement, @code{VOLATILE}
956 The @code{VOLATILE} statement and attribute.
958 @item
959 @cindex @code{IMPORT} statement
960 @cindex statement, @code{IMPORT}
961 The @code{IMPORT} statement, allowing to import
962 host-associated derived types.
964 @item The intrinsic modules @code{ISO_FORTRAN_ENVIRONMENT} is supported,
965 which contains parameters of the I/O units, storage sizes. Additionally,
966 procedures for C interoperability are available in the @code{ISO_C_BINDING}
967 module.
969 @item
970 @cindex @code{USE, INTRINSIC} statement
971 @cindex statement, @code{USE, INTRINSIC}
972 @cindex @code{ISO_FORTRAN_ENV} statement
973 @cindex statement, @code{ISO_FORTRAN_ENV}
974 @code{USE} statement with @code{INTRINSIC} and @code{NON_INTRINSIC}
975 attribute; supported intrinsic modules: @code{ISO_FORTRAN_ENV},
976 @code{ISO_C_BINDING}, @code{OMP_LIB} and @code{OMP_LIB_KINDS},
977 and @code{OPENACC}.
979 @item
980 Renaming of operators in the @code{USE} statement.
982 @end itemize
985 @node Fortran 2008 status
986 @section Fortran 2008 status
988 The latest version of the Fortran standard is ISO/IEC 1539-1:2010, informally
989 known as Fortran 2008.  The official version is available from International
990 Organization for Standardization (ISO) or its national member organizations.
991 The the final draft (FDIS) can be downloaded free of charge from
992 @url{http://www.nag.co.uk/@/sc22wg5/@/links.html}.  Fortran is developed by the
993 Working Group 5 of Sub-Committee 22 of the Joint Technical Committee 1 of the
994 International Organization for Standardization and the International
995 Electrotechnical Commission (IEC).  This group is known as
996 @uref{http://www.nag.co.uk/sc22wg5/, WG5}.
998 The GNU Fortran compiler supports several of the new features of Fortran 2008;
999 the @uref{https://gcc.gnu.org/wiki/Fortran2008Status, wiki} has some information
1000 about the current Fortran 2008 implementation status.  In particular, the
1001 following is implemented.
1003 @itemize
1004 @item The @option{-std=f2008} option and support for the file extensions 
1005 @file{.f08} and @file{.F08}.
1007 @item The @code{OPEN} statement now supports the @code{NEWUNIT=} option,
1008 which returns a unique file unit, thus preventing inadvertent use of the
1009 same unit in different parts of the program.
1011 @item The @code{g0} format descriptor and unlimited format items.
1013 @item The mathematical intrinsics @code{ASINH}, @code{ACOSH}, @code{ATANH},
1014 @code{ERF}, @code{ERFC}, @code{GAMMA}, @code{LOG_GAMMA}, @code{BESSEL_J0},
1015 @code{BESSEL_J1}, @code{BESSEL_JN}, @code{BESSEL_Y0}, @code{BESSEL_Y1},
1016 @code{BESSEL_YN}, @code{HYPOT}, @code{NORM2}, and @code{ERFC_SCALED}.
1018 @item Using complex arguments with @code{TAN}, @code{SINH}, @code{COSH},
1019 @code{TANH}, @code{ASIN}, @code{ACOS}, and @code{ATAN} is now possible;
1020 @code{ATAN}(@var{Y},@var{X}) is now an alias for @code{ATAN2}(@var{Y},@var{X}).
1022 @item Support of the @code{PARITY} intrinsic functions.
1024 @item The following bit intrinsics: @code{LEADZ} and @code{TRAILZ} for
1025 counting the number of leading and trailing zero bits, @code{POPCNT} and
1026 @code{POPPAR} for counting the number of one bits and returning the parity;
1027 @code{BGE}, @code{BGT}, @code{BLE}, and @code{BLT} for bitwise comparisons;
1028 @code{DSHIFTL} and @code{DSHIFTR} for combined left and right shifts,
1029 @code{MASKL} and @code{MASKR} for simple left and right justified masks,
1030 @code{MERGE_BITS} for a bitwise merge using a mask, @code{SHIFTA},
1031 @code{SHIFTL} and @code{SHIFTR} for shift operations, and the
1032 transformational bit intrinsics @code{IALL}, @code{IANY} and @code{IPARITY}.
1034 @item Support of the @code{EXECUTE_COMMAND_LINE} intrinsic subroutine.
1036 @item Support for the @code{STORAGE_SIZE} intrinsic inquiry function.
1038 @item The @code{INT@{8,16,32@}} and @code{REAL@{32,64,128@}} kind type
1039 parameters and the array-valued named constants @code{INTEGER_KINDS},
1040 @code{LOGICAL_KINDS}, @code{REAL_KINDS} and @code{CHARACTER_KINDS} of
1041 the intrinsic module @code{ISO_FORTRAN_ENV}.
1043 @item The module procedures @code{C_SIZEOF} of the intrinsic module
1044 @code{ISO_C_BINDINGS} and @code{COMPILER_VERSION} and @code{COMPILER_OPTIONS}
1045 of @code{ISO_FORTRAN_ENV}.
1047 @item Coarray support for serial programs with @option{-fcoarray=single} flag
1048 and experimental support for multiple images with the @option{-fcoarray=lib}
1049 flag.
1051 @item Submodules are supported. It should noted that @code{MODULEs} do not
1052 produce the smod file needed by the descendent @code{SUBMODULEs} unless they
1053 contain at least one @code{MODULE PROCEDURE} interface. The reason for this is
1054 that @code{SUBMODULEs} are useless without @code{MODULE PROCEDUREs}. See
1055 http://j3-fortran.org/doc/meeting/207/15-209.txt for a discussion and a draft
1056 interpretation. Adopting this interpretation has the advantage that code that
1057 does not use submodules does not generate smod files.
1059 @item The @code{DO CONCURRENT} construct is supported.
1061 @item The @code{BLOCK} construct is supported.
1063 @item The @code{STOP} and the new @code{ERROR STOP} statements now
1064 support all constant expressions. Both show the signals which were signaling
1065 at termination.
1067 @item Support for the @code{CONTIGUOUS} attribute.
1069 @item Support for @code{ALLOCATE} with @code{MOLD}.
1071 @item Support for the @code{IMPURE} attribute for procedures, which
1072 allows for @code{ELEMENTAL} procedures without the restrictions of
1073 @code{PURE}.
1075 @item Null pointers (including @code{NULL()}) and not-allocated variables
1076 can be used as actual argument to optional non-pointer, non-allocatable
1077 dummy arguments, denoting an absent argument.
1079 @item Non-pointer variables with @code{TARGET} attribute can be used as
1080 actual argument to @code{POINTER} dummies with @code{INTENT(IN)}.
1082 @item Pointers including procedure pointers and those in a derived
1083 type (pointer components) can now be initialized by a target instead
1084 of only by @code{NULL}.
1086 @item The @code{EXIT} statement (with construct-name) can be now be
1087 used to leave not only the @code{DO} but also the @code{ASSOCIATE},
1088 @code{BLOCK}, @code{IF}, @code{SELECT CASE} and @code{SELECT TYPE}
1089 constructs.
1091 @item Internal procedures can now be used as actual argument.
1093 @item Minor features: obsolesce diagnostics for @code{ENTRY} with
1094 @option{-std=f2008}; a line may start with a semicolon; for internal
1095 and module procedures @code{END} can be used instead of
1096 @code{END SUBROUTINE} and @code{END FUNCTION}; @code{SELECTED_REAL_KIND}
1097 now also takes a @code{RADIX} argument; intrinsic types are supported
1098 for @code{TYPE}(@var{intrinsic-type-spec}); multiple type-bound procedures
1099 can be declared in a single @code{PROCEDURE} statement; implied-shape
1100 arrays are supported for named constants (@code{PARAMETER}).
1101 @end itemize
1105 @node TS 29113 status
1106 @section Technical Specification 29113 Status
1108 GNU Fortran supports some of the new features of the Technical
1109 Specification (TS) 29113 on Further Interoperability of Fortran with C.
1110 The @uref{https://gcc.gnu.org/wiki/TS29113Status, wiki} has some information
1111 about the current TS 29113 implementation status.  In particular, the
1112 following is implemented.
1114 See also @ref{Further Interoperability of Fortran with C}.
1116 @itemize
1117 @item The @option{-std=f2008ts} option.
1119 @item The @code{OPTIONAL} attribute is allowed for dummy arguments
1120 of @code{BIND(C) procedures.}
1122 @item The @code{RANK} intrinsic is supported.
1124 @item GNU Fortran's implementation for variables with @code{ASYNCHRONOUS}
1125 attribute is compatible with TS 29113.
1127 @item Assumed types (@code{TYPE(*)}.
1129 @item Assumed-rank (@code{DIMENSION(..)}). However, the array descriptor
1130 of the TS is not yet supported.
1131 @end itemize
1134 @node TS 18508 status
1135 @section Technical Specification 18508 Status
1137 GNU Fortran supports the following new features of the Technical
1138 Specification 18508 on Additional Parallel Features in Fortran:
1140 @itemize
1141 @item The new atomic ADD, CAS, FETCH and ADD/OR/XOR, OR and XOR intrinsics.
1143 @item The @code{CO_MIN} and @code{CO_MAX} and @code{SUM} reduction intrinsics.
1144 And the @code{CO_BROADCAST} and @code{CO_REDUCE} intrinsic, except that those
1145 do not support polymorphic types or types with allocatable, pointer or
1146 polymorphic components.
1148 @item Events (@code{EVENT POST}, @code{EVENT WAIT}, @code{EVENT_QUERY})
1149 @end itemize
1152 @c ---------------------------------------------------------------------
1153 @c Compiler Characteristics
1154 @c ---------------------------------------------------------------------
1156 @node Compiler Characteristics
1157 @chapter Compiler Characteristics
1159 This chapter describes certain characteristics of the GNU Fortran
1160 compiler, that are not specified by the Fortran standard, but which
1161 might in some way or another become visible to the programmer.
1163 @menu
1164 * KIND Type Parameters::
1165 * Internal representation of LOGICAL variables::
1166 * Thread-safety of the runtime library::
1167 * Data consistency and durability::
1168 * Files opened without an explicit ACTION= specifier::
1169 * File operations on symbolic links::
1170 @end menu
1173 @node KIND Type Parameters
1174 @section KIND Type Parameters
1175 @cindex kind
1177 The @code{KIND} type parameters supported by GNU Fortran for the primitive
1178 data types are:
1180 @table @code
1182 @item INTEGER
1183 1, 2, 4, 8*, 16*, default: 4**
1185 @item LOGICAL
1186 1, 2, 4, 8*, 16*, default: 4**
1188 @item REAL
1189 4, 8, 10*, 16*, default: 4***
1191 @item COMPLEX
1192 4, 8, 10*, 16*, default: 4***
1194 @item DOUBLE PRECISION
1195 4, 8, 10*, 16*, default: 8***
1197 @item CHARACTER
1198 1, 4, default: 1
1200 @end table
1202 @noindent
1203 * not available on all systems @*
1204 ** unless @option{-fdefault-integer-8} is used @*
1205 *** unless @option{-fdefault-real-8} is used (see @ref{Fortran Dialect Options})
1207 @noindent
1208 The @code{KIND} value matches the storage size in bytes, except for
1209 @code{COMPLEX} where the storage size is twice as much (or both real and
1210 imaginary part are a real value of the given size).  It is recommended to use
1211 the @ref{SELECTED_CHAR_KIND}, @ref{SELECTED_INT_KIND} and
1212 @ref{SELECTED_REAL_KIND} intrinsics or the @code{INT8}, @code{INT16},
1213 @code{INT32}, @code{INT64}, @code{REAL32}, @code{REAL64}, and @code{REAL128}
1214 parameters of the @code{ISO_FORTRAN_ENV} module instead of the concrete values.
1215 The available kind parameters can be found in the constant arrays
1216 @code{CHARACTER_KINDS}, @code{INTEGER_KINDS}, @code{LOGICAL_KINDS} and
1217 @code{REAL_KINDS} in the @ref{ISO_FORTRAN_ENV} module.  For C interoperability,
1218 the kind parameters of the @ref{ISO_C_BINDING} module should be used.
1221 @node Internal representation of LOGICAL variables
1222 @section Internal representation of LOGICAL variables
1223 @cindex logical, variable representation
1225 The Fortran standard does not specify how variables of @code{LOGICAL}
1226 type are represented, beyond requiring that @code{LOGICAL} variables
1227 of default kind have the same storage size as default @code{INTEGER}
1228 and @code{REAL} variables.  The GNU Fortran internal representation is
1229 as follows.
1231 A @code{LOGICAL(KIND=N)} variable is represented as an
1232 @code{INTEGER(KIND=N)} variable, however, with only two permissible
1233 values: @code{1} for @code{.TRUE.} and @code{0} for
1234 @code{.FALSE.}.  Any other integer value results in undefined behavior.
1236 See also @ref{Argument passing conventions} and @ref{Interoperability with C}.
1239 @node Thread-safety of the runtime library
1240 @section Thread-safety of the runtime library
1241 @cindex thread-safety, threads
1243 GNU Fortran can be used in programs with multiple threads, e.g.@: by
1244 using OpenMP, by calling OS thread handling functions via the
1245 @code{ISO_C_BINDING} facility, or by GNU Fortran compiled library code
1246 being called from a multi-threaded program.
1248 The GNU Fortran runtime library, (@code{libgfortran}), supports being
1249 called concurrently from multiple threads with the following
1250 exceptions. 
1252 During library initialization, the C @code{getenv} function is used,
1253 which need not be thread-safe.  Similarly, the @code{getenv}
1254 function is used to implement the @code{GET_ENVIRONMENT_VARIABLE} and
1255 @code{GETENV} intrinsics.  It is the responsibility of the user to
1256 ensure that the environment is not being updated concurrently when any
1257 of these actions are taking place.
1259 The @code{EXECUTE_COMMAND_LINE} and @code{SYSTEM} intrinsics are
1260 implemented with the @code{system} function, which need not be
1261 thread-safe.  It is the responsibility of the user to ensure that
1262 @code{system} is not called concurrently.
1264 For platforms not supporting thread-safe POSIX functions, further
1265 functionality might not be thread-safe.  For details, please consult
1266 the documentation for your operating system.
1268 The GNU Fortran runtime library uses various C library functions that
1269 depend on the locale, such as @code{strtod} and @code{snprintf}.  In
1270 order to work correctly in locale-aware programs that set the locale
1271 using @code{setlocale}, the locale is reset to the default ``C''
1272 locale while executing a formatted @code{READ} or @code{WRITE}
1273 statement.  On targets supporting the POSIX 2008 per-thread locale
1274 functions (e.g. @code{newlocale}, @code{uselocale},
1275 @code{freelocale}), these are used and thus the global locale set
1276 using @code{setlocale} or the per-thread locales in other threads are
1277 not affected.  However, on targets lacking this functionality, the
1278 global LC_NUMERIC locale is set to ``C'' during the formatted I/O.
1279 Thus, on such targets it's not safe to call @code{setlocale}
1280 concurrently from another thread while a Fortran formatted I/O
1281 operation is in progress.  Also, other threads doing something
1282 dependent on the LC_NUMERIC locale might not work correctly if a
1283 formatted I/O operation is in progress in another thread.
1285 @node Data consistency and durability
1286 @section Data consistency and durability
1287 @cindex consistency, durability
1289 This section contains a brief overview of data and metadata
1290 consistency and durability issues when doing I/O.
1292 With respect to durability, GNU Fortran makes no effort to ensure that
1293 data is committed to stable storage. If this is required, the GNU
1294 Fortran programmer can use the intrinsic @code{FNUM} to retrieve the
1295 low level file descriptor corresponding to an open Fortran unit. Then,
1296 using e.g. the @code{ISO_C_BINDING} feature, one can call the
1297 underlying system call to flush dirty data to stable storage, such as
1298 @code{fsync} on POSIX, @code{_commit} on MingW, or @code{fcntl(fd,
1299 F_FULLSYNC, 0)} on Mac OS X. The following example shows how to call
1300 fsync:
1302 @smallexample
1303   ! Declare the interface for POSIX fsync function
1304   interface
1305     function fsync (fd) bind(c,name="fsync")
1306     use iso_c_binding, only: c_int
1307       integer(c_int), value :: fd
1308       integer(c_int) :: fsync
1309     end function fsync
1310   end interface
1312   ! Variable declaration
1313   integer :: ret
1315   ! Opening unit 10
1316   open (10,file="foo")
1318   ! ...
1319   ! Perform I/O on unit 10
1320   ! ...
1322   ! Flush and sync
1323   flush(10)
1324   ret = fsync(fnum(10))
1326   ! Handle possible error
1327   if (ret /= 0) stop "Error calling FSYNC"
1328 @end smallexample
1330 With respect to consistency, for regular files GNU Fortran uses
1331 buffered I/O in order to improve performance. This buffer is flushed
1332 automatically when full and in some other situations, e.g. when
1333 closing a unit. It can also be explicitly flushed with the
1334 @code{FLUSH} statement. Also, the buffering can be turned off with the
1335 @code{GFORTRAN_UNBUFFERED_ALL} and
1336 @code{GFORTRAN_UNBUFFERED_PRECONNECTED} environment variables. Special
1337 files, such as terminals and pipes, are always unbuffered. Sometimes,
1338 however, further things may need to be done in order to allow other
1339 processes to see data that GNU Fortran has written, as follows.
1341 The Windows platform supports a relaxed metadata consistency model,
1342 where file metadata is written to the directory lazily. This means
1343 that, for instance, the @code{dir} command can show a stale size for a
1344 file. One can force a directory metadata update by closing the unit,
1345 or by calling @code{_commit} on the file descriptor. Note, though,
1346 that @code{_commit} will force all dirty data to stable storage, which
1347 is often a very slow operation.
1349 The Network File System (NFS) implements a relaxed consistency model
1350 called open-to-close consistency. Closing a file forces dirty data and
1351 metadata to be flushed to the server, and opening a file forces the
1352 client to contact the server in order to revalidate cached
1353 data. @code{fsync} will also force a flush of dirty data and metadata
1354 to the server. Similar to @code{open} and @code{close}, acquiring and
1355 releasing @code{fcntl} file locks, if the server supports them, will
1356 also force cache validation and flushing dirty data and metadata.
1359 @node Files opened without an explicit ACTION= specifier
1360 @section Files opened without an explicit ACTION= specifier
1361 @cindex open, action
1363 The Fortran standard says that if an @code{OPEN} statement is executed
1364 without an explicit @code{ACTION=} specifier, the default value is
1365 processor dependent.  GNU Fortran behaves as follows:
1367 @enumerate
1368 @item Attempt to open the file with @code{ACTION='READWRITE'}
1369 @item If that fails, try to open with @code{ACTION='READ'}
1370 @item If that fails, try to open with @code{ACTION='WRITE'}
1371 @item If that fails, generate an error
1372 @end enumerate
1375 @node File operations on symbolic links
1376 @section File operations on symbolic links
1377 @cindex file, symbolic link
1379 This section documents the behavior of GNU Fortran for file operations on
1380 symbolic links, on systems that support them. 
1382 @itemize
1384 @item Results of INQUIRE statements of the ``inquire by file'' form will
1385 relate to the target of the symbolic link. For example,
1386 @code{INQUIRE(FILE="foo",EXIST=ex)} will set @var{ex} to @var{.true.} if
1387 @var{foo} is a symbolic link pointing to an existing file, and @var{.false.}
1388 if @var{foo} points to an non-existing file (``dangling'' symbolic link).
1390 @item Using the @code{OPEN} statement with a @code{STATUS="NEW"} specifier
1391 on a symbolic link will result in an error condition, whether the symbolic
1392 link points to an existing target or is dangling.
1394 @item If a symbolic link was connected, using the @code{CLOSE} statement
1395 with a @code{STATUS="DELETE"} specifier will cause the symbolic link itself
1396 to be deleted, not its target.
1398 @end itemize
1402 @c ---------------------------------------------------------------------
1403 @c Extensions
1404 @c ---------------------------------------------------------------------
1406 @c Maybe this chapter should be merged with the 'Standards' section,
1407 @c whenever that is written :-)
1409 @node Extensions
1410 @chapter Extensions
1411 @cindex extensions
1413 The two sections below detail the extensions to standard Fortran that are
1414 implemented in GNU Fortran, as well as some of the popular or
1415 historically important extensions that are not (or not yet) implemented.
1416 For the latter case, we explain the alternatives available to GNU Fortran
1417 users, including replacement by standard-conforming code or GNU
1418 extensions.
1420 @menu
1421 * Extensions implemented in GNU Fortran::
1422 * Extensions not implemented in GNU Fortran::
1423 @end menu
1426 @node Extensions implemented in GNU Fortran
1427 @section Extensions implemented in GNU Fortran
1428 @cindex extensions, implemented
1430 GNU Fortran implements a number of extensions over standard
1431 Fortran.  This chapter contains information on their syntax and
1432 meaning.  There are currently two categories of GNU Fortran
1433 extensions, those that provide functionality beyond that provided
1434 by any standard, and those that are supported by GNU Fortran
1435 purely for backward compatibility with legacy compilers.  By default,
1436 @option{-std=gnu} allows the compiler to accept both types of
1437 extensions, but to warn about the use of the latter.  Specifying
1438 either @option{-std=f95}, @option{-std=f2003} or @option{-std=f2008}
1439 disables both types of extensions, and @option{-std=legacy} allows both
1440 without warning.
1442 @menu
1443 * Old-style kind specifications::
1444 * Old-style variable initialization::
1445 * Extensions to namelist::
1446 * X format descriptor without count field::
1447 * Commas in FORMAT specifications::
1448 * Missing period in FORMAT specifications::
1449 * I/O item lists::
1450 * @code{Q} exponent-letter::
1451 * BOZ literal constants::
1452 * Real array indices::
1453 * Unary operators::
1454 * Implicitly convert LOGICAL and INTEGER values::
1455 * Hollerith constants support::
1456 * Cray pointers::
1457 * CONVERT specifier::
1458 * OpenMP::
1459 * OpenACC::
1460 * Argument list functions::
1461 * Read/Write after EOF marker::
1462 * STRUCTURE and RECORD::
1463 * UNION and MAP::
1464 @end menu
1466 @node Old-style kind specifications
1467 @subsection Old-style kind specifications
1468 @cindex kind, old-style
1470 GNU Fortran allows old-style kind specifications in declarations.  These
1471 look like:
1472 @smallexample
1473       TYPESPEC*size x,y,z
1474 @end smallexample
1475 @noindent
1476 where @code{TYPESPEC} is a basic type (@code{INTEGER}, @code{REAL},
1477 etc.), and where @code{size} is a byte count corresponding to the
1478 storage size of a valid kind for that type.  (For @code{COMPLEX}
1479 variables, @code{size} is the total size of the real and imaginary
1480 parts.)  The statement then declares @code{x}, @code{y} and @code{z} to
1481 be of type @code{TYPESPEC} with the appropriate kind.  This is
1482 equivalent to the standard-conforming declaration
1483 @smallexample
1484       TYPESPEC(k) x,y,z
1485 @end smallexample
1486 @noindent
1487 where @code{k} is the kind parameter suitable for the intended precision.  As
1488 kind parameters are implementation-dependent, use the @code{KIND},
1489 @code{SELECTED_INT_KIND} and @code{SELECTED_REAL_KIND} intrinsics to retrieve
1490 the correct value, for instance @code{REAL*8 x} can be replaced by:
1491 @smallexample
1492 INTEGER, PARAMETER :: dbl = KIND(1.0d0)
1493 REAL(KIND=dbl) :: x
1494 @end smallexample
1496 @node Old-style variable initialization
1497 @subsection Old-style variable initialization
1499 GNU Fortran allows old-style initialization of variables of the
1500 form:
1501 @smallexample
1502       INTEGER i/1/,j/2/
1503       REAL x(2,2) /3*0.,1./
1504 @end smallexample
1505 The syntax for the initializers is as for the @code{DATA} statement, but
1506 unlike in a @code{DATA} statement, an initializer only applies to the
1507 variable immediately preceding the initialization.  In other words,
1508 something like @code{INTEGER I,J/2,3/} is not valid.  This style of
1509 initialization is only allowed in declarations without double colons
1510 (@code{::}); the double colons were introduced in Fortran 90, which also
1511 introduced a standard syntax for initializing variables in type
1512 declarations.
1514 Examples of standard-conforming code equivalent to the above example
1515 are:
1516 @smallexample
1517 ! Fortran 90
1518       INTEGER :: i = 1, j = 2
1519       REAL :: x(2,2) = RESHAPE((/0.,0.,0.,1./),SHAPE(x))
1520 ! Fortran 77
1521       INTEGER i, j
1522       REAL x(2,2)
1523       DATA i/1/, j/2/, x/3*0.,1./
1524 @end smallexample
1526 Note that variables which are explicitly initialized in declarations
1527 or in @code{DATA} statements automatically acquire the @code{SAVE}
1528 attribute.
1530 @node Extensions to namelist
1531 @subsection Extensions to namelist
1532 @cindex Namelist
1534 GNU Fortran fully supports the Fortran 95 standard for namelist I/O
1535 including array qualifiers, substrings and fully qualified derived types.
1536 The output from a namelist write is compatible with namelist read.  The
1537 output has all names in upper case and indentation to column 1 after the
1538 namelist name.  Two extensions are permitted:
1540 Old-style use of @samp{$} instead of @samp{&}
1541 @smallexample
1542 $MYNML
1543  X(:)%Y(2) = 1.0 2.0 3.0
1544  CH(1:4) = "abcd"
1545 $END
1546 @end smallexample
1548 It should be noted that the default terminator is @samp{/} rather than
1549 @samp{&END}.
1551 Querying of the namelist when inputting from stdin.  After at least
1552 one space, entering @samp{?} sends to stdout the namelist name and the names of
1553 the variables in the namelist:
1554 @smallexample
1557 &mynml
1559  x%y
1560  ch
1561 &end
1562 @end smallexample
1564 Entering @samp{=?} outputs the namelist to stdout, as if
1565 @code{WRITE(*,NML = mynml)} had been called:
1566 @smallexample
1569 &MYNML
1570  X(1)%Y=  0.000000    ,  1.000000    ,  0.000000    ,
1571  X(2)%Y=  0.000000    ,  2.000000    ,  0.000000    ,
1572  X(3)%Y=  0.000000    ,  3.000000    ,  0.000000    ,
1573  CH=abcd,  /
1574 @end smallexample
1576 To aid this dialog, when input is from stdin, errors send their
1577 messages to stderr and execution continues, even if @code{IOSTAT} is set.
1579 @code{PRINT} namelist is permitted.  This causes an error if
1580 @option{-std=f95} is used.
1581 @smallexample
1582 PROGRAM test_print
1583   REAL, dimension (4)  ::  x = (/1.0, 2.0, 3.0, 4.0/)
1584   NAMELIST /mynml/ x
1585   PRINT mynml
1586 END PROGRAM test_print
1587 @end smallexample
1589 Expanded namelist reads are permitted.  This causes an error if 
1590 @option{-std=f95} is used.  In the following example, the first element
1591 of the array will be given the value 0.00 and the two succeeding
1592 elements will be given the values 1.00 and 2.00.
1593 @smallexample
1594 &MYNML
1595   X(1,1) = 0.00 , 1.00 , 2.00
1597 @end smallexample
1599 When writing a namelist, if no @code{DELIM=} is specified, by default a
1600 double quote is used to delimit character strings. If -std=F95, F2003,
1601 or F2008, etc, the delim status is set to 'none'.  Defaulting to
1602 quotes ensures that namelists with character strings can be subsequently
1603 read back in accurately.
1605 @node X format descriptor without count field
1606 @subsection @code{X} format descriptor without count field
1608 To support legacy codes, GNU Fortran permits the count field of the
1609 @code{X} edit descriptor in @code{FORMAT} statements to be omitted.
1610 When omitted, the count is implicitly assumed to be one.
1612 @smallexample
1613        PRINT 10, 2, 3
1614 10     FORMAT (I1, X, I1)
1615 @end smallexample
1617 @node Commas in FORMAT specifications
1618 @subsection Commas in @code{FORMAT} specifications
1620 To support legacy codes, GNU Fortran allows the comma separator
1621 to be omitted immediately before and after character string edit
1622 descriptors in @code{FORMAT} statements.
1624 @smallexample
1625        PRINT 10, 2, 3
1626 10     FORMAT ('FOO='I1' BAR='I2)
1627 @end smallexample
1630 @node Missing period in FORMAT specifications
1631 @subsection Missing period in @code{FORMAT} specifications
1633 To support legacy codes, GNU Fortran allows missing periods in format
1634 specifications if and only if @option{-std=legacy} is given on the
1635 command line.  This is considered non-conforming code and is
1636 discouraged.
1638 @smallexample
1639        REAL :: value
1640        READ(*,10) value
1641 10     FORMAT ('F4')
1642 @end smallexample
1644 @node I/O item lists
1645 @subsection I/O item lists
1646 @cindex I/O item lists
1648 To support legacy codes, GNU Fortran allows the input item list
1649 of the @code{READ} statement, and the output item lists of the
1650 @code{WRITE} and @code{PRINT} statements, to start with a comma.
1652 @node @code{Q} exponent-letter
1653 @subsection @code{Q} exponent-letter
1654 @cindex @code{Q} exponent-letter
1656 GNU Fortran accepts real literal constants with an exponent-letter
1657 of @code{Q}, for example, @code{1.23Q45}.  The constant is interpreted
1658 as a @code{REAL(16)} entity on targets that support this type.  If
1659 the target does not support @code{REAL(16)} but has a @code{REAL(10)}
1660 type, then the real-literal-constant will be interpreted as a
1661 @code{REAL(10)} entity.  In the absence of @code{REAL(16)} and
1662 @code{REAL(10)}, an error will occur.
1664 @node BOZ literal constants
1665 @subsection BOZ literal constants
1666 @cindex BOZ literal constants
1668 Besides decimal constants, Fortran also supports binary (@code{b}),
1669 octal (@code{o}) and hexadecimal (@code{z}) integer constants.  The
1670 syntax is: @samp{prefix quote digits quote}, were the prefix is
1671 either @code{b}, @code{o} or @code{z}, quote is either @code{'} or
1672 @code{"} and the digits are for binary @code{0} or @code{1}, for
1673 octal between @code{0} and @code{7}, and for hexadecimal between
1674 @code{0} and @code{F}.  (Example: @code{b'01011101'}.)
1676 Up to Fortran 95, BOZ literals were only allowed to initialize
1677 integer variables in DATA statements.  Since Fortran 2003 BOZ literals
1678 are also allowed as argument of @code{REAL}, @code{DBLE}, @code{INT}
1679 and @code{CMPLX}; the result is the same as if the integer BOZ
1680 literal had been converted by @code{TRANSFER} to, respectively,
1681 @code{real}, @code{double precision}, @code{integer} or @code{complex}.
1682 As GNU Fortran extension the intrinsic procedures @code{FLOAT},
1683 @code{DFLOAT}, @code{COMPLEX} and @code{DCMPLX} are treated alike.
1685 As an extension, GNU Fortran allows hexadecimal BOZ literal constants to
1686 be specified using the @code{X} prefix, in addition to the standard
1687 @code{Z} prefix.  The BOZ literal can also be specified by adding a
1688 suffix to the string, for example, @code{Z'ABC'} and @code{'ABC'Z} are
1689 equivalent.
1691 Furthermore, GNU Fortran allows using BOZ literal constants outside
1692 DATA statements and the four intrinsic functions allowed by Fortran 2003.
1693 In DATA statements, in direct assignments, where the right-hand side
1694 only contains a BOZ literal constant, and for old-style initializers of
1695 the form @code{integer i /o'0173'/}, the constant is transferred
1696 as if @code{TRANSFER} had been used; for @code{COMPLEX} numbers, only
1697 the real part is initialized unless @code{CMPLX} is used.  In all other
1698 cases, the BOZ literal constant is converted to an @code{INTEGER} value with
1699 the largest decimal representation.  This value is then converted
1700 numerically to the type and kind of the variable in question.
1701 (For instance, @code{real :: r = b'0000001' + 1} initializes @code{r}
1702 with @code{2.0}.) As different compilers implement the extension
1703 differently, one should be careful when doing bitwise initialization
1704 of non-integer variables.
1706 Note that initializing an @code{INTEGER} variable with a statement such
1707 as @code{DATA i/Z'FFFFFFFF'/} will give an integer overflow error rather
1708 than the desired result of @math{-1} when @code{i} is a 32-bit integer
1709 on a system that supports 64-bit integers.  The @samp{-fno-range-check}
1710 option can be used as a workaround for legacy code that initializes
1711 integers in this manner.
1713 @node Real array indices
1714 @subsection Real array indices
1715 @cindex array, indices of type real
1717 As an extension, GNU Fortran allows the use of @code{REAL} expressions
1718 or variables as array indices.
1720 @node Unary operators
1721 @subsection Unary operators
1722 @cindex operators, unary
1724 As an extension, GNU Fortran allows unary plus and unary minus operators
1725 to appear as the second operand of binary arithmetic operators without
1726 the need for parenthesis.
1728 @smallexample
1729        X = Y * -Z
1730 @end smallexample
1732 @node Implicitly convert LOGICAL and INTEGER values
1733 @subsection Implicitly convert @code{LOGICAL} and @code{INTEGER} values
1734 @cindex conversion, to integer
1735 @cindex conversion, to logical
1737 As an extension for backwards compatibility with other compilers, GNU
1738 Fortran allows the implicit conversion of @code{LOGICAL} values to
1739 @code{INTEGER} values and vice versa.  When converting from a
1740 @code{LOGICAL} to an @code{INTEGER}, @code{.FALSE.} is interpreted as
1741 zero, and @code{.TRUE.} is interpreted as one.  When converting from
1742 @code{INTEGER} to @code{LOGICAL}, the value zero is interpreted as
1743 @code{.FALSE.} and any nonzero value is interpreted as @code{.TRUE.}.
1745 @smallexample
1746         LOGICAL :: l
1747         l = 1
1748 @end smallexample
1749 @smallexample
1750         INTEGER :: i
1751         i = .TRUE.
1752 @end smallexample
1754 However, there is no implicit conversion of @code{INTEGER} values in
1755 @code{if}-statements, nor of @code{LOGICAL} or @code{INTEGER} values
1756 in I/O operations.
1758 @node Hollerith constants support
1759 @subsection Hollerith constants support
1760 @cindex Hollerith constants
1762 GNU Fortran supports Hollerith constants in assignments, function
1763 arguments, and @code{DATA} and @code{ASSIGN} statements.  A Hollerith
1764 constant is written as a string of characters preceded by an integer
1765 constant indicating the character count, and the letter @code{H} or
1766 @code{h}, and stored in bytewise fashion in a numeric (@code{INTEGER},
1767 @code{REAL}, or @code{complex}) or @code{LOGICAL} variable.  The
1768 constant will be padded or truncated to fit the size of the variable in
1769 which it is stored.
1771 Examples of valid uses of Hollerith constants:
1772 @smallexample
1773       complex*16 x(2)
1774       data x /16Habcdefghijklmnop, 16Hqrstuvwxyz012345/
1775       x(1) = 16HABCDEFGHIJKLMNOP
1776       call foo (4h abc)
1777 @end smallexample
1779 Invalid Hollerith constants examples:
1780 @smallexample
1781       integer*4 a
1782       a = 8H12345678 ! Valid, but the Hollerith constant will be truncated.
1783       a = 0H         ! At least one character is needed.
1784 @end smallexample
1786 In general, Hollerith constants were used to provide a rudimentary
1787 facility for handling character strings in early Fortran compilers,
1788 prior to the introduction of @code{CHARACTER} variables in Fortran 77;
1789 in those cases, the standard-compliant equivalent is to convert the
1790 program to use proper character strings.  On occasion, there may be a
1791 case where the intent is specifically to initialize a numeric variable
1792 with a given byte sequence.  In these cases, the same result can be
1793 obtained by using the @code{TRANSFER} statement, as in this example.
1794 @smallexample
1795       INTEGER(KIND=4) :: a
1796       a = TRANSFER ("abcd", a)     ! equivalent to: a = 4Habcd
1797 @end smallexample
1800 @node Cray pointers
1801 @subsection Cray pointers
1802 @cindex pointer, Cray
1804 Cray pointers are part of a non-standard extension that provides a
1805 C-like pointer in Fortran.  This is accomplished through a pair of
1806 variables: an integer "pointer" that holds a memory address, and a
1807 "pointee" that is used to dereference the pointer.
1809 Pointer/pointee pairs are declared in statements of the form:
1810 @smallexample
1811         pointer ( <pointer> , <pointee> )
1812 @end smallexample
1814 @smallexample
1815         pointer ( <pointer1> , <pointee1> ), ( <pointer2> , <pointee2> ), ...
1816 @end smallexample
1817 The pointer is an integer that is intended to hold a memory address.
1818 The pointee may be an array or scalar.  A pointee can be an assumed
1819 size array---that is, the last dimension may be left unspecified by
1820 using a @code{*} in place of a value---but a pointee cannot be an
1821 assumed shape array.  No space is allocated for the pointee.
1823 The pointee may have its type declared before or after the pointer
1824 statement, and its array specification (if any) may be declared
1825 before, during, or after the pointer statement.  The pointer may be
1826 declared as an integer prior to the pointer statement.  However, some
1827 machines have default integer sizes that are different than the size
1828 of a pointer, and so the following code is not portable:
1829 @smallexample
1830         integer ipt
1831         pointer (ipt, iarr)
1832 @end smallexample
1833 If a pointer is declared with a kind that is too small, the compiler
1834 will issue a warning; the resulting binary will probably not work
1835 correctly, because the memory addresses stored in the pointers may be
1836 truncated.  It is safer to omit the first line of the above example;
1837 if explicit declaration of ipt's type is omitted, then the compiler
1838 will ensure that ipt is an integer variable large enough to hold a
1839 pointer.
1841 Pointer arithmetic is valid with Cray pointers, but it is not the same
1842 as C pointer arithmetic.  Cray pointers are just ordinary integers, so
1843 the user is responsible for determining how many bytes to add to a
1844 pointer in order to increment it.  Consider the following example:
1845 @smallexample
1846         real target(10)
1847         real pointee(10)
1848         pointer (ipt, pointee)
1849         ipt = loc (target)
1850         ipt = ipt + 1       
1851 @end smallexample
1852 The last statement does not set @code{ipt} to the address of
1853 @code{target(1)}, as it would in C pointer arithmetic.  Adding @code{1}
1854 to @code{ipt} just adds one byte to the address stored in @code{ipt}.
1856 Any expression involving the pointee will be translated to use the
1857 value stored in the pointer as the base address.
1859 To get the address of elements, this extension provides an intrinsic
1860 function @code{LOC()}.  The @code{LOC()} function is equivalent to the
1861 @code{&} operator in C, except the address is cast to an integer type:
1862 @smallexample
1863         real ar(10)
1864         pointer(ipt, arpte(10))
1865         real arpte
1866         ipt = loc(ar)  ! Makes arpte is an alias for ar
1867         arpte(1) = 1.0 ! Sets ar(1) to 1.0
1868 @end smallexample
1869 The pointer can also be set by a call to the @code{MALLOC} intrinsic
1870 (see @ref{MALLOC}).
1872 Cray pointees often are used to alias an existing variable.  For
1873 example:
1874 @smallexample
1875         integer target(10)
1876         integer iarr(10)
1877         pointer (ipt, iarr)
1878         ipt = loc(target)
1879 @end smallexample
1880 As long as @code{ipt} remains unchanged, @code{iarr} is now an alias for
1881 @code{target}.  The optimizer, however, will not detect this aliasing, so
1882 it is unsafe to use @code{iarr} and @code{target} simultaneously.  Using
1883 a pointee in any way that violates the Fortran aliasing rules or
1884 assumptions is illegal.  It is the user's responsibility to avoid doing
1885 this; the compiler works under the assumption that no such aliasing
1886 occurs.
1888 Cray pointers will work correctly when there is no aliasing (i.e., when
1889 they are used to access a dynamically allocated block of memory), and
1890 also in any routine where a pointee is used, but any variable with which
1891 it shares storage is not used.  Code that violates these rules may not
1892 run as the user intends.  This is not a bug in the optimizer; any code
1893 that violates the aliasing rules is illegal.  (Note that this is not
1894 unique to GNU Fortran; any Fortran compiler that supports Cray pointers
1895 will ``incorrectly'' optimize code with illegal aliasing.)
1897 There are a number of restrictions on the attributes that can be applied
1898 to Cray pointers and pointees.  Pointees may not have the
1899 @code{ALLOCATABLE}, @code{INTENT}, @code{OPTIONAL}, @code{DUMMY},
1900 @code{TARGET}, @code{INTRINSIC}, or @code{POINTER} attributes.  Pointers
1901 may not have the @code{DIMENSION}, @code{POINTER}, @code{TARGET},
1902 @code{ALLOCATABLE}, @code{EXTERNAL}, or @code{INTRINSIC} attributes, nor
1903 may they be function results.  Pointees may not occur in more than one
1904 pointer statement.  A pointee cannot be a pointer.  Pointees cannot occur
1905 in equivalence, common, or data statements.
1907 A Cray pointer may also point to a function or a subroutine.  For
1908 example, the following excerpt is valid:
1909 @smallexample
1910   implicit none
1911   external sub
1912   pointer (subptr,subpte)
1913   external subpte
1914   subptr = loc(sub)
1915   call subpte()
1916   [...]
1917   subroutine sub
1918   [...]
1919   end subroutine sub
1920 @end smallexample
1922 A pointer may be modified during the course of a program, and this
1923 will change the location to which the pointee refers.  However, when
1924 pointees are passed as arguments, they are treated as ordinary
1925 variables in the invoked function.  Subsequent changes to the pointer
1926 will not change the base address of the array that was passed.
1928 @node CONVERT specifier
1929 @subsection @code{CONVERT} specifier
1930 @cindex @code{CONVERT} specifier
1932 GNU Fortran allows the conversion of unformatted data between little-
1933 and big-endian representation to facilitate moving of data
1934 between different systems.  The conversion can be indicated with
1935 the @code{CONVERT} specifier on the @code{OPEN} statement.
1936 @xref{GFORTRAN_CONVERT_UNIT}, for an alternative way of specifying
1937 the data format via an environment variable.
1939 Valid values for @code{CONVERT} are:
1940 @itemize @w{}
1941 @item @code{CONVERT='NATIVE'} Use the native format.  This is the default.
1942 @item @code{CONVERT='SWAP'} Swap between little- and big-endian.
1943 @item @code{CONVERT='LITTLE_ENDIAN'} Use the little-endian representation
1944 for unformatted files.
1945 @item @code{CONVERT='BIG_ENDIAN'} Use the big-endian representation for
1946 unformatted files.
1947 @end itemize
1949 Using the option could look like this:
1950 @smallexample
1951   open(file='big.dat',form='unformatted',access='sequential', &
1952        convert='big_endian')
1953 @end smallexample
1955 The value of the conversion can be queried by using
1956 @code{INQUIRE(CONVERT=ch)}.  The values returned are
1957 @code{'BIG_ENDIAN'} and @code{'LITTLE_ENDIAN'}.
1959 @code{CONVERT} works between big- and little-endian for
1960 @code{INTEGER} values of all supported kinds and for @code{REAL}
1961 on IEEE systems of kinds 4 and 8.  Conversion between different
1962 ``extended double'' types on different architectures such as
1963 m68k and x86_64, which GNU Fortran
1964 supports as @code{REAL(KIND=10)} and @code{REAL(KIND=16)}, will
1965 probably not work.
1967 @emph{Note that the values specified via the GFORTRAN_CONVERT_UNIT
1968 environment variable will override the CONVERT specifier in the
1969 open statement}.  This is to give control over data formats to
1970 users who do not have the source code of their program available.
1972 Using anything but the native representation for unformatted data
1973 carries a significant speed overhead.  If speed in this area matters
1974 to you, it is best if you use this only for data that needs to be
1975 portable.
1977 @node OpenMP
1978 @subsection OpenMP
1979 @cindex OpenMP
1981 OpenMP (Open Multi-Processing) is an application programming
1982 interface (API) that supports multi-platform shared memory 
1983 multiprocessing programming in C/C++ and Fortran on many 
1984 architectures, including Unix and Microsoft Windows platforms.
1985 It consists of a set of compiler directives, library routines,
1986 and environment variables that influence run-time behavior.
1988 GNU Fortran strives to be compatible to the 
1989 @uref{http://openmp.org/wp/openmp-specifications/,
1990 OpenMP Application Program Interface v4.0}.
1992 To enable the processing of the OpenMP directive @code{!$omp} in
1993 free-form source code; the @code{c$omp}, @code{*$omp} and @code{!$omp}
1994 directives in fixed form; the @code{!$} conditional compilation sentinels
1995 in free form; and the @code{c$}, @code{*$} and @code{!$} sentinels
1996 in fixed form, @command{gfortran} needs to be invoked with the
1997 @option{-fopenmp}.  This also arranges for automatic linking of the
1998 GNU Offloading and Multi Processing Runtime Library
1999 @ref{Top,,libgomp,libgomp,GNU Offloading and Multi Processing Runtime
2000 Library}.
2002 The OpenMP Fortran runtime library routines are provided both in a
2003 form of a Fortran 90 module named @code{omp_lib} and in a form of
2004 a Fortran @code{include} file named @file{omp_lib.h}.
2006 An example of a parallelized loop taken from Appendix A.1 of
2007 the OpenMP Application Program Interface v2.5:
2008 @smallexample
2009 SUBROUTINE A1(N, A, B)
2010   INTEGER I, N
2011   REAL B(N), A(N)
2012 !$OMP PARALLEL DO !I is private by default
2013   DO I=2,N
2014     B(I) = (A(I) + A(I-1)) / 2.0
2015   ENDDO
2016 !$OMP END PARALLEL DO
2017 END SUBROUTINE A1
2018 @end smallexample
2020 Please note:
2021 @itemize
2022 @item
2023 @option{-fopenmp} implies @option{-frecursive}, i.e., all local arrays
2024 will be allocated on the stack.  When porting existing code to OpenMP,
2025 this may lead to surprising results, especially to segmentation faults
2026 if the stacksize is limited.
2028 @item
2029 On glibc-based systems, OpenMP enabled applications cannot be statically
2030 linked due to limitations of the underlying pthreads-implementation.  It
2031 might be possible to get a working solution if 
2032 @command{-Wl,--whole-archive -lpthread -Wl,--no-whole-archive} is added
2033 to the command line.  However, this is not supported by @command{gcc} and
2034 thus not recommended.
2035 @end itemize
2037 @node OpenACC
2038 @subsection OpenACC
2039 @cindex OpenACC
2041 OpenACC is an application programming interface (API) that supports
2042 offloading of code to accelerator devices.  It consists of a set of
2043 compiler directives, library routines, and environment variables that
2044 influence run-time behavior.
2046 GNU Fortran strives to be compatible to the
2047 @uref{http://www.openacc.org/, OpenACC Application Programming
2048 Interface v2.0}.
2050 To enable the processing of the OpenACC directive @code{!$acc} in
2051 free-form source code; the @code{c$acc}, @code{*$acc} and @code{!$acc}
2052 directives in fixed form; the @code{!$} conditional compilation
2053 sentinels in free form; and the @code{c$}, @code{*$} and @code{!$}
2054 sentinels in fixed form, @command{gfortran} needs to be invoked with
2055 the @option{-fopenacc}.  This also arranges for automatic linking of
2056 the GNU Offloading and Multi Processing Runtime Library
2057 @ref{Top,,libgomp,libgomp,GNU Offloading and Multi Processing Runtime
2058 Library}.
2060 The OpenACC Fortran runtime library routines are provided both in a
2061 form of a Fortran 90 module named @code{openacc} and in a form of a
2062 Fortran @code{include} file named @file{openacc_lib.h}.
2064 Note that this is an experimental feature, incomplete, and subject to
2065 change in future versions of GCC.  See
2066 @uref{https://gcc.gnu.org/wiki/OpenACC} for more information.
2068 @node Argument list functions
2069 @subsection Argument list functions @code{%VAL}, @code{%REF} and @code{%LOC}
2070 @cindex argument list functions
2071 @cindex @code{%VAL}
2072 @cindex @code{%REF}
2073 @cindex @code{%LOC}
2075 GNU Fortran supports argument list functions @code{%VAL}, @code{%REF} 
2076 and @code{%LOC} statements, for backward compatibility with g77. 
2077 It is recommended that these should be used only for code that is 
2078 accessing facilities outside of GNU Fortran, such as operating system 
2079 or windowing facilities.  It is best to constrain such uses to isolated 
2080 portions of a program--portions that deal specifically and exclusively 
2081 with low-level, system-dependent facilities.  Such portions might well 
2082 provide a portable interface for use by the program as a whole, but are 
2083 themselves not portable, and should be thoroughly tested each time they 
2084 are rebuilt using a new compiler or version of a compiler.
2086 @code{%VAL} passes a scalar argument by value, @code{%REF} passes it by 
2087 reference and @code{%LOC} passes its memory location.  Since gfortran 
2088 already passes scalar arguments by reference, @code{%REF} is in effect 
2089 a do-nothing.  @code{%LOC} has the same effect as a Fortran pointer.
2091 An example of passing an argument by value to a C subroutine foo.:
2092 @smallexample
2094 C prototype      void foo_ (float x);
2096       external foo
2097       real*4 x
2098       x = 3.14159
2099       call foo (%VAL (x))
2100       end
2101 @end smallexample
2103 For details refer to the g77 manual
2104 @uref{https://gcc.gnu.org/@/onlinedocs/@/gcc-3.4.6/@/g77/@/index.html#Top}.
2106 Also, @code{c_by_val.f} and its partner @code{c_by_val.c} of the
2107 GNU Fortran testsuite are worth a look.
2109 @node Read/Write after EOF marker
2110 @subsection Read/Write after EOF marker
2111 @cindex @code{EOF}
2112 @cindex @code{BACKSPACE}
2113 @cindex @code{REWIND}
2115 Some legacy codes rely on allowing @code{READ} or @code{WRITE} after the
2116 EOF file marker in order to find the end of a file. GNU Fortran normally
2117 rejects these codes with a run-time error message and suggests the user
2118 consider @code{BACKSPACE} or @code{REWIND} to properly position
2119 the file before the EOF marker.  As an extension, the run-time error may
2120 be disabled using -std=legacy.
2123 @node STRUCTURE and RECORD
2124 @subsection @code{STRUCTURE} and @code{RECORD}
2125 @cindex @code{STRUCTURE}
2126 @cindex @code{RECORD}
2128 Record structures are a pre-Fortran-90 vendor extension to create
2129 user-defined aggregate data types.  GNU Fortran does not support
2130 record structures, only Fortran 90's ``derived types'', which have
2131 a different syntax.
2133 In many cases, record structures can easily be converted to derived types.
2134 To convert, replace @code{STRUCTURE /}@var{structure-name}@code{/}
2135 by @code{TYPE} @var{type-name}.  Additionally, replace
2136 @code{RECORD /}@var{structure-name}@code{/} by
2137 @code{TYPE(}@var{type-name}@code{)}. Finally, in the component access,
2138 replace the period (@code{.}) by the percent sign (@code{%}).
2140 Here is an example of code using the non portable record structure syntax:
2142 @example
2143 ! Declaring a structure named ``item'' and containing three fields:
2144 ! an integer ID, an description string and a floating-point price.
2145 STRUCTURE /item/
2146   INTEGER id
2147   CHARACTER(LEN=200) description
2148   REAL price
2149 END STRUCTURE
2151 ! Define two variables, an single record of type ``item''
2152 ! named ``pear'', and an array of items named ``store_catalog''
2153 RECORD /item/ pear, store_catalog(100)
2155 ! We can directly access the fields of both variables
2156 pear.id = 92316
2157 pear.description = "juicy D'Anjou pear"
2158 pear.price = 0.15
2159 store_catalog(7).id = 7831
2160 store_catalog(7).description = "milk bottle"
2161 store_catalog(7).price = 1.2
2163 ! We can also manipulate the whole structure
2164 store_catalog(12) = pear
2165 print *, store_catalog(12)
2166 @end example
2168 @noindent
2169 This code can easily be rewritten in the Fortran 90 syntax as following:
2171 @example
2172 ! ``STRUCTURE /name/ ... END STRUCTURE'' becomes
2173 ! ``TYPE name ... END TYPE''
2174 TYPE item
2175   INTEGER id
2176   CHARACTER(LEN=200) description
2177   REAL price
2178 END TYPE
2180 ! ``RECORD /name/ variable'' becomes ``TYPE(name) variable''
2181 TYPE(item) pear, store_catalog(100)
2183 ! Instead of using a dot (.) to access fields of a record, the
2184 ! standard syntax uses a percent sign (%)
2185 pear%id = 92316
2186 pear%description = "juicy D'Anjou pear"
2187 pear%price = 0.15
2188 store_catalog(7)%id = 7831
2189 store_catalog(7)%description = "milk bottle"
2190 store_catalog(7)%price = 1.2
2192 ! Assignments of a whole variable do not change
2193 store_catalog(12) = pear
2194 print *, store_catalog(12)
2195 @end example
2197 @noindent
2198 GNU Fortran implements STRUCTURES like derived types with the following
2199 rules and exceptions:
2201 @itemize @bullet
2202 @item Structures act like derived types with the @code{SEQUENCE} attribute.
2203 Otherwise they may contain no specifiers.
2205 @item Structures may share names with other symbols. For example, the following
2206 is invalid for derived types, but valid for structures:
2208 @smallexample
2209 structure /header/
2210   ! ...
2211 end structure
2212 record /header/ header
2213 @end smallexample
2215 @item Structure types may be declared nested within another parent structure.
2216 The syntax is:
2217 @smallexample
2218 structure /type-name/
2219     ...
2220     structure [/<type-name>/] <field-list>
2222 @end smallexample
2224 The type name may be ommitted, in which case the structure type itself is
2225 anonymous, and other structures of the same type cannot be instantiated. The
2226 following shows some examples:
2228 @example
2229 structure /appointment/
2230   ! nested structure definition: app_time is an array of two 'time'
2231   structure /time/ app_time (2) 
2232     integer(1) hour, minute
2233   end structure
2234   character(10) memo
2235 end structure
2237 ! The 'time' structure is still usable
2238 record /time/ now
2239 now = time(5, 30)
2243 structure /appointment/
2244   ! anonymous nested structure definition
2245   structure start, end
2246     integer(1) hour, minute
2247   end structure
2248   character(10) memo
2249 end structure
2250 @end example
2252 @item Structures may contain @code{UNION} blocks. For more detail see the
2253 section on @ref{UNION and MAP}.
2255 @item Structures support old-style initialization of components, like
2256 those described in @ref{Old-style variable initialization}. For array
2257 initializers, an initializer may contain a repeat specification of the form
2258 @code{<literal-integer> * <constant-initializer>}. The value of the integer
2259 indicates the number of times to repeat the constant initializer when expanding
2260 the initializer list.
2261 @end itemize
2263 @node UNION and MAP
2264 @subsection @code{UNION} and @code{MAP}
2265 @cindex @code{UNION}
2266 @cindex @code{MAP}
2268 Unions are an old vendor extension which were commonly used with the
2269 non-standard @ref{STRUCTURE and RECORD} extensions. Use of @code{UNION} and
2270 @code{MAP} is automatically enabled with @option{-fdec-structure}.
2272 A @code{UNION} declaration occurs within a structure; within the definition of
2273 each union is a number of @code{MAP} blocks. Each @code{MAP} shares storage
2274 with its sibling maps (in the same union), and the size of the union is the
2275 size of the largest map within it, just as with unions in C. The major
2276 difference is that component references do not indicate which union or map the
2277 component is in (the compiler gets to figure that out).
2279 Here is a small example:
2280 @smallexample
2281 structure /myunion/
2282 union
2283   map
2284     character(2) w0, w1, w2
2285   end map
2286   map
2287     character(6) long
2288   end map
2289 end union
2290 end structure
2292 record /myunion/ rec
2293 ! After this assignment...
2294 rec.long = 'hello!'
2296 ! The following is true:
2297 ! rec.w0 === 'he'
2298 ! rec.w1 === 'll'
2299 ! rec.w2 === 'o!'
2300 @end smallexample
2302 The two maps share memory, and the size of the union is ultimately six bytes:
2304 @example
2305 0    1    2    3    4   5   6     Byte offset
2306 -------------------------------
2307 |    |    |    |    |    |    |
2308 -------------------------------
2310 ^    W0   ^    W1   ^    W2   ^
2311  \-------/ \-------/ \-------/
2313 ^             LONG            ^
2314  \---------------------------/
2315 @end example
2317 Following is an example mirroring the layout of an Intel x86_64 register:
2319 @example
2320 structure /reg/
2321   union ! U0                ! rax
2322     map
2323       character(16) rx
2324     end map
2325     map
2326       character(8) rh         ! rah
2327       union ! U1
2328         map
2329           character(8) rl     ! ral
2330         end map
2331         map
2332           character(8) ex     ! eax
2333         end map
2334         map
2335           character(4) eh     ! eah
2336           union ! U2
2337             map
2338               character(4) el ! eal
2339             end map
2340             map
2341               character(4) x  ! ax
2342             end map
2343             map
2344               character(2) h  ! ah
2345               character(2) l  ! al
2346             end map
2347           end union
2348         end map
2349       end union
2350     end map
2351   end union
2352 end structure
2353 record /reg/ a
2355 ! After this assignment...
2356 a.rx     =     'AAAAAAAA.BBB.C.D'
2358 ! The following is true:
2359 a.rx === 'AAAAAAAA.BBB.C.D'
2360 a.rh === 'AAAAAAAA'
2361 a.rl ===         '.BBB.C.D'
2362 a.ex ===         '.BBB.C.D'
2363 a.eh ===         '.BBB'
2364 a.el ===             '.C.D'
2365 a.x  ===             '.C.D'
2366 a.h  ===             '.C'
2367 a.l  ===               '.D'
2368 @end example
2371 @node Extensions not implemented in GNU Fortran
2372 @section Extensions not implemented in GNU Fortran
2373 @cindex extensions, not implemented
2375 The long history of the Fortran language, its wide use and broad
2376 userbase, the large number of different compiler vendors and the lack of
2377 some features crucial to users in the first standards have lead to the
2378 existence of a number of important extensions to the language.  While
2379 some of the most useful or popular extensions are supported by the GNU
2380 Fortran compiler, not all existing extensions are supported.  This section
2381 aims at listing these extensions and offering advice on how best make
2382 code that uses them running with the GNU Fortran compiler.
2384 @c More can be found here:
2385 @c   -- https://gcc.gnu.org/onlinedocs/gcc-3.4.6/g77/Missing-Features.html
2386 @c   -- the list of Fortran and libgfortran bugs closed as WONTFIX:
2387 @c      http://tinyurl.com/2u4h5y
2389 @menu
2390 * ENCODE and DECODE statements::
2391 * Variable FORMAT expressions::
2392 @c * Q edit descriptor::
2393 @c * AUTOMATIC statement::
2394 @c * TYPE and ACCEPT I/O Statements::
2395 @c * .XOR. operator::
2396 @c * CARRIAGECONTROL, DEFAULTFILE, DISPOSE and RECORDTYPE I/O specifiers::
2397 @c * Omitted arguments in procedure call::
2398 * Alternate complex function syntax::
2399 * Volatile COMMON blocks::
2400 * OPEN( ... NAME=)::
2401 @end menu
2403 @node ENCODE and DECODE statements
2404 @subsection @code{ENCODE} and @code{DECODE} statements
2405 @cindex @code{ENCODE}
2406 @cindex @code{DECODE}
2408 GNU Fortran does not support the @code{ENCODE} and @code{DECODE}
2409 statements.  These statements are best replaced by @code{READ} and
2410 @code{WRITE} statements involving internal files (@code{CHARACTER}
2411 variables and arrays), which have been part of the Fortran standard since
2412 Fortran 77.  For example, replace a code fragment like
2414 @smallexample
2415       INTEGER*1 LINE(80)
2416       REAL A, B, C
2417 c     ... Code that sets LINE
2418       DECODE (80, 9000, LINE) A, B, C
2419  9000 FORMAT (1X, 3(F10.5))
2420 @end smallexample
2422 @noindent
2423 with the following:
2425 @smallexample
2426       CHARACTER(LEN=80) LINE
2427       REAL A, B, C
2428 c     ... Code that sets LINE
2429       READ (UNIT=LINE, FMT=9000) A, B, C
2430  9000 FORMAT (1X, 3(F10.5))
2431 @end smallexample
2433 Similarly, replace a code fragment like
2435 @smallexample
2436       INTEGER*1 LINE(80)
2437       REAL A, B, C
2438 c     ... Code that sets A, B and C
2439       ENCODE (80, 9000, LINE) A, B, C
2440  9000 FORMAT (1X, 'OUTPUT IS ', 3(F10.5))
2441 @end smallexample
2443 @noindent
2444 with the following:
2446 @smallexample
2447       CHARACTER(LEN=80) LINE
2448       REAL A, B, C
2449 c     ... Code that sets A, B and C
2450       WRITE (UNIT=LINE, FMT=9000) A, B, C
2451  9000 FORMAT (1X, 'OUTPUT IS ', 3(F10.5))
2452 @end smallexample
2455 @node Variable FORMAT expressions
2456 @subsection Variable @code{FORMAT} expressions
2457 @cindex @code{FORMAT}
2459 A variable @code{FORMAT} expression is format statement which includes
2460 angle brackets enclosing a Fortran expression: @code{FORMAT(I<N>)}.  GNU
2461 Fortran does not support this legacy extension.  The effect of variable
2462 format expressions can be reproduced by using the more powerful (and
2463 standard) combination of internal output and string formats.  For example,
2464 replace a code fragment like this:
2466 @smallexample
2467       WRITE(6,20) INT1
2468  20   FORMAT(I<N+1>)
2469 @end smallexample
2471 @noindent
2472 with the following:
2474 @smallexample
2475 c     Variable declaration
2476       CHARACTER(LEN=20) FMT
2477 c     
2478 c     Other code here...
2480       WRITE(FMT,'("(I", I0, ")")') N+1
2481       WRITE(6,FMT) INT1
2482 @end smallexample
2484 @noindent
2485 or with:
2487 @smallexample
2488 c     Variable declaration
2489       CHARACTER(LEN=20) FMT
2490 c     
2491 c     Other code here...
2493       WRITE(FMT,*) N+1
2494       WRITE(6,"(I" // ADJUSTL(FMT) // ")") INT1
2495 @end smallexample
2498 @node Alternate complex function syntax
2499 @subsection Alternate complex function syntax
2500 @cindex Complex function
2502 Some Fortran compilers, including @command{g77}, let the user declare
2503 complex functions with the syntax @code{COMPLEX FUNCTION name*16()}, as
2504 well as @code{COMPLEX*16 FUNCTION name()}.  Both are non-standard, legacy
2505 extensions.  @command{gfortran} accepts the latter form, which is more
2506 common, but not the former.
2509 @node Volatile COMMON blocks
2510 @subsection Volatile @code{COMMON} blocks
2511 @cindex @code{VOLATILE}
2512 @cindex @code{COMMON}
2514 Some Fortran compilers, including @command{g77}, let the user declare
2515 @code{COMMON} with the @code{VOLATILE} attribute. This is
2516 invalid standard Fortran syntax and is not supported by
2517 @command{gfortran}.  Note that @command{gfortran} accepts
2518 @code{VOLATILE} variables in @code{COMMON} blocks since revision 4.3.
2521 @node OPEN( ... NAME=)
2522 @subsection @code{OPEN( ... NAME=)}
2523 @cindex @code{NAM}
2525 Some Fortran compilers, including @command{g77}, let the user declare
2526 @code{OPEN( ... NAME=)}. This is
2527 invalid standard Fortran syntax and is not supported by
2528 @command{gfortran}.  @code{OPEN( ... NAME=)} should be replaced
2529 with @code{OPEN( ... FILE=)}.
2533 @c ---------------------------------------------------------------------
2534 @c ---------------------------------------------------------------------
2535 @c Mixed-Language Programming
2536 @c ---------------------------------------------------------------------
2538 @node Mixed-Language Programming
2539 @chapter Mixed-Language Programming
2540 @cindex Interoperability
2541 @cindex Mixed-language programming
2543 @menu
2544 * Interoperability with C::
2545 * GNU Fortran Compiler Directives::
2546 * Non-Fortran Main Program::
2547 * Naming and argument-passing conventions::
2548 @end menu
2550 This chapter is about mixed-language interoperability, but also applies
2551 if one links Fortran code compiled by different compilers.  In most cases,
2552 use of the C Binding features of the Fortran 2003 standard is sufficient,
2553 and their use is highly recommended.
2556 @node Interoperability with C
2557 @section Interoperability with C
2559 @menu
2560 * Intrinsic Types::
2561 * Derived Types and struct::
2562 * Interoperable Global Variables::
2563 * Interoperable Subroutines and Functions::
2564 * Working with Pointers::
2565 * Further Interoperability of Fortran with C::
2566 @end menu
2568 Since Fortran 2003 (ISO/IEC 1539-1:2004(E)) there is a
2569 standardized way to generate procedure and derived-type
2570 declarations and global variables which are interoperable with C
2571 (ISO/IEC 9899:1999).  The @code{bind(C)} attribute has been added
2572 to inform the compiler that a symbol shall be interoperable with C;
2573 also, some constraints are added.  Note, however, that not
2574 all C features have a Fortran equivalent or vice versa.  For instance,
2575 neither C's unsigned integers nor C's functions with variable number
2576 of arguments have an equivalent in Fortran.
2578 Note that array dimensions are reversely ordered in C and that arrays in
2579 C always start with index 0 while in Fortran they start by default with
2580 1.  Thus, an array declaration @code{A(n,m)} in Fortran matches
2581 @code{A[m][n]} in C and accessing the element @code{A(i,j)} matches
2582 @code{A[j-1][i-1]}.  The element following @code{A(i,j)} (C: @code{A[j-1][i-1]};
2583 assuming @math{i < n}) in memory is @code{A(i+1,j)} (C: @code{A[j-1][i]}).
2585 @node Intrinsic Types
2586 @subsection Intrinsic Types
2588 In order to ensure that exactly the same variable type and kind is used
2589 in C and Fortran, the named constants shall be used which are defined in the
2590 @code{ISO_C_BINDING} intrinsic module.  That module contains named constants
2591 for kind parameters and character named constants for the escape sequences
2592 in C.  For a list of the constants, see @ref{ISO_C_BINDING}.
2594 For logical types, please note that the Fortran standard only guarantees
2595 interoperability between C99's @code{_Bool} and Fortran's @code{C_Bool}-kind
2596 logicals and C99 defines that @code{true} has the value 1 and @code{false}
2597 the value 0.  Using any other integer value with GNU Fortran's @code{LOGICAL}
2598 (with any kind parameter) gives an undefined result.  (Passing other integer
2599 values than 0 and 1 to GCC's @code{_Bool} is also undefined, unless the
2600 integer is explicitly or implicitly casted to @code{_Bool}.)
2604 @node Derived Types and struct
2605 @subsection Derived Types and struct
2607 For compatibility of derived types with @code{struct}, one needs to use
2608 the @code{BIND(C)} attribute in the type declaration.  For instance, the
2609 following type declaration
2611 @smallexample
2612  USE ISO_C_BINDING
2613  TYPE, BIND(C) :: myType
2614    INTEGER(C_INT) :: i1, i2
2615    INTEGER(C_SIGNED_CHAR) :: i3
2616    REAL(C_DOUBLE) :: d1
2617    COMPLEX(C_FLOAT_COMPLEX) :: c1
2618    CHARACTER(KIND=C_CHAR) :: str(5)
2619  END TYPE
2620 @end smallexample
2622 matches the following @code{struct} declaration in C
2624 @smallexample
2625  struct @{
2626    int i1, i2;
2627    /* Note: "char" might be signed or unsigned.  */
2628    signed char i3;
2629    double d1;
2630    float _Complex c1;
2631    char str[5];
2632  @} myType;
2633 @end smallexample
2635 Derived types with the C binding attribute shall not have the @code{sequence}
2636 attribute, type parameters, the @code{extends} attribute, nor type-bound
2637 procedures.  Every component must be of interoperable type and kind and may not
2638 have the @code{pointer} or @code{allocatable} attribute.  The names of the
2639 components are irrelevant for interoperability.
2641 As there exist no direct Fortran equivalents, neither unions nor structs
2642 with bit field or variable-length array members are interoperable.
2644 @node Interoperable Global Variables
2645 @subsection Interoperable Global Variables
2647 Variables can be made accessible from C using the C binding attribute,
2648 optionally together with specifying a binding name.  Those variables
2649 have to be declared in the declaration part of a @code{MODULE},
2650 be of interoperable type, and have neither the @code{pointer} nor
2651 the @code{allocatable} attribute.
2653 @smallexample
2654   MODULE m
2655     USE myType_module
2656     USE ISO_C_BINDING
2657     integer(C_INT), bind(C, name="_MyProject_flags") :: global_flag
2658     type(myType), bind(C) :: tp
2659   END MODULE
2660 @end smallexample
2662 Here, @code{_MyProject_flags} is the case-sensitive name of the variable
2663 as seen from C programs while @code{global_flag} is the case-insensitive
2664 name as seen from Fortran.  If no binding name is specified, as for
2665 @var{tp}, the C binding name is the (lowercase) Fortran binding name.
2666 If a binding name is specified, only a single variable may be after the
2667 double colon.  Note of warning: You cannot use a global variable to
2668 access @var{errno} of the C library as the C standard allows it to be
2669 a macro.  Use the @code{IERRNO} intrinsic (GNU extension) instead.
2671 @node Interoperable Subroutines and Functions
2672 @subsection Interoperable Subroutines and Functions
2674 Subroutines and functions have to have the @code{BIND(C)} attribute to
2675 be compatible with C.  The dummy argument declaration is relatively
2676 straightforward.  However, one needs to be careful because C uses
2677 call-by-value by default while Fortran behaves usually similar to
2678 call-by-reference.  Furthermore, strings and pointers are handled
2679 differently.  Note that in Fortran 2003 and 2008 only explicit size
2680 and assumed-size arrays are supported but not assumed-shape or
2681 deferred-shape (i.e. allocatable or pointer) arrays.  However, those
2682 are allowed since the Technical Specification 29113, see
2683 @ref{Further Interoperability of Fortran with C}
2685 To pass a variable by value, use the @code{VALUE} attribute.
2686 Thus, the following C prototype
2688 @smallexample
2689 @code{int func(int i, int *j)}
2690 @end smallexample
2692 matches the Fortran declaration
2694 @smallexample
2695   integer(c_int) function func(i,j)
2696     use iso_c_binding, only: c_int
2697     integer(c_int), VALUE :: i
2698     integer(c_int) :: j
2699 @end smallexample
2701 Note that pointer arguments also frequently need the @code{VALUE} attribute,
2702 see @ref{Working with Pointers}.
2704 Strings are handled quite differently in C and Fortran.  In C a string
2705 is a @code{NUL}-terminated array of characters while in Fortran each string
2706 has a length associated with it and is thus not terminated (by e.g.
2707 @code{NUL}).  For example, if one wants to use the following C function,
2709 @smallexample
2710   #include <stdio.h>
2711   void print_C(char *string) /* equivalent: char string[]  */
2712   @{
2713      printf("%s\n", string);
2714   @}
2715 @end smallexample
2717 to print ``Hello World'' from Fortran, one can call it using
2719 @smallexample
2720   use iso_c_binding, only: C_CHAR, C_NULL_CHAR
2721   interface
2722     subroutine print_c(string) bind(C, name="print_C")
2723       use iso_c_binding, only: c_char
2724       character(kind=c_char) :: string(*)
2725     end subroutine print_c
2726   end interface
2727   call print_c(C_CHAR_"Hello World"//C_NULL_CHAR)
2728 @end smallexample
2730 As the example shows, one needs to ensure that the
2731 string is @code{NUL} terminated.  Additionally, the dummy argument
2732 @var{string} of @code{print_C} is a length-one assumed-size
2733 array; using @code{character(len=*)} is not allowed.  The example
2734 above uses @code{c_char_"Hello World"} to ensure the string
2735 literal has the right type; typically the default character
2736 kind and @code{c_char} are the same and thus @code{"Hello World"}
2737 is equivalent.  However, the standard does not guarantee this.
2739 The use of strings is now further illustrated using the C library
2740 function @code{strncpy}, whose prototype is
2742 @smallexample
2743   char *strncpy(char *restrict s1, const char *restrict s2, size_t n);
2744 @end smallexample
2746 The function @code{strncpy} copies at most @var{n} characters from
2747 string @var{s2} to @var{s1} and returns @var{s1}.  In the following
2748 example, we ignore the return value:
2750 @smallexample
2751   use iso_c_binding
2752   implicit none
2753   character(len=30) :: str,str2
2754   interface
2755     ! Ignore the return value of strncpy -> subroutine
2756     ! "restrict" is always assumed if we do not pass a pointer
2757     subroutine strncpy(dest, src, n) bind(C)
2758       import
2759       character(kind=c_char),  intent(out) :: dest(*)
2760       character(kind=c_char),  intent(in)  :: src(*)
2761       integer(c_size_t), value, intent(in) :: n
2762     end subroutine strncpy
2763   end interface
2764   str = repeat('X',30) ! Initialize whole string with 'X'
2765   call strncpy(str, c_char_"Hello World"//C_NULL_CHAR, &
2766                len(c_char_"Hello World",kind=c_size_t))
2767   print '(a)', str ! prints: "Hello WorldXXXXXXXXXXXXXXXXXXX"
2768   end
2769 @end smallexample
2771 The intrinsic procedures are described in @ref{Intrinsic Procedures}.
2773 @node Working with Pointers
2774 @subsection Working with Pointers
2776 C pointers are represented in Fortran via the special opaque derived type
2777 @code{type(c_ptr)} (with private components).  Thus one needs to
2778 use intrinsic conversion procedures to convert from or to C pointers.
2780 For some applications, using an assumed type (@code{TYPE(*)}) can be an
2781 alternative to a C pointer; see
2782 @ref{Further Interoperability of Fortran with C}.
2784 For example,
2786 @smallexample
2787   use iso_c_binding
2788   type(c_ptr) :: cptr1, cptr2
2789   integer, target :: array(7), scalar
2790   integer, pointer :: pa(:), ps
2791   cptr1 = c_loc(array(1)) ! The programmer needs to ensure that the
2792                           ! array is contiguous if required by the C
2793                           ! procedure
2794   cptr2 = c_loc(scalar)
2795   call c_f_pointer(cptr2, ps)
2796   call c_f_pointer(cptr2, pa, shape=[7])
2797 @end smallexample
2799 When converting C to Fortran arrays, the one-dimensional @code{SHAPE} argument
2800 has to be passed.
2802 If a pointer is a dummy-argument of an interoperable procedure, it usually
2803 has to be declared using the @code{VALUE} attribute.  @code{void*}
2804 matches @code{TYPE(C_PTR), VALUE}, while @code{TYPE(C_PTR)} alone
2805 matches @code{void**}.
2807 Procedure pointers are handled analogously to pointers; the C type is
2808 @code{TYPE(C_FUNPTR)} and the intrinsic conversion procedures are
2809 @code{C_F_PROCPOINTER} and @code{C_FUNLOC}.
2811 Let us consider two examples of actually passing a procedure pointer from
2812 C to Fortran and vice versa.  Note that these examples are also very
2813 similar to passing ordinary pointers between both languages. First,
2814 consider this code in C:
2816 @smallexample
2817 /* Procedure implemented in Fortran.  */
2818 void get_values (void (*)(double));
2820 /* Call-back routine we want called from Fortran.  */
2821 void
2822 print_it (double x)
2824   printf ("Number is %f.\n", x);
2827 /* Call Fortran routine and pass call-back to it.  */
2828 void
2829 foobar ()
2831   get_values (&print_it);
2833 @end smallexample
2835 A matching implementation for @code{get_values} in Fortran, that correctly
2836 receives the procedure pointer from C and is able to call it, is given
2837 in the following @code{MODULE}:
2839 @smallexample
2840 MODULE m
2841   IMPLICIT NONE
2843   ! Define interface of call-back routine.
2844   ABSTRACT INTERFACE
2845     SUBROUTINE callback (x)
2846       USE, INTRINSIC :: ISO_C_BINDING
2847       REAL(KIND=C_DOUBLE), INTENT(IN), VALUE :: x
2848     END SUBROUTINE callback
2849   END INTERFACE
2851 CONTAINS
2853   ! Define C-bound procedure.
2854   SUBROUTINE get_values (cproc) BIND(C)
2855     USE, INTRINSIC :: ISO_C_BINDING
2856     TYPE(C_FUNPTR), INTENT(IN), VALUE :: cproc
2858     PROCEDURE(callback), POINTER :: proc
2860     ! Convert C to Fortran procedure pointer.
2861     CALL C_F_PROCPOINTER (cproc, proc)
2863     ! Call it.
2864     CALL proc (1.0_C_DOUBLE)
2865     CALL proc (-42.0_C_DOUBLE)
2866     CALL proc (18.12_C_DOUBLE)
2867   END SUBROUTINE get_values
2869 END MODULE m
2870 @end smallexample
2872 Next, we want to call a C routine that expects a procedure pointer argument
2873 and pass it a Fortran procedure (which clearly must be interoperable!).
2874 Again, the C function may be:
2876 @smallexample
2878 call_it (int (*func)(int), int arg)
2880   return func (arg);
2882 @end smallexample
2884 It can be used as in the following Fortran code:
2886 @smallexample
2887 MODULE m
2888   USE, INTRINSIC :: ISO_C_BINDING
2889   IMPLICIT NONE
2891   ! Define interface of C function.
2892   INTERFACE
2893     INTEGER(KIND=C_INT) FUNCTION call_it (func, arg) BIND(C)
2894       USE, INTRINSIC :: ISO_C_BINDING
2895       TYPE(C_FUNPTR), INTENT(IN), VALUE :: func
2896       INTEGER(KIND=C_INT), INTENT(IN), VALUE :: arg
2897     END FUNCTION call_it
2898   END INTERFACE
2900 CONTAINS
2902   ! Define procedure passed to C function.
2903   ! It must be interoperable!
2904   INTEGER(KIND=C_INT) FUNCTION double_it (arg) BIND(C)
2905     INTEGER(KIND=C_INT), INTENT(IN), VALUE :: arg
2906     double_it = arg + arg
2907   END FUNCTION double_it
2909   ! Call C function.
2910   SUBROUTINE foobar ()
2911     TYPE(C_FUNPTR) :: cproc
2912     INTEGER(KIND=C_INT) :: i
2914     ! Get C procedure pointer.
2915     cproc = C_FUNLOC (double_it)
2917     ! Use it.
2918     DO i = 1_C_INT, 10_C_INT
2919       PRINT *, call_it (cproc, i)
2920     END DO
2921   END SUBROUTINE foobar
2923 END MODULE m
2924 @end smallexample
2926 @node Further Interoperability of Fortran with C
2927 @subsection Further Interoperability of Fortran with C
2929 The Technical Specification ISO/IEC TS 29113:2012 on further
2930 interoperability of Fortran with C extends the interoperability support
2931 of Fortran 2003 and Fortran 2008. Besides removing some restrictions
2932 and constraints, it adds assumed-type (@code{TYPE(*)}) and assumed-rank
2933 (@code{dimension}) variables and allows for interoperability of
2934 assumed-shape, assumed-rank and deferred-shape arrays, including
2935 allocatables and pointers.
2937 Note: Currently, GNU Fortran does not support the array descriptor
2938 (dope vector) as specified in the Technical Specification, but uses
2939 an array descriptor with different fields. The Chasm Language
2940 Interoperability Tools, @url{http://chasm-interop.sourceforge.net/},
2941 provide an interface to GNU Fortran's array descriptor.
2943 The Technical Specification adds the following new features, which
2944 are supported by GNU Fortran:
2946 @itemize @bullet
2948 @item The @code{ASYNCHRONOUS} attribute has been clarified and
2949 extended to allow its use with asynchronous communication in
2950 user-provided libraries such as in implementations of the
2951 Message Passing Interface specification.
2953 @item Many constraints have been relaxed, in particular for
2954 the @code{C_LOC} and @code{C_F_POINTER} intrinsics.
2956 @item The @code{OPTIONAL} attribute is now allowed for dummy
2957 arguments; an absent argument matches a @code{NULL} pointer.
2959 @item Assumed types (@code{TYPE(*)}) have been added, which may
2960 only be used for dummy arguments.  They are unlimited polymorphic
2961 but contrary to @code{CLASS(*)} they do not contain any type
2962 information, similar to C's @code{void *} pointers.  Expressions
2963 of any type and kind can be passed; thus, it can be used as
2964 replacement for @code{TYPE(C_PTR)}, avoiding the use of
2965 @code{C_LOC} in the caller.
2967 Note, however, that @code{TYPE(*)} only accepts scalar arguments,
2968 unless the @code{DIMENSION} is explicitly specified.  As
2969 @code{DIMENSION(*)} only supports array (including array elements) but
2970 no scalars, it is not a full replacement for @code{C_LOC}.  On the
2971 other hand, assumed-type assumed-rank dummy arguments
2972 (@code{TYPE(*), DIMENSION(..)}) allow for both scalars and arrays, but
2973 require special code on the callee side to handle the array descriptor.
2975 @item Assumed-rank arrays (@code{DIMENSION(..)}) as dummy argument
2976 allow that scalars and arrays of any rank can be passed as actual
2977 argument. As the Technical Specification does not provide for direct
2978 means to operate with them, they have to be used either from the C side
2979 or be converted using @code{C_LOC} and @code{C_F_POINTER} to scalars
2980 or arrays of a specific rank. The rank can be determined using the
2981 @code{RANK} intrinisic.
2982 @end itemize
2985 Currently unimplemented:
2987 @itemize @bullet
2989 @item GNU Fortran always uses an array descriptor, which does not
2990 match the one of the Technical Specification. The
2991 @code{ISO_Fortran_binding.h} header file and the C functions it
2992 specifies are not available.
2994 @item Using assumed-shape, assumed-rank and deferred-shape arrays in
2995 @code{BIND(C)} procedures is not fully supported. In particular,
2996 C interoperable strings of other length than one are not supported
2997 as this requires the new array descriptor.
2998 @end itemize
3001 @node GNU Fortran Compiler Directives
3002 @section GNU Fortran Compiler Directives
3004 The Fortran standard describes how a conforming program shall
3005 behave; however, the exact implementation is not standardized.  In order
3006 to allow the user to choose specific implementation details, compiler
3007 directives can be used to set attributes of variables and procedures
3008 which are not part of the standard.  Whether a given attribute is
3009 supported and its exact effects depend on both the operating system and
3010 on the processor; see
3011 @ref{Top,,C Extensions,gcc,Using the GNU Compiler Collection (GCC)}
3012 for details.
3014 For procedures and procedure pointers, the following attributes can
3015 be used to change the calling convention:
3017 @itemize
3018 @item @code{CDECL} -- standard C calling convention
3019 @item @code{STDCALL} -- convention where the called procedure pops the stack
3020 @item @code{FASTCALL} -- part of the arguments are passed via registers
3021 instead using the stack
3022 @end itemize
3024 Besides changing the calling convention, the attributes also influence
3025 the decoration of the symbol name, e.g., by a leading underscore or by
3026 a trailing at-sign followed by the number of bytes on the stack.  When
3027 assigning a procedure to a procedure pointer, both should use the same
3028 calling convention.
3030 On some systems, procedures and global variables (module variables and
3031 @code{COMMON} blocks) need special handling to be accessible when they
3032 are in a shared library.  The following attributes are available:
3034 @itemize
3035 @item @code{DLLEXPORT} -- provide a global pointer to a pointer in the DLL
3036 @item @code{DLLIMPORT} -- reference the function or variable using a
3037 global pointer
3038 @end itemize
3040 For dummy arguments, the @code{NO_ARG_CHECK} attribute can be used; in
3041 other compilers, it is also known as @code{IGNORE_TKR}.  For dummy arguments
3042 with this attribute actual arguments of any type and kind (similar to
3043 @code{TYPE(*)}), scalars and arrays of any rank (no equivalent
3044 in Fortran standard) are accepted.  As with @code{TYPE(*)}, the argument
3045 is unlimited polymorphic and no type information is available.
3046 Additionally, the argument may only be passed to dummy arguments
3047 with the @code{NO_ARG_CHECK} attribute and as argument to the
3048 @code{PRESENT} intrinsic function and to @code{C_LOC} of the
3049 @code{ISO_C_BINDING} module.
3051 Variables with @code{NO_ARG_CHECK} attribute shall be of assumed-type
3052 (@code{TYPE(*)}; recommended) or of type @code{INTEGER}, @code{LOGICAL},
3053 @code{REAL} or @code{COMPLEX}. They shall not have the @code{ALLOCATE},
3054 @code{CODIMENSION}, @code{INTENT(OUT)}, @code{POINTER} or @code{VALUE}
3055 attribute; furthermore, they shall be either scalar or of assumed-size
3056 (@code{dimension(*)}). As @code{TYPE(*)}, the @code{NO_ARG_CHECK} attribute
3057 requires an explicit interface.
3059 @itemize
3060 @item @code{NO_ARG_CHECK} -- disable the type, kind and rank checking
3061 @end itemize
3064 The attributes are specified using the syntax
3066 @code{!GCC$ ATTRIBUTES} @var{attribute-list} @code{::} @var{variable-list}
3068 where in free-form source code only whitespace is allowed before @code{!GCC$}
3069 and in fixed-form source code @code{!GCC$}, @code{cGCC$} or @code{*GCC$} shall
3070 start in the first column.
3072 For procedures, the compiler directives shall be placed into the body
3073 of the procedure; for variables and procedure pointers, they shall be in
3074 the same declaration part as the variable or procedure pointer.
3078 @node Non-Fortran Main Program
3079 @section Non-Fortran Main Program
3081 @menu
3082 * _gfortran_set_args:: Save command-line arguments
3083 * _gfortran_set_options:: Set library option flags
3084 * _gfortran_set_convert:: Set endian conversion
3085 * _gfortran_set_record_marker:: Set length of record markers
3086 * _gfortran_set_fpe:: Set when a Floating Point Exception should be raised
3087 * _gfortran_set_max_subrecord_length:: Set subrecord length
3088 @end menu
3090 Even if you are doing mixed-language programming, it is very
3091 likely that you do not need to know or use the information in this
3092 section.  Since it is about the internal structure of GNU Fortran,
3093 it may also change in GCC minor releases.
3095 When you compile a @code{PROGRAM} with GNU Fortran, a function
3096 with the name @code{main} (in the symbol table of the object file)
3097 is generated, which initializes the libgfortran library and then
3098 calls the actual program which uses the name @code{MAIN__}, for
3099 historic reasons.  If you link GNU Fortran compiled procedures
3100 to, e.g., a C or C++ program or to a Fortran program compiled by
3101 a different compiler, the libgfortran library is not initialized
3102 and thus a few intrinsic procedures do not work properly, e.g.
3103 those for obtaining the command-line arguments.
3105 Therefore, if your @code{PROGRAM} is not compiled with
3106 GNU Fortran and the GNU Fortran compiled procedures require
3107 intrinsics relying on the library initialization, you need to
3108 initialize the library yourself.  Using the default options,
3109 gfortran calls @code{_gfortran_set_args} and
3110 @code{_gfortran_set_options}.  The initialization of the former
3111 is needed if the called procedures access the command line
3112 (and for backtracing); the latter sets some flags based on the
3113 standard chosen or to enable backtracing.  In typical programs,
3114 it is not necessary to call any initialization function.
3116 If your @code{PROGRAM} is compiled with GNU Fortran, you shall
3117 not call any of the following functions.  The libgfortran
3118 initialization functions are shown in C syntax but using C
3119 bindings they are also accessible from Fortran.
3122 @node _gfortran_set_args
3123 @subsection @code{_gfortran_set_args} --- Save command-line arguments
3124 @fnindex _gfortran_set_args
3125 @cindex libgfortran initialization, set_args
3127 @table @asis
3128 @item @emph{Description}:
3129 @code{_gfortran_set_args} saves the command-line arguments; this
3130 initialization is required if any of the command-line intrinsics
3131 is called.  Additionally, it shall be called if backtracing is
3132 enabled (see @code{_gfortran_set_options}).
3134 @item @emph{Syntax}:
3135 @code{void _gfortran_set_args (int argc, char *argv[])}
3137 @item @emph{Arguments}:
3138 @multitable @columnfractions .15 .70
3139 @item @var{argc} @tab number of command line argument strings
3140 @item @var{argv} @tab the command-line argument strings; argv[0]
3141 is the pathname of the executable itself.
3142 @end multitable
3144 @item @emph{Example}:
3145 @smallexample
3146 int main (int argc, char *argv[])
3148   /* Initialize libgfortran.  */
3149   _gfortran_set_args (argc, argv);
3150   return 0;
3152 @end smallexample
3153 @end table
3156 @node _gfortran_set_options
3157 @subsection @code{_gfortran_set_options} --- Set library option flags
3158 @fnindex _gfortran_set_options
3159 @cindex libgfortran initialization, set_options
3161 @table @asis
3162 @item @emph{Description}:
3163 @code{_gfortran_set_options} sets several flags related to the Fortran
3164 standard to be used, whether backtracing should be enabled
3165 and whether range checks should be performed.  The syntax allows for
3166 upward compatibility since the number of passed flags is specified; for
3167 non-passed flags, the default value is used.  See also
3168 @pxref{Code Gen Options}.  Please note that not all flags are actually
3169 used.
3171 @item @emph{Syntax}:
3172 @code{void _gfortran_set_options (int num, int options[])}
3174 @item @emph{Arguments}:
3175 @multitable @columnfractions .15 .70
3176 @item @var{num} @tab number of options passed
3177 @item @var{argv} @tab The list of flag values
3178 @end multitable
3180 @item @emph{option flag list}:
3181 @multitable @columnfractions .15 .70
3182 @item @var{option}[0] @tab Allowed standard; can give run-time errors
3183 if e.g. an input-output edit descriptor is invalid in a given standard.
3184 Possible values are (bitwise or-ed) @code{GFC_STD_F77} (1),
3185 @code{GFC_STD_F95_OBS} (2), @code{GFC_STD_F95_DEL} (4), @code{GFC_STD_F95}
3186 (8), @code{GFC_STD_F2003} (16), @code{GFC_STD_GNU} (32),
3187 @code{GFC_STD_LEGACY} (64), @code{GFC_STD_F2008} (128),
3188 @code{GFC_STD_F2008_OBS} (256) and GFC_STD_F2008_TS (512). Default:
3189 @code{GFC_STD_F95_OBS | GFC_STD_F95_DEL | GFC_STD_F95 | GFC_STD_F2003
3190 | GFC_STD_F2008 | GFC_STD_F2008_TS | GFC_STD_F2008_OBS | GFC_STD_F77
3191 | GFC_STD_GNU | GFC_STD_LEGACY}.
3192 @item @var{option}[1] @tab Standard-warning flag; prints a warning to
3193 standard error.  Default: @code{GFC_STD_F95_DEL | GFC_STD_LEGACY}.
3194 @item @var{option}[2] @tab If non zero, enable pedantic checking.
3195 Default: off.
3196 @item @var{option}[3] @tab Unused.
3197 @item @var{option}[4] @tab If non zero, enable backtracing on run-time
3198 errors.  Default: off. (Default in the compiler: on.)
3199 Note: Installs a signal handler and requires command-line
3200 initialization using @code{_gfortran_set_args}.
3201 @item @var{option}[5] @tab If non zero, supports signed zeros.
3202 Default: enabled.
3203 @item @var{option}[6] @tab Enables run-time checking.  Possible values
3204 are (bitwise or-ed): GFC_RTCHECK_BOUNDS (1), GFC_RTCHECK_ARRAY_TEMPS (2),
3205 GFC_RTCHECK_RECURSION (4), GFC_RTCHECK_DO (16), GFC_RTCHECK_POINTER (32).
3206 Default: disabled.
3207 @item @var{option}[7] @tab Unused.
3208 @item @var{option}[8] @tab Show a warning when invoking @code{STOP} and
3209 @code{ERROR STOP} if a floating-point exception occurred. Possible values
3210 are (bitwise or-ed) @code{GFC_FPE_INVALID} (1), @code{GFC_FPE_DENORMAL} (2),
3211 @code{GFC_FPE_ZERO} (4), @code{GFC_FPE_OVERFLOW} (8),
3212 @code{GFC_FPE_UNDERFLOW} (16), @code{GFC_FPE_INEXACT} (32). Default: None (0).
3213 (Default in the compiler: @code{GFC_FPE_INVALID | GFC_FPE_DENORMAL |
3214 GFC_FPE_ZERO | GFC_FPE_OVERFLOW | GFC_FPE_UNDERFLOW}.)
3215 @end multitable
3217 @item @emph{Example}:
3218 @smallexample
3219   /* Use gfortran 4.9 default options.  */
3220   static int options[] = @{68, 511, 0, 0, 1, 1, 0, 0, 31@};
3221   _gfortran_set_options (9, &options);
3222 @end smallexample
3223 @end table
3226 @node _gfortran_set_convert
3227 @subsection @code{_gfortran_set_convert} --- Set endian conversion
3228 @fnindex _gfortran_set_convert
3229 @cindex libgfortran initialization, set_convert
3231 @table @asis
3232 @item @emph{Description}:
3233 @code{_gfortran_set_convert} set the representation of data for
3234 unformatted files.
3236 @item @emph{Syntax}:
3237 @code{void _gfortran_set_convert (int conv)}
3239 @item @emph{Arguments}:
3240 @multitable @columnfractions .15 .70
3241 @item @var{conv} @tab Endian conversion, possible values:
3242 GFC_CONVERT_NATIVE (0, default), GFC_CONVERT_SWAP (1),
3243 GFC_CONVERT_BIG (2), GFC_CONVERT_LITTLE (3).
3244 @end multitable
3246 @item @emph{Example}:
3247 @smallexample
3248 int main (int argc, char *argv[])
3250   /* Initialize libgfortran.  */
3251   _gfortran_set_args (argc, argv);
3252   _gfortran_set_convert (1);
3253   return 0;
3255 @end smallexample
3256 @end table
3259 @node _gfortran_set_record_marker
3260 @subsection @code{_gfortran_set_record_marker} --- Set length of record markers
3261 @fnindex _gfortran_set_record_marker
3262 @cindex libgfortran initialization, set_record_marker
3264 @table @asis
3265 @item @emph{Description}:
3266 @code{_gfortran_set_record_marker} sets the length of record markers
3267 for unformatted files.
3269 @item @emph{Syntax}:
3270 @code{void _gfortran_set_record_marker (int val)}
3272 @item @emph{Arguments}:
3273 @multitable @columnfractions .15 .70
3274 @item @var{val} @tab Length of the record marker; valid values
3275 are 4 and 8.  Default is 4.
3276 @end multitable
3278 @item @emph{Example}:
3279 @smallexample
3280 int main (int argc, char *argv[])
3282   /* Initialize libgfortran.  */
3283   _gfortran_set_args (argc, argv);
3284   _gfortran_set_record_marker (8);
3285   return 0;
3287 @end smallexample
3288 @end table
3291 @node _gfortran_set_fpe
3292 @subsection @code{_gfortran_set_fpe} --- Enable floating point exception traps
3293 @fnindex _gfortran_set_fpe
3294 @cindex libgfortran initialization, set_fpe
3296 @table @asis
3297 @item @emph{Description}:
3298 @code{_gfortran_set_fpe} enables floating point exception traps for
3299 the specified exceptions.  On most systems, this will result in a
3300 SIGFPE signal being sent and the program being aborted.
3302 @item @emph{Syntax}:
3303 @code{void _gfortran_set_fpe (int val)}
3305 @item @emph{Arguments}:
3306 @multitable @columnfractions .15 .70
3307 @item @var{option}[0] @tab IEEE exceptions.  Possible values are
3308 (bitwise or-ed) zero (0, default) no trapping,
3309 @code{GFC_FPE_INVALID} (1), @code{GFC_FPE_DENORMAL} (2),
3310 @code{GFC_FPE_ZERO} (4), @code{GFC_FPE_OVERFLOW} (8),
3311 @code{GFC_FPE_UNDERFLOW} (16), and @code{GFC_FPE_INEXACT} (32).
3312 @end multitable
3314 @item @emph{Example}:
3315 @smallexample
3316 int main (int argc, char *argv[])
3318   /* Initialize libgfortran.  */
3319   _gfortran_set_args (argc, argv);
3320   /* FPE for invalid operations such as SQRT(-1.0).  */
3321   _gfortran_set_fpe (1);
3322   return 0;
3324 @end smallexample
3325 @end table
3328 @node _gfortran_set_max_subrecord_length
3329 @subsection @code{_gfortran_set_max_subrecord_length} --- Set subrecord length
3330 @fnindex _gfortran_set_max_subrecord_length
3331 @cindex libgfortran initialization, set_max_subrecord_length
3333 @table @asis
3334 @item @emph{Description}:
3335 @code{_gfortran_set_max_subrecord_length} set the maximum length
3336 for a subrecord.  This option only makes sense for testing and
3337 debugging of unformatted I/O.
3339 @item @emph{Syntax}:
3340 @code{void _gfortran_set_max_subrecord_length (int val)}
3342 @item @emph{Arguments}:
3343 @multitable @columnfractions .15 .70
3344 @item @var{val} @tab the maximum length for a subrecord;
3345 the maximum permitted value is 2147483639, which is also
3346 the default.
3347 @end multitable
3349 @item @emph{Example}:
3350 @smallexample
3351 int main (int argc, char *argv[])
3353   /* Initialize libgfortran.  */
3354   _gfortran_set_args (argc, argv);
3355   _gfortran_set_max_subrecord_length (8);
3356   return 0;
3358 @end smallexample
3359 @end table
3362 @node Naming and argument-passing conventions
3363 @section Naming and argument-passing conventions
3365 This section gives an overview about the naming convention of procedures
3366 and global variables and about the argument passing conventions used by
3367 GNU Fortran.  If a C binding has been specified, the naming convention
3368 and some of the argument-passing conventions change.  If possible,
3369 mixed-language and mixed-compiler projects should use the better defined
3370 C binding for interoperability.  See @pxref{Interoperability with C}.
3372 @menu
3373 * Naming conventions::
3374 * Argument passing conventions::
3375 @end menu
3378 @node Naming conventions
3379 @subsection Naming conventions
3381 According the Fortran standard, valid Fortran names consist of a letter
3382 between @code{A} to @code{Z}, @code{a} to @code{z}, digits @code{0},
3383 @code{1} to @code{9} and underscores (@code{_}) with the restriction
3384 that names may only start with a letter.  As vendor extension, the
3385 dollar sign (@code{$}) is additionally permitted with the option
3386 @option{-fdollar-ok}, but not as first character and only if the
3387 target system supports it.
3389 By default, the procedure name is the lower-cased Fortran name with an
3390 appended underscore (@code{_}); using @option{-fno-underscoring} no
3391 underscore is appended while @code{-fsecond-underscore} appends two
3392 underscores.  Depending on the target system and the calling convention,
3393 the procedure might be additionally dressed; for instance, on 32bit
3394 Windows with @code{stdcall}, an at-sign @code{@@} followed by an integer
3395 number is appended.  For the changing the calling convention, see
3396 @pxref{GNU Fortran Compiler Directives}.
3398 For common blocks, the same convention is used, i.e. by default an
3399 underscore is appended to the lower-cased Fortran name.  Blank commons
3400 have the name @code{__BLNK__}.
3402 For procedures and variables declared in the specification space of a
3403 module, the name is formed by @code{__}, followed by the lower-cased
3404 module name, @code{_MOD_}, and the lower-cased Fortran name.  Note that
3405 no underscore is appended.
3408 @node Argument passing conventions
3409 @subsection Argument passing conventions
3411 Subroutines do not return a value (matching C99's @code{void}) while
3412 functions either return a value as specified in the platform ABI or
3413 the result variable is passed as hidden argument to the function and
3414 no result is returned.  A hidden result variable is used when the
3415 result variable is an array or of type @code{CHARACTER}.
3417 Arguments are passed according to the platform ABI. In particular,
3418 complex arguments might not be compatible to a struct with two real
3419 components for the real and imaginary part. The argument passing
3420 matches the one of C99's @code{_Complex}.  Functions with scalar
3421 complex result variables return their value and do not use a
3422 by-reference argument.  Note that with the @option{-ff2c} option,
3423 the argument passing is modified and no longer completely matches
3424 the platform ABI.  Some other Fortran compilers use @code{f2c}
3425 semantic by default; this might cause problems with
3426 interoperablility.
3428 GNU Fortran passes most arguments by reference, i.e. by passing a
3429 pointer to the data.  Note that the compiler might use a temporary
3430 variable into which the actual argument has been copied, if required
3431 semantically (copy-in/copy-out).
3433 For arguments with @code{ALLOCATABLE} and @code{POINTER}
3434 attribute (including procedure pointers), a pointer to the pointer
3435 is passed such that the pointer address can be modified in the
3436 procedure.
3438 For dummy arguments with the @code{VALUE} attribute: Scalar arguments
3439 of the type @code{INTEGER}, @code{LOGICAL}, @code{REAL} and
3440 @code{COMPLEX} are passed by value according to the platform ABI.
3441 (As vendor extension and not recommended, using @code{%VAL()} in the
3442 call to a procedure has the same effect.) For @code{TYPE(C_PTR)} and
3443 procedure pointers, the pointer itself is passed such that it can be
3444 modified without affecting the caller.
3445 @c FIXME: Document how VALUE is handled for CHARACTER, TYPE,
3446 @c CLASS and arrays, i.e. whether the copy-in is done in the caller
3447 @c or in the callee.
3449 For Boolean (@code{LOGICAL}) arguments, please note that GCC expects
3450 only the integer value 0 and 1.  If a GNU Fortran @code{LOGICAL}
3451 variable contains another integer value, the result is undefined.
3452 As some other Fortran compilers use @math{-1} for @code{.TRUE.},
3453 extra care has to be taken -- such as passing the value as
3454 @code{INTEGER}.  (The same value restriction also applies to other
3455 front ends of GCC, e.g. to GCC's C99 compiler for @code{_Bool}
3456 or GCC's Ada compiler for @code{Boolean}.)
3458 For arguments of @code{CHARACTER} type, the character length is passed
3459 as hidden argument.  For deferred-length strings, the value is passed
3460 by reference, otherwise by value.  The character length has the type
3461 @code{INTEGER(kind=4)}.  Note with C binding, @code{CHARACTER(len=1)}
3462 result variables are returned according to the platform ABI and no
3463 hidden length argument is used for dummy arguments; with @code{VALUE},
3464 those variables are passed by value.
3466 For @code{OPTIONAL} dummy arguments, an absent argument is denoted
3467 by a NULL pointer, except for scalar dummy arguments of type
3468 @code{INTEGER}, @code{LOGICAL}, @code{REAL} and @code{COMPLEX}
3469 which have the @code{VALUE} attribute.  For those, a hidden Boolean
3470 argument (@code{logical(kind=C_bool),value}) is used to indicate
3471 whether the argument is present.
3473 Arguments which are assumed-shape, assumed-rank or deferred-rank
3474 arrays or, with @option{-fcoarray=lib}, allocatable scalar coarrays use
3475 an array descriptor.  All other arrays pass the address of the
3476 first element of the array.  With @option{-fcoarray=lib}, the token
3477 and the offset belonging to nonallocatable coarrays dummy arguments
3478 are passed as hidden argument along the character length hidden
3479 arguments.  The token is an oparque pointer identifying the coarray
3480 and the offset is a passed-by-value integer of kind @code{C_PTRDIFF_T},
3481 denoting the byte offset between the base address of the coarray and
3482 the passed scalar or first element of the passed array.
3484 The arguments are passed in the following order
3485 @itemize @bullet
3486 @item Result variable, when the function result is passed by reference
3487 @item Character length of the function result, if it is a of type
3488 @code{CHARACTER} and no C binding is used
3489 @item The arguments in the order in which they appear in the Fortran
3490 declaration
3491 @item The the present status for optional arguments with value attribute,
3492 which are internally passed by value
3493 @item The character length and/or coarray token and offset for the first
3494 argument which is a @code{CHARACTER} or a nonallocatable coarray dummy
3495 argument, followed by the hidden arguments of the next dummy argument
3496 of such a type
3497 @end itemize
3500 @c ---------------------------------------------------------------------
3501 @c Coarray Programming
3502 @c ---------------------------------------------------------------------
3504 @node Coarray Programming
3505 @chapter Coarray Programming
3506 @cindex Coarrays
3508 @menu
3509 * Type and enum ABI Documentation::
3510 * Function ABI Documentation::
3511 @end menu
3514 @node Type and enum ABI Documentation
3515 @section Type and enum ABI Documentation
3517 @menu
3518 * caf_token_t::
3519 * caf_register_t::
3520 @end menu
3522 @node caf_token_t
3523 @subsection @code{caf_token_t}
3525 Typedef of type @code{void *} on the compiler side. Can be any data
3526 type on the library side.
3528 @node caf_register_t
3529 @subsection @code{caf_register_t}
3531 Indicates which kind of coarray variable should be registered.
3533 @verbatim
3534 typedef enum caf_register_t {
3535   CAF_REGTYPE_COARRAY_STATIC,
3536   CAF_REGTYPE_COARRAY_ALLOC,
3537   CAF_REGTYPE_LOCK_STATIC,
3538   CAF_REGTYPE_LOCK_ALLOC,
3539   CAF_REGTYPE_CRITICAL,
3540   CAF_REGTYPE_EVENT_STATIC,
3541   CAF_REGTYPE_EVENT_ALLOC
3543 caf_register_t;
3544 @end verbatim
3547 @node Function ABI Documentation
3548 @section Function ABI Documentation
3550 @menu
3551 * _gfortran_caf_init:: Initialiation function
3552 * _gfortran_caf_finish:: Finalization function
3553 * _gfortran_caf_this_image:: Querying the image number
3554 * _gfortran_caf_num_images:: Querying the maximal number of images
3555 * _gfortran_caf_register:: Registering coarrays
3556 * _gfortran_caf_deregister:: Deregistering coarrays
3557 * _gfortran_caf_send:: Sending data from a local image to a remote image
3558 * _gfortran_caf_get:: Getting data from a remote image
3559 * _gfortran_caf_sendget:: Sending data between remote images
3560 * _gfortran_caf_lock:: Locking a lock variable
3561 * _gfortran_caf_unlock:: Unlocking a lock variable
3562 * _gfortran_caf_event_post:: Post an event
3563 * _gfortran_caf_event_wait:: Wait that an event occurred
3564 * _gfortran_caf_event_query:: Query event count
3565 * _gfortran_caf_sync_all:: All-image barrier
3566 * _gfortran_caf_sync_images:: Barrier for selected images
3567 * _gfortran_caf_sync_memory:: Wait for completion of segment-memory operations
3568 * _gfortran_caf_error_stop:: Error termination with exit code
3569 * _gfortran_caf_error_stop_str:: Error termination with string
3570 * _gfortran_caf_atomic_define:: Atomic variable assignment
3571 * _gfortran_caf_atomic_ref:: Atomic variable reference
3572 * _gfortran_caf_atomic_cas:: Atomic compare and swap
3573 * _gfortran_caf_atomic_op:: Atomic operation
3574 * _gfortran_caf_co_broadcast:: Sending data to all images
3575 * _gfortran_caf_co_max:: Collective maximum reduction
3576 * _gfortran_caf_co_min:: Collective minimum reduction
3577 * _gfortran_caf_co_sum:: Collective summing reduction
3578 * _gfortran_caf_co_reduce:: Generic collective reduction
3579 @end menu
3582 @node _gfortran_caf_init
3583 @subsection @code{_gfortran_caf_init} --- Initialiation function
3584 @cindex Coarray, _gfortran_caf_init
3586 @table @asis
3587 @item @emph{Description}:
3588 This function is called at startup of the program before the Fortran main
3589 program, if the latter has been compiled with @option{-fcoarray=lib}.
3590 It takes as arguments the command-line arguments of the program.  It is
3591 permitted to pass to @code{NULL} pointers as argument; if non-@code{NULL},
3592 the library is permitted to modify the arguments.
3594 @item @emph{Syntax}:
3595 @code{void _gfortran_caf_init (int *argc, char ***argv)}
3597 @item @emph{Arguments}:
3598 @multitable @columnfractions .15 .70
3599 @item @var{argc} @tab intent(inout) An integer pointer with the number of
3600 arguments passed to the program or @code{NULL}.
3601 @item @var{argv} @tab intent(inout) A pointer to an array of strings with the
3602 command-line arguments or @code{NULL}.
3603 @end multitable
3605 @item @emph{NOTES}
3606 The function is modelled after the initialization function of the Message
3607 Passing Interface (MPI) specification.  Due to the way coarray registration
3608 works, it might not be the first call to the libaray.  If the main program is
3609 not written in Fortran and only a library uses coarrays, it can happen that
3610 this function is never called.  Therefore, it is recommended that the library
3611 does not rely on the passed arguments and whether the call has been done.
3612 @end table
3615 @node _gfortran_caf_finish
3616 @subsection @code{_gfortran_caf_finish} --- Finalization function
3617 @cindex Coarray, _gfortran_caf_finish
3619 @table @asis
3620 @item @emph{Description}:
3621 This function is called at the end of the Fortran main program, if it has
3622 been compiled with the @option{-fcoarray=lib} option.
3624 @item @emph{Syntax}:
3625 @code{void _gfortran_caf_finish (void)}
3627 @item @emph{NOTES}
3628 For non-Fortran programs, it is recommended to call the function at the end
3629 of the main program.  To ensure that the shutdown is also performed for
3630 programs where this function is not explicitly invoked, for instance
3631 non-Fortran programs or calls to the system's exit() function, the library
3632 can use a destructor function.  Note that programs can also be terminated
3633 using the STOP and ERROR STOP statements; those use different library calls.
3634 @end table
3637 @node _gfortran_caf_this_image
3638 @subsection @code{_gfortran_caf_this_image} --- Querying the image number
3639 @cindex Coarray, _gfortran_caf_this_image
3641 @table @asis
3642 @item @emph{Description}:
3643 This function returns the current image number, which is a positive number.
3645 @item @emph{Syntax}:
3646 @code{int _gfortran_caf_this_image (int distance)}
3648 @item @emph{Arguments}:
3649 @multitable @columnfractions .15 .70
3650 @item @var{distance} @tab As specified for the @code{this_image} intrinsic
3651 in TS18508. Shall be a nonnegative number.
3652 @end multitable
3654 @item @emph{NOTES}
3655 If the Fortran intrinsic @code{this_image} is invoked without an argument, which
3656 is the only permitted form in Fortran 2008, GCC passes @code{0} as
3657 first argument.
3658 @end table
3661 @node _gfortran_caf_num_images
3662 @subsection @code{_gfortran_caf_num_images} --- Querying the maximal number of images
3663 @cindex Coarray, _gfortran_caf_num_images
3665 @table @asis
3666 @item @emph{Description}:
3667 This function returns the number of images in the current team, if
3668 @var{distance} is 0 or the number of images in the parent team at the specified
3669 distance. If failed is -1, the function returns the number of all images at
3670 the specified distance; if it is 0, the function returns the number of
3671 nonfailed images, and if it is 1, it returns the number of failed images.
3673 @item @emph{Syntax}:
3674 @code{int _gfortran_caf_num_images(int distance, int failed)}
3676 @item @emph{Arguments}:
3677 @multitable @columnfractions .15 .70
3678 @item @var{distance} @tab the distance from this image to the ancestor.
3679 Shall be positive.
3680 @item @var{failed} @tab shall be -1, 0, or 1
3681 @end multitable
3683 @item @emph{NOTES}
3684 This function follows TS18508. If the num_image intrinsic has no arguments,
3685 the the compiler passes @code{distance=0} and @code{failed=-1} to the function.
3686 @end table
3689 @node _gfortran_caf_register
3690 @subsection @code{_gfortran_caf_register} --- Registering coarrays
3691 @cindex Coarray, _gfortran_caf_deregister
3693 @table @asis
3694 @item @emph{Description}:
3695 Allocates memory for a coarray and creates a token to identify the coarray. The
3696 function is called for both coarrays with @code{SAVE} attribute and using an
3697 explicit @code{ALLOCATE} statement. If an error occurs and @var{STAT} is a
3698 @code{NULL} pointer, the function shall abort with printing an error message
3699 and starting the error termination.  If no error occurs and @var{STAT} is
3700 present, it shall be set to zero. Otherwise, it shall be set to a positive
3701 value and, if not-@code{NULL}, @var{ERRMSG} shall be set to a string describing
3702 the failure. The function shall return a pointer to the requested memory
3703 for the local image as a call to @code{malloc} would do.
3705 For @code{CAF_REGTYPE_COARRAY_STATIC} and @code{CAF_REGTYPE_COARRAY_ALLOC},
3706 the passed size is the byte size requested.  For @code{CAF_REGTYPE_LOCK_STATIC},
3707 @code{CAF_REGTYPE_LOCK_ALLOC} and @code{CAF_REGTYPE_CRITICAL} it is the array
3708 size or one for a scalar.
3711 @item @emph{Syntax}:
3712 @code{void *caf_register (size_t size, caf_register_t type, caf_token_t *token,
3713 int *stat, char *errmsg, int errmsg_len)}
3715 @item @emph{Arguments}:
3716 @multitable @columnfractions .15 .70
3717 @item @var{size} @tab For normal coarrays, the byte size of the coarray to be
3718 allocated; for lock types and event types, the number of elements.
3719 @item @var{type} @tab one of the caf_register_t types.
3720 @item @var{token} @tab intent(out) An opaque pointer identifying the coarray.
3721 @item @var{stat} @tab intent(out) For allocatable coarrays, stores the STAT=;
3722 may be NULL
3723 @item @var{errmsg} @tab intent(out) When an error occurs, this will be set to
3724 an error message; may be NULL
3725 @item @var{errmsg_len} @tab the buffer size of errmsg.
3726 @end multitable
3728 @item @emph{NOTES}
3729 Nonalloatable coarrays have to be registered prior use from remote images.
3730 In order to guarantee this, they have to be registered before the main
3731 program. This can be achieved by creating constructor functions. That is what
3732 GCC does such that also nonallocatable coarrays the memory is allocated and no
3733 static memory is used.  The token permits to identify the coarray; to the
3734 processor, the token is a nonaliasing pointer. The library can, for instance,
3735 store the base address of the coarray in the token, some handle or a more
3736 complicated struct.
3738 For normal coarrays, the returned pointer is used for accesses on the local
3739 image. For lock types, the value shall only used for checking the allocation
3740 status. Note that for critical blocks, the locking is only required on one
3741 image; in the locking statement, the processor shall always pass always an
3742 image index of one for critical-block lock variables
3743 (@code{CAF_REGTYPE_CRITICAL}). For lock types and critical-block variables,
3744 the initial value shall be unlocked (or, respecitively, not in critical
3745 section) such as the value false; for event types, the initial state should
3746 be no event, e.g. zero.
3747 @end table
3750 @node _gfortran_caf_deregister
3751 @subsection @code{_gfortran_caf_deregister} --- Deregistering coarrays
3752 @cindex Coarray, _gfortran_caf_deregister
3754 @table @asis
3755 @item @emph{Description}:
3756 Called to free the memory of a coarray; the processor calls this function for
3757 automatic and explicit deallocation.  In case of an error, this function shall
3758 fail with an error message, unless the @var{STAT} variable is not null.
3760 @item @emph{Syntax}:
3761 @code{void caf_deregister (const caf_token_t *token, int *stat, char *errmsg,
3762 int errmsg_len)}
3764 @item @emph{Arguments}:
3765 @multitable @columnfractions .15 .70
3766 @item @var{stat} @tab intent(out) Stores the STAT=; may be NULL
3767 @item @var{errmsg} @tab intent(out) When an error occurs, this will be set
3768 to an error message; may be NULL
3769 @item @var{errmsg_len} @tab the buffer size of errmsg.
3770 @end multitable
3772 @item @emph{NOTES}
3773 For nonalloatable coarrays this function is never called.  If a cleanup is
3774 required, it has to be handled via the finish, stop and error stop functions,
3775 and via destructors.
3776 @end table
3779 @node _gfortran_caf_send
3780 @subsection @code{_gfortran_caf_send} --- Sending data from a local image to a remote image
3781 @cindex Coarray, _gfortran_caf_send
3783 @table @asis
3784 @item @emph{Description}:
3785 Called to send a scalar, an array section or whole array from a local
3786 to a remote image identified by the image_index.
3788 @item @emph{Syntax}:
3789 @code{void _gfortran_caf_send (caf_token_t token, size_t offset,
3790 int image_index, gfc_descriptor_t *dest, caf_vector_t *dst_vector,
3791 gfc_descriptor_t *src, int dst_kind, int src_kind, bool may_require_tmp)}
3793 @item @emph{Arguments}:
3794 @multitable @columnfractions .15 .70
3795 @item @var{token} @tab intent(in)  An opaque pointer identifying the coarray.
3796 @item @var{offset} @tab By which amount of bytes the actual data is shifted
3797 compared to the base address of the coarray.
3798 @item @var{image_index} @tab The ID of the remote image; must be a positive
3799 number.
3800 @item @var{dest} @tab intent(in) Array descriptor for the remote image for the
3801 bounds and the size. The base_addr shall not be accessed.
3802 @item @var{dst_vector} @tab intent(int)  If not NULL, it contains the vector
3803 subscript of the destination array; the values are relative to the dimension
3804 triplet of the dest argument.
3805 @item @var{src} @tab intent(in) Array descriptor of the local array to be
3806 transferred to the remote image
3807 @item @var{dst_kind} @tab Kind of the destination argument
3808 @item @var{src_kind} @tab Kind of the source argument
3809 @item @var{may_require_tmp} @tab The variable is false it is known at compile
3810 time that the @var{dest} and @var{src} either cannot overlap or overlap (fully
3811 or partially) such that walking @var{src} and @var{dest} in element wise
3812 element order (honoring the stride value) will not lead to wrong results.
3813 Otherwise, the value is true.
3814 @end multitable
3816 @item @emph{NOTES}
3817 It is permitted to have image_id equal the current image; the memory of the
3818 send-to and the send-from might (partially) overlap in that case. The
3819 implementation has to take care that it handles this case, e.g. using
3820 @code{memmove} which handles (partially) overlapping memory. If
3821 @var{may_require_tmp} is true, the library might additionally create a
3822 temporary variable, unless additional checks show that this is not required
3823 (e.g. because walking backward is possible or because both arrays are
3824 contiguous and @code{memmove} takes care of overlap issues).
3826 Note that the assignment of a scalar to an array is permitted. In addition,
3827 the library has to handle numeric-type conversion and for strings, padding
3828 and different character kinds.
3829 @end table
3832 @node _gfortran_caf_get
3833 @subsection @code{_gfortran_caf_get} --- Getting data from a remote image
3834 @cindex Coarray, _gfortran_caf_get
3836 @table @asis
3837 @item @emph{Description}:
3838 Called to get an array section or whole array from a a remote,
3839 image identified by the image_index.
3841 @item @emph{Syntax}:
3842 @code{void _gfortran_caf_get_desc (caf_token_t token, size_t offset,
3843 int image_index, gfc_descriptor_t *src, caf_vector_t *src_vector,
3844 gfc_descriptor_t *dest, int src_kind, int dst_kind, bool may_require_tmp)}
3846 @item @emph{Arguments}:
3847 @multitable @columnfractions .15 .70
3848 @item @var{token} @tab intent(in)  An opaque pointer identifying the coarray.
3849 @item @var{offset} @tab By which amount of bytes the actual data is shifted
3850 compared to the base address of the coarray.
3851 @item @var{image_index} @tab The ID of the remote image; must be a positive
3852 number.
3853 @item @var{dest} @tab intent(in) Array descriptor of the local array to be
3854 transferred to the remote image
3855 @item @var{src} @tab intent(in) Array descriptor for the remote image for the
3856 bounds and the size. The base_addr shall not be accessed.
3857 @item @var{src_vector} @tab intent(int)  If not NULL, it contains the vector
3858 subscript of the destination array; the values are relative to the dimension
3859 triplet of the dest argument.
3860 @item @var{dst_kind} @tab Kind of the destination argument
3861 @item @var{src_kind} @tab Kind of the source argument
3862 @item @var{may_require_tmp} @tab The variable is false it is known at compile
3863 time that the @var{dest} and @var{src} either cannot overlap or overlap (fully
3864 or partially) such that walking @var{src} and @var{dest} in element wise
3865 element order (honoring the stride value) will not lead to wrong results.
3866 Otherwise, the value is true.
3867 @end multitable
3869 @item @emph{NOTES}
3870 It is permitted to have image_id equal the current image; the memory of the
3871 send-to and the send-from might (partially) overlap in that case. The
3872 implementation has to take care that it handles this case, e.g. using
3873 @code{memmove} which handles (partially) overlapping memory. If
3874 @var{may_require_tmp} is true, the library might additionally create a
3875 temporary variable, unless additional checks show that this is not required
3876 (e.g. because walking backward is possible or because both arrays are
3877 contiguous and @code{memmove} takes care of overlap issues).
3879 Note that the library has to handle numeric-type conversion and for strings,
3880 padding and different character kinds.
3881 @end table
3884 @node _gfortran_caf_sendget
3885 @subsection @code{_gfortran_caf_sendget} --- Sending data between remote images
3886 @cindex Coarray, _gfortran_caf_sendget
3888 @table @asis
3889 @item @emph{Description}:
3890 Called to send a scalar, an array section or whole array from a remote image
3891 identified by the src_image_index to a remote image identified by the
3892 dst_image_index.
3894 @item @emph{Syntax}:
3895 @code{void _gfortran_caf_sendget (caf_token_t dst_token, size_t dst_offset,
3896 int dst_image_index, gfc_descriptor_t *dest, caf_vector_t *dst_vector,
3897 caf_token_t src_token, size_t src_offset, int src_image_index,
3898 gfc_descriptor_t *src, caf_vector_t *src_vector, int dst_kind, int src_kind,
3899 bool may_require_tmp)}
3901 @item @emph{Arguments}:
3902 @multitable @columnfractions .15 .70
3903 @item @var{dst_token} @tab intent(in)  An opaque pointer identifying the
3904 destination coarray.
3905 @item @var{dst_offset} @tab  By which amount of bytes the actual data is
3906 shifted compared to the base address of the destination coarray.
3907 @item @var{dst_image_index} @tab The ID of the destination remote image; must
3908 be a positive number.
3909 @item @var{dest} @tab intent(in) Array descriptor for the destination
3910 remote image for the bounds and the size. The base_addr shall not be accessed.
3911 @item @var{dst_vector} @tab intent(int)  If not NULL, it contains the vector
3912 subscript of the destination array; the values are relative to the dimension
3913 triplet of the dest argument.
3914 @item @var{src_token} @tab An opaque pointer identifying the source coarray.
3915 @item @var{src_offset} @tab By which amount of bytes the actual data is shifted
3916 compared to the base address of the source coarray.
3917 @item @var{src_image_index} @tab The ID of the source remote image; must be a
3918 positive number.
3919 @item @var{src} @tab intent(in) Array descriptor of the local array to be
3920 transferred to the remote image.
3921 @item @var{src_vector} @tab intent(in) Array descriptor of the local array to
3922 be transferred to the remote image
3923 @item @var{dst_kind} @tab Kind of the destination argument
3924 @item @var{src_kind} @tab Kind of the source argument
3925 @item @var{may_require_tmp} @tab The variable is false it is known at compile
3926 time that the @var{dest} and @var{src} either cannot overlap or overlap (fully
3927 or partially) such that walking @var{src} and @var{dest} in element wise
3928 element order (honoring the stride value) will not lead to wrong results.
3929 Otherwise, the value is true.
3930 @end multitable
3932 @item @emph{NOTES}
3933 It is permitted to have image_ids equal; the memory of the send-to and the
3934 send-from might (partially) overlap in that case. The implementation has to
3935 take care that it handles this case, e.g. using @code{memmove} which handles
3936 (partially) overlapping memory. If @var{may_require_tmp} is true, the library
3937 might additionally create a temporary variable, unless additional checks show
3938 that this is not required (e.g. because walking backward is possible or because
3939 both arrays are contiguous and @code{memmove} takes care of overlap issues).
3941 Note that the assignment of a scalar to an array is permitted. In addition,
3942 the library has to handle numeric-type conversion and for strings, padding and
3943 different character kinds.
3944 @end table
3947 @node _gfortran_caf_lock
3948 @subsection @code{_gfortran_caf_lock} --- Locking a lock variable
3949 @cindex Coarray, _gfortran_caf_lock
3951 @table @asis
3952 @item @emph{Description}:
3953 Acquire a lock on the given image on a scalar locking variable or for the
3954 given array element for an array-valued variable. If the @var{aquired_lock}
3955 is @code{NULL}, the function return after having obtained the lock. If it is
3956 nonnull, the result is is assigned the value true (one) when the lock could be
3957 obtained and false (zero) otherwise.  Locking a lock variable which has already
3958 been locked by the same image is an error.
3960 @item @emph{Syntax}:
3961 @code{void _gfortran_caf_lock (caf_token_t token, size_t index, int image_index,
3962 int *aquired_lock, int *stat, char *errmsg, int errmsg_len)}
3964 @item @emph{Arguments}:
3965 @multitable @columnfractions .15 .70
3966 @item @var{token} @tab intent(in) An opaque pointer identifying the coarray.
3967 @item @var{index} @tab Array index; first array index is 0. For scalars, it is
3968 always 0.
3969 @item @var{image_index} @tab The ID of the remote image; must be a positive
3970 number.
3971 @item @var{aquired_lock} @tab intent(out) If not NULL, it returns whether lock
3972 could be obtained
3973 @item @var{stat} @tab intent(out) Stores the STAT=; may be NULL
3974 @item @var{errmsg} @tab intent(out) When an error occurs, this will be set to
3975 an error message; may be NULL
3976 @item @var{errmsg_len} @tab the buffer size of errmsg.
3977 @end multitable
3979 @item @emph{NOTES}
3980 This function is also called for critical blocks; for those, the array index
3981 is always zero and the image index is one.  Libraries are permitted to use other
3982 images for critical-block locking variables.
3983 @end table
3985 @node _gfortran_caf_unlock
3986 @subsection @code{_gfortran_caf_lock} --- Unlocking a lock variable
3987 @cindex Coarray, _gfortran_caf_unlock
3989 @table @asis
3990 @item @emph{Description}:
3991 Release a lock on the given image on a scalar locking variable or for the
3992 given array element for an array-valued variable. Unlocking a lock variable
3993 which is unlocked or has been locked by a different image is an error.
3995 @item @emph{Syntax}:
3996 @code{void _gfortran_caf_unlock (caf_token_t token, size_t index, int image_index,
3997 int *stat, char *errmsg, int errmsg_len)}
3999 @item @emph{Arguments}:
4000 @multitable @columnfractions .15 .70
4001 @item @var{token} @tab intent(in) An opaque pointer identifying the coarray.
4002 @item @var{index} @tab Array index; first array index is 0. For scalars, it is
4003 always 0.
4004 @item @var{image_index} @tab The ID of the remote image; must be a positive
4005 number.
4006 @item @var{stat} @tab intent(out) For allocatable coarrays, stores the STAT=;
4007 may be NULL
4008 @item @var{errmsg} @tab intent(out) When an error occurs, this will be set to
4009 an error message; may be NULL
4010 @item @var{errmsg_len} @tab the buffer size of errmsg.
4011 @end multitable
4013 @item @emph{NOTES}
4014 This function is also called for critical block; for those, the array index
4015 is always zero and the image index is one.  Libraries are permitted to use other
4016 images for critical-block locking variables.
4017 @end table
4019 @node _gfortran_caf_event_post
4020 @subsection @code{_gfortran_caf_event_post} --- Post an event
4021 @cindex Coarray, _gfortran_caf_event_post
4023 @table @asis
4024 @item @emph{Description}:
4025 Increment the event count of the specified event variable.
4027 @item @emph{Syntax}:
4028 @code{void _gfortran_caf_event_post (caf_token_t token, size_t index,
4029 int image_index, int *stat, char *errmsg, int errmsg_len)}
4031 @item @emph{Arguments}:
4032 @multitable @columnfractions .15 .70
4033 @item @var{token} @tab intent(in) An opaque pointer identifying the coarray.
4034 @item @var{index} @tab Array index; first array index is 0. For scalars, it is
4035 always 0.
4036 @item @var{image_index} @tab The ID of the remote image; must be a positive
4037 number; zero indicates the current image when accessed noncoindexed.
4038 @item @var{stat} @tab intent(out) Stores the STAT=; may be NULL
4039 @item @var{errmsg} @tab intent(out) When an error occurs, this will be set to
4040 an error message; may be NULL
4041 @item @var{errmsg_len} @tab the buffer size of errmsg.
4042 @end multitable
4044 @item @emph{NOTES}
4045 This acts like an atomic add of one to the remote image's event variable.
4046 The statement is an image-control statement but does not imply sync memory.
4047 Still, all preceeding push communications of this image to the specified
4048 remote image has to be completed before @code{event_wait} on the remote
4049 image returns.
4050 @end table
4054 @node _gfortran_caf_event_wait
4055 @subsection @code{_gfortran_caf_event_wait} --- Wait that an event occurred
4056 @cindex Coarray, _gfortran_caf_event_wait
4058 @table @asis
4059 @item @emph{Description}:
4060 Wait until the event count has reached at least the specified
4061 @var{until_count}; if so, atomically decrement the event variable by this
4062 amount and return.
4064 @item @emph{Syntax}:
4065 @code{void _gfortran_caf_event_wait (caf_token_t token, size_t index,
4066 int until_count, int *stat, char *errmsg, int errmsg_len)}
4068 @item @emph{Arguments}:
4069 @multitable @columnfractions .15 .70
4070 @item @var{token} @tab intent(in) An opaque pointer identifying the coarray.
4071 @item @var{index} @tab Array index; first array index is 0. For scalars, it is
4072 always 0.
4073 @item @var{until_count} @tab The number of events which have to be available
4074 before the function returns.
4075 @item @var{stat} @tab intent(out) Stores the STAT=; may be NULL
4076 @item @var{errmsg} @tab intent(out) When an error occurs, this will be set to
4077 an error message; may be NULL
4078 @item @var{errmsg_len} @tab the buffer size of errmsg.
4079 @end multitable
4081 @item @emph{NOTES}
4082 This function only operates on a local coarray. It acts like a loop checking
4083 atomically the value of the event variable, breaking if the value is greater
4084 or equal the requested number of counts. Before the function returns, the
4085 event variable has to be decremented by the requested @var{until_count} value.
4086 A possible implementation would be a busy loop for a certain number of spins
4087 (possibly depending on the number of threads relative to the number of available
4088 cores) followed by other waiting strategy such as a sleeping wait (possibly with
4089 an increasing number of sleep time) or, if possible, a futex wait.
4091 The statement is an image-control statement but does not imply sync memory.
4092 Still, all preceeding push communications to this image of images having
4093 issued a @code{event_push} have to be completed before this function returns.
4094 @end table
4098 @node _gfortran_caf_event_query
4099 @subsection @code{_gfortran_caf_event_query} --- Query event count
4100 @cindex Coarray, _gfortran_caf_event_query
4102 @table @asis
4103 @item @emph{Description}:
4104 Return the event count of the specified event count.
4106 @item @emph{Syntax}:
4107 @code{void _gfortran_caf_event_query (caf_token_t token, size_t index,
4108 int image_index, int *count, int *stat)}
4110 @item @emph{Arguments}:
4111 @multitable @columnfractions .15 .70
4112 @item @var{token} @tab intent(in) An opaque pointer identifying the coarray.
4113 @item @var{index} @tab Array index; first array index is 0. For scalars, it is
4114 always 0.
4115 @item @var{image_index} @tab The ID of the remote image; must be a positive
4116 number; zero indicates the current image when accessed noncoindexed.
4117 @item @var{count} @tab intent(out) The number of events currently posted to
4118 the event variable
4119 @item @var{stat} @tab intent(out) Stores the STAT=; may be NULL
4120 @end multitable
4122 @item @emph{NOTES}
4123 The typical use is to check the local even variable to only call
4124 @code{event_wait} when the data is available. However, a coindexed variable
4125 is permitted; there is no ordering or synchronization implied.  It acts like
4126 an atomic fetch of the value of the event variable.
4127 @end table
4129 @node _gfortran_caf_sync_all
4130 @subsection @code{_gfortran_caf_sync_all} --- All-image barrier
4131 @cindex Coarray, _gfortran_caf_sync_all
4133 @table @asis
4134 @item @emph{Description}:
4135 Synchronization of all images in the current team; the program only continues
4136 on a given image after this function has been called on all images of the
4137 current team.  Additionally, it ensures that all pending data transfers of
4138 previous segment have completed.
4140 @item @emph{Syntax}:
4141 @code{void _gfortran_caf_sync_all (int *stat, char *errmsg, int errmsg_len)}
4143 @item @emph{Arguments}:
4144 @multitable @columnfractions .15 .70
4145 @item @var{stat} @tab intent(out) Stores the status STAT= and may be NULL.
4146 @item @var{errmsg} @tab intent(out) When an error occurs, this will be set to
4147 an error message; may be NULL
4148 @item @var{errmsg_len} @tab the buffer size of errmsg.
4149 @end multitable
4150 @end table
4154 @node _gfortran_caf_sync_images
4155 @subsection @code{_gfortran_caf_sync_images} --- Barrier for selected images
4156 @cindex Coarray, _gfortran_caf_sync_images
4158 @table @asis
4159 @item @emph{Description}:
4160 Synchronization between the specified images; the program only continues on a
4161 given image after this function has been called on all images specified for
4162 that image. Note that one image can wait for all other images in the current
4163 team (e.g. via @code{sync images(*)}) while those only wait for that specific
4164 image.  Additionally, @code{sync images} it ensures that all pending data
4165 transfers of previous segment have completed.
4167 @item @emph{Syntax}:
4168 @code{void _gfortran_caf_sync_images (int count, int images[], int *stat,
4169 char *errmsg, int errmsg_len)}
4171 @item @emph{Arguments}:
4172 @multitable @columnfractions .15 .70
4173 @item @var{count} @tab the number of images which are provided in the next
4174 argument.  For a zero-sized array, the value is zero.  For @code{sync
4175 images (*)}, the value is @math{-1}.
4176 @item @var{images} @tab intent(in) an array with the images provided by the
4177 user. If @var{count} is zero, a NULL pointer is passed.
4178 @item @var{stat} @tab intent(out) Stores the status STAT= and may be NULL.
4179 @item @var{errmsg} @tab intent(out) When an error occurs, this will be set to
4180 an error message; may be NULL
4181 @item @var{errmsg_len} @tab the buffer size of errmsg.
4182 @end multitable
4183 @end table
4187 @node _gfortran_caf_sync_memory
4188 @subsection @code{_gfortran_caf_sync_memory} --- Wait for completion of segment-memory operations
4189 @cindex Coarray, _gfortran_caf_sync_memory
4191 @table @asis
4192 @item @emph{Description}:
4193 Acts as optimization barrier between different segments. It also ensures that
4194 all pending memory operations of this image have been completed.
4196 @item @emph{Syntax}:
4197 @code{void _gfortran_caf_sync_memory (int *stat, char *errmsg, int errmsg_len)}
4199 @item @emph{Arguments}:
4200 @multitable @columnfractions .15 .70
4201 @item @var{stat} @tab intent(out) Stores the status STAT= and may be NULL.
4202 @item @var{errmsg} @tab intent(out) When an error occurs, this will be set to
4203 an error message; may be NULL
4204 @item @var{errmsg_len} @tab the buffer size of errmsg.
4205 @end multitable
4207 @item @emph{NOTE} A simple implementation could be
4208 @code{__asm__ __volatile__ ("":::"memory")} to prevent code movements.
4209 @end table
4213 @node _gfortran_caf_error_stop
4214 @subsection @code{_gfortran_caf_error_stop} --- Error termination with exit code
4215 @cindex Coarray, _gfortran_caf_error_stop
4217 @table @asis
4218 @item @emph{Description}:
4219 Invoked for an @code{ERROR STOP} statement which has an integer argument.  The
4220 function should terminate the program with the specified exit code.
4223 @item @emph{Syntax}:
4224 @code{void _gfortran_caf_error_stop (int32_t error)}
4226 @item @emph{Arguments}:
4227 @multitable @columnfractions .15 .70
4228 @item @var{error} @tab the exit status to be used.
4229 @end multitable
4230 @end table
4234 @node _gfortran_caf_error_stop_str
4235 @subsection @code{_gfortran_caf_error_stop_str} --- Error termination with string
4236 @cindex Coarray, _gfortran_caf_error_stop_str
4238 @table @asis
4239 @item @emph{Description}:
4240 Invoked for an @code{ERROR STOP} statement which has a string as argument.  The
4241 function should terminate the program with a nonzero-exit code.
4243 @item @emph{Syntax}:
4244 @code{void _gfortran_caf_error_stop (const char *string, int32_t len)}
4246 @item @emph{Arguments}:
4247 @multitable @columnfractions .15 .70
4248 @item @var{string} @tab the error message (not zero terminated)
4249 @item @var{len} @tab the length of the string
4250 @end multitable
4251 @end table
4255 @node _gfortran_caf_atomic_define
4256 @subsection @code{_gfortran_caf_atomic_define} --- Atomic variable assignment
4257 @cindex Coarray, _gfortran_caf_atomic_define
4259 @table @asis
4260 @item @emph{Description}:
4261 Assign atomically a value to an integer or logical variable.
4263 @item @emph{Syntax}:
4264 @code{void _gfortran_caf_atomic_define (caf_token_t token, size_t offset,
4265 int image_index, void *value, int *stat, int type, int kind)}
4267 @item @emph{Arguments}:
4268 @multitable @columnfractions .15 .70
4269 @item @var{token} @tab intent(in) An opaque pointer identifying the coarray.
4270 @item @var{offset} @tab By which amount of bytes the actual data is shifted
4271 compared to the base address of the coarray.
4272 @item @var{image_index} @tab The ID of the remote image; must be a positive
4273 number; zero indicates the current image when used noncoindexed.
4274 @item @var{value} @tab intent(in) the value to be assigned, passed by reference.
4275 @item @var{stat} @tab intent(out) Stores the status STAT= and may be NULL.
4276 @item @var{type} @tab the data type, i.e. @code{BT_INTEGER} (1) or
4277 @code{BT_LOGICAL} (2).
4278 @item @var{kind} @tab The kind value (only 4; always @code{int})
4279 @end multitable
4280 @end table
4284 @node _gfortran_caf_atomic_ref
4285 @subsection @code{_gfortran_caf_atomic_ref} --- Atomic variable reference
4286 @cindex Coarray, _gfortran_caf_atomic_ref
4288 @table @asis
4289 @item @emph{Description}:
4290 Reference atomically a value of a kind-4 integer or logical variable.
4292 @item @emph{Syntax}:
4293 @code{void _gfortran_caf_atomic_ref (caf_token_t token, size_t offset,
4294 int image_index, void *value, int *stat, int type, int kind)}
4296 @item @emph{Arguments}:
4297 @item @emph{Arguments}:
4298 @multitable @columnfractions .15 .70
4299 @item @var{token} @tab intent(in) An opaque pointer identifying the coarray.
4300 @item @var{offset} @tab By which amount of bytes the actual data is shifted
4301 compared to the base address of the coarray.
4302 @item @var{image_index} @tab The ID of the remote image; must be a positive
4303 number; zero indicates the current image when used noncoindexed.
4304 @item @var{value} @tab intent(out) The variable assigned the atomically
4305 referenced variable.
4306 @item @var{stat} @tab intent(out) Stores the status STAT= and may be NULL.
4307 @item @var{type} @tab the data type, i.e. @code{BT_INTEGER} (1) or
4308 @code{BT_LOGICAL} (2).
4309 @item @var{kind} @tab The kind value (only 4; always @code{int})
4310 @end multitable
4311 @end table
4315 @node _gfortran_caf_atomic_cas
4316 @subsection @code{_gfortran_caf_atomic_cas} --- Atomic compare and swap
4317 @cindex Coarray, _gfortran_caf_atomic_cas
4319 @table @asis
4320 @item @emph{Description}:
4321 Atomic compare and swap of a kind-4 integer or logical variable. Assigns
4322 atomically the specified value to the atomic variable, if the latter has
4323 the value specified by the passed condition value.
4325 @item @emph{Syntax}:
4326 @code{void _gfortran_caf_atomic_cas (caf_token_t token, size_t offset,
4327 int image_index, void *old, void *compare, void *new_val, int *stat,
4328 int type, int kind)}
4330 @item @emph{Arguments}:
4331 @multitable @columnfractions .15 .70
4332 @item @var{token} @tab intent(in) An opaque pointer identifying the coarray.
4333 @item @var{offset} @tab By which amount of bytes the actual data is shifted
4334 compared to the base address of the coarray.
4335 @item @var{image_index} @tab The ID of the remote image; must be a positive
4336 number; zero indicates the current image when used noncoindexed.
4337 @item @var{old} @tab intent(out) the value which the atomic variable had
4338 just before the cas operation.
4339 @item @var{compare} @tab intent(in) The value used for comparision.
4340 @item @var{new_val} @tab intent(in) The new value for the atomic variable,
4341 assigned to the atomic variable, if @code{compare} equals the value of the
4342 atomic variable.
4343 @item @var{stat} @tab intent(out) Stores the status STAT= and may be NULL.
4344 @item @var{type} @tab the data type, i.e. @code{BT_INTEGER} (1) or
4345 @code{BT_LOGICAL} (2).
4346 @item @var{kind} @tab The kind value (only 4; always @code{int})
4347 @end multitable
4348 @end table
4352 @node _gfortran_caf_atomic_op
4353 @subsection @code{_gfortran_caf_atomic_op} --- Atomic operation
4354 @cindex Coarray, _gfortran_caf_atomic_op
4356 @table @asis
4357 @item @emph{Description}:
4358 Apply an operation atomically to an atomic integer or logical variable.
4359 After the operation, @var{old} contains the value just before the operation,
4360 which, respectively, adds (GFC_CAF_ATOMIC_ADD) atomically the @code{value} to
4361 the atomic integer variable or does a bitwise AND, OR or exclusive OR of the
4362 between the atomic variable and @var{value}; the result is then stored in the
4363 atomic variable.
4365 @item @emph{Syntax}:
4366 @code{void _gfortran_caf_atomic_op (int op, caf_token_t token, size_t offset,
4367 int image_index, void *value, void *old, int *stat, int type, int kind)}
4369 @item @emph{Arguments}:
4370 @multitable @columnfractions .15 .70
4371 @item @var{op} @tab the operation to be performed; possible values
4372 @code{GFC_CAF_ATOMIC_ADD} (1), @code{GFC_CAF_ATOMIC_AND} (2),
4373 @code{GFC_CAF_ATOMIC_OR} (3), @code{GFC_CAF_ATOMIC_XOR} (4).
4374 @item @var{token} @tab intent(in) An opaque pointer identifying the coarray.
4375 @item @var{offset} @tab By which amount of bytes the actual data is shifted
4376 compared to the base address of the coarray.
4377 @item @var{image_index} @tab The ID of the remote image; must be a positive
4378 number; zero indicates the current image when used noncoindexed.
4379 @item @var{old} @tab intent(out) the value which the atomic variable had
4380 just before the atomic operation.
4381 @item @var{val} @tab intent(in) The new value for the atomic variable,
4382 assigned to the atomic variable, if @code{compare} equals the value of the
4383 atomic variable.
4384 @item @var{stat} @tab intent(out) Stores the status STAT= and may be NULL.
4385 @item @var{type} @tab the data type, i.e. @code{BT_INTEGER} (1) or
4386 @code{BT_LOGICAL} (2).
4387 @item @var{kind} @tab The kind value (only 4; always @code{int})
4388 @end multitable
4389 @end table
4394 @node _gfortran_caf_co_broadcast
4395 @subsection @code{_gfortran_caf_co_broadcast} --- Sending data to all images
4396 @cindex Coarray, _gfortran_caf_co_broadcast
4398 @table @asis
4399 @item @emph{Description}:
4400 Distribute a value from a given image to all other images in the team. Has to
4401 be called collectively.
4403 @item @emph{Syntax}:
4404 @code{void _gfortran_caf_co_broadcast (gfc_descriptor_t *a,
4405 int source_image, int *stat, char *errmsg, int errmsg_len)}
4407 @item @emph{Arguments}:
4408 @multitable @columnfractions .15 .70
4409 @item @var{a} @tab intent(inout) And array descriptor with the data to be
4410 breoadcasted (on @var{source_image}) or to be received (other images).
4411 @item @var{source_image} @tab The ID of the image from which the data should
4412 be taken.
4413 @item @var{stat} @tab intent(out) Stores the status STAT= and may be NULL.
4414 @item @var{errmsg} @tab intent(out) When an error occurs, this will be set to
4415 an error message; may be NULL
4416 @item @var{errmsg_len} @tab the buffer size of errmsg.
4417 @end multitable
4418 @end table
4422 @node _gfortran_caf_co_max
4423 @subsection @code{_gfortran_caf_co_max} --- Collective maximum reduction
4424 @cindex Coarray, _gfortran_caf_co_max
4426 @table @asis
4427 @item @emph{Description}:
4428 Calculates the for the each array element of the variable @var{a} the maximum
4429 value for that element in the current team; if @var{result_image} has the
4430 value 0, the result shall be stored on all images, otherwise, only on the
4431 specified image. This function operates on numeric values and character
4432 strings.
4434 @item @emph{Syntax}:
4435 @code{void _gfortran_caf_co_max (gfc_descriptor_t *a, int result_image,
4436 int *stat, char *errmsg, int a_len, int errmsg_len)}
4438 @item @emph{Arguments}:
4439 @multitable @columnfractions .15 .70
4440 @item @var{a} @tab intent(inout) And array descriptor with the data to be
4441 breoadcasted (on @var{source_image}) or to be received (other images).
4442 @item @var{result_image} @tab The ID of the image to which the reduced
4443 value should be copied to; if zero, it has to be copied to all images.
4444 @item @var{stat} @tab intent(out) Stores the status STAT= and may be NULL.
4445 @item @var{errmsg} @tab intent(out) When an error occurs, this will be set to
4446 an error message; may be NULL
4447 @item @var{a_len} @tab The string length of argument @var{a}.
4448 @item @var{errmsg_len} @tab the buffer size of errmsg.
4449 @end multitable
4451 @item @emph{NOTES}
4452 If @var{result_image} is nonzero, the value on all images except of the
4453 specified one become undefined; hence, the library may make use of this.
4454 @end table
4458 @node _gfortran_caf_co_min
4459 @subsection @code{_gfortran_caf_co_min} --- Collective minimum reduction
4460 @cindex Coarray, _gfortran_caf_co_min
4462 @table @asis
4463 @item @emph{Description}:
4464 Calculates the for the each array element of the variable @var{a} the minimum
4465 value for that element in the current team; if @var{result_image} has the
4466 value 0, the result shall be stored on all images, otherwise, only on the
4467 specified image. This function operates on numeric values and character
4468 strings.
4470 @item @emph{Syntax}:
4471 @code{void _gfortran_caf_co_min (gfc_descriptor_t *a, int result_image,
4472 int *stat, char *errmsg, int a_len, int errmsg_len)}
4474 @item @emph{Arguments}:
4475 @multitable @columnfractions .15 .70
4476 @item @var{a} @tab intent(inout) And array descriptor with the data to be
4477 breoadcasted (on @var{source_image}) or to be received (other images).
4478 @item @var{result_image} @tab The ID of the image to which the reduced
4479 value should be copied to; if zero, it has to be copied to all images.
4480 @item @var{stat} @tab intent(out) Stores the status STAT= and may be NULL.
4481 @item @var{errmsg} @tab intent(out) When an error occurs, this will be set to
4482 an error message; may be NULL
4483 @item @var{a_len} @tab The string length of argument @var{a}.
4484 @item @var{errmsg_len} @tab the buffer size of errmsg.
4485 @end multitable
4487 @item @emph{NOTES}
4488 If @var{result_image} is nonzero, the value on all images except of the
4489 specified one become undefined; hence, the library may make use of this.
4490 @end table
4494 @node _gfortran_caf_co_sum
4495 @subsection @code{_gfortran_caf_co_sum} --- Collective summing reduction
4496 @cindex Coarray, _gfortran_caf_co_sum
4498 @table @asis
4499 @item @emph{Description}:
4500 Calculates the for the each array element of the variable @var{a} the sum
4501 value for that element in the current team; if @var{result_image} has the
4502 value 0, the result shall be stored on all images, otherwise, only on the
4503 specified image. This function operates on numeric values.
4505 @item @emph{Syntax}:
4506 @code{void _gfortran_caf_co_sum (gfc_descriptor_t *a, int result_image,
4507 int *stat, char *errmsg, int errmsg_len)}
4509 @item @emph{Arguments}:
4510 @multitable @columnfractions .15 .70
4511 @item @var{a} @tab intent(inout) And array descriptor with the data to be
4512 breoadcasted (on @var{source_image}) or to be received (other images).
4513 @item @var{result_image} @tab The ID of the image to which the reduced
4514 value should be copied to; if zero, it has to be copied to all images.
4515 @item @var{stat} @tab intent(out) Stores the status STAT= and may be NULL.
4516 @item @var{errmsg} @tab intent(out) When an error occurs, this will be set to
4517 an error message; may be NULL
4518 @item @var{errmsg_len} @tab the buffer size of errmsg.
4519 @end multitable
4521 @item @emph{NOTES}
4522 If @var{result_image} is nonzero, the value on all images except of the
4523 specified one become undefined; hence, the library may make use of this.
4524 @end table
4528 @node _gfortran_caf_co_reduce
4529 @subsection @code{_gfortran_caf_co_reduce} --- Generic collective reduction
4530 @cindex Coarray, _gfortran_caf_co_reduce
4532 @table @asis
4533 @item @emph{Description}:
4534 Calculates the for the each array element of the variable @var{a} the reduction
4535 value for that element in the current team; if @var{result_image} has the
4536 value 0, the result shall be stored on all images, otherwise, only on the
4537 specified image. The @var{opr} is a pure function doing a mathematically
4538 commutative and associative operation.
4540 The @var{opr_flags} denote the following; the values are bitwise ored.
4541 @code{GFC_CAF_BYREF} (1) if the result should be returned
4542 by value; @code{GFC_CAF_HIDDENLEN} (2) whether the result and argument
4543 string lengths shall be specified as hidden argument;
4544 @code{GFC_CAF_ARG_VALUE} (4) whether the arguments shall be passed by value,
4545 @code{GFC_CAF_ARG_DESC} (8) whether the arguments shall be passed by descriptor.
4548 @item @emph{Syntax}:
4549 @code{void _gfortran_caf_co_reduce (gfc_descriptor_t *a,
4550 void * (*opr) (void *, void *), int opr_flags, int result_image,
4551 int *stat, char *errmsg, int a_len, int errmsg_len)}
4553 @item @emph{Arguments}:
4554 @multitable @columnfractions .15 .70
4555 @item @var{opr} @tab Function pointer to the reduction function.
4556 @item @var{opr_flags} @tab Flags regarding the reduction function
4557 @item @var{a} @tab intent(inout) And array descriptor with the data to be
4558 breoadcasted (on @var{source_image}) or to be received (other images).
4559 @item @var{result_image} @tab The ID of the image to which the reduced
4560 value should be copied to; if zero, it has to be copied to all images.
4561 @item @var{stat} @tab intent(out) Stores the status STAT= and may be NULL.
4562 @item @var{errmsg} @tab intent(out) When an error occurs, this will be set to
4563 an error message; may be NULL
4564 @item @var{a_len} @tab The string length of argument @var{a}.
4565 @item @var{errmsg_len} @tab the buffer size of errmsg.
4566 @end multitable
4568 @item @emph{NOTES}
4569 If @var{result_image} is nonzero, the value on all images except of the
4570 specified one become undefined; hence, the library may make use of this.
4571 For character arguments, the result is passed as first argument, followed
4572 by the result string length, next come the two string arguments, followed
4573 by the two hidden arguments. With C binding, there are no hidden arguments
4574 and by-reference passing and either only a single character is passed or
4575 an array descriptor.
4576 @end table
4579 @c Intrinsic Procedures
4580 @c ---------------------------------------------------------------------
4582 @include intrinsic.texi
4585 @tex
4586 \blankpart
4587 @end tex
4589 @c ---------------------------------------------------------------------
4590 @c Contributing
4591 @c ---------------------------------------------------------------------
4593 @node Contributing
4594 @unnumbered Contributing
4595 @cindex Contributing
4597 Free software is only possible if people contribute to efforts
4598 to create it.
4599 We're always in need of more people helping out with ideas
4600 and comments, writing documentation and contributing code.
4602 If you want to contribute to GNU Fortran,
4603 have a look at the long lists of projects you can take on.
4604 Some of these projects are small,
4605 some of them are large;
4606 some are completely orthogonal to the rest of what is
4607 happening on GNU Fortran,
4608 but others are ``mainstream'' projects in need of enthusiastic hackers.
4609 All of these projects are important!
4610 We will eventually get around to the things here,
4611 but they are also things doable by someone who is willing and able.
4613 @menu
4614 * Contributors::
4615 * Projects::
4616 * Proposed Extensions::
4617 @end menu
4620 @node Contributors
4621 @section Contributors to GNU Fortran
4622 @cindex Contributors
4623 @cindex Credits
4624 @cindex Authors
4626 Most of the parser was hand-crafted by @emph{Andy Vaught}, who is
4627 also the initiator of the whole project.  Thanks Andy!
4628 Most of the interface with GCC was written by @emph{Paul Brook}.
4630 The following individuals have contributed code and/or
4631 ideas and significant help to the GNU Fortran project
4632 (in alphabetical order):
4634 @itemize @minus
4635 @item Janne Blomqvist
4636 @item Steven Bosscher
4637 @item Paul Brook
4638 @item Tobias Burnus
4639 @item Fran@,{c}ois-Xavier Coudert
4640 @item Bud Davis
4641 @item Jerry DeLisle
4642 @item Erik Edelmann
4643 @item Bernhard Fischer
4644 @item Daniel Franke
4645 @item Richard Guenther
4646 @item Richard Henderson
4647 @item Katherine Holcomb
4648 @item Jakub Jelinek
4649 @item Niels Kristian Bech Jensen
4650 @item Steven Johnson
4651 @item Steven G. Kargl
4652 @item Thomas Koenig
4653 @item Asher Langton
4654 @item H. J. Lu
4655 @item Toon Moene
4656 @item Brooks Moses
4657 @item Andrew Pinski
4658 @item Tim Prince
4659 @item Christopher D. Rickett
4660 @item Richard Sandiford
4661 @item Tobias Schl@"uter
4662 @item Roger Sayle
4663 @item Paul Thomas
4664 @item Andy Vaught
4665 @item Feng Wang
4666 @item Janus Weil
4667 @item Daniel Kraft
4668 @end itemize
4670 The following people have contributed bug reports,
4671 smaller or larger patches,
4672 and much needed feedback and encouragement for the
4673 GNU Fortran project: 
4675 @itemize @minus
4676 @item Bill Clodius
4677 @item Dominique d'Humi@`eres
4678 @item Kate Hedstrom
4679 @item Erik Schnetter
4680 @item Joost VandeVondele
4681 @end itemize
4683 Many other individuals have helped debug,
4684 test and improve the GNU Fortran compiler over the past few years,
4685 and we welcome you to do the same!
4686 If you already have done so,
4687 and you would like to see your name listed in the
4688 list above, please contact us.
4691 @node Projects
4692 @section Projects
4694 @table @emph
4696 @item Help build the test suite
4697 Solicit more code for donation to the test suite: the more extensive the
4698 testsuite, the smaller the risk of breaking things in the future! We can
4699 keep code private on request.
4701 @item Bug hunting/squishing
4702 Find bugs and write more test cases! Test cases are especially very
4703 welcome, because it allows us to concentrate on fixing bugs instead of
4704 isolating them.  Going through the bugzilla database at
4705 @url{https://gcc.gnu.org/@/bugzilla/} to reduce testcases posted there and
4706 add more information (for example, for which version does the testcase
4707 work, for which versions does it fail?) is also very helpful.
4709 @end table
4712 @node Proposed Extensions
4713 @section Proposed Extensions
4715 Here's a list of proposed extensions for the GNU Fortran compiler, in no particular
4716 order.  Most of these are necessary to be fully compatible with
4717 existing Fortran compilers, but they are not part of the official
4718 J3 Fortran 95 standard.
4720 @subsection Compiler extensions:
4721 @itemize @bullet
4722 @item
4723 User-specified alignment rules for structures.
4725 @item
4726 Automatically extend single precision constants to double.
4728 @item
4729 Compile code that conserves memory by dynamically allocating common and
4730 module storage either on stack or heap.
4732 @item
4733 Compile flag to generate code for array conformance checking (suggest -CC).
4735 @item
4736 User control of symbol names (underscores, etc).
4738 @item
4739 Compile setting for maximum size of stack frame size before spilling
4740 parts to static or heap.
4742 @item
4743 Flag to force local variables into static space.
4745 @item
4746 Flag to force local variables onto stack.
4747 @end itemize
4750 @subsection Environment Options
4751 @itemize @bullet
4752 @item
4753 Pluggable library modules for random numbers, linear algebra.
4754 LA should use BLAS calling conventions.
4756 @item
4757 Environment variables controlling actions on arithmetic exceptions like
4758 overflow, underflow, precision loss---Generate NaN, abort, default.
4759 action.
4761 @item
4762 Set precision for fp units that support it (i387).
4764 @item
4765 Variable for setting fp rounding mode.
4767 @item
4768 Variable to fill uninitialized variables with a user-defined bit
4769 pattern.
4771 @item
4772 Environment variable controlling filename that is opened for that unit
4773 number.
4775 @item
4776 Environment variable to clear/trash memory being freed.
4778 @item
4779 Environment variable to control tracing of allocations and frees.
4781 @item
4782 Environment variable to display allocated memory at normal program end.
4784 @item
4785 Environment variable for filename for * IO-unit.
4787 @item
4788 Environment variable for temporary file directory.
4790 @item
4791 Environment variable forcing standard output to be line buffered (Unix).
4793 @end itemize
4796 @c ---------------------------------------------------------------------
4797 @c GNU General Public License
4798 @c ---------------------------------------------------------------------
4800 @include gpl_v3.texi
4804 @c ---------------------------------------------------------------------
4805 @c GNU Free Documentation License
4806 @c ---------------------------------------------------------------------
4808 @include fdl.texi
4812 @c ---------------------------------------------------------------------
4813 @c Funding Free Software
4814 @c ---------------------------------------------------------------------
4816 @include funding.texi
4818 @c ---------------------------------------------------------------------
4819 @c Indices
4820 @c ---------------------------------------------------------------------
4822 @node Option Index
4823 @unnumbered Option Index
4824 @command{gfortran}'s command line options are indexed here without any
4825 initial @samp{-} or @samp{--}.  Where an option has both positive and
4826 negative forms (such as -foption and -fno-option), relevant entries in
4827 the manual are indexed under the most appropriate form; it may sometimes
4828 be useful to look up both forms.
4829 @printindex op
4831 @node Keyword Index
4832 @unnumbered Keyword Index
4833 @printindex cp
4835 @bye