I'm working with some legacy Fortran code and discovered some warnings using compile-time caller-callee mismatch detection (ifort's -gen-interfaces -warn interfaces). I received some warning in the following situations:
The caller passes a variable real*8 x (i.e. scalar) to a subroutine, while the subroutine expects a real*8 x(1) (i.e. an array)
The opposite from case 1: The caller passes a real*8 x(1) to a subroutine, while the subroutine declares x as real*8 x
Now, is that acceptable? As far as I can see there is no problem with that, I'm I right? Or could there arise any problems?
Failure would occur if the target abi isn't compatible with this standard violation. For the case where the callee array could be declared intent(in), it can be fixed by promoting the caller argument with constructor e.g. [x]
Related
With Intel's ifort versions 2021.6.0+/ ifx 2022.1.0+ I am receiving error messages during compilation, specifically error #8284 about argument mismatch with an interface, which I suspect is erroneous.
Before I proceed to escalate this with the Intel team, I was wondering;
is the following code Standard conforming? I was under the impression that it was indeed legal and that the compiler is incorrect in this case.
MWE
program main
use iso_c_binding
call foo("Fortran Arg")
contains
function istring_(o) result(v)
character(len=*), intent(in) :: o
character(len=:, kind=c_char), allocatable :: v
v = trim(o)//c_null_char
end function istring_
subroutine foo(fileName)
interface
subroutine C_API(fileName) bind(C, name="foo")
use, intrinsic :: iso_c_binding
character(len=1, kind=c_char), dimension(*), intent(in) :: fileName
end subroutine C_API
end interface
character(len=*), intent(in) :: fileName
call C_API(fileName=istring_(fileName))
end subroutine foo
end program main
#include "stdio.h"
void foo(const char* fileName) { printf("%s\n", fileName); }
Output
/app/example.f90(21): error #8284: If the actual argument is scalar, the dummy argument shall be scalar unless the actual argument is of type character or is an element of an array that is not assumed shape, pointer, or polymorphic. [FILENAME]
call C_API(fileName=istring_(fileName))
---------^
Fix
Replacing the istring_ call in the interface with a local variable compiles which seems to indicate to me that this is a potential bug/regression.
--- tmp.f90 2023-01-05 10:19:30.778230819 +0000
+++ tmp2.f90 2023-01-05 10:19:36.342418329 +0000
## -18,6 +18,8 ##
end subroutine C_API
end interface
character(len=*), intent(in) :: fileName
- call C_API(fileName=istring_(fileName))
+ character(len=:), allocatable :: fileNameC
+ fileNameC = istring_(fileName)
+ call C_API(fileName=fileNameC)
end subroutine foo
end program main
Additional Info
GFortran, Intel's older versions compilers and flang-trunk all can compile the MWE.
Your program may be non-conforming, in which case the compiler is allowed to respond with any gibberish it chooses.
This doesn't mean that there is no issue to report to the vendor.
Consider the problematic line:
v = trim(o)//c_null_char
This violates the Fortran standard in the case that default character (corresponding to o and trim(o)) has different kind type parameter from that of c_null_char (the C character kind if that exists). While unlikely, this is possible. (Even more extreme is the case that c_char has the value -1 in which case the program is even more non-conforming.)
However, even in this case we have to concern ourselves with quality of implementation issues.
Let's pretend the compiler has default and C characters of different kind. If our compiler rejects the source code with the message
v = trim(o)//c_null_char
^
|-------------------------------|
Error: too many chickens crossing the road at |
we'd quite legitimately be a touch annoyed with the compiler vendor. We'd consider this a bug (or a too trendy company we want to avoid).
The Intel compiler isn't rejecting your program because of this reason (and it's likely the case that C and default characters are the same).
Let's apply the same QoI assessment to the actual error message.
If the actual argument is scalar, the dummy argument shall be scalar unless the actual argument is of type character or is an element of an array that is not assumed shape, pointer, or polymorphic. [FILENAME]
A compiler of high quality would have the error message meaningful when produced. Here, the actual argument is a scalar and the dummy argument is an array, so the error message is not wildly out a place.
(The standard's requirement is actually slightly more restrictive than the error message notes, but this can be accepted.)
The actual argument is of type (C) character making the error message unhelpful.
Additional to the temporary variable as a workaround, there are several others available:
call C_API(fileName=(istring_(fileName)))
call C_API(fileName=istring_(fileName)//c_char_'')
These add weight to the belief that the code is conforming, but the point of my answer here is that conformance doesn't actually matter in terms of whether the error message is valuable. Even if something is wrong with the subroutine reference, or program as a whole, a high quality compiler would not report in this way.
For completeness, let's look at that actual argument in more detail (and convince ourself that the subroutine reference is legitimate).
The subroutine reference
call C_API(fileName=istring_(fileName))
is to the subroutine C_API, with the actual argument istring_(fileName) using the keyword fileName.
We're allowed to use that keyword, and filename is the name of the dummy argument.
istring_(filename) is a (non-variable) primary expression, because istring_ is the name of the accessible internal function of the same host.1 This primary is evaluated before the subroutine reference and we note that the function result is a scalar C character. Exactly as we and the error message are expecting.
1 Note that you don't have implicit none in the program. You want to use this (or implicit none (external)) to ensure that an external integer function isn't used by a typographical mistake. In which case the compiler error would be entirely correct.
Intrinsic polymorphic assignment is a recent feature of some Fortran compilers (e.g. ifort 18, nagfor 6.2) that is not available in older versions (e.g. ifort 17, gfortran 6.3). A well-known solution that works with these older versions is to use a defined assignment as in the example below (taken and adapted from the book of Chivers and Sleightholme):
module deftypes
type, abstract :: shape_t
integer :: x = 0, y = 0
end type shape_t
type, extends(shape_t) :: circle_t
integer :: radius = 0
end type circle_t
interface assignment(=)
module procedure generic_shape_assign
end interface
contains
subroutine generic_shape_assign ( lhs, rhs )
class(shape_t), intent(in ) :: rhs
class(shape_t), allocatable, intent(out) :: lhs
print*,' --> in generic_shape_assign'
allocate(lhs, source = rhs)
end subroutine generic_shape_assign
end module deftypes
program check_assign
use deftypes
implicit none
class(shape_t), allocatable :: myshape
type (circle_t) :: mycirc1, mycirc2
mycirc1 = circle_t ( 1, 2, 3 )
print*,'A polymorphic assignment: myshape = mycirc1'
myshape = mycirc1
print*,'An intrinsic assignment: mycirc2 = mycirc1'
mycirc2 = mycirc1
end program check_assign
This example, compiles and works well with ifort 15.0.3 and gfortran 6.3.0. But with nagfor 6.2 I get the following error during the compilation (for the line mycirc2=mycirc1):
Error: check_assign.f90, line 41: Incorrect data type CIRCLE_T (expected SHAPE_T) for argument LHS (no. 1) of GENERIC_SHAPE_ASSIGN
It's not clear to me why this compiler is trying to use the defined assignment in the instruction mycirc2 = mycirc1 while these two variables are not allocatable polymorphic ones.
Of course, if I delete the defined assignment it works with nagfor but not with the other old compilers. Any idea where this error came from and how to get around it?
I believe that the compiler is correct to reject this program. However, if you have a support contract with NAG I strongly advise asking them over taking my comments as definitive.
I will show my reasoning.
It is clear that the reference to the specific procedure generic_shape_assign like
type(circle_t) mycirc1, mycirc2
call generic_shape_assign(mycirc2, mycirc1)
is not valid. It fails because the actual argument mycirc2, corresponding to the allocatable polymorphic dummy argument lhs:
is not allocatable;
is not of the same declared type as the corresponding dummy argument;
is not polymorphic.
The error message you quote covers rejection of the program for violating this second.
So, that means that generic_shape_assign is not a valid specific procedure (for this reference) with generic specification assignment(=), right? And thus no defined assignment is chosen and the compiler should fall back to intrinsic assignment?
This is where things get murky (at least to me).
I think that the specific subroutine generic_shape_assign is chosen for the defined assignment and the compiler is therefore correct to reject your program because you aren't calling this specific subroutine correctly.
Let's look further, using Fortran 2008 7.2.1.4 where there's definition of when an assignment statement is a defined assignment statement.
To decide whether the subroutine generic_shape_assign defines the defined assignment statement mycirc2=mycirc1 we look at the given points:
generic_shape_assign is a subroutine with two dummy arguments (lhs and rhs here);
the interface block gives generic_shape_assign the generic spec assignment(=);
lhs (of type shape_t) is type compatible with mycirc2 (of dynamic type circle_t); rhs similarly;
there are no type parameters for dummy or actual arguments;
the ranks (being scalar) of the dummy and actual arguments match.
We meet all of the requirements for this being a defined assignment: there is no requirement which states that defined assignment requires the chosen subroutine to be callable!
In summary:
It's not clear to me why this compiler is trying to use the defined assignment in the instruction mycirc2 = mycirc1 while these two variables are not allocatable polymorphic ones.
Because whether defined assignment is used is unrelated to whether the left- and right-hand sides are polymorphic or allocatable.
Finally, I think the diagnostic message from the compiler could be improved whether my reasoning is correct or incorrect.
This question is connected to the problem: how to detect violation of intent(in) inside subprograms. But I haven't found the answer in the related question Enforce intent(in) declared variables in Fortran as constant also in called subroutines/functions.
A variable which is declared as intent(in) can be modified by another subprogram/function with omitted intent declaration.
For example:
module test
implicit none
contains
subroutine fun1(x)
real(8), intent(in)::x
call fun2(x)
end subroutine
subroutine fun2(x)
real(8) :: x
x = 10
end subroutine
end module
This code can be compiled without any errors/warnings by gfortran and ifort. So my questions are:
Is it possible to forbid omitting intent declaration?
Is it possible to force a Fortran compiler to interpret omitted intent as intent(inout)?
Both answers are NO. Unspecified intent is fundamentally different from all other intents. It is different from intent(inout), because you can pass a nondefinable expression to a subroutine with unspecified intent.
Also in many contexts it is not allowed to specify intent at all (procedure arguments, pointers in Fortran 95,...)
If you want to require specifying of intent, you may define your subroutine as pure but it does much more than that. But it may be the right thing for you. It forbids any side-effects.
I think you should get a compile error due to the automatically defined interface. I would expect the same with a wrong dimension for example (I switched the fun2 dummy argument x to z that I think demonstrates more clearly my point).
module test
implicit none
contains
subroutine fun1(x)
real(8), intent(in)::x
call fun2(x)
end subroutine
subroutine fun2(z)
real(3) :: z
z = 10
end subroutine
end module
In a subroutine or function an input variable can be defined with intent(in) and the compiler assures that within the subroutine the variable can not be altered. As soon as the variable is passed (by reference) to another subroutine this subroutine is able to alter the variable without compiler warning.
This was tested with gfortran with the code:
program Test
integer i
i = 21 ! half the truth
call test(i)
write (*,*) "21 expected, but is 42: ", i
end program
subroutine test(i)
integer, intent(in) :: i
call doSomethingNasty(i)
end subroutine
subroutine doSomethingNasty(i)
integer :: i
i = 42 ! set the full truth ;-)
end subroutine
My questions are:
Is this the normal behaviour for all compilers?
Is there a way to force the compilers to assure that the variable is really constant and that alterations would be presented as compiler errors? I mean something like the const keyword in C/C++ which is also checked against the called functions which also need to assure that the constant is treated accordingly and that no reference is escaping.
I found the possibility to pass the variable to the subroutine by "value" via passing it trough an expression like test((i)). For numeric variables, this is understandable and ok, but this seems to work with gfortran for arrays, derived types and pointers, too. Does this work with other compilers, too? Is it a safe way to protect my local variables?
With sufficient compiler options gfortran generates a warning for your example, that an implicit interface is used.
If you make the interface explicit by placing the subroutines into a module, and use intents for all arguments, gfortran will catch the problem:
module mysubs
contains
subroutine test(i)
integer, intent(in) :: i
call doSomethingNasty(i)
end subroutine
subroutine doSomethingNasty(i)
integer, intent (inout) :: i
i = 42 ! set the full truth ;-)
end subroutine
end module mysubs
program Test_intent_in
use mysubs
integer i
i = 21 ! half the truth
call test(i)
write (*,*) "21 expected, but is 42: ", i
end program Test_intent_in
gfortran gives error message:
call doSomethingNasty(i)
1
Error: Procedure argument at (1) is INTENT(IN) while interface specifies INTENT(INOUT)
When pass the argument "(i)" you are passing an expression rather than a variable. The expression is not definable and thus should not be used as an actual argument for an "out" or "inout" dummy argument.
Another approach for argument "safety": you can also use the "value" attribute in the declaration of a dummy argument to essentially make a local copy of the argument and guarantee that the actual argument won't be altered.
Edit:
As kemiisto pointed out, "contains" also makes the interface known. I don't like "contains" because the variable scoping ... all variables of the parent program are visible. Try this test code out:
PROGRAM contains_tst
INTEGER :: i, m
i = 21
m = 22
CALL test(m)
CONTAINS
SUBROUTINE test(j)
INTEGER, INTENT(IN) :: j
write (*, *) i, j
END SUBROUTINE test
END PROGRAM contains_tst
As soon as the variable is passed (by reference)
A warning note: Fortran standard does not specify how variables are passed (by reference, by value or in any other way). This is implementation dependent. Fortran is quite different from C/C++. Better stop to think in C-way. It will be misleading.
1) Yes and no. It is implementation dependent. First of all INTENT attribute specifies your intentions. As you can see in Fortran standard, Section 5.3.10, NOTE 5.17 (you can get the Final Draft of so-called Fortran 2008 by link at the beginning of this page http://fortranwiki.org/fortran/show/Fortran+2008):
Argument intent specifications serve several purposes in addition to
documenting the intended use of dummy arguments. A processor can check
whether an INTENT (IN) dummy argument is used in a way that could
redefine it. [...]
compiler ("processor") can (not should) check such things.
Secondly (as I already mentioned) you can not be sure that for argument with INTENT(IN) compiler will choose to pass it by value and not by reference. In this case the choice was by reference. At least it seems that i in test subroutine was passed by reference. The next subroutine. The default INTENT is INOUT. That is why it is possible to change the value of argument i (with unspecified that's why default INTENT) in doSomethingNasty. Once again i was passed by reference. Or maybe it even was "copy-in/copy-out". Such freedom exists to allow compiler perform optimizations.
2) No. If I understand you correctly you need something similar to constant references (to achieve what is called "const correctness"). But we do not even have references in Fortran, so obviously there are no constant references.
3) There is a way to protect local variables. As M. S. B. pointed out in his answer place your subroutines in MODULEs (or in CONTAINS section of main program) and always specify INTENT attributes for variables. I've tried to compile the code below with different Fortran compilers available to me
PROGRAM main
INTEGER :: i
i = 21
CALL test(i)
WRITE (*,*) "21 expected, but is 42: ", i
CONTAINS
SUBROUTINE test(i)
INTEGER, INTENT(IN) :: i
CALL do_something_nasty(i)
END SUBROUTINE test
SUBROUTINE do_something_nasty(i)
INTEGER, INTENT(INOUT) :: i
i = 42
END SUBROUTINE do_something_nasty
END PROGRAM main
and all compilers (GNU, Intel, Open64, Portland and g95) issued an error message. I think that other compilers (Pathscale, IBM) will behave the same way.
Good practice dictates that subroutine arguments in Fortran should each have a specified intent (i.e. intent(in), intent(out) or intent(inout) as described this question):
subroutine bar (a, b)
real, intent(in) :: a
real, intent(inout) :: b
b = b + a
...
However, not specifying an intent is valid Fortran:
subroutine bar (a, b)
real, intent(in) :: a
real :: b
b = b + a
...
Are there any real differences beyond compile time checking for an argument specified as intent(inout) and an argument without a specified intent? Is there anything I should worry about if I'm retrofitting intents to older, intent free, code?
According to The Fortran 2003 Handbook by Adams, et al., there is one difference between an intent(inout) argument and argument without specified intent. The actual argument (i.e., in the caller) in the intent(inout) case must always be definable. If the intent is not specified, the argument must be definable if execution of the subroutine attempts to define the dummy argument. definable means setting the value: dummy_arg = 2.0. Clearly the actual argument should be a variable if this is done. For intent(inout) the actual argument must be definable whether or not the subroutine does this. Without no intent specified, it depends on what happens on that particular invocation of the subroutine -- if the subroutine doesn't define the variable, it is OK; if it does, than there is a problem -- cases such as writing to an actual argument that is a constant will obviously cause problems.
This doesn't mean that the compiler will diagnose all of these cases -- what the standard requires a compiler to diagnose is a different issue. It would be close to impossible to detect all errors of the intent-not-specified case requirement at compile time, since violations depend on the run-time flow of the code. It is much easier for the compiler to diagnose the intent(inout) case and warn you of problems with the code.
Your question prompts me to wonder (lots to do right now) whether you might encounter a difference in behaviour if your code passes a PARAMETER as an actual argument which your sub-program then attempts to write to. Without an INTENT declaration the compiler might let this go, leading to odd behaviour. With the declaration I'd expect a compile-time error.
You and I might think that there is no difference between INOUT and no INTENT declaration, but don't forget that there are a lot of old Fortran programs out there and that compatibility with older language versions is an important feature of new standards. If it was correct (but dodgy) FORTRAN77 then a lot of people expect their code to remain correct (still dodgy) with a Fortran 90+ compiler.
A quick read of the 2003 standard does indicate that there is a difference between INOUT and no INTENT, but more close reading is required. If you do test this let us know your conclusions; if I have time later I will test it myself and let you know.
To understand the role of intent in/out, you need to know that internally, Fortran effectively passes variables by reference. This isn't always the same as actually passing by reference.
If you pass an internal subsection of an 2-D array to a subroutine, ie: data(i1:i2, j1:j2), then Fortran copies that data into a contiguous section of memory, and passes the new address to the routine. Upon returning, the data is copied back into its original location.
By specifying INTENT, the compiler can know to skip one of the copying operations.
It not only acts as a failsafe for modifying data that you want to remain unchanged, but also can speed up your code when dealing with large datasets.
To somehow expand M.S.B.'s answer, omitting intent gives you more flexibility, at the cost of less compile-time checking. Without intent, you can pass a literal constant if you know the code branch will not attempt to modify it, with intent(inout) the compiler will probably bark at you if you try it. This may be useful with "dual" procedures that will modify or not some argument depending on the options, for example:
subroutine copy(x,a,readwrite)
integer :: x, a
integer, intent(in) :: readwrite
if (readwrite == 0) then
x = a
else
a = x
end if
end subroutine
If you want to add intent to x and a, it must be inout for both, because both are potentially read and modified. But that will not allow you to write e.g.
call copy(x,3,0) ! equiv. to x=3
call copy(42,a,1) ! equiv. to a=42
This example is quite silly, but think of a more elaborate subroutine that can read from or write to a file with some complex formatting. (I'm not saying that's the best solution, but it's something you can easily find.)