31
Draft Technical Specification October 14, 2015 ISO/IEC JTC 1/SC 22/WG 14 N1974 TECHNICAL ISO/IEC TS SPECIFICATION 18661-5 First edition 201y-mm-dd Information technology — Programming languages, their environments, and system software interfaces — Floating-point extensions for C — Part 5: Supplementary attributes Technologies de l’information — Langages de programmation, leurs environnements et interfaces du logiciel système — Extensions à virgule flottante pour C — Partie 5: Attributs supplémentaires Reference number ISO/IEC TS 18661-5:201y(E)

TECHNICAL ISO/IEC TS SPECIFICATION 18661-5 · TECHNICAL ISO/IEC TS SPECIFICATION 18661-5 ... Technologies de l’information — Langages de programmation, leurs environnements et

  • Upload
    ledan

  • View
    227

  • Download
    2

Embed Size (px)

Citation preview

DraftTechnicalSpecification–October14,2015 ISO/IECJTC1/SC22/WG14N1974

TECHNICAL ISO/IECTSSPECIFICATION 18661-5

Firstedition201y-mm-dd

Informationtechnology—Programminglanguages,theirenvironments,andsystemsoftwareinterfaces—Floating-pointextensionsforC—

Part5:Supplementaryattributes

Technologies de l’information — Langages de programmation, leurs environnements et interfaces dulogicielsystème—ExtensionsàvirguleflottantepourC—

Partie5:Attributssupplémentaires

ReferencenumberISO/IECTS18661-5:201y(E)

ISO/IECTS18661-5 DraftTechnicalSpecification–October14,2015 WG14N1974

ii ©ISO/IEC2015–Allrightsreserved

©ISO/IEC2015 Allrightsreserved.Unlessotherwisespecified,nopartofthispublicationmaybereproducedorutilizedotherwiseinanyformorbyanymeans,electronicormechanical,includingphotocopying,orpostingontheinternetoranintranet,withoutpriorwrittenpermission.PermissioncanberequestedfromeitherISOattheaddressbeloworISO’smemberbodyinthecountryoftherequester.

ISOcopyrightofficeCasepostale56•CH-1211Geneva20Tel.+41227490111Fax+41227490947E-mailcopyright@iso.orgWebwww.iso.org

PublishedinSwitzerland

COPYRIGHTPROTECTEDDOCUMENT

WG14N1974 DraftTechnicalSpecification–October14,2015 ISO/IECTS18661-5

©ISO/IEC2015–Allrightsreserved iii

Foreword.......................................................................................................................................................................ivIntroduction..................................................................................................................................................................v1 Scope.........................................................................................................................................................................12 Conformance..........................................................................................................................................................13 Normativereferences.........................................................................................................................................14 Termsanddefinitions........................................................................................................................................25 Cstandardconformance....................................................................................................................................25.1 Freestandingimplementations....................................................................................................................25.2 Predefinedmacros...........................................................................................................................................26 Standardpragmas................................................................................................................................................27 Evaluationformats..............................................................................................................................................38 Optimizationcontrols.........................................................................................................................................69 Reproducibility...................................................................................................................................................1110 Alternateexceptionhandling......................................................................................................................14Bibliography................................................................................................................................................................23

ISO/IECTS18661-5 DraftTechnicalSpecification–October14,2015 WG14N1974

iv ©ISO/IEC2015–Allrightsreserved

ForewordISO (the International Organization for Standardization) and IEC (the International ElectrotechnicalCommission) form the specialized system for worldwide standardization. National bodies that aremembers of ISO or IEC participate in the development of International Standards through technicalcommitteesestablishedbytherespectiveorganizationtodealwithparticularfieldsoftechnicalactivity.ISO and IEC technical committees collaborate in fields of mutual interest. Other internationalorganizations, governmental andnon-governmental, in liaisonwith ISOand IEC, also takepart in thework.Inthefieldofinformationtechnology,ISOandIEChaveestablishedajointtechnicalcommittee,ISO/IECJTC1.

The procedures used to develop this document and those intended for its further maintenance aredescribedintheISO/IECDirectives,Part1.Inparticularthedifferentapprovalcriterianeededforthedifferent types of document should be noted. This document was drafted in accordance with theeditorialrulesoftheISO/IECDirectives,Part2(seewww.iso.org/directives).

Attentionisdrawntothepossibilitythatsomeoftheelementsofthisdocumentmaybethesubjectofpatent rights. ISO and IEC shall not be held responsible for identifying any or all such patent rights.Details of any patent rights identified during the development of the document will be in theIntroductionand/orontheISOlistofpatentdeclarationsreceived(seewww.iso.org/patents).

Anytradenameusedinthisdocumentisinformationgivenfortheconvenienceofusersanddoesnotconstituteanendorsement.

For an explanation on the meaning of ISO specific terms and expressions related to conformityassessment, as well as information about ISO's adherence to the WTO principles in the TechnicalBarrierstoTrade(TBT)seethefollowingURL:Foreword-Supplementaryinformation

Thecommitteeresponsible for thisdocument is ISO/IEC JTC1, Informationtechnology,SubcommitteeSC22,Programminglanguages,theirenvironments,andsystemsoftwareinterfaces.

ISO/IEC TS 18661 consists of the following parts, under the general title Information technology—Programminglanguages,theirenvironments,andsystemsoftwareinterfaces—Floating-pointextensionsforC:

⎯ Part1:Binaryfloating-pointarithmetic

⎯ Part2:Decimalfloating-pointarithmetic

⎯ Part3:Interchangeandextendedtypes

⎯ Part4:Supplementaryfunctions

⎯ Part5:Supplementaryattributes

ISO/IECTS18661-1updatesISO/IEC9899:2011,Informationtechnology—ProgrammingLanguageC,annex F in particular, to support all required features of ISO/IEC/IEEE 60559:2011, Informationtechnology—MicroprocessorSystems—Floating-pointarithmetic.ISO/IEC TS 18661-2 supersedes ISO/IEC TR 24732:2009, Information technology — Programminglanguages,theirenvironmentsandsystemsoftwareinterfaces—ExtensionfortheprogramminglanguageCtosupportdecimalfloating-pointarithmetic.ISO/IEC TS 18661-3, ISO/IEC TS 18661-4, and ISO/IEC TS 18661-5 specify extensions to ISO/IEC9899:2011forfeaturesrecommendedinISO/IEC/IEEE60559:2011.

WG14N1974 DraftTechnicalSpecification–October14,2015 ISO/IECTS18661-5

©ISO/IEC2015–Allrightsreserved v

IntroductionBackground

IEC60559floating-pointstandard

The IEEE 754-1985 standard for binary floating-point arithmetic was motivated by an expandingdiversity in floating-point data representation and arithmetic, whichmadewriting robust programs,5debugging, and moving programs between systems exceedingly difficult. Now the great majority ofsystems provide data formats and arithmetic operations according to this standard. The IEC60559:1989 international standard was equivalent to the IEEE 754-1985 standard. Its stated goalswerethefollowing:

1 Facilitatemovementofexistingprograms fromdiversecomputers to those thatadhere to10thisstandard.

2 Enhance the capabilities and safety available to programmerswho, though not expert innumerical methods, may well be attempting to produce numerically sophisticatedprograms.However,werecognizethatutilityandsafetyaresometimesantagonists.

3 Encourageexpertstodevelopanddistributerobustandefficientnumericalprogramsthat15areportable,bywayofminoreditingandrecompilation,ontoanycomputerthatconformsto thisstandardandpossessesadequatecapacity.Whenrestrictedtoadeclaredsubsetofthestandard,theseprogramsshouldproduceidenticalresultsonallconformingsystems.

4 Providedirectsupportfor

a. Execution-timediagnosisofanomalies20

b. Smootherhandlingofexceptions

c. Intervalarithmeticatareasonablecost

5 Providefordevelopmentof

a. Standardelementaryfunctionssuchasexpandcos

b. Veryhighprecision(multiword)arithmetic25

c. Couplingofnumericalandsymbolicalgebraiccomputation

6 Enableratherthanprecludefurtherrefinementsandextensions.

Totheseends,thestandardspecifiedafloating-pointmodelcomprisingthefollowing:

— formats – for binary floating-point data, including representations for Not-a-Number (NaN) andsignedinfinitiesandzeros30

— operations – basic arithmetic operations (addition, multiplication, etc.) on the format data tocompose a well-defined, closed arithmetic system; also specified conversions between floating-pointformatsanddecimalcharactersequences,andafewauxiliaryoperations

— context – status flags for detecting exceptional conditions (invalid operation, division by zero,overflow,underflow,andinexact)andcontrolsforchoosingdifferentroundingmethods35

ISO/IECTS18661-5 DraftTechnicalSpecification–October14,2015 WG14N1974

vi ©ISO/IEC2015–Allrightsreserved

TheISO/IEC/IEEE60559:2011internationalstandardisequivalenttotheIEEE754-2008standardforfloating-pointarithmetic,whichisamajorrevisiontoIEEE754-1985.

The revised standard specifies more formats, including decimal as well as binary. It adds a 128-bitbinary format to itsbasic formats. It defines extended formats for all of itsbasic formats. It specifiesdatainterchangeformats(whichmayormaynotbearithmetic),includinga16-bitbinaryformatandan5unboundedtowerofwiderformats.Toconformtothefloating-pointstandard,animplementationmustprovideatleastoneofthebasicformats,alongwiththerequiredoperations.

Therevisedstandardspecifiesmoreoperations.Newrequirementsinclude–amongothers–arithmeticoperations that round their result to a narrower format than the operands (with just one rounding),more conversionswith integer types,more classifications and comparisons, andmoreoperations for10managingflagsandmodes.Newrecommendationsincludeanextensivesetofmathematical functionsandsevenreductionfunctionsforsumsandscaledproducts.

The revised standard places more emphasis on reproducible results, which is reflected in itsstandardizationofmoreoperations.Forthemostpart,behaviorsarecompletelyspecified.Thestandardrequiresconversionsbetween floating-point formatsanddecimalcharactersequences tobecorrectly15roundedforatleastthreemoredecimaldigitsthanisrequiredtodistinguishallnumbersinthewidestsupported binary format; it fully specifies conversions involving any number of decimal digits. Itrecommendsthattranscendentalfunctionsbecorrectlyrounded.

The revised standard requires away to specify a constant rounding direction for a static portion ofcode, with details left to programming language standards. This feature potentially allows rounding20controlwithoutincurringtheoverheadofruntimeaccesstoaglobal(orthread)roundingmode.

Otherfeaturesrecommendedbytherevisedstandardincludealternatemethodsforexceptionhandling,controls for expression evaluation (allowing or disallowing various optimizations), support for fullyreproducibleresults,andsupportforprogramdebugging.

Therevisedstandard,likeitspredecessor,definesitsmodeloffloating-pointarithmeticintheabstract.25It neither defines the way in which operations are expressed (which might vary depending on thecomputer language or other interface being used), nor does it define the concrete representation(specific layout in storage, or in aprocessor's register, for example)ofdataor context, except that itdoes define specific encodings that are to be used for the exchange of floating-point data betweendifferentimplementationsthatconformtothespecification.30

IEC60559doesnotincludebindingsofitsfloating-pointmodelforparticularprogramminglanguages.However, the revised standard does include guidance for programming language standards, inrecognition of the fact that features of the floating-point standard, even if well supported in thehardware,arenotavailabletousersunlesstheprogramminglanguageprovidesacommensuratelevelofsupport.Theimplementation’scombinationofbothhardwareandsoftwaredeterminesconformance35tothefloating-pointstandard.

CsupportforIEC60559

The C standard specifies floating-point arithmetic using an abstract model. The representation of afloating-point number is specified in an abstract form where the constituent components (sign,exponent,significand)of therepresentationaredefinedbutnot the internalsof thesecomponents. In40particular, the exponent range, significand size, and the base (or radix) are implementation-defined.Thisallowsflexibilityforanimplementationtotakeadvantageofitsunderlyinghardwarearchitecture.Furthermore,certainbehaviorsofoperationsarealsoimplementation-defined,forexampleintheareaofhandlingofspecialnumbersandinexceptions.

WG14N1974 DraftTechnicalSpecification–October14,2015 ISO/IECTS18661-5

©ISO/IEC2015–Allrightsreserved vii

Thereasonforthisapproachishistorical.AtthetimewhenCwasfirststandardized,beforethefloating-point standard was established, there were various hardware implementations of floating-pointarithmeticincommonuse.Specifyingtheexactdetailsofarepresentationwouldhavemademostoftheexistingimplementationsatthetimenotconforming.

Beginningwith ISO/IEC9899:1999(C99),Chas includedanoptionalsecond levelof specification for5implementations supporting the floating-point standard. C99, in conditionally normative annex F,introduced nearly complete support for the IEC 60559:1989 standard for binary floating-pointarithmetic. Also, C99’s informative annex G offered a specification of complex arithmetic that iscompatiblewithIEC60559:1989.

ISO/IEC9899:2011(C11)includesrefinementstotheC99floating-pointspecification,thoughitisstill10basedonIEC60559:1989.C11upgradedannexGfrom“informative”to“conditionallynormative”.

ISO/IEC TR 24732:2009 introduced partial C support for the decimal floating-point arithmetic inISO/IEC/IEEE60559:2011. ISO/IECTR24732, forwhichtechnicalcontentwascompletedwhile IEEE754-2008wasstill in the laterstagesofdevelopment,specifiesdecimal typesbasedonISO/IEC/IEEE60559:2011decimalformats,thoughitdoesnotincludealloftheoperationsrequiredbyISO/IEC/IEEE1560559:2011.

Purpose

The purpose of ISO/IECTS 18661 is to provide a C language binding for ISO/IEC/IEEE 60559:2011,basedon theC11 standard, thatdelivers thegoalsof ISO/IEC/IEEE60559 tousers and is feasible toimplement.Itisorganizedintofiveparts.20

ISO/IEC TS 18661-1 provides changes to C11 that cover all the requirements, plus some basicrecommendations, of ISO/IEC/IEEE 60559:2011 for binary floating-point arithmetic. Cimplementations intending to support ISO/IEC/IEEE 60559:2011 are expected to conform toconditionallynormativeannexFasenhancedbythechangesinISO/IECTS18661-1.

ISO/IEC TS 18661-2 enhances ISO/IEC TR 24732 to cover all the requirements, plus some basic25recommendations, of ISO/IEC/IEEE 60559:2011 for decimal floating-point arithmetic. Cimplementations intending to provide an extension for decimal floating-point arithmetic supportingISO/IEC/IEEE60559:2011areexpectedtoconformtoISO/IECTS18661-2.

ISO/IECTS18661-3(Interchangeandextendedtypes),ISO/IECTS18661-4(Supplementaryfunctions),and ISO/IEC TS 18661-5 (Supplementary attributes) cover recommended features of ISO/IEC/IEEE3060559:2011. C implementations intending to provide extensions for these features are expected toconformtothecorrespondingparts.

Additionalbackgroundonsupplementaryattributes

ISO/IEC/IEEE 60559:2011 defines alternatives for certain attributes of floating-point semantics andintends that programming languages provide means by which a program can specify which of the35alternative semantics apply to a givenblock of code. Theprogram specification of attributes is to beconstant(fixedattranslationtime),notdynamic(changeableatexecutiontime).

ISO/IEC TS 18661 provides these attributes by means of standard pragmas, where the pragmaparametersrepresentthealternativesemantics.

TheFENV_ROUND andFENV_DEC_ROUNDpragmas, specified in ISO/IECTS18661-1and ISO/IECTS4018661-2, respectively, provide the rounding direction attributes required by ISO/IEC/IEEE60559:2011.

ISO/IECTS18661-5 DraftTechnicalSpecification–October14,2015 WG14N1974

viii ©ISO/IEC2015–Allrightsreserved

ISO/IEC/IEEE60559:2011recommendsattributesfor

— preferredWidth: evaluation formats for floating-point operations

— value-changing optimizations: allow/disallow program transformations that might affect floating-point result values 5

— alternate exception handling: methods of handling floating-point exceptions

— reproducibility: support for getting floating-point result values and exceptions that are exactly reproducible on other systems 10

ThispartofISO/IECTS18661specifiespragmasthatprovidetheseattributes.

Note that the pragmas introduced by ISO/IEC TS 18661 are similar to the floating-point pragmas(FENV_ACCESS, FP_CONTRACT, CX_LIMITED_RANGE) that are already in ISO/IEC 9899. They allhavethesamegeneralsyntacticform,usagerequirements,andrangeofeffect.

DRAFTTECHNICALSPECIFICATION ISO/IEC/TS18661-5:201y(E)

©ISO/IEC2015–Allrightsreserved 1

Informationtechnology—Programminglanguages,theirenvironments,andsystemsoftwareinterfaces—Floating-pointextensionsforC—5Part5:Supplementaryattributes

1 Scope

This part of ISO/IEC TS 18661 extends programming language C to include support for attributesspecifiedandrecommendedinISO/IEC/IEEE60559:2011.10

2 Conformance

AnimplementationconformstothispartofISO/IECTS18661if

a) itmeetstherequirementsforaconformingimplementationofC11withallthechangestoC11asspecifiedinparts1-5ofISO/IECTS18661;15

b) itconformstoISO/IECTS18661-1orISO/IECTS18661-2(orboth);and

c) itdefines__STDC_IEC_60559_ATTRIBS__to201ymmL.Animplementationconformstotheoptionalspecificationforalternateexceptionhandlinginthispart20ofISO/IECTS18661if,inadditiontotheabove,

d) itdefines__STDC_IEC_60559_ATTRIB_ALTERNATE_EXCEPTION_HANDLING__to201ymmL.

3 Normativereferences

The following documents, inwhole or in part, are normatively referenced in this document and areindispensable for its application. For dated references, only the edition cited applies. For undated25references,thelatesteditionofthereferenceddocument(includinganyamendments)applies.

ISO/IEC9899:2011,Informationtechnology—Programminglanguages—C

ISO/IEC/IEEE 60559:2011, Information technology— Microprocessor Systems— Floating-pointarithmetic

ISO/IECTS18661-1:2014, Information technology—Programming languages, their environmentsand30systemsoftwareinterfaces—Floating-pointextensionsforC—Part1:Binaryfloating-pointarithmetic

ISO/IECTS18661-2:2015, Information technology—Programming languages, their environmentsandsystemsoftwareinterfaces—Floating-pointextensionsforC—Part2:Decimalfloating-pointarithmetic

ISO/IECTS18661-5 DraftTechnicalSpecification–October14,2015 WG14N1974

2 ©ISO/IEC2015–Allrightsreserved

ISO/IECTS18661-3:2015, Information technology—Programming languages, their environmentsandsystemsoftwareinterfaces—Floating-pointextensionsforC—Part3:Interchangeandextendedtypes

ISO/IECTS18661-4:2015,InformationTechnology—Programminglanguages,theirenvironments,andsystemsoftwareinterfaces—Floating-pointextensionsforC—Part4:Supplementaryfunctions

4 Termsanddefinitions5

For the purposes of this document, the terms and definitions given in ISO/IEC 9899:2011,ISO/IEC/IEEE 60559:2011, ISO/IEC TS 18661-1:2014, ISO/IEC TS 18661-2:2015, ISO/IECTS18661-3:2015,ISO/IECTS18661-4:2015,andthefollowingapply.

4.1

C1110standardISO/IEC9899:2011,Informationtechnology—ProgramminglanguagesC,includingTechnicalCorrigendum1(ISO/IEC9899:2011/Cor.1:2012)

5 Cstandardconformance

5.1 Freestandingimplementations

ThespecificationinC11+TS18661-1+TS18661-2allowsfreestandingimplementationstoconformto15thispartofISO/IECTS18661.

5.2 Predefinedmacros

ChangetoC11+TS18661-1+TS18661-2+TS18661-3+TS18661-4:

In6.10.8.3#1,add:

__STDC_IEC_60559_ATTRIBS__ The integer constant 201ymmL, intended to indicate20supportofattributesspecifiedandrecommendedinIEC60559.

__STDC_IEC_60559_ATTRIB_ALTERNATE_EXCEPTION_HANDLING__ The integerconstant201ymmL,intendedtoindicatesupportofthealternateexceptionhandlingattributesspecifiedandrecommendedinIEC60559.

6 Standardpragmas25

C11 provides standard pragmas (6.10.6) for specifying certain attributes pertaining to floating-pointbehaviorwithinacompoundstatementorfile.ThispartofISO/IECTS16881extendsthispracticebyintroducingadditionalstandardpragmastosupporttheattributesrecommendedbyIEC60559.

ChangetoC11+TS18661-1+TS18661-2+TS18661-3+TS18661-4:

In6.10.6#2,appendtothelistofstandardpragmas:30

#pragma STDC FENV_FLT_EVAL_METHOD width #pragma STDC FENV_DEC_EVAL_METHOD width #pragma STDC FENV_ALLOW_VALUE_CHANGING_OPTIMIZATION on-off-switch#pragma STDC FENV_ALLOW_ASSOCIATIVE_LAW on-off-switch#pragma STDC FENV_ALLOW_DISTRIBUTIVE_LAW on-off-switch35#pragma STDC FENV_ALLOW_MULTIPLY_BY_RECIPROCAL on-off-switch

WG14N1974 DraftTechnicalSpecification–October14,2015 ISO/IECTS18661-5

©ISO/IEC2015–Allrightsreserved 3

#pragma STDC FENV_ALLOW_ZERO_SUBNORMAL on-off-switch#pragma STDC FENV_ALLOW_CONTRACT_FMA on-off-switch#pragma STDC FENV_ALLOW_CONTRACT_OPERATION_CONVERSION on-off-switch#pragma STDC FENV_ALLOW_CONTRACT on-off-switch#pragma STDC FENV_REPRODUCIBLE on-off-switch 5#pragma STDC FENV_EXCEPTaction except-list

width:specifiedwiththepragmas(7.6.1c,7.6.1d)

action,except-list:specifiedwiththepragma(7.6.1g.1)

7 Evaluationformats

IEC 60559 recommends attributes for specifying a preferred width for operation results. These10preferredwidths correspond to the evaluation formats defined in C11, thoughC11does not providemeansfortheusertocontroltheevaluationformat.ThispartofISO/IECTS16881providespragmasin<fenv.h>tocontroltheevaluationformat,usingconstantswiththevaluesoftheFLT_EVAL_METHODandDEC_EVAL_METHODmacros(5.2.4.2.2a)torepresenttheevaluationformats.

TheevaluationmethodsinC99applytofloating-pointoperators,butnottomathfunctions.Hence,they15donotapplytotheIEC60559operationsthatareprovidedaslibraryfunctions.Thisclausespecifiesamacro theusercandefine tocause thegenericmacros in<tgmath.h> tobeevaluated like floating-operators.

ChangestoC11+TS18661-1+TS18661-2+TS18661-3+TS18661-4:

After5.2.4.2.2a#3,insert:20

[3a] The FLT_EVAL_METHOD and DEC_EVAL_METHOD macros characterize the use ofevaluation formats at the point in the programwhere themacro is used. Thus, the values ofthesemacros reflect the state of any evaluationmethod pragmas (7.6.1c, 7.6.1d) that are ineffect. Thesemacros shall not be used in a#if or#elif expression within the scope of acorrespondingevaluationmethodpragma.25

After7.6.1b,insert:

7.6.1c Evaluationmethodpragma

Synopsis

[1] #define __STDC_WANT_IEC_60559_ATTRIBS_EXT__ #include <fenv.h> 30#pragma STDC FENV_FLT_EVAL_METHOD width

Description

[2] TheFENV_FLT_EVAL_METHOD pragma sets the evaluationmethod for standard floatingtypes and for binary interchange and extended floating types to the evaluation methodrepresentedbywidth.Theparameterwidthisanexpressioninoneoftheforms35

0 decimal-constant−decimal-constant

ISO/IECTS18661-5 DraftTechnicalSpecification–October14,2015 WG14N1974

4 ©ISO/IEC2015–Allrightsreserved

or

DEFAULT

where the value of an expression is a possible value of the FLT_EVAL_METHOD macro, asspecified in 5.2.4.2.2a. An expression represents the evaluationmethod corresponding to itsvalue (5.2.4.2.2a) and DEFAULT designates the implementation’s default evaluation method5(characterized by the FLT_EVAL_METHOD macro where no FENV_FLT_EVAL_METHODpragmaisineffect).widthmaybe-1,0,orDEFAULT.Which,ifany,othervaluesofwidtharesupportedisimplementation-defined.Useofunsupportedvaluesofwidthresultsinundefinedbehavior.Thepragmashalloccureitheroutsideexternaldeclarationsorprecedingallexplicitdeclarationsandstatementsinsideacompoundstatement.Whenoutsideexternaldeclarations,10thepragmatakeseffect fromitsoccurrenceuntilanotherFENV_FLT_EVAL_METHODpragmaisencountered,oruntiltheendofthetranslationunit.Wheninsideacompoundstatement,thepragma takeseffect from itsoccurrencesuntil anotherFENV_FLT_EVAL_METHOD pragma isencountered(includingwithinanestedcompoundstatement),oruntiltheendofthecompoundstatement; at the end of a compound statement the state for the pragma is restored to its15conditionjustbeforethecompoundstatement.

7.6.1d Evaluationmethodpragmafordecimal

Synopsis

[1] #define __STDC_WANT_IEC_60559_DFP_EXT__ #define __STDC_WANT_IEC_60559_ATTRIBS_EXT__ 20#include <fenv.h> #pragma STDC FENV_DEC_EVAL_METHOD width

Description

[2]TheFENV_DEC_EVAL_METHODpragmasetstheevaluationmethodfordecimalinterchangeand extended floating types to the evaluation method represented bywidth. The parameter25widthisanexpressioninoneoftheforms

0 decimal-constant−decimal-constant

or30

DEFAULT

where the value of an expression is a possible value of the DEC_EVAL_METHOD macro, asspecified in 5.2.4.2.2a. An expression represents the evaluationmethod corresponding to itsvalue (5.2.4.2.2a) and DEFAULT designates the implementation’s default evaluation method(characterized by the DEC_EVAL_METHOD macro where no FENV_DEC_EVAL_METHOD35pragmaisineffect).widthmaybe-1,1,orDEFAULT.Which, ifany,othervaluesofwidtharesupportedisimplementation-defined.Useofunsupportedvaluesofwidthresultsinundefinedbehavior.Thepragmashalloccureitheroutsideexternaldeclarationsorprecedingallexplicitdeclarationsandstatementsinsideacompoundstatement.Whenoutsideexternaldeclarations,thepragmatakeseffect fromitsoccurrenceuntilanotherFENV_DEC_EVAL_METHODpragma40isencountered,oruntiltheendofthetranslationunit.Wheninsideacompoundstatement,thepragma takeseffect from itsoccurrencesuntil anotherFENV_DEC_EVAL_METHOD pragma is

WG14N1974 DraftTechnicalSpecification–October14,2015 ISO/IECTS18661-5

©ISO/IEC2015–Allrightsreserved 5

encountered(includingwithinanestedcompoundstatement),oruntiltheendofthecompoundstatement; at the end of a compound statement the state for the pragma is restored to itsconditionjustbeforethecompoundstatement.

Attheendof7.12#2,append:

[2] …. These typesreflect the evaluation method where no evaluation method pragma5(7.6.1c,7.6.1d)isineffect.

[2a] For each of the types above, a type-like macro with the same name expands to adesignation for the type whose range and precision (5.2.4.2.2a) are used for evaluatingoperationsandconstantsof thecorrespondingstandard,binary,ordecimal floating type.Themacro reflects the actual evaluation method, which might be determined by an evaluation10methodpragma(7.6.1c,7.6.1d).Useof#undeftoremovethemacrodefinitionwillensurethattheactualtypewillbereferredto.

After7.25#2,insert:

[2a]Exceptforfunctionsthatroundresulttoanarrowertype,ifthemacro

__STDC_TGMATH_OPERATOR_EVALUATION__ 15

isdefinedat thepoint in theprogramwhere<tgmath.h> is first included, the formatof thegeneric parameters of the function invoked by a type-generic macro is determined by theeffectiveevaluationmethod(see5.2.4.2.2and5.2.4.2.2a),basedonthetypesoftheargumentsforgenericparameters.Thesemantictypeoftheexpandedtype-genericmacroisunchangedbytheevaluationmethod.Neithertheargumentsforgenericparametersnortheresultarenarrowedtotheir20semantic types. Thus, (if the macro __STDC_TGMATH_OPERATOR_EVALUATION__ isappropriatelydefined) theevaluationmethodaffects theoperationsprovidedbytype-genericmacrosandfloating-pointoperatorsinthesameway.SeeEXAMPLE2below.

Afterthefirstbulletin7.25#3c,insertthebullet:

Ifthemacro25

__STDC_TGMATH_OPERATOR_EVALUATION__

isdefinedat thepoint in theprogramwhere<tgmath.h> is first included, the formatof thegenericparametersofthefunctioninvokedisgivenbytheeffectiveevaluationmethodbasedonthe type determined below. The semantic type of the expanded type-generic macro isunchangedbytheevaluationmethod.30

In7.25#7,change“EXAMPLE”to“EXAMPLE1”.

ISO/IECTS18661-5 DraftTechnicalSpecification–October14,2015 WG14N1974

6 ©ISO/IEC2015–Allrightsreserved

After7.25#7,append:

[7a]EXAMPLE2 Thefollowingcodeuseswideevaluationtoavoidoverflowandunderflow.

#define __STDC_WANT_IEC_60559_ATTRIBS_EXT__ #define __STDC_TGMATH_OPERATOR_EVALUATION__ #include <fenv.h> 5#include <tgmath.h> { #pragma STDC FLT_EVAL_METHOD 1 float x, y, z; ….10 z = sqrt(x * x + y * y); }

Becauseoftheuseoftheevaluationmethodpragma,thesumofsquares,whosesemantictypeisfloat, is evaluatedwith the range and precision ofdouble, hence does not overflow orunderflow.Theexpanded<tgmath.h>macrosqrtacquiresthesemantictypeof itsargument:15float.However,becausethemacro__STDC_TGMATH_OPERATOR_EVALUATION__isdefinedbeforetheinclusionof<tgmath.h>,thesqrtmacrobehaveslikeanoperatorwithrespecttothe evaluation method and does not narrow its argument to its semantic type. Without thedefinition of the macro __STDC_TGMATH_OPERATOR_EVALUATION__, the sqrt macrowould expand to sqrtf and its evaluated argument would be converted to float, which20mightoverfloworunderflow.

8 Optimizationcontrols

IEC60559recommendsattributestoallowanddisallowvalue-changingoptimizations,individuallyandcollectively.C11AnnexFdisallowsvalue-changingoptimizations,exceptforcontractions(whichcanbecontrolled as a group with the FP_CONTRACT pragma). This part of ISO/IEC TS 18661 provides25pragmas toallowordisallowcertainvalue-changingoptimizations, including thosementioned in IEC60559.Thesepragmasapplytoallfloatingtypes,notjusttherealfloatingtypes(whichprovidetheIEC60559formats).

ChangetoC11+TS18661-1+TS18661-2+TS18661-3+TS18661-4:

After7.6.1d,insert:30

7.6.1e Optimizationcontrolpragmas

[1] The pragmas in this subclause can be used to allow the implementation to do certainfloating-point optimizations that are generally disallowed because the optimization mightchange values of floating-point expressions. These pragmas apply to all floating types. It isunspecifiedwhetheroptimizationsallowedbythesepragmasoccurconsistently,oratall.These35pragmas (amongother standardpragmas) apply to user code. Theydonot apply to code foroperatorsorlibraryfunctionsthatmightbeplacedinlinebytheimplementation.

[2]Someofthepragmasallowoptimizationsbasedonidentitiesofrealnumberarithmeticthatarenotvalid for(IEC60559) floating-pointarithmetic(5.1.2.3,F.9.2).Optimizationsbasedonidentities that arevalid for floating-point arithmetic arealwaysallowed.Optimizationsbased40onidentitiesderivedfromidentitieswhoseuseisallowed(eitherbyastandardpragmaorbyvirtueofbeingvalidforfloating-pointarithmetic)mayalsobedone.

[3]Thesepragmasdonotaffecttherequirementsonvolatileoratomicvariables.

WG14N1974 DraftTechnicalSpecification–October14,2015 ISO/IECTS18661-5

©ISO/IEC2015–Allrightsreserved 7

[4] Each pragma shall occur either outside external declarations or preceding all explicitdeclarationsandstatementsinsideacompoundstatement.Whenoutsideexternaldeclarations,the pragma takes effect, on each optimization it controls, from its occurrence until anotherpragma that affects the sameoptimization is encountered, or until the end of the translationunit. When inside a compound statement, the pragma takes effect, on each optimization it5controls, from its occurrence until another pragma that affects the same optimization isencountered(includingwithinanestedcompoundstatement),oruntiltheendofthecompoundstatement; at the end of a compound statement the state for allowing each optimizationcontrolledbythepragmaisrestoredtoitsconditionjustbeforethecompoundstatement.

7.6.1e.1TheFENV_ALLOW_VALUE_CHANGING_OPTIMIZATIONpragma10

Synopsis

[1] #define __STDC_WANT_IEC_60559_ATTRIBS_EXT__ #include <fenv.h> #pragma STDC FENV_ALLOW_VALUE_CHANGING_OPTIMIZATION on-off-switch

Description15

[1]Thispragma is equivalent toall theoptimizationpragmas specifiedbelow,with the samevalueofon-off-switch(ON,OFF,orDEFAULT).

[2]NOTE TheFENV_ALLOW_VALUE_CHANGING_OPTIMIZATION pragmadoesnot affecttheevaluationmethods.Nevertheless,anevaluationmethodcharacterizedbyanegativevalueof width (5.2.4.2.2a) might allow for indeterminable evaluation formats, hence unspecified20resultvalues.

7.6.1e.2TheFENV_ALLOW_ASSOCIATIVE_LAWpragma

Synopsis

[1] #define __STDC_WANT_IEC_60559_ATTRIBS_EXT__ #include <fenv.h> 25#pragma STDC FENV_ALLOW_ASSOCIATIVE_LAW on-off-switch

Description

[2]Thispragmaallowsordisallowsoptimizationsbasedon the associative laws for additionandmultiplication

x+(y+z)=(x+y)+z30x×(y×z)=(x×y)×z

whereon-off-switchisoneof

ON–allowapplicationoftheassociativelaws

OFF–donotallowapplicationoftheassociativelaws

DEFAULT–“off”35

ISO/IECTS18661-5 DraftTechnicalSpecification–October14,2015 WG14N1974

8 ©ISO/IEC2015–Allrightsreserved

[3] Note that this pragma allows optimizations based on similar mathematical identitiesinvolvingsubtractionanddivision.Forexample,sincetheidentityx−y=x+(−y)isvalidforIEC60559floating-pointarithmetic(F.9.2),thispragmaalsoallowsoptimizationsbasedon

x+(y−z)=(x+y)−z

Similarly, if the states for this pragma and theFENV_ALLOW_MULTIPLY_BY_RECIPROCAL5pragma(7.6.1e.4)areboth“on”,thenoptimizationsbasedonthefollowingareallowed:

x×(y/z)=(x×y)/z

Notealsothat,sincethecommutativelaws

x+y=y+xx×y=y×x10

are valid for IEC 60559 floating-point arithmetic, the pragma allows optimizations based onidentitiesderivedfromtheassociativeandcommutativelaws,suchas

x+(z+y)=(x+y)+z

7.6.1e.3TheFENV_ALLOW_DISTRIBUTIVE_LAWpragma

Synopsis15

[1] #define __STDC_WANT_IEC_60559_ATTRIBS_EXT__ #include <fenv.h> #pragma STDC FENV_ALLOW_DISTRIBUTIVE_LAW on-off-switch

Description

[2] This pragma allows or disallows optimizations based on the distributive laws for20multiplicationanddivision

x×(y+z)=(x×y)+(x×z)x×(y−z)=(x×y)−(x×z)(x+y)/z=(x/z)+(y/z)(x−y)/z=(x/z)−(y/z)25

whereon-off-switchisoneof

ON–allowapplicationofthedistributivelaws

OFF–donotallowapplicationofthedistributivelaws

DEFAULT–“off”

7.6.1e.4TheFENV_ALLOW_MULTIPLY_BY_RECIPROCALpragma30

Synopsis

[1] #define __STDC_WANT_IEC_60559_ATTRIBS_EXT__ #include <fenv.h> #pragma STDC FENV_ALLOW_MULTIPLY_BY_RECIPROCAL on-off-switch

WG14N1974 DraftTechnicalSpecification–October14,2015 ISO/IECTS18661-5

©ISO/IEC2015–Allrightsreserved 9

Description

[2]This pragma allowsor disallowsoptimizations basedon themathematical equivalence ofdivisionandmultiplicationbythereciprocalofthedenominator

x/y=x×(1/y)

whereon-off-switchisoneof5

ON–allowmultiplybyreciprocal

OFF–donotallowmultiplybyreciprocal

DEFAULT–“off”

7.6.1e.5TheFENV_ALLOW_ZERO_SUBNORMALpragma

Synopsis10

[1] #define __STDC_WANT_IEC_60559_ATTRIBS_EXT__ #include <fenv.h> #pragma STDC FENV_ALLOW_ZERO_SUBNORMAL on-off-switch

Description

[2]Thispragmaallowsordisallowsreplacementof subnormaloperandsandresultsbyzero,15whereon-off-switchisoneof

ON–allowreplacementofsubnormalswithzero

OFF–donotallowreplacementofsubnormalswithzero

DEFAULT–“off”

[3]Within the scopeof thispragma, the floating-pointoperationsaffectedby thepragmaare20the same operations as would be affected by the FENV_ROUND and FENV_DEC_ROUNDpragmas(7.6.1a,7.6.1b).Thus,subnormaloperandsandresultsofaffectedoperationsmaybereplaced by zero. Functions not affected by the pragma behave as though noFENV_ALLOW_ZERO_SUBNORMALpragmawereineffectatthesiteofthecall.

7.6.1e.6TheFENV_ALLOW_CONTRACT_FMApragma25

Synopsis

[1] #define __STDC_WANT_IEC_60559_ATTRIBS_EXT__ #include <fenv.h> #pragma STDC FENV_ALLOW_CONTRACT_FMA on-off-switch

ISO/IECTS18661-5 DraftTechnicalSpecification–October14,2015 WG14N1974

10 ©ISO/IEC2015–Allrightsreserved

Description

[2] This pragma allows or disallows contraction (6.5) of floating-point multiply and add orsubtract(withtheresultofthemultiply)

x * y + zx * y − z5x + y * zx − y * z

whereon-off-switchisoneof

ON–allowcontractionforfloating-pointmultiply-add

OFF–donotallowcontractionforfloating-pointmultiply-add10

DEFAULT–implementationdefinedwhether“on”or“off”

[3]NOTE IEC60559usesthetermsynthesizeinsteadofcontract.

7.6.1e.7TheFENV_ALLOW_CONTRACT_OPERATION_CONVERSIONpragma

Synopsis

[1] #define __STDC_WANT_IEC_60559_ATTRIBS_EXT__ 15#include <fenv.h> #pragma STDC FENV_ALLOW_CONTRACT_OPERATION_CONVERSION on-off-switch

Description

[2] This pragma allows or disallows contraction (6.5) of a floating-point operation and aconversion(oftheresultoftheoperation),whereon-off-switchisoneof20

ON–allowcontractionforfloating-pointoperation-conversion

OFF–donotallowcontractionforfloating-pointoperation-conversion

DEFAULT–implementationdefinedwhether“on”or“off”

[3]Within the scopeof thispragma, the floating-pointoperationsaffectedby thepragmaarethe same operations as would be affected by the FENV_ROUND and FENV_DEC_ROUND25pragmas(7.6.1a,7.6.1b).Thus,anaffectedoperationmaybecontractedwithaconversionofitsresult. Functions not affected by the pragma behave as though noFENV_ALLOW_CONTRACT_OPERATION_CONVERSIONpragmawereineffectatthesiteofthecall.

WG14N1974 DraftTechnicalSpecification–October14,2015 ISO/IECTS18661-5

©ISO/IEC2015–Allrightsreserved 11

[4]EXAMPLE Forthecodesequence

#define __STDC_WANT_IEC_60559_ATTRIBS_EXT__ #include <fenv.h> #include <math.h> #pragma STDC FENV_ALLOW_CONTRACT_OPERATION_CONVERSION ON 5float f1, f2; double d1, d2; … f1 = d1 * d2; f2 = sqrt(d1); 10

themultiply (operation) and assignment (conversion) are allowed to be evaluatedwith just onerounding(totherangeandprecisionoffloat).Iftheon-off-switchforthepragmawereOFF,thenthemultiply would have to be rounded according to the evaluationmethod and the assignmentwould require a second rounding. With the given code, the sqrt function may be replaced byfsqrt,avoidingtheneedforaseparateoperationtoconvertthedoubleresultofsqrttofloat.15

7.6.1e.8TheFENV_ALLOW_CONTRACTpragma

Synopsis

[1] #define __STDC_WANT_IEC_60559_ATTRIBS_EXT__ #include <fenv.h> #pragma STDC FENV_ALLOW_CONTRACT on-off-switch 20

Description

[2]Thispragmaallowsordisallowscontraction(6.5) for floating-pointoperations,whereon-off-switchisoneof

ON–allowcontractionforfloating-pointoperations

OFF–donotallowcontractionforfloating-pointoperations25

DEFAULT–implementationdefinedwhether“on”or“off”

[3] The optimizations controlled by this pragma include those controlled by theFENV_ALLOW_CONTRACT_FMA and FENV_ALLOW_CONTRACT_OPERATION_CONVERSIONpragmas.

[4] This pragma is equivalent to theFP_CONTRACT pragma in<math.h>: the two pragmas30may be used interchangeably, provided the appropriate header is included and theimplementationdefines__STDC_WANT_IEC_60559_ATTRIBS_EXT__.

9 Reproducibility

IEC 60559 recommends an attribute to facilitate writing programs whose floating-point results andexception flags will be reproducible on any implementation that supports the language and library35featuresusedbytheprogram.Suchcodemustuseonlythosefeaturesofthelanguageandlibrarythatsupportreproducibleresults.Thesefeaturesincludeoneswithawell-definedbindingtoreproduciblefeaturesofIEC60559,sothatnounspecifiedorimplementation-definedbehaviorisadmitted.ThispartofISO/IECTS18661providesapragmatosupporttheIEC60559attributeforreproducibleresultsandgivesrequirementsforprogramstohavereproducibleresults.40

ISO/IECTS18661-5 DraftTechnicalSpecification–October14,2015 WG14N1974

12 ©ISO/IEC2015–Allrightsreserved

ChangetoC11+TS18661-1+TS18661-2+TS18661-3+TS18661-4:

After7.6.1e,insert:

7.6.1f Reproducibleresults

[1]ThepragmainthissubclausesupportsthereproducibleresultsattributerecommendedinIEC 60559. Where the state of the pragma is “on”, floating-point numerical results and5exception flags are reproducible on implementations that define__STDC_IEC_60559_ATTRIBS__andthatsupportthelanguageandlibraryfeaturesusedbythe source code, provided the source code uses a limited set of features as described below(7.6.1f.2).

[2] An implementation that defines __STDC_IEC_60559_ATTRIBS__ also defines either10__STDC_IEC_60559_BFP__ or __STDC_IEC_60559_DFP__, or both. If theimplementation defines __STDC_IEC_60559_BFP__, it supports reproducible results forbinary floating-pointarithmetic. If the implementationdefines__STDC_IEC_60559_DFP__,it supports reproducible results for decimal floating-point arithmetic. If the implementationdefines__STDC_IEC_60559_TYPES__, then itsupportsreproducibleresults forcodeusing15its interchange floating types. If the implementationdefines__STDC_IEC_60559_FUNCS__and it provides a set of correctly rounded math functions (7.31.6a), then it supportsreproducibleresultsforcodeusingcorrectlyroundedmathfunctionsfromthatset.

7.6.1f.1TheFENV_REPRODUCIBLEpragma

Synopsis20

[1] #define __STDC_WANT_IEC_60559_ATTRIBS_EXT__ #include <fenv.h> #pragma STDC FENV_REPRODUCIBLE on-off-switch

Description

[2]Thispragmaenablesordisables support for reproducible results.Thepragmashalloccur25eitheroutsideexternaldeclarationsorprecedingallexplicitdeclarationsandstatementsinsidea compound statement.When outside external declarations, the pragma takes effect from itsoccurrenceuntilanotherFENV_REPRODUCIBLEpragmaisencountered,oruntiltheendofthetranslation unit. When inside a compound statement, the pragma takes effect from itsoccurrence until another FENV_REPRODUCIBLE pragma is encountered (including within a30nested compound statement), or until the end of the compound statement; at the end of acompound statement the state for the pragma is restored to its condition just before thecompoundstatement.

[3]Ifthestateofthepragmais“on”,thentheeffectsofthefollowingareimplied

#pragma STDC FENV_ACCESS ON 35#pragma STDC FENV_ALLOW_VALUE_CHANGING_OPTIMIZATION OFF

andif__STDC_IEC_60559_BFP__isdefined

#pragma STDC FENV_FLT_EVAL_METHOD 0

WG14N1974 DraftTechnicalSpecification–October14,2015 ISO/IECTS18661-5

©ISO/IEC2015–Allrightsreserved 13

andif__STDC_IEC_60559_DFP__isdefined

#pragma STDC FENV_DEC_EVAL_METHOD 1

[4] If the pragma appears with the on-off-switch OFF under the effect of a pragma withon-off-switchON,thenthestatesoftheFENV_ACCESSpragma,thevalue-changingoptimizationpragmas,andtheevaluationmethodpragmas(evenanevaluationmethodpragmawhosestate5was explicitly changed under the effect of the pragmawith on-off-switchON) revert to theirstates prior to the pragmawith on-off-switchON. The pragmawithon-off-switchOFF has noeffectifitoccurswherethestateofthepragmais“off”.

[5]The“default”stateofthepragmais“off”.

[6] The implementation should produce a diagnostic message if, where the state of the10FENV_REPRODUCIBLE pragma is “on”, the source code uses a language or library featurewhoseresultsmaynotbereproducible.

7.6.1f.2Reproduciblecode

[1] Following are requirements for a code sequence in order that its results will bereproducible.Ifthecodeusesoptionalfeaturesnotedbelow,thenresultsarereproducibleonly15onimplementationsthatsupportthosefeatures.

⎯ The code translates into a sequence of floating-point operations that are bound to IEC60559operations,asdescribedinF.3inthetableentitled“Operationbinding”.

⎯ Thecodedoesnotcontainanyusethatmayresultinundefinedbehavior.Thecodedoesnotdependonanybehaviorthatisunspecified,implementation-defined,orlocale-specific.See20AnnexJ.

⎯ ThecodeisundertheeffectoftheFENV_REPRODUCIBLEpragma(withstate“on”).

⎯ Thecodedoesnotsetthestateofanypragmathatallowsvalue-changingoptimizationsto“on”or“default”.

⎯ ThecodedoesnotsetthestateoftheFENV_ACCESSpragmato“off”or“default”.25

⎯ ThecodedoesnotusetheFENV_FLT_EVAL_METHODpragmawithanywidthexcept0or1.Supportforwidthequalto1isanoptionalfeature.

⎯ ThecodedoesnotusetheFENV_DEC_EVAL_METHODpragmawithanywidthexcept1or2.Supportforwidthequalto2isanoptionalfeature.

⎯ Use of an FENV_EXCEPT pragma with an except-list that includes sub-exceptions is an30optionalfeature.

⎯ ThecodedoesnotuseanFENV_EXCEPTpragmawithanactionBREAK,TRY,orCATCH.

⎯ Thecodedoesnotusethelong doubletype.

⎯ If__STDC_IEC_60559_BFP__ is not definedby the implementation, the codedoesnotuseanystandardfloatingtypes.35

ISO/IECTS18661-5 DraftTechnicalSpecification–October14,2015 WG14N1974

14 ©ISO/IEC2015–Allrightsreserved

⎯ Evenif__STDC_IEC_60559_TYPES__isdefined,thecodedoesnotuseextendedfloatingtypes.Evenif__STDC_IEC_60559_TYPES__isdefined,someinterchangefloatingtypesareoptionalfeatures.

⎯ Thecodedoesnotusecomplexorimaginarytypes.

⎯ ThecodedoesnotusesignalingNaNs.5

⎯ Thecodedoesnotusetheremquofunctions.

⎯ Thecodedoesnotdependonthesignofazeroresultorthequantumofadecimalresultforthefmin,fmax,fminmag,andfmaxmagfunctionswhentheargumentsareequal.

⎯ Thecodedoesnotdependonthepayloads(F.10.13)orsignbitsofquietNaNs.

⎯ Thecodedoesnotdependonthe“underflow”or“inexact”floating-pointexceptionsorflags.10

⎯ Thecodedoesnotuseextendedintegertypes.

⎯ The code does not depend on conversions between binary floating types and charactersequences with more than M + 3 significant decimal digits, where M is 17 if__STDC_IEC_60559_TYPES__ is not defined (by the implementation), and M is1+⎡p×log10(2)⎤, where p is the precision of the widest supported binary interchange15floating type, if __STDC_IEC_60559_TYPES__ is defined. Even if__STDC_IEC_60559_TYPES__ is defined, support for interchange floating typeswiderthan binary64 is an optional feature. (This specification differs from IEC 60559 whichrequires that an implementation supporting reproducibility not limit the number ofsignificantdecimaldigitsforcorrectrounding.)20

⎯ Thecodedoesnotdependontheactualcharactersequenceinprintfresultswithstylea(orA), nor does it depend on numerical values of such resultswhen the precision is notsufficientforanexactrepresentation.

10Alternateexceptionhandling

IEC 60559 arithmetic raises floating-point exceptions as a way to inform the program when an25operationencountersproblematic inputs, such thatnooneresultwouldbesuitable forall situations.ThedefaultexceptionhandlinginIEC60559isintendedtobemoreusefulinmoresituationsthanotherschemes,oratleastpredictable.However,otherexceptionhandlingismoreusefulincertainsituations.Thus,IEC60559describesalternateexceptionhandlingandrecommendsthatprogramminglanguagesprovideameansfortheprogramtospecifywhichexceptionhandlingwillbedone.30

ChangestoC11+TS18661-1+TS18661-2+TS18661-3+TS18661-4:

After7.6.1f.2,insert:

7.6.1g Alternateexceptionhandling

[1]Whenafloating-pointexceptionisraised,theIEC60559defaultexceptionhandlingsetstheappropriate exception flag(s), returns a specified result, and continues execution. IEC 6055935alsoprescribesalternateexceptionhandling.Thepragmainthissubclauseprovidesameansfortheprogramtochoosethemethodofexceptionhandling.Thepragmaappliestooperationsonallfloating-pointtypes.

WG14N1974 DraftTechnicalSpecification–October14,2015 ISO/IECTS18661-5

©ISO/IEC2015–Allrightsreserved 15

[2] For the “underflow” exception, the chosen exception handling occurs if the exception israised,whetherthedefaultresultwouldbeexactorinexact,unlessstatedotherwise.

[3] Alternate exception handling is an optional feature for implementations that support IEC60559attributes.Implementationsthatprovidethefeaturedefinethemacro

__STDC_IEC_60559_ATTRIB_ALTERNATE_EXCEPTION_HANDLING__ 5

aswellas

__STDC_IEC_60559_ATTRIBS__

See6.10.8.3.

7.6.1g.1TheFENV_EXCEPT pragma

Synopsis10

[1] #define __STDC_WANT_IEC_60559_ATTRIBS_EXT__ #include <fenv.h> #pragma STDC FENV_EXCEPT action except-list

Description

[2]TheFENV_EXCEPTpragmasetsthemethodspecifiedbyactionforhandlingtheexceptions15representedbyexcept-list.

[3] The pragma shall occur either outside external declarations, unless stated otherwise, orprecedingallexplicitdeclarationsandstatementsinsideacompoundstatement,whichthenisthecompoundstatementassociatedwiththepragma.Whenoutsideexternaldeclarations,thepragmaaction foradesignatedexceptiontakeseffectfromtheoccurrenceofthepragmauntil20anotherFENV_EXCEPTpragmadesignatingthesameexceptionisencountered,oruntiltheendofthetranslationunit.Wheninsideacompoundstatement,thepragmaactionforadesignatedexceptiontakeseffectfromtheoccurrenceofthepragmauntilanotherFENV_EXCEPTpragmadesignating the same exception is encountered (including within a nested compoundstatement),oruntil theendof thecompoundstatement;at theendofacompoundstatement25thestate forhandlingeachexceptions inexcept-list isrestoredto itscondition justbeforethecompoundstatement.

[4]WithinthescopeofanFENV_EXCEPTpragma,thefloating-pointoperationsaffectedbythepragma are the same operations as would be affected by the FENV_ROUND andFENV_DEC_ROUNDpragmas(7.6.1a,7.6.1b).Thus,exceptionsraisedbyaffectedoperationsare30handled according to the specified action. Functions not affected by the pragma behave asthoughnoFENV_EXCEPTpragmawereineffectatthesiteofthecall.

[5]WithinthescopeofanFENV_EXCEPTpragma,explicitlyaccessingtheflagofadesignatedexceptionresultsinundefinedbehavior.

ISO/IECTS18661-5 DraftTechnicalSpecification–October14,2015 WG14N1974

16 ©ISO/IEC2015–Allrightsreserved

[6] except-list shall be a comma-separated list of supported exception designations (or onesupported exception designation). The supported exception designations shall include theexceptionmacroidentifiers(7.6)

FE_DIVBYZERO FE_INEXACT 5FE_INVALID FE_OVERFLOW FE_UNDERFLOW FE_ALL_EXCEPT

andshouldincludedesignationsforthesub-exceptions10

— “invalid”floating-pointexceptionsfromaddandsubtractoperatorsandfunctionsthataddorsubtract(7.12.13a.1,7.12.13a.2),notcausedbysignalingNaNinput

FE_INVALID_ADD

— “invalid” floating-point exceptions from divide operators and functions that divide(7.12.13a.4),notcausedbysignalingNaNinput15

FE_INVALID_DIV

— “invalid” floating-point exceptions from functions that compute multiply-add (7.12.13.1,7.12.13a.5)and fromcontractedmultiplyandaddoperators,notcausedbysignalingNaNinput

FE_INVALID_FMA 20

— “invalid” floating-point exceptions from conversions from floating to integer types, notcausedbysignalingNaNinput

FE_INVALID_INT

— “invalid” floating-point exceptions from ilogb and llogb functions, not caused bysignalingNaNinput25

FE_INVALID_ILOGB

— “invalid” floating-point exceptions from multiply operators and functions that multiply(7.12.13a.3),notcausedbysignalingNaNinput

FE_INVALID_MUL

— “invalid” floating-point exceptions from thequantize functions, not causedby signaling30NaNinput

FE_INVALID_QUANTIZE

— “invalid”floating-pointexceptionsfromtheremainderandremquofunctions,notcausedbysignalingNaNinput

FE_INVALID_REM 35

— “invalid” floating-point exceptions from functions that compute square root (7.12.7.5,7.12.13a.6),notcausedbysignalingNaNinput

FE_INVALID_SQRT

—“invalid”floating-pointexceptionscausedbysignalingNaNinputFE_INVALID_SNAN 40

WG14N1974 DraftTechnicalSpecification–October14,2015 ISO/IECTS18661-5

©ISO/IEC2015–Allrightsreserved 17

— “invalid” floating-point exceptions from relational operators and comparisonmacros, notcausedbysignalingNaNinput

FE_INVALID_UNORDERED

— “divide-by-zero”floating-pointexceptionsfromdivideoperatorsandfunctionsthatdivideFE_DIVBYZERO_ZERO 5

— “divide-by-zero”floating-pointexceptionsfromlogarithmandlogbfunctionsFE_DIVBYZERO_LOG

[7]actionshallbeadesignationofasupportedexceptionhandlingmethod,whichshallinclude

— defaultexceptionhandling(asspecifiedinIEC60559).DEFAULT 10

— defaultexceptionhandling,butwithoutsettingtheflag.NO_FLAG

— defaultexceptionhandling,butwhethertheflagisset(aswithdefaultexceptionhandling),andforwhichoperationsandtheiroccurrences,isunspecified.

OPTIONAL_FLAG 15

— abrupt underflow. If an “underflow” floating-point exception occurs (see IEC 60559), theoperationdeliversaresultwithmagnitudezeroortheminimumnormalmagnitude(fortheresult format) andwith the same signas thedefault result, sets the “underflow” floating-pointexceptionflag,andraisesthe“inexact”floating-pointexception.When

20roundingtonearest,tiestoevenroundingtonearest,tiesawayfromzero

or

roundingtowardzero

theresultmagnitudeiszero.Whenroundingtowardpositiveinfinity,theresultmagnitude25istheminimumnormalmagnitudeiftheresultsignispositive,andzeroiftheresultsignisnegative.When rounding toward negative infinity, the result magnitude is theminimumnormalmagnitudeiftheresultsignisnegative,andzeroiftheresultsignispositive.Abruptunderflow has no effect on the interpretation of subnormal operands. The action has noeffectifFE_UNDERFLOWisnotincludedinexcept-list.30

ABRUPT_UNDERFLOW

— break.Terminateexecutionofthecompoundstatementassociatedwiththepragma.Then,continueexecutionaftertheassociatedcompoundstatement.Whenterminationoccurs,thefollowing apply:if the execution to completion of the associated compound statement(without the break) would at any point modify an object, the value of the object is35indeterminate; if the executionwouldmodify the state of thedynamic roundingmodeorany state maintained by the standard library (e.g., in the I/O system), the state isunspecified; the values of flags for the designated exceptions are unspecified. (Thus,termination may occur as soon as possible after the exception is raised, to maximizeperformance.)Thepragmawiththisactionshallappearonlyinacompoundstatement.40

BREAK

ISO/IECTS18661-5 DraftTechnicalSpecification–October14,2015 WG14N1974

18 ©ISO/IEC2015–Allrightsreserved

Thefollowingtwoactionsworktogether.Thepragmaswiththeseactionsshallappearonlyincompoundstatements.Acompoundstatementassociatedwithatryactionmaybepairedwithoneormorecompoundstatementseachassociatedwithacatchaction.Compoundstatementsassociated with catch actions shall appear contiguously immediately below the compoundstatementassociatedwiththetryaction,exceptforwhitespace(includingcomments).5— try.Thedesignatedexceptionsmaybehandledbyacatchaction.Itisunspecifiedwhether

flags for designated exceptions that are set in the execution of the associated compoundstatement are restored to their states before the associated compound statement. Theassociatedcompoundstatementshallnotbethestatementofaselection(6.8.4)oriteration10(6.8.5) statement. There shall be no jumps into or out of the associated compoundstatement,otherthantohandleanexception,asspecifiedbelow.

TRY

— catch.Ifanyexceptionwiththesamedesignationforboththetryactionandacatchactionoccursintheexecutionofthecompoundstatementassociatedwiththetryaction,jumptoa15compoundstatementassociatedwithsomeoccurringexceptionwiththesamedesignationfor the try action and a catch action. Upon completion of the associated compoundstatement, continue execution after the last of the compound statements associatedwithcatchactions.Eachexceptiondesignationshallbelistedinatmostoneofthepragmaswithacatchaction.The jumptargetshouldbeacompoundstatementassociatedwith the first20occurringdesignatedexception.Whenthejumpoccurs,thefollowingapply:iftheexecutionoftheassociatedcompoundstatementtocompletion(withoutthejump)wouldatanypointmodifyanobject,thevalueoftheobjectisindeterminate;iftheexecutionwouldmodifythestateofthedynamicroundingmodeoranystatemaintainedbythestandardlibrary(e.g.,intheI/Osystem),thestateisunspecified.(Thus,thejumpmayoccurassoonaspossibleafter25the exception is raised, to maximize performance). The compound statement associatedwith a catch action is executed only to handle an exception occurring in the compoundstatementassociatedwith the try action.Thereshallbenoother jumps intooroutof thecompoundstatementassociatedwithacatchaction.

CATCH30

Thefollowingtwoactionsworktogether.Thepragmaswiththeseactionsshallappearonlyincompound statements. A compound statement associated with a delayed-try action may bepaired with one ormore compound statements each associated with a delayed-catch action.Compound statements associated with delayed-catch actions shall appear contiguouslyimmediatelybelowthecompoundstatementassociatedwiththedelayed-tryaction,exceptfor35whitespace(andcomments).For (optional)supportofsub-expressions, theexceptions, flags,andfunctionsinthespecificationbelowareassumedtobeextendedforsub-expressions.— delayed-try. The designated exceptionsmay be handled by adelayed-catch action. Before

executing the compound statement associated with the delayed-try action, save (as by40fegetexceptflag) the statesof the flags for thedesignatedexceptions, and then clear(as by feclearexcept) the designated exceptions. After normal completion of theassociated compound statement, re-save the states of the designated exceptions. Thenrestore (as by fesetexceptflag) the designated exception flag states before theassociated compound statement. The associated compound statement shall not be the45statementofaselection(6.8.4)oriteration(6.8.5)statement.Thereshallbenojumpsintooroutoftheassociatedcompoundstatement.

DELAYED_TRY

— delayed-catch. Test (as by fetestexceptflag) the exception flag states saved aftercompletion of the compound statement associated with the delayed-try action. If any50

WG14N1974 DraftTechnicalSpecification–October14,2015 ISO/IECTS18661-5

©ISO/IEC2015–Allrightsreserved 19

exceptionwith the samedesignation for thedelayed-try actionandadelayed-catch actionoccurred (as determined by flag state tests), jump to the first compound statementassociatedwithanoccurringexceptionwiththesamedesignationforthedelayed-tryactionand a delayed-catch action. Upon completion of the associated compound statement,continueexecutionafterthelastofthecompoundstatementsassociatedwithdelayed-catch5actions. Each exception designation shall be listed in atmost one of the pragmaswith adelayed-catch action. The compound statement associated with a delayed-catch action isexecutedonlytohandleanexceptionoccurringinthecompoundstatementassociatedwiththedelayed-tryaction.Thereshallbenootherjumpsintooroutofthecompoundstatementassociatedwithadelayed-catchaction.10

DELAYED_CATCH

EXAMPLE Thisexampleillustratesbehavioraldifferencesbetweentryandcatchactionsanddelayed-tryanddelayed-catchactions.

Codesequencewithtryandcatchactions:

#pragma STDC FENV_ACCESS ON 15#include <fenv.h> double d[n]; float f[n]; …{ 20

#pragma STDC FENV_EXCEPT TRY FE_DIVBYZERO, FE_OVERFLOW for (i=0; i<n; i++) {

f[i] = 1.0 / d[i]; }

} 25{

#pragma STDC FENV_EXCEPT CATCH FE_DIVBYZERO printf(“divide-by-zero\n”);

} { 30

#pragma STDC FENV_EXCEPT CATCH FE_OVERFLOW printf(“overflow\n”);

} …

Thesamecodebutwithdelayed-tryanddelayed-catchactions:35

ISO/IECTS18661-5 DraftTechnicalSpecification–October14,2015 WG14N1974

20 ©ISO/IEC2015–Allrightsreserved

#pragma STDC FENV_ACCESS ON #include <fenv.h> double d[n]; float f[n]; …5{

#pragma STDC FENV_EXCEPT DELAYED_TRY \ FE_DIVBYZERO, FE_OVERFLOW

for (i=0; i<n; i++) { f[i] = 1.0 / d[i]; 10

} } {

#pragma STDC FENV_EXCEPT DELAYED_CATCH FE_DIVBYZERO printf(“divide-by-zero\n”); 15

} {

#pragma STDC FENV_EXCEPT DELAYED_CATCH FE_OVERFLOW printf(“overflow\n”);

} 20…

Thefollowingtableshowsexamplesofinputsandresultsforthetwocodesequencesabove.

try-catch delayed-try–delayed-catchInputd 0.5,0.0Results f=1/ d indeterminate,

indeterminate2.0,infinity

output “divide-by-zero” “divide-by-zero”“divide-by-zero”flag unspecified(setorrestored) restored“overflow”flag unchanged restored(unchanged)

Inputd 0.5,−1e100Results f=1/ d indeterminate,

indeterminate2.0,infinity

output “overflow” “overflow”“divide-by-zero”flag unchanged restored(unchanged)“overflow”flag unspecified(setorrestored) restored

Inputd −1e100,0.0

Results f=1/ d indeterminate,

indeterminateinfinity,infinity

output “overflow”(recommended)or“divide-by-zero”

“divide-by-zero”

“divide-by-zero”flag unspecified(setorrestored) restored“overflow”flag unspecified(setorrestored) restored

WG14N1974 DraftTechnicalSpecification–October14,2015 ISO/IECTS18661-5

©ISO/IEC2015–Allrightsreserved 21

NOTE Thedelayed-tryanddelayed-catchactionsaredeterministic.Theycanbeimplementedwith the floating-pointexception flags.The followingcodesequence isequivalent to thecodesequenceusingdelayed-tryanddelayed-catchintheexampleabove.

#pragma STDC FENV_ACCESS ON #include <fenv.h> 5double d[n]; float f[n]; …{

fexcept_t old_except, new_except; 10fegetexceptflag(&old_except, FE_DIVBYZERO | FE_OVERFLOW); feclearexcept(FE_DIVBYZERO | FE_OVERFLOW); {

for (i=0; i<n; i++) { f[i] = 1.0 / d[i]; 15

} } fegetexceptflag(&new_except, FE_DIVBYZERO | FE_OVERFLOW); fesetexceptflag(&old_except, FE_DIVBYZERO | FE_OVERFLOW); if (fetestexceptflag(&new_except, FE_DIVBYZERO)) { 20 printf(“divide-by-zero\n”); } else if (fetestexceptflag(&new_except, FE_OVERFLOW)) { printf(“overflow\n”); } 25

} …

NOTE The try and catch actions are not deterministic (see example above), which allowsmoreimplementationflexibilityforbetterperformance.30Inmostcases,thetryandcatchactionscanbeimplementedlikedelayed-tryanddelayed-catchactions, though not for the “underflow” exception (which occurs without causing the“underflow” flag to be set, in cases of exact results near the underflow threshold). Such animplementation would not always handle the first occurring designated exception, as35recommended.Animplementationoftryandcatchactionsusingfloating-pointexceptiontrapsmightwellbeable to handle the first occurring designated exception (including “underflow”), asrecommended,andachievebetterperformance.40

In7.6.1g.1,inthetrybullet,attachafootnotetothewording:

Theassociatedcompoundstatementshallnotbethestatementofaselection(6.8.4)oriteration(6.8.5)statement.

wherethefootnoteis:

*) The compound statements associated with a try action and its catch actions, together45enclosedinbraces,maybethestatementofaselectionoriterationstatement.Forexample,thefollowingcodesegmentispermitted:

ISO/IECTS18661-5 DraftTechnicalSpecification–October14,2015 WG14N1974

22 ©ISO/IEC2015–Allrightsreserved

for (i = 0; i < n; i++) { {

#pragma STDC FENV_EXCEPT TRY FE_OVERFLOW y[i] = x[i] * x[i];

} 5{

#pragma STDC FENV_EXCEPT CATCH FE_OVERFLOW y[i] = DBL_MAX;

} } 10

In6.5.16.2,infootnote113,change:

For example, if annex F is in effect, the floating types involvedhave IEC60559 formats, andFLT_EVAL_METHODis0,theequivalentcodewouldbe:

to:

For example, if annex F is supported, the floating types involved have IEC 60559 formats,15FLT_EVAL_METHODis0,andnoFENV_EXCEPTpragmaisineffect,theequivalentcodewouldbe:

WG14N1974 DraftTechnicalSpecification–October14,2015 ISO/IECTS18661-5

©ISO/IEC2015–Allrightsreserved 23

Bibliography

[1] IEC60559:1989,Binaryfloating-pointarithmeticformicroprocessorsystems,secondedition

[2] IEEE754−1985,IEEEStandardforBinaryFloating-PointArithmetic

[3] IEEE754-2008,IEEEStandardforFloating-PointArithmetic

[4] IEEE854−1987,IEEEStandardforRadix-IndependentFloating-PointArithmetic5

[5] ISO/IEC9899:2011/Cor.1:2012, Information technology— Programming languages—C/TechnicalCorrigendum1