Commit graph

501 commits

Author SHA1 Message Date
Tim
8225c81dbf
[flang][debug] Add compressed DWARF support in Flang (#212584)
Re-use most of the clang implementation for compressed DWARF support in
flang.

AI attribution: Co-developed with Claude Opus 4.6
2026-07-31 13:10:14 -05:00
Razvan Lupusoru
b8bd63c69c
[flang][acc] Emit NYI messages for unsupported directives (#211894)
Add an OpenACC MLIR pass that emits not-yet-implemented messages for
unsupported directives immediately after HLFIR generation. This allows
OpenACC dialect operations to be emitted with -emit-hlfir while making
full compilation fail early with clear diagnostics, instead of later
when unhandled OpenACC operations reach LLVM dialect conversion.
2026-07-27 10:10:49 -07:00
Tom Eccles
170a479b64
[flang][Driver] Add option for real sum reassociation (#207377)
Compiler driver option for #207371: -freal-sum-reassociation. 
Disabled by default.

Assisted-by: Codex
2026-07-09 10:52:54 +01:00
Eugene Epshteyn
d1ad52f0ca
[flang][NFC] Remove unnecessary #include directives across flang (#207640)
Audit of every #include directive in flang/lib/ and
flang/include/flang/:

- Remove 423 #include directives (293 from lib/ translation units, 23
from lib-private headers, 107 from public headers) that are not needed:
no entity declared by the removed header is used - directly or in any
conditional-compilation branch (Windows, macOS, ARM/PowerPC,
REAL(16)/REAL(2) configuration macros) - in the including file, and for
headers no consumer in flang/lib, flang/tools, flang/unittests, or
flang-rt relies on the include as a re-export. Load-bearing includes
were examined and retained: textual .inc/.def expansions, tablegen
pass-header declaration/definition pairings, dialect headers carrying
generated-op interface dependencies, config-macro providers (e.g.
float128.h ahead of matmul-instances.inc guards), and ADL formatting
machinery (Evaluate/formatting.h).

- Add 5 missing direct #includes in lib translation units that used
entities only via now-removed transitive includes, and drop one
vestigial 'using namespace Fortran::runtime;' whose declaring header no
longer arrives transitively (nothing namespace-qualified from it was
used), per the include rules in flang/docs/C++style.md.

Assisted-by: AI
2026-07-08 00:53:12 +00:00
Chi-Chun, Chen
8e8e4e50f5
[flang][OpenMP][NFC] Move variant-matching context to semantics (#207087)
Move FlangOMPContext from lowering into semantics as the
MLIR-independent OmpVariantMatchContext. This lets an upcoming semantic
check reuse the matcher to skip the loop-nest checks for a metadirective
variant that cannot be selected on the current target, such as a
`device={kind(nohost)}` variant in a host compilation. No functional
change to metadirective lowering.

Assisted with copilot.
2026-07-06 11:33:34 -05:00
Sergio Afonso
1548349165
[Flang][OpenMP][MLIR] Improve SPMD-No-Loop handling (#206953)
This patch modifies the handling of the
`-fopenmp-assume-teams-oversubscription` and
`-fopenmp-assume-threads-oversubscription` compiler options in Flang and
the corresponding `omp.flags` MLIR attribute to have this information
present on both host and target device MLIR modules. This is necessary
to ensure SPMD to SPMD-No-Loop kernel promotion happens uniformly and no
divergence between host and device representations of the same target
region is introduced.

The identification of the kernel type in Flang lowering is updated to
address some broken edge cases. In particular, no SPMD to SPMD-No-Loop
transformation is performed on `target parallel do [simd]` kernels. A
split `target + parallel loop` is now marked SPMD, which was a case
missed previously, and the trip count on `target teams ompx_bare`
kernels isn't host evaluated even if removing the `ompx_bare` clause
would result in a valid SPMD kernel.
2026-07-01 16:54:06 +01:00
kwyatt-ext
5c02f7530c
[flang] Enumeration Type: (PR 2/5) Name Resolution + Expression + Relational + SELECT CASE (#193028)
This PR completes the addition of enumeration types to the symbol table.
It adds core semantic analysis for ENUMERATION TYPE, name resolution,
expression analysis for constructors and relational operators, and
SELECT CASE support. Also includes a bug fix for non-constant
enumeration comparisons in Relate() (scope() → GetScope()).

It is the 2nd of 5 stacked PRs.

AI Usage Disclosure: AI tools (Claude Opus 4.6) were used to assist with
implementation of this feature and test code generation. I have
reviewed, modified, and tested all AI-generated code.

---------

Co-authored-by: Kevin Wyatt <kwyatt@hpe.com>
2026-06-30 12:24:57 -05:00
Joseph Huber
2a215f473f
[Clang] Refactor and consolidate color diagnostic handling (#202441)
Summary:
This PR tries to consolidate the color output handling in Clang. The
motivation was noticing that `-Xclang -ast-dump` would not behave like
`-fcolor-diagnostics` and would output ANSI codes to a file when I tried
to pipe it.

This PR primarily turns the handling into a tri-state enum keyed off of
`-f[no]-color-diagnostics`. The default/auto case will be if the target
stream supports colors. Getting this to work required a lot of seemingly
unrelated plumbing.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-06-29 15:30:10 -05:00
Andre Kuhlenschmidt
f5d5ff9089
[flang][semantics][OpenACC] Warn for DEFAULT(NONE) scalars by default (#205683)
Change OpenACC `DEFAULT(NONE)` scalar handling to use the
pre-OpenACC-3.2 scalar behavior by default while emitting a warning.
Scalars referenced in a `default(none)` compute region without an
explicit data clause now warn by default instead of erroring. Arrays and
other non-scalars still error under `default(none)`.

Users can opt into OpenACC 3.2 strict scalar behavior with:
`-fopenacc-default-none-scalars-strict` and the default scalar warning
can be suppressed with: `-Wno-openacc-default-none-scalars-strict`
2026-06-25 16:17:37 -07:00
Kaviya Rajendiran
dd499f88bf
[Flang][Driver]Add support for option '-fpseudo-probe-for-profiling' in flang (#205046)
Added support for option `-fpseudo-probe-for-profiling` in flang.

- When the option `-fpseudo-probe-for-profiling` is passed, the compiler
sets the` PseudoProbeForProfiling` flag and triggers the
`SampleProfileProbePass`. This pass inserts `llvm.pseudoprobe(..)`
intrinsic calls and `!llvm.pseudo_probe_desc` metadata into the IR.
2026-06-25 11:35:32 +05:30
shivaramaarao
12aefe26ce
[Flang][Driver] Support for -fsplit-lto-unit option in flang driver (#202858)
When mixing Fortran objects from Flang with C/C++ objects compiled by
Clang during a combined LTO build, it is necessary to ensure that all
files use the same setting for split-lto-unit. This requires the support
for -fsplit-lto-unit option in the flang driver. This support is added
as part of this commit.

 Co-authored-by: Shivarama Rao <shivarama.rao@amd.com>
2026-06-18 16:45:58 +05:30
Andre Kuhlenschmidt
6f57b64897
[flang][semantics] Clean up -frelaxed-c-loc-checks warning flag handling (#203071)
When I originally implemented this I was confused about how
LanguageFeature warning flags work. Drop the separate UsageWarning::CLoc
in favour of using LanguageFeature::RelaxedCLocChecks (renamed from
RelaxedCLoc to match the feature flag) as the warning flag directly. The
warning is off by default since the user has already opted into this
extension using the feature flag; use -Wrelaxed-c-loc-checks alongside
-frelaxed-c-loc-checks to opt in. Update the test and docs accordingly.
2026-06-10 12:48:04 -07:00
Sairudra More
2befcb4d32
[flang] Restrict O0 hlfir.assign scalar-to-array inlining to OpenMP target device (#201774)
Follow-up to #197092.

That PR fixed the OpenMP target-device case by running scalar-to-array
`hlfir.assign` inlining at `-O0`, so device code would not lower through
`_FortranAAssign`.

However, running that path for normal host `-g -O0` also changed
debugging behavior: a breakpoint on a scalar broadcast like `arr = 11`
could be hit once per array element because the assignment became an
inline loop.

This patch restricts the `-O0` scalar-RHS-only inlining path to OpenMP
target-device compilation. Host `-O0` keeps the existing
`_FortranAAssign` path and debugger behavior, while device `-O0` still
avoids the runtime call.

Two focused tests cover both sides:
- host `-O0` scalar broadcast keeps `_FortranAAssign`
- OpenMP target-device `-O0` scalar broadcast avoids `_FortranAAssign`

Fixing debug locations for generated inline loops more generally is left
as separate follow-up work.
The broader debug-location issue for generated inline assignment loops
is tracked separately in #202065.
2026-06-08 21:36:35 +05:30
Andre Kuhlenschmidt
15375d8479
[flang][openacc] change option feature flag names to address comments. (#200037)
- Fixes FeatureFlags and CLI flags to use OpenACC instead of ACC.
- Offline comments further refined the name to be
OpenACCDefaultNoneScalarsStrict
- Which changes the semantics requiring the user to opt out of the
default behavior, instead of opt-in to an extension.
- Also makes the CLI flag OptOut instead of OptIn to match the cli
behavior.
- Gets rid of the unneeded warning flag since FeatureFlags have both a
disabled bit and a warning bit.
- Updates old test for these changes and adds a new test to document all
the different cli configurations.
2026-06-03 09:17:39 -07:00
Andre Kuhlenschmidt
fdf8fb6c13
[flang][openacc] add extension which accepts multiple names in a OpenACC routine directive (#200296)
This PR adds an extension which allows one or more function names in a
single named routine directive. This is treated as multiple named
routine directives with the same clauses. The bind clause is forbidden.
The empty list of names isn't excepted. Routine clauses are stable under
unparsing.

This PR tests Parsing, Unparsing, Semantics, and Lowering.
2026-06-03 07:50:30 -07:00
Michael Kruse
911eddeed7
[Flang] Fix omp_lib.h location and search path (#201104)
Before this PR, omp_lib.h is emitted to `${PREFIX}/include` or
`${PREFIX}/lib/clang/<version>/include` (install prefix) and
`${PREFIX}/runtime/src/omp_lib.h` (builddir prefix). It is never found
there because the driver only adds `${PREFIX}/include/flang/OpenMP` to
the include path.

Fix the `omp_lib.h` include by using the same mechanism as the
omp_lib.mod; that is, move it to
`${PREFIX}/lib/clang/<version>/finclude/flang/<target-triple>`. The
search path is already added by the driver via
`-fintrinsics-modules-path` by the driver. Although omp_lib.h currently
does not contain anything target-specific, it could do so in the future
and I don't think it is worth the effort to add a mechanism without the
target triple. It should also me consistent with omp_lib.mod.

The changes in detail consist of:
1. Move the omp_lib.h output in the builddir to
`${RUNTIMES_OUTPUT_RESOURCE_MOD_DIR}`. This already takes care of
whether it is a bootstrapping build or not.
3. Move the omp_lib.h install dir to
`${RUNTIMES_INSTALL_RESOURCE_MOD_PATH}`.
4. Remove the implicit search path `include/flang/OpenMP` from the
frontend. There is nothing in there anyway.
5. Hardcoding the include search path for testing to the
`LLVM_RUNTIME_TARGETS=default` build becomes unnecessary. This was way
the `include-omp-header.f90` test was still passing, although it would
not work outside the regression tests. Essentially, it tested
lit.site.cfg, not the driver.
6. Replace the old `include-omp-header.f90` test. It created a temporary
`omp_lib.h` that interferes with any other test that use `include
omp_lib.h` (there currently isn't but I originally intended to add the
replacement as an additional omp_lib.h test which resulted in a flaky
test while the original test was there). Due to how the %flang(_fc1)
substitution works, lookup order may also vary.
2026-06-03 15:26:50 +02:00
Abid Qadeer
fe2f7e4099
[flang] Support -ffunction-sections and -fdata-sections. (#199731)
Wire the flags through the driver, frontend, and TargetMachine, and add
driver and codegen lit tests.

Fixes https://github.com/llvm/llvm-project/issues/163550

---------

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-06-02 18:53:30 +01:00
Michael Kruse
22e13e71ed
[Flang] Fix device-side module lookup (#200863)
When invoking flang with device-offloading (eg. `flang modfile.f90
-fopenmp --offload-arch=gfx90a`), it will invoke the frontend twice:
once for the host architecture, and a second time for the architecture
specified with `--offload-arch`. However, both frontend invocations are
going to write `modfile.mod` (or whatever the module name in
`modfile.f90`), and as a result the second one for gfx90a will be what
the file contains after the driver invocation returns. Until #171515
both version of the file were identical, but now both files are using a
different set of builtin modules. Since Flang's mod files store the
checksums of used module files in them, this can result in a checksum
mismatch error. For instance, modfile.mod being the gfx90a version, and
then using it to compile with `flang modfile.f90
--target=x86_64-linux-gnu`) will have a checksum mismath.

flang -fc1 host x86_64        --> modfile.mod --> lib/clang/23/finclude/flang/x86_64-linux-gnu/iso_fortran_env.mod
                                 /  /     \  \
flang -fc1 -foffload-device nvptx  /       \  lib/clang/23/finclude/flang/nvptx64-nvidia-cuda/iso_fortran_env.mod
                                  /         \
flang -fc1 -foffload-device amdgcn           lib/clang/23/finclude/flang/amdgcn-amd-amdhsa/iso_fortran_env.mod

We fix this by

1. Not overwriting the `--target` host module file with the
   `--offload-arch` module; the auxiliary target is the canonical version
   for its contents; and

2. Ignore checksum errors when using an intrinsic module during
   offloading. The device version should be compatible with the host
   version, just with definitions which the .mod file will eventually
   import from the intrinsic module at compile-time.
2026-06-02 01:47:56 +02:00
ejose02
f6758a5664
[flang] Fix -E -dM macro dumping for stdin and .f90 inputs (#200144)
Issue:
flang -E -dM does not consistently print predefined macros for stdin and
.f90 inputs, unlike expected behavior.

Root cause:
Flang only initialized predefined macros when preprocessing was implied
by -cpp or suffix-based inference (mustBePreprocessed), but not when -dM
alone requested macro dumping.

Fix:
Treat -dM as an explicit trigger to initialize macro predefinitions in,
and add a stdin regression test for flang -E -dM - < /dev/null.

Fixes #198234
2026-05-28 12:30:20 +01:00
Eugene Epshteyn
df8819852e
Revert "[Flang] Adding -ffree-line-length-<value> flag" (#199018)
Reverts llvm/llvm-project#192941 due to various important apps failures.
2026-05-21 13:22:47 +00:00
Shilei Tian
9997b11c64
[NFC][AMDGPU] Move AMDGPU related code out of generic TargetParser.cpp (#198433) 2026-05-19 16:16:23 -04:00
Jean-Didier PAILLEUX
960ae6f812
[Flang] Adding -ffree-line-length-<value> flag (#192941)
Added support for the `-ffree-line-length-<value>` flag in Flang, which
is equivalent to `-ffixed-line-length-<value>` but in free form.
This flag is supported by gfortran and can be used in some applications.

---------

Co-authored-by: Tarun Prabhu <tarunprabhu@gmail.com>
Co-authored-by: Andre Kuhlenschmidt <andre.kuhlenschmidt@gmail.com>
2026-05-19 17:07:20 +02:00
Michael Kruse
60e95e5d26
[Flang][Driver] Add per-target search path for modules (#196558)
Adds the version- and target-specific path

    ../lib/clang/<version>/finclude/flang/<target>

to the intrinsic module search path in addition to

    ../finclude/flang

with the former taking precedence if a module file should exist in both.
The version/target-specific path is added by the driver by passing
`-fintrinsic-modules-path` to the `-fc1` invocation. This is consistent
with gfortran and the usual pattern that the driver resolves paths into
the resource path, not the frontend.

This PR adds nothing into that directory, which will be done in #171515.

Extracted out of #171515 as requested by
https://github.com/llvm/llvm-project/pull/171515#pullrequestreview-4179212219

---------

Co-authored-by: Tarun Prabhu <tarun@lanl.gov>
2026-05-19 10:55:47 +02:00
Andre Kuhlenschmidt
4628cbd042
[flang][openacc] add optional extension to allow default none scalars (#197718)
Adds the flag, `-facc-allow-default-none-scalars`. When this flag is
enabled, Flang reverts to the pre-3.2 behavior: scalar variables
referenced inside a `default(none)` compute region without an explicit
data clause do not produce an error. Instead, Flang infers implicit data
attributes for those scalars via the same implicit-copy logic applied in
regions without `default(none)`.

- Adds tests and documentation.
- Makes an explicit extensions doc for OpenACC to mirror the OpenMP
extensions doc.
- Moves the intentional deviations to from the standard to the
extensions doc.
2026-05-18 20:46:51 +00:00
Andre Kuhlenschmidt
1b475206d0
[flang][docs][nfc] Wordsmith -frelaxed-c-loc-checks flag description (#197804)
Clarify that unexpected behavior reflects the compiler's design choice
not to track aliases from non-target non-pointer C_LOC() arguments,
rather than implying a compiler defect. Align phrasing across
FlangOptions.td and Extensions.md.

Also add the `-checks` suffix to the flag per @sscalpone's suggestion.
2026-05-14 15:03:28 -07:00
Kareem Ergawy
bc124ced14
[flang] Remove do concurrent mapping experimental warning (#195009) 2026-05-14 21:59:01 +02:00
Krzysztof Parzyszek
42b4cb6aeb
[flang] Implement -Wno-<warning> flags for driver diagnostics (#196354)
Utilize clang::ProcessWarningOptions function to process -Wno-...
options.

This has the side effect that without additional changes it would cause
driver warnings to become errors with -Werror. That would be a change
from the existing behavior, so make sure that these warnings remain
unaffected.

Modify the diagnostic emitter to add the disabling option at the end of
the emitted diagnostic.

Fixes https://github.com/llvm/llvm-project/issues/195921

---------

Co-authored-by: Tarun Prabhu <tarun@lanl.gov>
2026-05-14 14:54:09 -05:00
Kelvin Li
1451eaf4e1
[flang] Emit module summary for ThinLTO (#195999)
This patch is to enable emitting module summary for ThinLTO.
2026-05-14 13:43:38 -04:00
Eugene Epshteyn
cc4922b276
[flang] Remove legacy (non-HLFIR) lowering and related options (#196205)
Drop the user-facing options that selected the legacy non-HLFIR lowering
path, the always-true `LowerToHighLevelFIR` lowering option, and the
descriptor-discretization debug switch:

- `-flang-experimental-hlfir` and `-flang-deprecated-no-hlfir` (flang
  driver and `-fc1`)
- `-hlfir` / `--hlfir` (bbc)
- `--use-desc-for-alloc` (bbc, debug)

Remove every `if (lowerToHighLevelFIR()) { ... } else { ... }` branch in
`lib/Lower/`, keeping the HLFIR side. Delete the now-unused legacy
helpers in `Bridge.cpp` (`copyVarFIR`, both
`genNoHLFIRPointerAssignment`
overloads, the legacy block of `genAssignment`) and the always-empty
`createMutableProperties` together with its four dead helpers in
`Allocatable.cpp`. Drop the corresponding `alwaysUseBox` parameter from
`createMutableBox`.

Note: tests were modified in
https://github.com/llvm/llvm-project/pull/196137

Assisted-by: AI
2026-05-11 10:43:19 -04:00
Andre Kuhlenschmidt
c6bf92e51d
[flang][semantics] Add a flag to relax some of the semantic constraints on C_LOC (#195112)
This PR adds a flag that downgrades some of the semantic constraints on
C_LOC so that it can be used more like LOC. Without the flag behavior is
unmodified, with the flag the constraint that the address be object
pointer or target is removed. There are other constraints we might
consider relaxing, but I think this is a start.
2026-05-04 17:22:31 +00:00
Michael Klemm
40ad10a8ae
[Flang] Fix -Wopen-mp-* and -Wopen-acc-* flag spellings (#188434)
The CamelCase-to-hyphenated conversion was incorrectly splitting
"OpenMP" and "OpenACC" into "open-mp" and "open-acc", producing wrong -W
flag names like -Wopen-mp-usage instead of -Wopenmp-usage. Fix the
conversion to treat these as compound names, keep the old spellings as
deprecated aliases, and emit a warning when deprecated spellings are
used.

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-28 17:26:29 +02:00
Abid Qadeer
0b449f6692
[flang] Fix abort on invalid -fdo-concurrent-to-openmp value. (#193929)
We observed that following command can cause an assertion fail
 `flang -fopenmp -fdo-concurrent-to-openmp=devic,e` <file>

It happened because `parseDoConcurrentMapping` reported an error but
still called `val.value()` on failure, tripping std::optional
assertions.

The fix is to return false on error and wire return into
`createFromArgs`.
2026-04-24 17:15:32 +01:00
Eugene Epshteyn
49dad16724
[flang] Ignore -fno-realloc-lhs for polymorphic allocatable LHS with warning (#192697)
When -fno-realloc-lhs is specified and the LHS of an assignment is a
polymorphic allocatable (class(*) or class(T)), reallocation semantics
are required by the Fortran 2003 standard for dynamic type tracking and
cannot be safely skipped. Previously, the compiler generated invalid FIR
in such cases (type mismatch between i32 and
!fir.class<!fir.heap<none>>), causing a compilation error.

With this change, when -fno-realloc-lhs is in effect and a polymorphic
allocatable LHS is detected, the compiler emits a warning that the
option is being ignored for that assignment and proceeds with
reallocation semantics.
2026-04-23 09:34:11 -04:00
Arthur Eubanks
561cf0c4f5
[NFC] Move TimePasses globals from Pass.h to PassTimingInfo.h (#192352)
They don't belong in the legacy pass manager-specific header, they apply
to both pass managers, plus the pass manager isn't the right layer to
put the bools anyway.
2026-04-15 22:58:20 +00:00
Fangrui Song
1b275a177f
[flang] -fno-integrated-as: set DisableIntegratedAS (#191346)
https://reviews.llvm.org/D124669 added -fno-integrated-as driver option
but not the fc1 option.
As a result, the backend kept MCAsmInfo::useIntegratedAssembler() set
and emitted LLVM-only directives such as `.prefalign`
(https://github.com/llvm/llvm-project/pull/155529), which GNU as
rejects:

```
a.s: Assembler messages:
a.s: Error: unknown pseudo-op: `.prefalign'
```

Follow clang and introduce fc1 -no-integrated-as to set
`CodeGenOpts.DisableIntegratedAS` and
llvm::TargetOptions::DisableIntegratedAS.
2026-04-13 10:22:08 -07:00
Kaviya Rajendiran
d6d7d0aca0
[Flang][Driver] Add support for '-fprofile-sample-use' option (#188697)
When the `-fprofile-sample-use=sample.prof` option is passed, the
compiler records the profile file path in `SampleProfileFile` . This
value is later used by the `SampleProfileLoaderPass`, which loads the
sample profile and injects the corresponding profiling metadata in the
LLVM IR.
2026-04-07 10:00:10 +05:30
Kelvin Li
b322fa67be
[flang][PPC] Set PPC default target features (#188343)
This patch is to align with how clang sets up the target features for
PowerPC in order to benefit the inlining in LTO.
2026-03-26 12:25:50 -04:00
Kaviya Rajendiran
3009211573
[LLVM-Flang] Add support for -fdebug-info-for-profiling option (#188022)
Added support for option "-fdebug-info-for-profiling" in flang.

- When the option `-fdebug-info-for-profiling` option is passed, 
compiler sets the `DebugInfoForProfiling` flag and triggers the
`AddDiscriminatorsPass`. This pass inserts additional debug metadata,
specifically discriminator values into the IR to improve the profiling
precision.
- Additionally `-add-debug-info` pass has been updated to emit an extra
field, `debugInfoForProfiling: true` inside the generated DICompileUnit
metadata node.
2026-03-26 12:19:46 +05:30
Jan Leyonberg
d7e60d5250
[NFC][OpenMP][mlir][flang] Move OMP offloading module attribute handling from flang to mlir (#186409)
This patch moves the OpenMP offloding module attributes handling from
flang to mlir so that it can be reused in ClangIR was well.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
Co-authored-by: Michael Kruse <github@meinersbur.de>
2026-03-25 16:08:32 -04:00
Sairudra More
111bafff9b
[flang] Add runtime trampoline pool for W^X compliance (#183108)
Flang currently lowers internal procedures passed as actual arguments
using LLVM's `llvm.init.trampoline` / `llvm.adjust.trampoline`
intrinsics, which require an executable stack. On modern Linux
toolchains and security-hardened kernels that enforce W^X (Write XOR
Execute), this causes link-time failures (`ld.lld: error: ... requires
an executable stack`) or runtime `SEGV` from NX violations.

This patch introduces a runtime trampoline pool that allocates
trampolines from a dedicated `mmap`'d region instead of the stack. The
pool toggles page permissions between writable (for patching) and
executable (for dispatch), so the stack stays non-executable throughout.
On macOS, MAP_JIT and `pthread_jit_write_protect_np` are used for the
same effect. An i-cache flush (`__builtin___clear_cache` on Linux,
`sys_icache_invalidate` on macOS) is performed after each write→exec
transition.

The feature is gated behind a new driver flag, `-fsafe-trampoline` (off
by default), which threads through the frontend into the
`BoxedProcedurePass`. When enabled, the pass emits calls to
`_FortranATrampolineInit`, `_FortranATrampolineAdjust`, and
`_FortranATrampolineFree` instead of the legacy intrinsics. The legacy
path is completely untouched when the flag is off.

The pool is a singleton with a fixed capacity (default 1024 slots,
overridable via `FLANG_TRAMPOLINE_POOL_SIZE`). Slot size varies by
target (32 bytes on x86-64/AArch64, 48 on PPC64, 64 fallback). Each slot
holds a small architecture-specific stub, currently x86-64 (17 bytes,
using `r10` as the nest/static-chain register) and AArch64 (24 bytes,
using `x15`). The implementation compiles on all architectures but will
crash at runtime with a clear diagnostic if trampoline emission is
actually attempted on an unsupported target. This avoids breaking the
flang-rt build on e.g. RISC-V or PPC64.

Freed slots are poisoned (the callee pointer is overwritten with a
sentinel) and recycled into a freelist, so the pool can sustain
long-running programs that repeatedly create and destroy closures.

A few design choices worth calling out:

The runtime avoids all C++ runtime dependencies, no `std::mutex`, no
`operator new`, no function-local statics with hidden guard variables.
Locking is via flang-rt's own `Lock` / `CriticalSection`, memory is via
`AllocateMemoryOrCrash` / `FreeMemory`, and the singleton uses explicit
double-checked locking with a raw pointer. This was done so the
trampoline pool links cleanly in minimal / freestanding flang-rt
configurations.

`_FortranATrampolineFree` calls are inserted immediately before every
`func.return` in the enclosing host function. This is a conservative but
correct strategy. The trampoline handle cannot outlive the host's stack
frame since the closure captures the host's local variables by
reference.

The GNU_STACK note is verified via a dedicated integration test
(`safe-trampoline-gnustack.f90`) that compiles and links a Fortran
program using the runtime path, then inspects the ELF with
`llvm-readelf` to confirm the stack segment is `RW` (not `RWE`).

**Test coverage:**

- `flang/test/Driver/fsafe-trampoline.f90` — flag forwarding (on, off,
default)
- `flang/test/Fir/boxproc-safe-trampoline.fir` — FIR-level FileCheck for
emitted runtime calls
- `flang/test/Lower/safe-trampoline.f90` — end-to-end lowering
- `flang-rt/test/Driver/safe-trampoline-gnustack.f90` — GNU_STACK ELF
verification

Closes #182813

Co-authored-by: Sairudra More <moresair@pe31.hpc.amslabs.hpecorp.net>
2026-03-10 16:16:05 +05:30
Slava Zakharin
5230955af7
[flang,acc] Support -ffp-maxmin-behavior option in lowering. (#184730)
This patch adds `flang -fc1` option `-ffp-maxmin-behavior` and
propagates it throughout Flang, so that semantics context,
lowering and the pass pipeline builder can use it.

MAX/MIN intrinsic and OpenACC max/min reduction lowering
are now controlled by the option.

I kept the `Legacy` mode, which is the default and matches the current
behavior. I am going to test and merge a follow-up patch that
replaces `Legacy` with `Portable`.

RFC:
https://discourse.llvm.org/t/flang-canonical-and-optimizable-representation-for-min-max/90037
2026-03-06 12:21:58 -08:00
Yangyu Chen
7f0a343a8e
[flang] Implement -grecord-command-line for Flang (#181686)
Enable Flang to match Clang behavior for command-line recording in DWARF
producer strings when using -grecord-command-line.

Signed-off-by: Yangyu Chen <cyy@cyyself.name>
2026-02-28 01:45:52 +08:00
Alexis Engelke
b82c7fc652
[CMake][LLVM] Add PCH infrastructure and LLVMSupport PCH (#176420)
This patch implements PCH support. PCH is enabled by default, unless
noted below, and can be disabled with
-DCMAKE_DISABLE_PRECOMPILE_HEADERS=ON.

* Libraries can define precompiled headers using a newly added
PRECOMPILE_HEADERS keyword. If specified, the listed headers will be
compiled into a pre-compiled header using standard CMake mechanisms.

* Libraries that don't define their own PRECOMPILE_HEADERS but directly
depend on a library or component that defines its own PCH will reuse
that PCH. This reuse is not transitive to prevent excessive use of
unrelated headers. If multiple dependencies provide a reusable PCH, the
first one with the longest dependency chain (stored in the CMake target
property LLVM_PCH_PRIORITY) is used. However, due to CMake limitations,
only PCH from targets that are already defined can be reused; therefore
libraries that should reuse a PCH must be defined later in the CMake
file (=> add_subdirectory order matters).

* Libraries and executables can prevent PCH reuse with the keyword
DISABLE_PCH_REUSE. This both prevents reuse from dependencies and reuse
by other dependants. This is useful when, e.g., internal headers are
used in the PCH or the used headers are unlikely to provide benefits for
dependants.

* Precompiled headers are only used for C++ sources, not for C.

* With GCC, PCH provide very little benefits (tested with GCC 14 and 15)
due to increased template instatiation costs, but substantially increase
max-rss and build directory size. Therefore, disable PCH with GCC by
default; this can be explicitly overridden on the command line with
-DCMAKE_DISABLE_PRECOMPILE_HEADERS=OFF.

* With ccache and non-Clang compilers, changes in macro definitions are
not always accurately forwarded with ccache's preprocessed mode. To be
on the safe side, when ccache is enabled, disable PCH with all non-Clang
compilers; this can be explicitly overridden.

* With sccache, changes in macro definitions are not identified, which
in some cases can lead to false positive cache hits. Conservatively
disable PCH with sccache by default.

* Add a base PCH to LLVMSupport, which includes widely used standard
library and Support+ADT headers. The pch.h is placed in include so that
later PCH headers can extend that list of headers.

* Flang PCH use is ported to the general mechanism.

Addition of PCH headers for other components (e.g., IR, CodeGen) will be
posted as separate PRs.

RFC:
https://discourse.llvm.org/t/rfc-use-pre-compiled-headers-to-speed-up-llvm-build-by-1-5-2x/89345
2026-02-20 12:07:18 +01:00
Justin Fargnoli
9475f6af81
Reland "[NVPTX] Validate user-specified PTX version against SM version" (#180116)
Previous commit message: 

>Previous commit message: 
>
>> Original commit message:
>>
>>>When users explicitly specify a PTX version via -mattr=+ptxNN that's
insufficient for their target SM, we now emit a fatal error. Previously,
we silently upgraded the PTX version to the minimum required for the
target SM.
>>>
>>>When no SM or PTX version is specified, we now use PTX 3.2 (the
minimum for the default SM 3.0) instead of PTX 6.0.
>>
>>The following commits should fix the failures that arose when I
previously tried to land this commit:
>>
>>

>>9fc5fd0ad6
should address the llvm-nvptx*-nvidia-* build failures:
https://github.com/llvm/llvm-project/pull/174834#issuecomment-3742242651
>>
>>

>>600514a637
should address the MLIR failures
>
>The previous commit was reverted with
d23cb79ba4
because the
[mlir-nvidia](https://lab.llvm.org/buildbot/#/builders/138/builds/24797)
and
[mlir-nvidia-gcc7](https://lab.llvm.org/buildbot/#/builders/116/builds/23929)
Buildbots were failing.
>
>Those tests failed because MLIR's default SM was 5.0, which caused
NVPTX
to target PTX ISA v4.0, which did not support the intrinsics used in the
failing tests.
>

>243f011577
should address this by bumping MLIR's default SM to 7.5. Now, using
MLIR's new default SM, NVPTX
targets the PTX ISA v6.3, which supports the intrinsics used in the
failing tests.

---

The previous commit was reverted with
e9b578a4d7
[because](https://github.com/llvm/llvm-project/pull/179304#issuecomment-3856301333)
the clang driver set the default PTX ISA version to v4.2 when no CUDA
installation is found. However, given our patch, we should not set a
default; instead, let the LLVM backend select the appropriate PTX ISA
version for the target SM.
2026-02-10 18:11:54 +00:00
Justin Fargnoli
e9b578a4d7
Revert "Reland "[NVPTX] Validate user-specified PTX version against SM version"" (#180035)
Reverts llvm/llvm-project#179304 due to
https://github.com/llvm/llvm-project/pull/179304#issuecomment-3856100622
2026-02-05 13:24:58 -08:00
Justin Fargnoli
ca93dd399e
Reland "[NVPTX] Validate user-specified PTX version against SM version" (#179304)
Previous commit message: 

> Original commit message:
>
>>When users explicitly specify a PTX version via -mattr=+ptxNN that's
insufficient for their target SM, we now emit a fatal error. Previously,
we silently upgraded the PTX version to the minimum required for the
target SM.
>>
>>When no SM or PTX version is specified, we now use PTX 3.2 (the
minimum for the default SM 3.0) instead of PTX 6.0.
>
>The following commits should fix the failures that arose when I
previously tried to land this commit:
>

>9fc5fd0ad6
should address the llvm-nvptx*-nvidia-* build failures:
https://github.com/llvm/llvm-project/pull/174834#issuecomment-3742242651
>

>600514a637
should address the MLIR failures

---

The previous commit was reverted with
d23cb79ba4 because the
[mlir-nvidia](https://lab.llvm.org/buildbot/#/builders/138/builds/24797)
and
[mlir-nvidia-gcc7](https://lab.llvm.org/buildbot/#/builders/116/builds/23929)
Buildbots were failing.

Those tests failed because MLIR's default SM was 5.0, which caused NVPTX
to target PTX ISA v4.0, which did not support the intrinsics used in the
failing tests.

243f011577 should address this by bumping
MLIR's default SM to 7.5. Now, using MLIR's new default SM, NVPTX
targets the PTX ISA v6.3, which supports the intrinsics used in the
failing tests.
2026-02-05 17:42:41 +00:00
Justin Fargnoli
d23cb79ba4
Revert "Reland "[NVPTX] Validate user-specified PTX version against SM version"" (#178046)
Reverts llvm/llvm-project#177459

`mlir-nvidia` and `mlir-nvidia-gcc7` Buildbots are failing. 

The blamelist is small and likely because of my change. Preemptively
reverting.
2026-01-26 12:48:59 -08:00
Justin Fargnoli
487b69ae0a
Reland "[NVPTX] Validate user-specified PTX version against SM version" (#177459)
Original commit message: 

> When users explicitly specify a PTX version via -mattr=+ptxNN that's
insufficient for their target SM, we now emit a fatal error. Previously,
we silently upgraded the PTX version to the minimum required for the
target SM.
>
>When no SM or PTX version is specified, we now use PTX 3.2 (the minimum
for the default SM 3.0) instead of PTX 6.0.

---

The following commits should fix the failures that arose when I
previously tried to land this commit:

- 9fc5fd0ad6 should address the
`llvm-nvptx*-nvidia-*` build failures:
https://github.com/llvm/llvm-project/pull/174834#issuecomment-3742242651

- 600514a63760c6730e4cd970d2fcead9c5a897b3 should address the MLIR
failures
2026-01-26 19:47:05 +00:00
Eugene Epshteyn
69eac707ed
[flang] Support -f(no-)protect-parens (#170505)
Driver/compiler option plumbing to get -f(no-)protect-parens supported
on flang. (This option was already supported in clang, so extended the
option config to enable it in flang.)

In the compiler, support it in code gen options and in lowering options.
Hooked up lowering options with the code by @alexey-bataev that turns
off reassociation transformations.

Co-authored-by: Alexey Bataev <a.bataev@outlook.com>
2026-01-23 12:21:09 -05:00
Mehdi Amini
af39416f8b
Revert "[NVPTX] Validate user-specified PTX version against SM version" (#175760)
Reverts llvm/llvm-project#174834

Bots are broken.
2026-01-13 14:33:12 +00:00