[cfe-dev] Calling main() is ub based optimizations

Mehdi Amini via cfe-dev cfe-dev at lists.llvm.org
Mon Nov 14 08:30:35 PST 2016


> On Nov 14, 2016, at 8:29 AM, Mehdi Amini <mehdi.amini at apple.com> wrote:
> 
> 
>> On Nov 14, 2016, at 3:11 AM, David Chisnall via cfe-dev <cfe-dev at lists.llvm.org> wrote:
>> 
>> On 14 Nov 2016, at 10:58, Ben Taylor <brtaylor92 at gmail.com> wrote:
>>> 
>>> The relevant piece of standardese seems to be 3.6.1.3 in the C++17 working draft (n4606) standard, which reads in part:
>>> 
>>> "The function main shall not be used within a program. The linkage (3.5) of main is implementation-defined. A program that defines main as deleted or that declares main to be inline, static, or constexpr is ill-formed. The main function shall not be declared with a linkage-specification (7.5). A program that declares a variable main at global scope or that declares the name main with C language linkage (in any namespace) is ill-formed."
>>> 
>>> So the cases you suggest, by my reading, should not be UB but rather a compile error.
>> 
>> It sounds as if calling main from C++ should be a compile error.  It’s not clear what’s expected to happen if a C compilation unit calls a C++ main.
> 
> Isn’t the very beginning "The function main shall not be used within a program” enough?

It should also cover the “taking the address” part as well.

— 
Mehdi



> 
> 
> 
>> The C compiler doesn’t know to warn about this, because it doesn’t know that main is implemented in C++.  The C++ compiler can’t emit main with a linkage type that prevents it, because otherwise _start (or equivalent) can’t call main, yet apparently is free to optimise on the assumption that this will never be the case.  It sounds like either WG14, WG21, or both need a defect report about interoperability here.
>> 
>> If we’re doing LTO, then we could warn on attempting to merge a non-norecurse declaration of main with a norecurse definition.  If we’re not, then I don’t know if we have enough information by the link stage to know if a relocation against main is safe or not (particularly as the C++ standard doesn’t appear to prevent taking the address of main or comparing against the result.
>> 
>> David
>> 
>> _______________________________________________
>> cfe-dev mailing list
>> cfe-dev at lists.llvm.org
>> http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-dev
> 




More information about the cfe-dev mailing list