1//===-- Flang.cpp - Flang+LLVM ToolChain Implementations --------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
9#include "Flang.h"
10#include "Arch/RISCV.h"
11#include "CommonArgs.h"
12
13#include "clang/Basic/CodeGenOptions.h"
14#include "clang/Driver/Options.h"
15#include "llvm/Frontend/Debug/Options.h"
16#include "llvm/Support/FileSystem.h"
17#include "llvm/Support/Path.h"
18#include "llvm/TargetParser/RISCVISAInfo.h"
19#include "llvm/TargetParser/RISCVTargetParser.h"
20
21#include <cassert>
22
23using namespace clang::driver;
24using namespace clang::driver::tools;
25using namespace clang;
26using namespace llvm::opt;
27
28/// Add -x lang to \p CmdArgs for \p Input.
29static void addDashXForInput(const ArgList &Args, const InputInfo &Input,
30 ArgStringList &CmdArgs) {
31 CmdArgs.push_back(Elt: "-x");
32 // Map the driver type to the frontend type.
33 CmdArgs.push_back(Elt: types::getTypeName(Id: Input.getType()));
34}
35
36void Flang::addFortranDialectOptions(const ArgList &Args,
37 ArgStringList &CmdArgs) const {
38 Args.addAllArgs(
39 CmdArgs, {options::OPT_ffixed_form, options::OPT_ffree_form,
40 options::OPT_ffixed_line_length_EQ, options::OPT_fopenacc,
41 options::OPT_finput_charset_EQ, options::OPT_fimplicit_none,
42 options::OPT_fno_implicit_none, options::OPT_fbackslash,
43 options::OPT_fno_backslash, options::OPT_flogical_abbreviations,
44 options::OPT_fno_logical_abbreviations,
45 options::OPT_fxor_operator, options::OPT_fno_xor_operator,
46 options::OPT_falternative_parameter_statement,
47 options::OPT_fdefault_real_8, options::OPT_fdefault_integer_8,
48 options::OPT_fdefault_double_8, options::OPT_flarge_sizes,
49 options::OPT_fno_automatic});
50}
51
52void Flang::addPreprocessingOptions(const ArgList &Args,
53 ArgStringList &CmdArgs) const {
54 Args.addAllArgs(CmdArgs,
55 {options::OPT_P, options::OPT_D, options::OPT_U,
56 options::OPT_I, options::OPT_cpp, options::OPT_nocpp});
57}
58
59/// @C shouldLoopVersion
60///
61/// Check if Loop Versioning should be enabled.
62/// We look for the last of one of the following:
63/// -Ofast, -O4, -O<number> and -f[no-]version-loops-for-stride.
64/// Loop versioning is disabled if the last option is
65/// -fno-version-loops-for-stride.
66/// Loop versioning is enabled if the last option is one of:
67/// -floop-versioning
68/// -Ofast
69/// -O4
70/// -O3
71/// For all other cases, loop versioning is is disabled.
72///
73/// The gfortran compiler automatically enables the option for -O3 or -Ofast.
74///
75/// @return true if loop-versioning should be enabled, otherwise false.
76static bool shouldLoopVersion(const ArgList &Args) {
77 const Arg *LoopVersioningArg = Args.getLastArg(
78 options::OPT_Ofast, options::OPT_O, options::OPT_O4,
79 options::OPT_floop_versioning, options::OPT_fno_loop_versioning);
80 if (!LoopVersioningArg)
81 return false;
82
83 if (LoopVersioningArg->getOption().matches(options::ID: OPT_fno_loop_versioning))
84 return false;
85
86 if (LoopVersioningArg->getOption().matches(options::ID: OPT_floop_versioning))
87 return true;
88
89 if (LoopVersioningArg->getOption().matches(options::ID: OPT_Ofast) ||
90 LoopVersioningArg->getOption().matches(options::ID: OPT_O4))
91 return true;
92
93 if (LoopVersioningArg->getOption().matches(options::ID: OPT_O)) {
94 StringRef S(LoopVersioningArg->getValue());
95 unsigned OptLevel = 0;
96 // Note -Os or Oz woould "fail" here, so return false. Which is the
97 // desiered behavior.
98 if (S.getAsInteger(Radix: 10, Result&: OptLevel))
99 return false;
100
101 return OptLevel > 2;
102 }
103
104 llvm_unreachable("We should not end up here");
105 return false;
106}
107
108void Flang::addOtherOptions(const ArgList &Args, ArgStringList &CmdArgs) const {
109 Args.addAllArgs(CmdArgs,
110 {options::OPT_module_dir, options::OPT_fdebug_module_writer,
111 options::OPT_fintrinsic_modules_path, options::OPT_pedantic,
112 options::OPT_std_EQ, options::OPT_W_Joined,
113 options::OPT_fconvert_EQ, options::OPT_fpass_plugin_EQ,
114 options::OPT_funderscoring, options::OPT_fno_underscoring});
115
116 llvm::codegenoptions::DebugInfoKind DebugInfoKind;
117 if (Args.hasArg(options::OPT_gN_Group)) {
118 Arg *gNArg = Args.getLastArg(options::OPT_gN_Group);
119 DebugInfoKind = debugLevelToInfoKind(A: *gNArg);
120 } else if (Args.hasArg(options::OPT_g_Flag)) {
121 DebugInfoKind = llvm::codegenoptions::FullDebugInfo;
122 } else {
123 DebugInfoKind = llvm::codegenoptions::NoDebugInfo;
124 }
125 addDebugInfoKind(CmdArgs, DebugInfoKind);
126}
127
128void Flang::addCodegenOptions(const ArgList &Args,
129 ArgStringList &CmdArgs) const {
130 Arg *stackArrays =
131 Args.getLastArg(options::OPT_Ofast, options::OPT_fstack_arrays,
132 options::OPT_fno_stack_arrays);
133 if (stackArrays &&
134 !stackArrays->getOption().matches(options::OPT_fno_stack_arrays))
135 CmdArgs.push_back(Elt: "-fstack-arrays");
136
137 if (shouldLoopVersion(Args))
138 CmdArgs.push_back(Elt: "-fversion-loops-for-stride");
139
140 Args.addAllArgs(CmdArgs, {options::OPT_flang_experimental_hlfir,
141 options::OPT_flang_deprecated_no_hlfir,
142 options::OPT_fno_ppc_native_vec_elem_order,
143 options::OPT_fppc_native_vec_elem_order});
144}
145
146void Flang::addPicOptions(const ArgList &Args, ArgStringList &CmdArgs) const {
147 // ParsePICArgs parses -fPIC/-fPIE and their variants and returns a tuple of
148 // (RelocationModel, PICLevel, IsPIE).
149 llvm::Reloc::Model RelocationModel;
150 unsigned PICLevel;
151 bool IsPIE;
152 std::tie(args&: RelocationModel, args&: PICLevel, args&: IsPIE) =
153 ParsePICArgs(ToolChain: getToolChain(), Args);
154
155 if (auto *RMName = RelocationModelName(Model: RelocationModel)) {
156 CmdArgs.push_back(Elt: "-mrelocation-model");
157 CmdArgs.push_back(Elt: RMName);
158 }
159 if (PICLevel > 0) {
160 CmdArgs.push_back(Elt: "-pic-level");
161 CmdArgs.push_back(Elt: PICLevel == 1 ? "1" : "2");
162 if (IsPIE)
163 CmdArgs.push_back(Elt: "-pic-is-pie");
164 }
165}
166
167void Flang::AddAArch64TargetArgs(const ArgList &Args,
168 ArgStringList &CmdArgs) const {
169 // Handle -msve_vector_bits=<bits>
170 if (Arg *A = Args.getLastArg(options::OPT_msve_vector_bits_EQ)) {
171 StringRef Val = A->getValue();
172 const Driver &D = getToolChain().getDriver();
173 if (Val.equals(RHS: "128") || Val.equals(RHS: "256") || Val.equals(RHS: "512") ||
174 Val.equals(RHS: "1024") || Val.equals(RHS: "2048") || Val.equals(RHS: "128+") ||
175 Val.equals(RHS: "256+") || Val.equals(RHS: "512+") || Val.equals(RHS: "1024+") ||
176 Val.equals(RHS: "2048+")) {
177 unsigned Bits = 0;
178 if (!Val.consume_back(Suffix: "+")) {
179 [[maybe_unused]] bool Invalid = Val.getAsInteger(Radix: 10, Result&: Bits);
180 assert(!Invalid && "Failed to parse value");
181 CmdArgs.push_back(
182 Elt: Args.MakeArgString(Str: "-mvscale-max=" + llvm::Twine(Bits / 128)));
183 }
184
185 [[maybe_unused]] bool Invalid = Val.getAsInteger(Radix: 10, Result&: Bits);
186 assert(!Invalid && "Failed to parse value");
187 CmdArgs.push_back(
188 Elt: Args.MakeArgString(Str: "-mvscale-min=" + llvm::Twine(Bits / 128)));
189 // Silently drop requests for vector-length agnostic code as it's implied.
190 } else if (!Val.equals("scalable"))
191 // Handle the unsupported values passed to msve-vector-bits.
192 D.Diag(diag::err_drv_unsupported_option_argument)
193 << A->getSpelling() << Val;
194 }
195}
196
197void Flang::AddRISCVTargetArgs(const ArgList &Args,
198 ArgStringList &CmdArgs) const {
199 const llvm::Triple &Triple = getToolChain().getTriple();
200 // Handle -mrvv-vector-bits=<bits>
201 if (Arg *A = Args.getLastArg(options::OPT_mrvv_vector_bits_EQ)) {
202 StringRef Val = A->getValue();
203 const Driver &D = getToolChain().getDriver();
204
205 // Get minimum VLen from march.
206 unsigned MinVLen = 0;
207 StringRef Arch = riscv::getRISCVArch(Args, Triple);
208 auto ISAInfo = llvm::RISCVISAInfo::parseArchString(
209 Arch, /*EnableExperimentalExtensions*/ EnableExperimentalExtension: true);
210 // Ignore parsing error.
211 if (!errorToBool(Err: ISAInfo.takeError()))
212 MinVLen = (*ISAInfo)->getMinVLen();
213
214 // If the value is "zvl", use MinVLen from march. Otherwise, try to parse
215 // as integer as long as we have a MinVLen.
216 unsigned Bits = 0;
217 if (Val.equals(RHS: "zvl") && MinVLen >= llvm::RISCV::RVVBitsPerBlock) {
218 Bits = MinVLen;
219 } else if (!Val.getAsInteger(Radix: 10, Result&: Bits)) {
220 // Only accept power of 2 values beteen RVVBitsPerBlock and 65536 that
221 // at least MinVLen.
222 if (Bits < MinVLen || Bits < llvm::RISCV::RVVBitsPerBlock ||
223 Bits > 65536 || !llvm::isPowerOf2_32(Value: Bits))
224 Bits = 0;
225 }
226
227 // If we got a valid value try to use it.
228 if (Bits != 0) {
229 unsigned VScaleMin = Bits / llvm::RISCV::RVVBitsPerBlock;
230 CmdArgs.push_back(
231 Elt: Args.MakeArgString(Str: "-mvscale-max=" + llvm::Twine(VScaleMin)));
232 CmdArgs.push_back(
233 Elt: Args.MakeArgString(Str: "-mvscale-min=" + llvm::Twine(VScaleMin)));
234 } else if (!Val.equals(RHS: "scalable")) {
235 // Handle the unsupported values passed to mrvv-vector-bits.
236 D.Diag(diag::err_drv_unsupported_option_argument)
237 << A->getSpelling() << Val;
238 }
239 }
240}
241
242void Flang::AddX86_64TargetArgs(const ArgList &Args,
243 ArgStringList &CmdArgs) const {
244 if (Arg *A = Args.getLastArg(options::OPT_masm_EQ)) {
245 StringRef Value = A->getValue();
246 if (Value == "intel" || Value == "att") {
247 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-mllvm"));
248 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-x86-asm-syntax=" + Value));
249 } else {
250 getToolChain().getDriver().Diag(diag::err_drv_unsupported_option_argument)
251 << A->getSpelling() << Value;
252 }
253 }
254}
255
256static void addVSDefines(const ToolChain &TC, const ArgList &Args,
257 ArgStringList &CmdArgs) {
258
259 unsigned ver = 0;
260 const VersionTuple vt = TC.computeMSVCVersion(D: nullptr, Args);
261 ver = vt.getMajor() * 10000000 + vt.getMinor().value_or(u: 0) * 100000 +
262 vt.getSubminor().value_or(u: 0);
263 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-D_MSC_VER=" + Twine(ver / 100000)));
264 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-D_MSC_FULL_VER=" + Twine(ver)));
265 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-D_WIN32"));
266
267 const llvm::Triple &triple = TC.getTriple();
268 if (triple.isAArch64()) {
269 CmdArgs.push_back(Elt: "-D_M_ARM64=1");
270 } else if (triple.isX86() && triple.isArch32Bit()) {
271 CmdArgs.push_back(Elt: "-D_M_IX86=600");
272 } else if (triple.isX86() && triple.isArch64Bit()) {
273 CmdArgs.push_back(Elt: "-D_M_X64=100");
274 } else {
275 llvm_unreachable(
276 "Flang on Windows only supports X86_32, X86_64 and AArch64");
277 }
278}
279
280static void processVSRuntimeLibrary(const ToolChain &TC, const ArgList &Args,
281 ArgStringList &CmdArgs) {
282 assert(TC.getTriple().isKnownWindowsMSVCEnvironment() &&
283 "can only add VS runtime library on Windows!");
284 // if -fno-fortran-main has been passed, skip linking Fortran_main.a
285 bool LinkFortranMain = !Args.hasArg(options::OPT_no_fortran_main);
286 if (TC.getTriple().isKnownWindowsMSVCEnvironment()) {
287 CmdArgs.push_back(Elt: Args.MakeArgString(
288 Str: "--dependent-lib=" + TC.getCompilerRTBasename(Args, Component: "builtins")));
289 }
290 unsigned RTOptionID = options::OPT__SLASH_MT;
291 if (auto *rtl = Args.getLastArg(options::OPT_fms_runtime_lib_EQ)) {
292 RTOptionID = llvm::StringSwitch<unsigned>(rtl->getValue())
293 .Case("static", options::OPT__SLASH_MT)
294 .Case("static_dbg", options::OPT__SLASH_MTd)
295 .Case("dll", options::OPT__SLASH_MD)
296 .Case("dll_dbg", options::OPT__SLASH_MDd)
297 .Default(options::OPT__SLASH_MT);
298 }
299 switch (RTOptionID) {
300 case options::OPT__SLASH_MT:
301 CmdArgs.push_back(Elt: "-D_MT");
302 CmdArgs.push_back(Elt: "--dependent-lib=libcmt");
303 if (LinkFortranMain)
304 CmdArgs.push_back(Elt: "--dependent-lib=Fortran_main.static.lib");
305 CmdArgs.push_back(Elt: "--dependent-lib=FortranRuntime.static.lib");
306 CmdArgs.push_back(Elt: "--dependent-lib=FortranDecimal.static.lib");
307 break;
308 case options::OPT__SLASH_MTd:
309 CmdArgs.push_back(Elt: "-D_MT");
310 CmdArgs.push_back(Elt: "-D_DEBUG");
311 CmdArgs.push_back(Elt: "--dependent-lib=libcmtd");
312 if (LinkFortranMain)
313 CmdArgs.push_back(Elt: "--dependent-lib=Fortran_main.static_dbg.lib");
314 CmdArgs.push_back(Elt: "--dependent-lib=FortranRuntime.static_dbg.lib");
315 CmdArgs.push_back(Elt: "--dependent-lib=FortranDecimal.static_dbg.lib");
316 break;
317 case options::OPT__SLASH_MD:
318 CmdArgs.push_back(Elt: "-D_MT");
319 CmdArgs.push_back(Elt: "-D_DLL");
320 CmdArgs.push_back(Elt: "--dependent-lib=msvcrt");
321 if (LinkFortranMain)
322 CmdArgs.push_back(Elt: "--dependent-lib=Fortran_main.dynamic.lib");
323 CmdArgs.push_back(Elt: "--dependent-lib=FortranRuntime.dynamic.lib");
324 CmdArgs.push_back(Elt: "--dependent-lib=FortranDecimal.dynamic.lib");
325 break;
326 case options::OPT__SLASH_MDd:
327 CmdArgs.push_back(Elt: "-D_MT");
328 CmdArgs.push_back(Elt: "-D_DEBUG");
329 CmdArgs.push_back(Elt: "-D_DLL");
330 CmdArgs.push_back(Elt: "--dependent-lib=msvcrtd");
331 if (LinkFortranMain)
332 CmdArgs.push_back(Elt: "--dependent-lib=Fortran_main.dynamic_dbg.lib");
333 CmdArgs.push_back(Elt: "--dependent-lib=FortranRuntime.dynamic_dbg.lib");
334 CmdArgs.push_back(Elt: "--dependent-lib=FortranDecimal.dynamic_dbg.lib");
335 break;
336 }
337}
338
339void Flang::AddAMDGPUTargetArgs(const ArgList &Args,
340 ArgStringList &CmdArgs) const {
341 if (Arg *A = Args.getLastArg(options::OPT_mcode_object_version_EQ)) {
342 StringRef Val = A->getValue();
343 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-mcode-object-version=" + Val));
344 }
345}
346
347void Flang::addTargetOptions(const ArgList &Args,
348 ArgStringList &CmdArgs) const {
349 const ToolChain &TC = getToolChain();
350 const llvm::Triple &Triple = TC.getEffectiveTriple();
351 const Driver &D = TC.getDriver();
352
353 std::string CPU = getCPUName(D, Args, T: Triple);
354 if (!CPU.empty()) {
355 CmdArgs.push_back(Elt: "-target-cpu");
356 CmdArgs.push_back(Elt: Args.MakeArgString(Str: CPU));
357 }
358
359 addOutlineAtomicsArgs(D, TC: getToolChain(), Args, CmdArgs, Triple);
360
361 // Add the target features.
362 switch (TC.getArch()) {
363 default:
364 break;
365 case llvm::Triple::aarch64:
366 getTargetFeatures(D, Triple, Args, CmdArgs, /*ForAs*/ ForAS: false);
367 AddAArch64TargetArgs(Args, CmdArgs);
368 break;
369
370 case llvm::Triple::r600:
371 case llvm::Triple::amdgcn:
372 getTargetFeatures(D, Triple, Args, CmdArgs, /*ForAs*/ ForAS: false);
373 AddAMDGPUTargetArgs(Args, CmdArgs);
374 break;
375 case llvm::Triple::riscv64:
376 getTargetFeatures(D, Triple, Args, CmdArgs, /*ForAs*/ ForAS: false);
377 AddRISCVTargetArgs(Args, CmdArgs);
378 break;
379 case llvm::Triple::x86_64:
380 getTargetFeatures(D, Triple, Args, CmdArgs, /*ForAs*/ ForAS: false);
381 AddX86_64TargetArgs(Args, CmdArgs);
382 break;
383 }
384
385 if (Arg *A = Args.getLastArg(options::OPT_fveclib)) {
386 StringRef Name = A->getValue();
387 if (Name == "SVML") {
388 if (Triple.getArch() != llvm::Triple::x86 &&
389 Triple.getArch() != llvm::Triple::x86_64)
390 D.Diag(diag::err_drv_unsupported_opt_for_target)
391 << Name << Triple.getArchName();
392 } else if (Name == "LIBMVEC-X86") {
393 if (Triple.getArch() != llvm::Triple::x86 &&
394 Triple.getArch() != llvm::Triple::x86_64)
395 D.Diag(diag::err_drv_unsupported_opt_for_target)
396 << Name << Triple.getArchName();
397 } else if (Name == "SLEEF" || Name == "ArmPL") {
398 if (Triple.getArch() != llvm::Triple::aarch64 &&
399 Triple.getArch() != llvm::Triple::aarch64_be)
400 D.Diag(diag::err_drv_unsupported_opt_for_target)
401 << Name << Triple.getArchName();
402 }
403
404 if (Triple.isOSDarwin()) {
405 // flang doesn't currently suport nostdlib, nodefaultlibs. Adding these
406 // here incase they are added someday
407 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
408 if (A->getValue() == StringRef{"Accelerate"}) {
409 CmdArgs.push_back(Elt: "-framework");
410 CmdArgs.push_back(Elt: "Accelerate");
411 }
412 }
413 }
414 A->render(Args, Output&: CmdArgs);
415 }
416
417 if (Triple.isKnownWindowsMSVCEnvironment()) {
418 processVSRuntimeLibrary(TC, Args, CmdArgs);
419 addVSDefines(TC, Args, CmdArgs);
420 }
421
422 // TODO: Add target specific flags, ABI, mtune option etc.
423}
424
425void Flang::addOffloadOptions(Compilation &C, const InputInfoList &Inputs,
426 const JobAction &JA, const ArgList &Args,
427 ArgStringList &CmdArgs) const {
428 bool IsOpenMPDevice = JA.isDeviceOffloading(OKind: Action::OFK_OpenMP);
429 bool IsHostOffloadingAction = JA.isHostOffloading(OKind: Action::OFK_OpenMP) ||
430 JA.isHostOffloading(OKind: C.getActiveOffloadKinds());
431
432 // Skips the primary input file, which is the input file that the compilation
433 // proccess will be executed upon (e.g. the host bitcode file) and
434 // adds other secondary input (e.g. device bitcode files for embedding to the
435 // -fembed-offload-object argument or the host IR file for proccessing
436 // during device compilation to the fopenmp-host-ir-file-path argument via
437 // OpenMPDeviceInput). This is condensed logic from the ConstructJob
438 // function inside of the Clang driver for pushing on further input arguments
439 // needed for offloading during various phases of compilation.
440 for (size_t i = 1; i < Inputs.size(); ++i) {
441 if (Inputs[i].getType() == types::TY_Nothing) {
442 // contains nothing, so it's skippable
443 } else if (IsHostOffloadingAction) {
444 CmdArgs.push_back(
445 Elt: Args.MakeArgString(Str: "-fembed-offload-object=" +
446 getToolChain().getInputFilename(Input: Inputs[i])));
447 } else if (IsOpenMPDevice) {
448 if (Inputs[i].getFilename()) {
449 CmdArgs.push_back(Elt: "-fopenmp-host-ir-file-path");
450 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Inputs[i].getFilename()));
451 } else {
452 llvm_unreachable("missing openmp host-ir file for device offloading");
453 }
454 } else {
455 llvm_unreachable(
456 "unexpectedly given multiple inputs or given unknown input");
457 }
458 }
459
460 if (IsOpenMPDevice) {
461 // -fopenmp-is-target-device is passed along to tell the frontend that it is
462 // generating code for a device, so that only the relevant code is emitted.
463 CmdArgs.push_back(Elt: "-fopenmp-is-target-device");
464
465 // When in OpenMP offloading mode, enable debugging on the device.
466 Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_target_debug_EQ);
467 if (Args.hasFlag(options::OPT_fopenmp_target_debug,
468 options::OPT_fno_openmp_target_debug, /*Default=*/false))
469 CmdArgs.push_back(Elt: "-fopenmp-target-debug");
470
471 // When in OpenMP offloading mode, forward assumptions information about
472 // thread and team counts in the device.
473 if (Args.hasFlag(options::OPT_fopenmp_assume_teams_oversubscription,
474 options::OPT_fno_openmp_assume_teams_oversubscription,
475 /*Default=*/false))
476 CmdArgs.push_back(Elt: "-fopenmp-assume-teams-oversubscription");
477 if (Args.hasFlag(options::OPT_fopenmp_assume_threads_oversubscription,
478 options::OPT_fno_openmp_assume_threads_oversubscription,
479 /*Default=*/false))
480 CmdArgs.push_back(Elt: "-fopenmp-assume-threads-oversubscription");
481 if (Args.hasArg(options::OPT_fopenmp_assume_no_thread_state))
482 CmdArgs.push_back(Elt: "-fopenmp-assume-no-thread-state");
483 if (Args.hasArg(options::OPT_fopenmp_assume_no_nested_parallelism))
484 CmdArgs.push_back(Elt: "-fopenmp-assume-no-nested-parallelism");
485 if (Args.hasArg(options::OPT_nogpulib))
486 CmdArgs.push_back(Elt: "-nogpulib");
487 }
488}
489
490static void addFloatingPointOptions(const Driver &D, const ArgList &Args,
491 ArgStringList &CmdArgs) {
492 StringRef FPContract;
493 bool HonorINFs = true;
494 bool HonorNaNs = true;
495 bool ApproxFunc = false;
496 bool SignedZeros = true;
497 bool AssociativeMath = false;
498 bool ReciprocalMath = false;
499
500 if (const Arg *A = Args.getLastArg(options::OPT_ffp_contract)) {
501 const StringRef Val = A->getValue();
502 if (Val == "fast" || Val == "off") {
503 FPContract = Val;
504 } else if (Val == "on") {
505 // Warn instead of error because users might have makefiles written for
506 // gfortran (which accepts -ffp-contract=on)
507 D.Diag(diag::warn_drv_unsupported_option_for_flang)
508 << Val << A->getOption().getName() << "off";
509 FPContract = "off";
510 } else
511 // Clang's "fast-honor-pragmas" option is not supported because it is
512 // non-standard
513 D.Diag(diag::err_drv_unsupported_option_argument)
514 << A->getSpelling() << Val;
515 }
516
517 for (const Arg *A : Args) {
518 auto optId = A->getOption().getID();
519 switch (optId) {
520 // if this isn't an FP option, skip the claim below
521 default:
522 continue;
523
524 case options::OPT_fhonor_infinities:
525 HonorINFs = true;
526 break;
527 case options::OPT_fno_honor_infinities:
528 HonorINFs = false;
529 break;
530 case options::OPT_fhonor_nans:
531 HonorNaNs = true;
532 break;
533 case options::OPT_fno_honor_nans:
534 HonorNaNs = false;
535 break;
536 case options::OPT_fapprox_func:
537 ApproxFunc = true;
538 break;
539 case options::OPT_fno_approx_func:
540 ApproxFunc = false;
541 break;
542 case options::OPT_fsigned_zeros:
543 SignedZeros = true;
544 break;
545 case options::OPT_fno_signed_zeros:
546 SignedZeros = false;
547 break;
548 case options::OPT_fassociative_math:
549 AssociativeMath = true;
550 break;
551 case options::OPT_fno_associative_math:
552 AssociativeMath = false;
553 break;
554 case options::OPT_freciprocal_math:
555 ReciprocalMath = true;
556 break;
557 case options::OPT_fno_reciprocal_math:
558 ReciprocalMath = false;
559 break;
560 case options::OPT_Ofast:
561 [[fallthrough]];
562 case options::OPT_ffast_math:
563 HonorINFs = false;
564 HonorNaNs = false;
565 AssociativeMath = true;
566 ReciprocalMath = true;
567 ApproxFunc = true;
568 SignedZeros = false;
569 FPContract = "fast";
570 break;
571 case options::OPT_fno_fast_math:
572 HonorINFs = true;
573 HonorNaNs = true;
574 AssociativeMath = false;
575 ReciprocalMath = false;
576 ApproxFunc = false;
577 SignedZeros = true;
578 // -fno-fast-math should undo -ffast-math so I return FPContract to the
579 // default. It is important to check it is "fast" (the default) so that
580 // --ffp-contract=off -fno-fast-math --> -ffp-contract=off
581 if (FPContract == "fast")
582 FPContract = "";
583 break;
584 }
585
586 // If we handled this option claim it
587 A->claim();
588 }
589
590 if (!HonorINFs && !HonorNaNs && AssociativeMath && ReciprocalMath &&
591 ApproxFunc && !SignedZeros &&
592 (FPContract == "fast" || FPContract.empty())) {
593 CmdArgs.push_back(Elt: "-ffast-math");
594 return;
595 }
596
597 if (!FPContract.empty())
598 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-ffp-contract=" + FPContract));
599
600 if (!HonorINFs)
601 CmdArgs.push_back(Elt: "-menable-no-infs");
602
603 if (!HonorNaNs)
604 CmdArgs.push_back(Elt: "-menable-no-nans");
605
606 if (ApproxFunc)
607 CmdArgs.push_back(Elt: "-fapprox-func");
608
609 if (!SignedZeros)
610 CmdArgs.push_back(Elt: "-fno-signed-zeros");
611
612 if (AssociativeMath && !SignedZeros)
613 CmdArgs.push_back(Elt: "-mreassociate");
614
615 if (ReciprocalMath)
616 CmdArgs.push_back(Elt: "-freciprocal-math");
617}
618
619static void renderRemarksOptions(const ArgList &Args, ArgStringList &CmdArgs,
620 const InputInfo &Input) {
621 StringRef Format = "yaml";
622 if (const Arg *A = Args.getLastArg(options::OPT_fsave_optimization_record_EQ))
623 Format = A->getValue();
624
625 CmdArgs.push_back(Elt: "-opt-record-file");
626
627 const Arg *A = Args.getLastArg(options::OPT_foptimization_record_file_EQ);
628 if (A) {
629 CmdArgs.push_back(Elt: A->getValue());
630 } else {
631 SmallString<128> F;
632
633 if (Args.hasArg(options::OPT_c) || Args.hasArg(options::OPT_S)) {
634 if (Arg *FinalOutput = Args.getLastArg(options::OPT_o))
635 F = FinalOutput->getValue();
636 }
637
638 if (F.empty()) {
639 // Use the input filename.
640 F = llvm::sys::path::stem(path: Input.getBaseInput());
641 }
642
643 SmallString<32> Extension;
644 Extension += "opt.";
645 Extension += Format;
646
647 llvm::sys::path::replace_extension(path&: F, extension: Extension);
648 CmdArgs.push_back(Elt: Args.MakeArgString(Str: F));
649 }
650
651 if (const Arg *A =
652 Args.getLastArg(options::OPT_foptimization_record_passes_EQ)) {
653 CmdArgs.push_back(Elt: "-opt-record-passes");
654 CmdArgs.push_back(Elt: A->getValue());
655 }
656
657 if (!Format.empty()) {
658 CmdArgs.push_back(Elt: "-opt-record-format");
659 CmdArgs.push_back(Elt: Format.data());
660 }
661}
662
663void Flang::ConstructJob(Compilation &C, const JobAction &JA,
664 const InputInfo &Output, const InputInfoList &Inputs,
665 const ArgList &Args, const char *LinkingOutput) const {
666 const auto &TC = getToolChain();
667 const llvm::Triple &Triple = TC.getEffectiveTriple();
668 const std::string &TripleStr = Triple.getTriple();
669
670 const Driver &D = TC.getDriver();
671 ArgStringList CmdArgs;
672 DiagnosticsEngine &Diags = D.getDiags();
673
674 // Invoke ourselves in -fc1 mode.
675 CmdArgs.push_back(Elt: "-fc1");
676
677 // Add the "effective" target triple.
678 CmdArgs.push_back(Elt: "-triple");
679 CmdArgs.push_back(Elt: Args.MakeArgString(Str: TripleStr));
680
681 if (isa<PreprocessJobAction>(Val: JA)) {
682 CmdArgs.push_back(Elt: "-E");
683 if (Args.getLastArg(options::OPT_dM)) {
684 CmdArgs.push_back(Elt: "-dM");
685 }
686 } else if (isa<CompileJobAction>(Val: JA) || isa<BackendJobAction>(Val: JA)) {
687 if (JA.getType() == types::TY_Nothing) {
688 CmdArgs.push_back(Elt: "-fsyntax-only");
689 } else if (JA.getType() == types::TY_AST) {
690 CmdArgs.push_back(Elt: "-emit-ast");
691 } else if (JA.getType() == types::TY_LLVM_IR ||
692 JA.getType() == types::TY_LTO_IR) {
693 CmdArgs.push_back(Elt: "-emit-llvm");
694 } else if (JA.getType() == types::TY_LLVM_BC ||
695 JA.getType() == types::TY_LTO_BC) {
696 CmdArgs.push_back(Elt: "-emit-llvm-bc");
697 } else if (JA.getType() == types::TY_PP_Asm) {
698 CmdArgs.push_back(Elt: "-S");
699 } else {
700 assert(false && "Unexpected output type!");
701 }
702 } else if (isa<AssembleJobAction>(Val: JA)) {
703 CmdArgs.push_back(Elt: "-emit-obj");
704 } else {
705 assert(false && "Unexpected action class for Flang tool.");
706 }
707
708 const InputInfo &Input = Inputs[0];
709 types::ID InputType = Input.getType();
710
711 // Add preprocessing options like -I, -D, etc. if we are using the
712 // preprocessor (i.e. skip when dealing with e.g. binary files).
713 if (types::getPreprocessedType(Id: InputType) != types::TY_INVALID)
714 addPreprocessingOptions(Args, CmdArgs);
715
716 addFortranDialectOptions(Args, CmdArgs);
717
718 // Color diagnostics are parsed by the driver directly from argv and later
719 // re-parsed to construct this job; claim any possible color diagnostic here
720 // to avoid warn_drv_unused_argument.
721 Args.getLastArg(options::OPT_fcolor_diagnostics,
722 options::OPT_fno_color_diagnostics);
723 if (Diags.getDiagnosticOptions().ShowColors)
724 CmdArgs.push_back(Elt: "-fcolor-diagnostics");
725
726 // LTO mode is parsed by the Clang driver library.
727 LTOKind LTOMode = D.getLTOMode(/* IsOffload */ false);
728 assert(LTOMode != LTOK_Unknown && "Unknown LTO mode.");
729 if (LTOMode == LTOK_Full)
730 CmdArgs.push_back(Elt: "-flto=full");
731 else if (LTOMode == LTOK_Thin) {
732 Diags.Report(
733 DiagID: Diags.getCustomDiagID(L: DiagnosticsEngine::Warning,
734 FormatString: "the option '-flto=thin' is a work in progress"));
735 CmdArgs.push_back(Elt: "-flto=thin");
736 }
737
738 // -fPIC and related options.
739 addPicOptions(Args, CmdArgs);
740
741 // Floating point related options
742 addFloatingPointOptions(D, Args, CmdArgs);
743
744 // Add target args, features, etc.
745 addTargetOptions(Args, CmdArgs);
746
747 // Add Codegen options
748 addCodegenOptions(Args, CmdArgs);
749
750 // Add R Group options
751 Args.AddAllArgs(CmdArgs, options::OPT_R_Group);
752
753 // Remarks can be enabled with any of the `-f.*optimization-record.*` flags.
754 if (willEmitRemarks(Args))
755 renderRemarksOptions(Args, CmdArgs, Input);
756
757 // Add other compile options
758 addOtherOptions(Args, CmdArgs);
759
760 // Forward flags for OpenMP. We don't do this if the current action is an
761 // device offloading action other than OpenMP.
762 if (Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
763 options::OPT_fno_openmp, false) &&
764 (JA.isDeviceOffloading(Action::OFK_None) ||
765 JA.isDeviceOffloading(Action::OFK_OpenMP))) {
766 switch (D.getOpenMPRuntime(Args)) {
767 case Driver::OMPRT_OMP:
768 case Driver::OMPRT_IOMP5:
769 // Clang can generate useful OpenMP code for these two runtime libraries.
770 CmdArgs.push_back(Elt: "-fopenmp");
771 Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_version_EQ);
772
773 // FIXME: Clang supports a whole bunch more flags here.
774 break;
775 default:
776 // By default, if Clang doesn't know how to generate useful OpenMP code
777 // for a specific runtime library, we just don't pass the '-fopenmp' flag
778 // down to the actual compilation.
779 // FIXME: It would be better to have a mode which *only* omits IR
780 // generation based on the OpenMP support so that we get consistent
781 // semantic analysis, etc.
782 const Arg *A = Args.getLastArg(options::OPT_fopenmp_EQ);
783 D.Diag(diag::warn_drv_unsupported_openmp_library)
784 << A->getSpelling() << A->getValue();
785 break;
786 }
787 }
788
789 // Pass the path to compiler resource files.
790 CmdArgs.push_back(Elt: "-resource-dir");
791 CmdArgs.push_back(Elt: D.ResourceDir.c_str());
792
793 // Offloading related options
794 addOffloadOptions(C, Inputs, JA, Args, CmdArgs);
795
796 // Forward -Xflang arguments to -fc1
797 Args.AddAllArgValues(CmdArgs, options::OPT_Xflang);
798
799 CodeGenOptions::FramePointerKind FPKeepKind =
800 getFramePointerKind(Args, Triple);
801
802 const char *FPKeepKindStr = nullptr;
803 switch (FPKeepKind) {
804 case CodeGenOptions::FramePointerKind::None:
805 FPKeepKindStr = "-mframe-pointer=none";
806 break;
807 case CodeGenOptions::FramePointerKind::NonLeaf:
808 FPKeepKindStr = "-mframe-pointer=non-leaf";
809 break;
810 case CodeGenOptions::FramePointerKind::All:
811 FPKeepKindStr = "-mframe-pointer=all";
812 break;
813 }
814 assert(FPKeepKindStr && "unknown FramePointerKind");
815 CmdArgs.push_back(Elt: FPKeepKindStr);
816
817 // Forward -mllvm options to the LLVM option parser. In practice, this means
818 // forwarding to `-fc1` as that's where the LLVM parser is run.
819 for (const Arg *A : Args.filtered(options::OPT_mllvm)) {
820 A->claim();
821 A->render(Args, CmdArgs);
822 }
823
824 for (const Arg *A : Args.filtered(options::OPT_mmlir)) {
825 A->claim();
826 A->render(Args, CmdArgs);
827 }
828
829 // Remove any unsupported gfortran diagnostic options
830 for (const Arg *A : Args.filtered(options::OPT_flang_ignored_w_Group)) {
831 A->claim();
832 D.Diag(diag::warn_drv_unsupported_diag_option_for_flang)
833 << A->getOption().getName();
834 }
835
836 // Optimization level for CodeGen.
837 if (const Arg *A = Args.getLastArg(options::OPT_O_Group)) {
838 if (A->getOption().matches(options::OPT_O4)) {
839 CmdArgs.push_back(Elt: "-O3");
840 D.Diag(diag::warn_O4_is_O3);
841 } else if (A->getOption().matches(options::OPT_Ofast)) {
842 CmdArgs.push_back(Elt: "-O3");
843 } else {
844 A->render(Args, Output&: CmdArgs);
845 }
846 }
847
848 assert((Output.isFilename() || Output.isNothing()) && "Invalid output.");
849 if (Output.isFilename()) {
850 CmdArgs.push_back(Elt: "-o");
851 CmdArgs.push_back(Elt: Output.getFilename());
852 }
853
854 assert(Input.isFilename() && "Invalid input.");
855
856 if (Args.getLastArg(options::OPT_save_temps_EQ))
857 Args.AddLastArg(CmdArgs, options::OPT_save_temps_EQ);
858
859 addDashXForInput(Args, Input, CmdArgs);
860
861 CmdArgs.push_back(Elt: Input.getFilename());
862
863 // TODO: Replace flang-new with flang once the new driver replaces the
864 // throwaway driver
865 const char *Exec = Args.MakeArgString(Str: D.GetProgramPath(Name: "flang-new", TC));
866 C.addCommand(C: std::make_unique<Command>(args: JA, args: *this,
867 args: ResponseFileSupport::AtFileUTF8(),
868 args&: Exec, args&: CmdArgs, args: Inputs, args: Output));
869}
870
871Flang::Flang(const ToolChain &TC) : Tool("flang-new", "flang frontend", TC) {}
872
873Flang::~Flang() {}
874

source code of clang/lib/Driver/ToolChains/Flang.cpp