Skip to content

[SYCL][FE][Driver] Implement floating point accuracy control #8280

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 55 commits into from
Jun 14, 2023
Merged
Show file tree
Hide file tree
Changes from 12 commits
Commits
Show all changes
55 commits
Select commit Hold shift + click to select a range
79792b3
Implement floating point accuracy.
zahiraam Feb 9, 2023
c3029ee
Responded to review comments and added more to the implementation.
zahiraam Feb 13, 2023
fa51800
Added option falt-math-library and fixed a few things with fpbuiltin-…
zahiraam Feb 14, 2023
b584e3d
Added a cc1 option triggered by the fp-accuracy option.
zahiraam Mar 1, 2023
ec2dfbc
Merge remote-tracking branch 'remote/sycl' into FPAccuracy
zahiraam Apr 4, 2023
be478d8
Remove TargetInfoLibrary dependency.
zahiraam Apr 6, 2023
4c23010
Fix a few things.
zahiraam Apr 6, 2023
db8c415
Merge remote-tracking branch 'remote/sycl' into FPAccuracy
zahiraam Apr 6, 2023
2bcd2a8
Fix a few things.
zahiraam Apr 6, 2023
bdf5dbe
Adding code to support the option.
zahiraam Apr 18, 2023
d796b5f
Fix formatting issues and remove unused code.
zahiraam Apr 18, 2023
6c005d8
Fix format issues.
zahiraam Apr 18, 2023
b93d9ec
Respond to review.
zahiraam Apr 18, 2023
17eb30f
Fix typo.
zahiraam Apr 18, 2023
4ffd86f
Add a group to the diag and fixed typo.
zahiraam Apr 18, 2023
bd458b9
Fixed typo.
zahiraam Apr 18, 2023
80c131a
Hooking BE code with FE.
zahiraam Apr 24, 2023
faae1a0
Responded to review.
zahiraam Apr 25, 2023
bbabbb5
Fix format.
zahiraam Apr 25, 2023
ef29dfc
Merge remote-tracking branch 'remote/sycl' into FPAccuracy
zahiraam Apr 25, 2023
8aabc41
Responded to review comments.
zahiraam Apr 25, 2023
6681fc2
Fixed Lit test failures.
zahiraam Apr 26, 2023
20fd09b
Fixed sincos issue and did some code refactoring.
zahiraam Apr 26, 2023
300d2fe
Remove FPAccuracyMap.
zahiraam Apr 27, 2023
1e148b3
Added testing for the all the fpbuiltin.
zahiraam May 1, 2023
4f6089a
Fix format.
zahiraam May 1, 2023
5a61b28
Fix format.
zahiraam May 1, 2023
f02d393
Fix format.
zahiraam May 1, 2023
061ca9f
Merge remote-tracking branch 'remote/sycl' into FPAccuracy
zahiraam May 1, 2023
edb89ce
Added default mode.
zahiraam May 5, 2023
ec3be13
Responded to reviews.
zahiraam May 5, 2023
9cce8b7
Fix format.
zahiraam May 5, 2023
2ea8d5a
Added support for math-errno.
zahiraam May 8, 2023
7abea95
Fixed diag comment.
zahiraam May 8, 2023
773f1ed
Fix lit test.
zahiraam May 8, 2023
68c9a70
Fixed Diag.
zahiraam May 9, 2023
a7c7546
Merge remote-tracking branch 'remote/sycl' into FPAccuracy
zahiraam May 9, 2023
bffc1fd
Responded to review comments.
zahiraam May 9, 2023
7900b87
Responded to review comments.
zahiraam May 18, 2023
a71e5f2
Responded to review comments.
zahiraam May 19, 2023
a05458f
Responded to review comments.
zahiraam May 25, 2023
02831e8
Responded to review comments.
zahiraam May 26, 2023
680bd47
Merge remote-tracking branch 'remote/sycl' into FPAccuracy
zahiraam May 30, 2023
c3f2ca2
Fix format.
zahiraam May 30, 2023
10715d3
Merge remote-tracking branch 'remote/sycl' into FPAccuracy
zahiraam May 30, 2023
a3803db
Re-wrote the condition to make it more readable. Edited the comment
zahiraam May 31, 2023
98ed36d
Responded to review comments.
zahiraam Jun 6, 2023
cdfec2c
Merge remote-tracking branch 'remote/sycl' into FPAccuracy
zahiraam Jun 6, 2023
831aa36
Merge remote-tracking branch 'remote/sycl' into FPAccuracy
zahiraam Jun 8, 2023
a0adb9e
Merge remote-tracking branch 'remote/sycl' into FPAccuracy
zahiraam Jun 9, 2023
d3d470e
Responded to review for CmakeLists.txt.
zahiraam Jun 12, 2023
e08362e
Responded to review about the AttrList.
zahiraam Jun 12, 2023
6d5890d
Fixed typo.
zahiraam Jun 12, 2023
7d3c976
Merge remote-tracking branch 'remote/sycl' into FPAccuracy
zahiraam Jun 12, 2023
9c86522
Merge remote-tracking branch 'remote/sycl' into FPAccuracy
zahiraam Jun 13, 2023
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions clang/include/clang/Basic/Attr.td
Original file line number Diff line number Diff line change
Expand Up @@ -2741,6 +2741,13 @@ def ReturnsTwice : InheritableAttr {
let SimpleHandler = 1;
}

def FPBuiltinMaxError : StmtAttr {
let Spellings = [Clang<"fpbultin_max_error">];
let Subjects = SubjectList<[Function]>;
let Documentation = [Undocumented];
let SimpleHandler = 1;
}

def DisableTailCalls : InheritableAttr {
let Spellings = [Clang<"disable_tail_calls">];
let Subjects = SubjectList<[Function, ObjCMethod]>;
Expand Down
4 changes: 4 additions & 0 deletions clang/include/clang/Basic/DiagnosticDriverKinds.td
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,10 @@ def err_drv_no_cuda_libdevice : Error<
"via '--cuda-path', or pass '-nocudalib' to build without linking with "
"libdevice">;

def warn_function_fp_accuray_already_set : Warning <"FP accuracy value of '%0' has already "
"been assigned to function '%1'">;
def warn_all_fp_accuray_already_set : Warning <"FP accuracy value of '%0' has already "
"been assigned to all functions in the program">;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should there be a way to disable these diagnostics?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why would we want to disable them?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It is an informative diagnostic, but typically warnings have a way to be disabled.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I can create the warning in a new group:
def FPAccuracyWrongValue : DiagGroup<"wrong-value-of-fp-accuracy">;
and then use the -Wno-wrong-value-of-fp-accuracy on the command line to disable the warning. Is that what you mean?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yup, that's what I mean. Maybe: "fp-accuracy-value" would be sufficient here for the name.

def err_drv_no_rocm_device_lib : Error<
"cannot find ROCm device library%select{| for %1|for ABI version %1}0; provide its path via "
"'--rocm-path' or '--rocm-device-lib-path', or pass '-nogpulib' to build "
Expand Down
1 change: 1 addition & 0 deletions clang/include/clang/Basic/FPOptions.def
Original file line number Diff line number Diff line change
Expand Up @@ -26,4 +26,5 @@ OPTION(AllowReciprocal, bool, 1, NoSignedZero)
OPTION(AllowApproxFunc, bool, 1, AllowReciprocal)
OPTION(FPEvalMethod, LangOptions::FPEvalMethodKind, 2, AllowApproxFunc)
OPTION(Float16ExcessPrecision, LangOptions::ExcessPrecisionKind, 2, FPEvalMethod)
OPTION(FPAccuracy, LangOptions::FPAccuracyKind, 2, Float16ExcessPrecision)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This requires 3 bits to store all the values of FPAccuracyKind (are we missing test coverage? I would have expected that to cause a failure somewhere.)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I changed it to be 3 bits, but not sure what testing I should be doing to catch the error? The LIT test in the Driver folder is exercising all values of FPAccuracyKind and was passing with the 2 bits width.

#undef OPTION
1 change: 1 addition & 0 deletions clang/include/clang/Basic/LangOptions.def
Original file line number Diff line number Diff line change
Expand Up @@ -336,6 +336,7 @@ BENIGN_LANGOPT(RoundingMath, 1, false, "Do not assume default floating-point rou
BENIGN_ENUM_LANGOPT(FPExceptionMode, FPExceptionModeKind, 2, FPE_Default, "FP Exception Behavior Mode type")
BENIGN_ENUM_LANGOPT(FPEvalMethod, FPEvalMethodKind, 2, FEM_UnsetOnCommandLine, "FP type used for floating point arithmetic")
ENUM_LANGOPT(Float16ExcessPrecision, ExcessPrecisionKind, 2, FPP_Standard, "Intermediate truncation behavior for floating point arithmetic")
BENIGN_ENUM_LANGOPT(FPAccuracy, FPAccuracyKind, 2, FPA_Default, "Accuracy for floating point operations and library functions")
LANGOPT(NoBitFieldTypeAlign , 1, 0, "bit-field type alignment")
LANGOPT(HexagonQdsp6Compat , 1, 0, "hexagon-qdsp6 backward compatibility")
LANGOPT(ObjCAutoRefCount , 1, 0, "Objective-C automated reference counting")
Expand Down
17 changes: 17 additions & 0 deletions clang/include/clang/Basic/LangOptions.h
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
#include "clang/Basic/TargetCXXABI.h"
#include "clang/Basic/Visibility.h"
#include "llvm/ADT/FloatingPointMode.h"
#include "llvm/ADT/MapVector.h"
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't see a map-vector being used?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Left over from previous version. Removed.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this still here for the std::map usage below?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The include is still here?

#include "llvm/ADT/StringRef.h"
#include "llvm/TargetParser/Triple.h"
#include <optional>
Expand Down Expand Up @@ -303,6 +304,15 @@ class LangOptions : public LangOptionsBase {

enum ExcessPrecisionKind { FPP_Standard, FPP_Fast, FPP_None };

enum FPAccuracyKind {
FPA_Default,
FPA_High,
FPA_Medium,
FPA_Low,
FPA_Sycl,
FPA_Cuda
};

/// Possible exception handling behavior.
enum class ExceptionHandlingKind { None, SjLj, WinEH, DwarfCFI, Wasm };

Expand Down Expand Up @@ -386,6 +396,13 @@ class LangOptions : public LangOptionsBase {
IncompleteOnly = 3,
};

using FPAccuracyMapTy =
llvm::MapVector<std::string, std::string, llvm::StringMap<unsigned>>;
FPAccuracyMapTy FPAccuracyMap;
using FPAccuracyFuncMapTy =
llvm::MapVector<std::string, FPAccuracyMapTy, llvm::StringMap<unsigned>>;
FPAccuracyFuncMapTy FPAccuracyFuncMap;

public:
/// The used language standard.
LangStandard::Kind LangStd;
Expand Down
12 changes: 12 additions & 0 deletions clang/include/clang/Driver/Options.td
Original file line number Diff line number Diff line change
Expand Up @@ -1700,6 +1700,13 @@ def ffp_exception_behavior_EQ : Joined<["-"], "ffp-exception-behavior=">, Group<
Values<"ignore,maytrap,strict">, NormalizedValuesScope<"LangOptions">,
NormalizedValues<["FPE_Ignore", "FPE_MayTrap", "FPE_Strict"]>,
MarshallingInfoEnum<LangOpts<"FPExceptionMode">, "FPE_Default">;
def ffp_accuracy_EQ : Joined<["-"], "ffp-accuracy=">, Group<f_Group>, Flags<[CC1Option]>,
HelpText<"Specifies the required accuracy for floating-point operations and library calls.">,
Values<"default,high,medium,low,sycl,cuda">, NormalizedValuesScope<"LangOptions">,
NormalizedValues<["FPA_Default", "FPA_High", "FPA_Medium", "FPA_Low", "FPA_Sycl", "FPA_Cuda"]>,
MarshallingInfoEnum<LangOpts<"FPAccuracy">, "FPA_Default">;
def ffp_accuracy_attr_EQ : Joined<["-"], "ffp-accuracy-attr=">, Group<f_Group>, Flags<[CC1Option]>;

defm fast_math : BoolFOption<"fast-math",
LangOpts<"FastMath">, DefaultFalse,
PosFlag<SetTrue, [CC1Option, CoreOption, FC1Option, FlangOption], "Allow aggressive, lossy floating-point optimizations",
Expand Down Expand Up @@ -6946,6 +6953,11 @@ class CLRemainingArgsJoined<string name> : Option<["/", "-"], name,
// (We don't put any of these in cl_compile_Group as the options they alias are
// already in the right group.)

def _SLASH_Qfp_accuracy_EQ : CLJoined<"Qfp-accuracy=">,
Alias<ffp_accuracy_EQ>;
def _SLASH_Qfp_accuracy_COL : CLJoined<"Qfp-accuracy:">,
Alias<ffp_accuracy_EQ>,HelpText<"Defines the accuracy for math library "
"functions.">;
def _SLASH_Brepro : CLFlag<"Brepro">,
HelpText<"Do not write current time into COFF output (breaks link.exe /incremental)">,
Alias<mno_incremental_linker_compatible>;
Expand Down
3 changes: 3 additions & 0 deletions clang/include/clang/Frontend/CompilerInvocation.h
Original file line number Diff line number Diff line change
Expand Up @@ -276,6 +276,9 @@ class CompilerInvocation : public CompilerInvocationRefBase,
std::vector<std::string> &Includes,
DiagnosticsEngine &Diags);

static void ParseFpAccuracyArgs(LangOptions &Opts, llvm::opt::ArgList &Args,
DiagnosticsEngine &Diags);

/// Generate command line options from LangOptions.
static void GenerateLangArgs(const LangOptions &Opts,
SmallVectorImpl<const char *> &Args,
Expand Down
34 changes: 28 additions & 6 deletions clang/lib/CodeGen/CGBuiltin.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -489,13 +489,35 @@ static Value *EmitISOVolatileStore(CodeGenFunction &CGF, const CallExpr *E) {
return Store;
}

static CallInst *CreateBuiltinCallWithAttr(CodeGenFunction &CGF,
llvm::Function *F,
ArrayRef<Value *> Args) {
llvm::CallInst *CI = CGF.Builder.CreateCall(F, Args);
unsigned BuiltinID = CGF.getCurrentBuiltinID();
StringRef Name = CGF.CGM.getContext().BuiltinInfo.getName(BuiltinID);
llvm::AttributeList AttrList;
CGF.CGM.getFPAccuracyFuncAttributes(Name, AttrList);
// TODO: Needs some processing here to call fp::getAccuracyForFPBuiltin
// before setting the attribute for the call.
CI->setAttributes(AttrList);
return CI;
}

// Emit a simple mangled intrinsic that has 1 argument and a return type
// matching the argument type. Depending on mode, this may be a constrained
// floating-point intrinsic.
static Value *emitUnaryMaybeConstrainedFPBuiltin(CodeGenFunction &CGF,
const CallExpr *E, unsigned IntrinsicID,
unsigned ConstrainedIntrinsicID) {
llvm::Value *Src0 = CGF.EmitScalarExpr(E->getArg(0));
if (!CGF.getLangOpts().FPAccuracyMap.empty()) {
Function *Func = CGF.CGM.getIntrinsic(IntrinsicID, Src0->getType());
return CreateBuiltinCallWithAttr(CGF, Func, {Src0});
}
if (!CGF.getLangOpts().FPAccuracyFuncMap.empty()) {
Function *Func = CGF.CGM.getIntrinsic(IntrinsicID, Src0->getType());
return CreateBuiltinCallWithAttr(CGF, Func, {Src0});
}

if (CGF.Builder.getIsFPConstrained()) {
CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, E);
Expand Down Expand Up @@ -2216,6 +2238,8 @@ RValue CodeGenFunction::EmitBuiltinExpr(const GlobalDecl GD, unsigned BuiltinID,
Result.Val.getFloat()));
}

CurrentBuiltinIDRAII CB(*this, BuiltinID);

// If current long-double semantics is IEEE 128-bit, replace math builtins
// of long-double with f128 equivalent.
// TODO: This mutation should also be applied to other targets other than PPC,
Expand Down Expand Up @@ -2276,9 +2300,8 @@ RValue CodeGenFunction::EmitBuiltinExpr(const GlobalDecl GD, unsigned BuiltinID,
case Builtin::BI__builtin_cosf16:
case Builtin::BI__builtin_cosl:
case Builtin::BI__builtin_cosf128:
return RValue::get(emitUnaryMaybeConstrainedFPBuiltin(*this, E,
Intrinsic::cos,
Intrinsic::experimental_constrained_cos));
return RValue::get(emitUnaryMaybeConstrainedFPBuiltin(
*this, E, Intrinsic::cos, Intrinsic::fpbuiltin_cos));

case Builtin::BIexp:
case Builtin::BIexpf:
Expand Down Expand Up @@ -2481,9 +2504,8 @@ RValue CodeGenFunction::EmitBuiltinExpr(const GlobalDecl GD, unsigned BuiltinID,
case Builtin::BI__builtin_sinf16:
case Builtin::BI__builtin_sinl:
case Builtin::BI__builtin_sinf128:
return RValue::get(emitUnaryMaybeConstrainedFPBuiltin(*this, E,
Intrinsic::sin,
Intrinsic::experimental_constrained_sin));
return RValue::get(emitUnaryMaybeConstrainedFPBuiltin(
*this, E, Intrinsic::sin, Intrinsic::fpbuiltin_cos));

case Builtin::BIsqrt:
case Builtin::BIsqrtf:
Expand Down
16 changes: 16 additions & 0 deletions clang/lib/CodeGen/CGCall.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1840,6 +1840,22 @@ void CodeGenModule::getDefaultFunctionAttributes(StringRef Name,
bool HasOptnone,
bool AttrOnCallSite,
llvm::AttrBuilder &FuncAttrs) {
for (const auto &M : getLangOpts().FPAccuracyMap) {
llvm::StringSet<> FuncOwnAttrs;
FuncAttrs.addAttribute("fpaccuracy=", M.second);
FuncOwnAttrs.insert(M.first);
}
if (!getLangOpts().FPAccuracyFuncMap.empty()) {
llvm::StringSet<> FuncOwnAttrs;
auto FuncMapIt = getLangOpts().FPAccuracyFuncMap.find(Name.str());
if (FuncMapIt != getLangOpts().FPAccuracyFuncMap.end()) {
for (const std::pair<std::string, std::string> &AttrPair :
FuncMapIt->second) {
FuncAttrs.addAttribute("fpaccuracy=", AttrPair.second);
FuncOwnAttrs.insert(AttrPair.first);
}
}
}
// OptimizeNoneAttr takes precedence over -Os or -Oz. No warning needed.
if (!HasOptnone) {
if (CodeGenOpts.OptimizeSize)
Expand Down
22 changes: 22 additions & 0 deletions clang/lib/CodeGen/CodeGenFunction.h
Original file line number Diff line number Diff line change
Expand Up @@ -1597,6 +1597,28 @@ class CodeGenFunction : public CodeGenTypeCache {
SourceLocation LastStopPoint;

public:
/// Class to manage the BuiltinID for the current builtin expression during
/// processing in EmitBuiltinExpr.
class CurrentBuiltinIDRAII {
CodeGenFunction &CGF;
unsigned SavedBuiltinID;

public:
CurrentBuiltinIDRAII(CodeGenFunction &CGF, unsigned BuiltinID)
: CGF(CGF), SavedBuiltinID(CGF.CurrentBuiltinID) {
CGF.CurrentBuiltinID = BuiltinID;
}
~CurrentBuiltinIDRAII() { CGF.CurrentBuiltinID = SavedBuiltinID; }
};

private:
unsigned CurrentBuiltinID = /*NotBuiltin*/ 0;

public:
unsigned getCurrentBuiltinID() {
assert(CurrentBuiltinID != /*NotBuiltin*/ 0);
return CurrentBuiltinID;
}
/// Source location information about the default argument or member
/// initializer expression we're evaluating, if any.
CurrentSourceLocExprScope CurSourceLocExprScope;
Expand Down
9 changes: 9 additions & 0 deletions clang/lib/CodeGen/CodeGenModule.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -7852,3 +7852,12 @@ void CodeGenModule::moveLazyEmissionStates(CodeGenModule *NewBuilder) {

NewBuilder->ABI->MangleCtx = std::move(ABI->MangleCtx);
}

void CodeGenModule::getFPAccuracyFuncAttributes(StringRef Name,
llvm::AttributeList &AttrList) {
llvm::AttrBuilder FuncAttrs(getLLVMContext());
getDefaultFunctionAttributes(Name, /*HasOptNone*/ false,
/*AttrOnCallSite*/ true, FuncAttrs);
AttrList = llvm::AttributeList::get(
getLLVMContext(), llvm::AttributeList::FunctionIndex, FuncAttrs);
}
3 changes: 3 additions & 0 deletions clang/lib/CodeGen/CodeGenModule.h
Original file line number Diff line number Diff line change
Expand Up @@ -1591,6 +1591,9 @@ class CodeGenModule : public CodeGenTypeCache {
/// because we'll lose all important information after each repl.
void moveLazyEmissionStates(CodeGenModule *NewBuilder);

void getFPAccuracyFuncAttributes(StringRef Name,
llvm::AttributeList &AttrList);

private:
llvm::Constant *GetOrCreateLLVMFunction(
StringRef MangledName, llvm::Type *Ty, GlobalDecl D, bool ForVTable,
Expand Down
21 changes: 21 additions & 0 deletions clang/lib/Driver/ToolChains/Clang.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -5981,6 +5981,27 @@ void Clang::ConstructJob(Compilation &C, const JobAction &JA,
<< A->getAsString(Args) << TripleStr;
}

std::string FpAccuracyAttr;
auto RenderFPAccuracyOptions = [&FpAccuracyAttr](const Twine &optStr) {
optStr.isSingleStringRef();
if (FpAccuracyAttr.empty())
FpAccuracyAttr = std::move(std::string("-ffp-accuracy-attr="));
else
FpAccuracyAttr += " ";
FpAccuracyAttr += optStr.str();
};
for (const Arg *A : Args) {
unsigned OptionID = A->getOption().getID();
switch (OptionID) {
case options::OPT_ffp_accuracy_EQ:
RenderFPAccuracyOptions(A->getValue());
A->claim();
break;
}
}
if (!FpAccuracyAttr.empty())
CmdArgs.push_back(Args.MakeArgString(FpAccuracyAttr));

// Decide whether to use verbose asm. Verbose assembly is the default on
// toolchains which have the integrated assembler on by default.
bool IsIntegratedAssemblerDefault = TC.IsIntegratedAssemblerDefault();
Expand Down
76 changes: 76 additions & 0 deletions clang/lib/Frontend/CompilerInvocation.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -3323,6 +3323,21 @@ void CompilerInvocation::GenerateLangArgs(const LangOptions &Opts,
#include "clang/Driver/Options.inc"
#undef LANG_OPTION_WITH_MARSHALLING

for (const auto &M : Opts.FPAccuracyMap) {
SmallString<128> S;
S += M.second;
GenerateArg(Args, OPT_ffp_accuracy_attr_EQ, S, SA);
}
for (const auto &F : Opts.FPAccuracyFuncMap) {
for (const auto &C : F.second) {
SmallString<128> S;
S += C.second;
S += ':';
S += F.first;
GenerateArg(Args, OPT_ffp_accuracy_attr_EQ, S, SA);
}
}

// The '-fcf-protection=' option is generated by CodeGenOpts generator.

if (Opts.ObjC) {
Expand Down Expand Up @@ -3565,6 +3580,65 @@ void CompilerInvocation::GenerateLangArgs(const LangOptions &Opts,
GenerateArg(Args, OPT_fno_gpu_rdc, SA);
}

void CompilerInvocation::ParseFpAccuracyArgs(LangOptions &Opts, ArgList &Args,
DiagnosticsEngine &Diags) {
for (StringRef Values : Args.getAllArgValues(OPT_ffp_accuracy_attr_EQ)) {
SmallVector<StringRef, 8> ValuesArr;
Values.split(ValuesArr, ' ');
for (const auto &Val : ValuesArr) {
SmallVector<StringRef, 3> ValElement;
Val.split(ValElement, ':');
// The option is of the form -ffp-accuracy=value.
if (ValElement.size() == 1) {
StringRef FPAccuracy = ValElement[0];
if (!(FPAccuracy.equals("default") || FPAccuracy.equals("high") ||
FPAccuracy.equals("low") || FPAccuracy.equals("medium") ||
FPAccuracy.equals("sycl") || FPAccuracy.equals("cuda")))
Diags.Report(diag::err_drv_unsupported_option_argument)
<< "ffp-accuracy" << FPAccuracy;
std::pair<LangOptions::FPAccuracyMapTy::iterator, bool> Result =
Opts.FPAccuracyMap.insert({"fp-accuracy", FPAccuracy.str()});
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't understand what FPAccuracyMap is mapping. What is the difference between this and FPAccuracyFuncMap?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

FPAccuracyMap creates a map between fp-accuracy and the value of accuracy given of the command line.
For example: clang -c -ffp-accuracy=high t1.c
will create FPAccuracyMap with:
[fp-accuracy -> high]

FPAccuracyFuncMap will create a map between the functions on the command line and an FPAccuracyMap.
For example: clang -c -ffp-accuracy=high:[f1,f2] -ffp-accuracy=low:[f3] t1.c
will create a FPAccuracyFunMap with:
[f1 -> [fp-accuracy ->high]]
[f2 -> [fp-accuracy ->high]]
[f3 -> [fp-accuracy ->low]]

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

So is there ever more than one entry in FPAccuracyMap?

if (!Result.second) {
Diags.Report(diag::warn_all_fp_accuray_already_set)
<< Result.first->second;
}
}
// The option is of the form -ffp-accuracy=value:[f1, ... fn].
if (ValElement.size() == 2) {
SmallVector<StringRef, 30> FuncList;
ValElement[1].split(FuncList, ',');
for (StringRef FuncName : FuncList) {
if (FuncName.front() == '[')
FuncName = FuncName.drop_front(1);
if (FuncName.back() == ']')
FuncName = FuncName.drop_back(1);
auto FuncMapIt = Opts.FPAccuracyFuncMap.find(FuncName.str());
if (FuncMapIt != Opts.FPAccuracyFuncMap.end()) {
// The math function has already been assigned an fp accuracy.
std::pair<LangOptions::FPAccuracyMapTy::iterator, bool> Result =
FuncMapIt->second.insert({"fp-accuracy", ValElement[0].str()});
if (!Result.second) {
Diags.Report(diag::warn_function_fp_accuray_already_set)
<< Result.first->second << FuncName.str();
}
} else {
LangOptions::FPAccuracyMapTy FPAccMap;
StringRef FPAccuracy = ValElement[0];
if (!(FPAccuracy.equals("default") || FPAccuracy.equals("high") ||
FPAccuracy.equals("low") || FPAccuracy.equals("medium") ||
FPAccuracy.equals("sycl") || FPAccuracy.equals("cuda")))
Diags.Report(diag::err_drv_unsupported_option_argument)
<< "ffp-accuracy" << FPAccuracy;
FPAccMap.insert({"fp-accuracy", FPAccuracy.str()});
Opts.FPAccuracyFuncMap.insert(
{FuncName.str(), std::move(FPAccMap)});
}
}
}
}
}
}

bool CompilerInvocation::ParseLangArgs(LangOptions &Opts, ArgList &Args,
InputKind IK, const llvm::Triple &T,
std::vector<std::string> &Includes,
Expand Down Expand Up @@ -3721,6 +3795,8 @@ bool CompilerInvocation::ParseLangArgs(LangOptions &Opts, ArgList &Args,
#include "clang/Driver/Options.inc"
#undef LANG_OPTION_WITH_MARSHALLING

ParseFpAccuracyArgs(Opts, Args, Diags);

if (const Arg *A = Args.getLastArg(OPT_fcf_protection_EQ)) {
StringRef Name = A->getValue();
if (Name == "full" || Name == "branch") {
Expand Down
Loading