https://github.com/bcardosolopes created https://github.com/llvm/llvm-project/pull/239774
Second step towards issuing -Wreturn-type from ClangIR instead of Clang's CFG, building on the `implicit` fall-off terminator from #238696. This PR does not yet hook it up to the rest of Clang warning infrastructure, nor has a flag to substitute the CFG one. That's a change with more design decisions, rewiring in Sema, etc - better discuss in its own PR (third step), here I'm focusing on the analysis. Add `cir::analyzeFallOff`, the CIR counterpart of Sema's CFG-based `CheckFallThrough` behind -Wreturn-type. It classifies a function as never, never-and-no-return, maybe or always falling off its end. - Walks structured CIR: each region reports how control leaves it and region ops combine their regions' exits. Noreturn calls, traps and throws are the edges Sema uses to tell maybe from always; gotos and labels are followed as in the CFG. - For a coroutine, only the code written in its body is analyzed, with `cir.co_return` as its return. - `cir::mayFallOff` is a cheap, conservative pre-check that spares most functions the full walk. - The module entry point analyzes functions in parallel. - `-cir-fall-off-analysis` reports the result as remarks, for tests. Cost against Sema's check on the 5 slowest selfhost TUs (ms, -ftime-trace, median of 3). Build is the CFG or CIRGen; the check excludes it. ``` | TU | Engine | Build (CFG / CIRGen) | Fall-off check | |-------------------|---------|---------------------:|-------------------------| | CIRDialect.cpp | CFG | 388.7 | 42.5 | | | ClangIR | 11,188.2 | 14.0 (24.0 on 1 thread) | | OpenACC.cpp | CFG | 198.1 | 21.1 | | | ClangIR | 6,407.4 | 7.1 (12.7 on 1 thread) | | SLPVectorizer.cpp | CFG | 150.3 | 20.6 | | | ClangIR | 8,178.2 | 8.8 (18.3 on 1 thread) | | Disasm.cpp | CFG | 66.3 | 8.8 | | | ClangIR | 473.9 | 1.0 (0.3 on 1 thread) | | OpenMPDialect.cpp | CFG | 217.2 | 23.6 | | | ClangIR | 5,981.7 | 4.4 (12.5 on 1 thread) | ``` Known differences from the CFG check, left for incremental follow-ups (if they make sense): - Constant conditions are folded only through CIR's folders, while the CFG evaluates them (e.g. `while (alwaysTrue())` with a constexpr call). - The handlers of a try whose body cannot throw are not analyzed, since CIRGen drops them. - Noreturn destructors of temporaries created in a conditional operand (`b ? T() : U()`, `&&`, `||`) are not seen as noreturn. - Calls to virtual `[[noreturn]]` methods and to `analyzer_noreturn` functions are not marked noreturn by CIRGen. - Functions CIRGen does not emit (unused inline functions, constexpr-only functions, uncalled lambdas) and blocks are not analyzed (requires ObjC NYIs). >From 0061f5d9cbf4d3fc320b18cd568ad59921be933c Mon Sep 17 00:00:00 2001 From: Bruno Cardoso Lopes <[email protected]> Date: Wed, 28 Oct 2026 15:35:18 -0700 Subject: [PATCH] [CIR] Add an analysis classifying how control reaches a function's end Second step towards issuing -Wreturn-type from ClangIR instead of Clang's CFG, building on the `implicit` fall-off terminator from #238696. Add `cir::analyzeFallOff`, the CIR counterpart of Sema's CFG-based `CheckFallThrough` behind -Wreturn-type. It classifies a function as never, never-and-no-return, maybe or always falling off its end. - Walks structured CIR: each region reports how control leaves it and region ops combine their regions' exits. Noreturn calls, traps and throws are the edges Sema uses to tell maybe from always; gotos and labels are followed as in the CFG. - For a coroutine, only the code written in its body is analyzed, with `cir.co_return` as its return. - `cir::mayFallOff` is a cheap, conservative pre-check that spares most functions the full walk. - The module entry point analyzes functions in parallel. - `-cir-fall-off-analysis` reports the result as remarks, for tests. Cost against Sema's check on the 5 slowest selfhost TUs (ms, -ftime-trace, median of 3). Build is the CFG or CIRGen; the check excludes it. ``` | TU | Engine | Build (CFG / CIRGen) | Fall-off check | |-------------------|---------|---------------------:|-------------------------| | CIRDialect.cpp | CFG | 388.7 | 42.5 | | | ClangIR | 11,188.2 | 14.0 (24.0 on 1 thread) | | OpenACC.cpp | CFG | 198.1 | 21.1 | | | ClangIR | 6,407.4 | 7.1 (12.7 on 1 thread) | | SLPVectorizer.cpp | CFG | 150.3 | 20.6 | | | ClangIR | 8,178.2 | 8.8 (18.3 on 1 thread) | | Disasm.cpp | CFG | 66.3 | 8.8 | | | ClangIR | 473.9 | 1.0 (0.3 on 1 thread) | | OpenMPDialect.cpp | CFG | 217.2 | 23.6 | | | ClangIR | 5,981.7 | 4.4 (12.5 on 1 thread) | ``` Assisted-by: Claude Code (Opus 5.5). --- .../CIR/Dialect/Analysis/CIRFallOffAnalysis.h | 66 ++ clang/include/clang/CIR/Dialect/Passes.h | 1 + clang/include/clang/CIR/Dialect/Passes.td | 14 + .../Dialect/Analysis/CIRFallOffAnalysis.cpp | 713 ++++++++++++++++++ clang/lib/CIR/Dialect/Analysis/CMakeLists.txt | 1 + .../lib/CIR/Dialect/Transforms/CMakeLists.txt | 2 + .../Transforms/FallOffAnalysisPass.cpp | 36 + .../test/CIR/Analysis/fall-off-coroutine.cpp | 182 +++++ clang/test/CIR/Analysis/fall-off.c | 180 +++++ clang/test/CIR/Analysis/fall-off.cpp | 281 +++++++ clang/tools/cir-opt/cir-opt.cpp | 4 + 11 files changed, 1480 insertions(+) create mode 100644 clang/include/clang/CIR/Dialect/Analysis/CIRFallOffAnalysis.h create mode 100644 clang/lib/CIR/Dialect/Analysis/CIRFallOffAnalysis.cpp create mode 100644 clang/lib/CIR/Dialect/Transforms/FallOffAnalysisPass.cpp create mode 100644 clang/test/CIR/Analysis/fall-off-coroutine.cpp create mode 100644 clang/test/CIR/Analysis/fall-off.c create mode 100644 clang/test/CIR/Analysis/fall-off.cpp diff --git a/clang/include/clang/CIR/Dialect/Analysis/CIRFallOffAnalysis.h b/clang/include/clang/CIR/Dialect/Analysis/CIRFallOffAnalysis.h new file mode 100644 index 00000000000000..4896ba7ca5dfb3 --- /dev/null +++ b/clang/include/clang/CIR/Dialect/Analysis/CIRFallOffAnalysis.h @@ -0,0 +1,66 @@ +//===- CIRFallOffAnalysis.h - Can control flow off the end of a function --===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +// +// This file declares an analysis that classifies whether control can reach the +// end of a function body, the CIR counterpart of the CFG-based fall-off check +// behind -Wreturn-type. It runs on CIRGen output, where the terminator emitted +// for flowing off the end of a body is marked `implicit`. +// +//===----------------------------------------------------------------------===// + +#ifndef CLANG_CIR_DIALECT_ANALYSIS_CIRFALLOFFANALYSIS_H +#define CLANG_CIR_DIALECT_ANALYSIS_CIRFALLOFFANALYSIS_H + +#include "clang/CIR/Dialect/IR/CIRDialect.h" +#include "llvm/ADT/STLFunctionalExtras.h" +#include "llvm/ADT/SmallVector.h" + +namespace mlir { +class ModuleOp; +} // namespace mlir + +namespace cir { + +/// How control can reach the end of a function body. Mirrors the +/// classification used by Sema's CFG-based fall-off check. +enum class FallOffKind { + /// The function was not analyzed (e.g. it has no body). + Unknown, + /// Control never reaches the end of the body, but a return is reachable. + Never, + /// Control never reaches the end of the body and no return is reachable. + NeverAndNoReturn, + /// Control reaches the end of the body on some paths only. + Maybe, + /// Control reaches the end of the body on every path that completes. + Always, +}; + +llvm::StringRef stringifyFallOffKind(FallOffKind kind); + +/// Classify whether control can flow off the end of `func`'s body. +FallOffKind analyzeFallOff(cir::FuncOp func); + +/// A cheap, conservative check of whether control may reach the end of +/// `func`. When false, analyzeFallOff(func) is never or never-and-no-return. +bool mayFallOff(cir::FuncOp func); + +struct FallOffResult { + cir::FuncOp func; + FallOffKind kind = FallOffKind::Unknown; +}; + +/// analyzeFallOff over the definitions `filter` accepts (all if null), in +/// parallel when allowed: `filter` may run concurrently. In module order. +llvm::SmallVector<FallOffResult> +analyzeFallOff(mlir::ModuleOp module, + llvm::function_ref<bool(cir::FuncOp)> filter = nullptr); + +} // namespace cir + +#endif // CLANG_CIR_DIALECT_ANALYSIS_CIRFALLOFFANALYSIS_H diff --git a/clang/include/clang/CIR/Dialect/Passes.h b/clang/include/clang/CIR/Dialect/Passes.h index 7c09a42bed949f..42570fb7f66462 100644 --- a/clang/include/clang/CIR/Dialect/Passes.h +++ b/clang/include/clang/CIR/Dialect/Passes.h @@ -41,6 +41,7 @@ createCallConvLoweringPass(cir::CallConvTarget target, std::unique_ptr<Pass> createHoistAllocasPass(); std::unique_ptr<Pass> createLoweringPreparePass(); std::unique_ptr<Pass> createGotoSolverPass(); +std::unique_ptr<Pass> createFallOffAnalysisPass(); std::unique_ptr<Pass> createIdiomRecognizerPass(); std::unique_ptr<Pass> createLibOptPass(); diff --git a/clang/include/clang/CIR/Dialect/Passes.td b/clang/include/clang/CIR/Dialect/Passes.td index 787a9d8f29b899..e696f4dcdba556 100644 --- a/clang/include/clang/CIR/Dialect/Passes.td +++ b/clang/include/clang/CIR/Dialect/Passes.td @@ -88,6 +88,20 @@ def CIRFlattenCFG : Pass<"cir-flatten-cfg"> { let dependentDialects = ["cir::CIRDialect"]; } +def FallOffAnalysis : Pass<"cir-fall-off-analysis", "mlir::ModuleOp"> { + let summary = "Report how control reaches the end of each function"; + let description = [{ + Runs the fall-off analysis behind ClangIR's -Wreturn-type on every + function definition and emits a remark per function with its + classification: never, never-and-no-return, maybe, always or unknown. + This exposes the analysis to cir-opt tests; clang calls the analysis + directly and reports -Wreturn-type, not these remarks. The IR is not + modified. + }]; + let constructor = "mlir::createFallOffAnalysisPass()"; + let dependentDialects = ["cir::CIRDialect"]; +} + def GotoSolver : Pass<"cir-goto-solver", "mlir::ModuleOp"> { let summary = "Replaces goto operations with branches"; let description = [{ diff --git a/clang/lib/CIR/Dialect/Analysis/CIRFallOffAnalysis.cpp b/clang/lib/CIR/Dialect/Analysis/CIRFallOffAnalysis.cpp new file mode 100644 index 00000000000000..21e4efd37bb6cc --- /dev/null +++ b/clang/lib/CIR/Dialect/Analysis/CIRFallOffAnalysis.cpp @@ -0,0 +1,713 @@ +//===- CIRFallOffAnalysis.cpp - Can control flow off the end of a function ===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +// +// A reachability walk over structured CIR. Each region reports how control +// leaves it (falling through, break, continue, explicit return, or reaching an +// `implicit` terminator), and each structured operation combines the exits of +// its regions according to its semantics. Reachable noreturn calls, user +// traps and throws are recorded as the abnormal and fake edges Sema's CFG +// check uses to tell "maybe" from "always". +// +//===----------------------------------------------------------------------===// + +#include "clang/CIR/Dialect/Analysis/CIRFallOffAnalysis.h" + +#include "mlir/IR/BuiltinOps.h" +#include "mlir/IR/Matchers.h" +#include "mlir/IR/Threading.h" +#include "mlir/Interfaces/SideEffectInterfaces.h" +#include "clang/CIR/Dialect/IR/CIRDialect.h" +#include "llvm/ADT/DenseMap.h" +#include "llvm/ADT/DenseSet.h" +#include "llvm/Support/TimeProfiler.h" + +using namespace cir; + +namespace { + +/// How control can leave a region or a structured operation. +struct Exits { + bool normal = false; + bool breaks = false; + bool continues = false; + bool explicitReturn = false; + bool implicitReturn = false; + // Outcomes of a reachable `cir.condition` terminating the region. + bool condTrue = false; + bool condFalse = false; + + /// Merge the exits that escape an enclosed operation. + void mergeEscaping(const Exits &other) { + breaks |= other.breaks; + continues |= other.continues; + explicitReturn |= other.explicitReturn; + implicitReturn |= other.implicitReturn; + } + + bool any() const { + return normal || breaks || continues || explicitReturn || implicitReturn; + } +}; + +class FallOffAnalyzer { +public: + explicit FallOffAnalyzer(FuncOp func, bool tailOnly = false) + : func(func), tailOnly(tailOnly) {} + + FallOffKind run(); + + /// Conservatively, whether `op` alone completes when entered at the top. A + /// label inside it, or dead code that may hold one, means yes. + bool mayCompleteFromTop(mlir::Operation *op) { + assert(tailOnly && "needs a tail-only analyzer"); + return visitStructured(op, /*entered=*/true).normal || unsure; + } + +private: + Exits visitRegion(mlir::Region ®ion, bool entered); + Exits visitStructured(mlir::Operation *op, bool entered); + Exits visitLoop(LoopOpInterface loop, bool entered); + Exits visitSwitch(SwitchOp op, bool entered); + Exits visitCleanupScope(CleanupScopeOp op, bool entered); + void visitTerminator(mlir::Operation *op, Exits &exits, + llvm::SmallVectorImpl<mlir::Block *> &liveSuccessors); + void addAddressTakenLabels(); + void updateLabelAncestors(); + + /// Whether a dead operation still needs a visit because a label inside it + /// can be reached through a goto. + bool containsTargetedLabel(mlir::Operation *op) const { + return labelAncestors.contains(op); + } + bool isTargetedLabel(mlir::Operation *op) const { + auto label = mlir::dyn_cast<LabelOp>(op); + return label && targetedLabels.contains(label.getLabelAttr()); + } + + FuncOp func; + bool tailOnly; + bool unsure = false; + bool abnormalEdge = false; + bool fakeEdge = false; + /// Labels control can reach through a goto or an indirect branch, and the + /// operations enclosing them. + llvm::DenseSet<mlir::StringAttr> targetedLabels; + llvm::DenseSet<mlir::Operation *> labelAncestors; + /// Labels targeted by the gotos reached so far. + llvm::DenseSet<mlir::StringAttr> reachedGotoTargets; + /// Whether a cir.indirect_goto is reachable; it can reach every label whose + /// address is taken. + bool reachedIndirectGoto = false; + bool addedAddressTakenLabels = false; + /// The function's labels, collected once a goto makes them matter. + std::optional<llvm::SmallVector<LabelOp>> labels; + /// The enclosing switches, innermost last. A reachable switch dispatches to + /// all of its cases, wherever they are nested in its body. + struct SwitchState { + bool entered = false; + bool hasDefault = false; + }; + llvm::SmallVector<SwitchState> switches; + + bool inEnteredSwitch() const { + return !switches.empty() && switches.back().entered; + } +}; + +} // namespace + +/// Fold `value` to a constant through side-effect-free operations. +static mlir::Attribute foldToConstant(mlir::Value value, unsigned depth = 0) { + mlir::Attribute attr; + if (mlir::matchPattern(value, mlir::m_Constant(&attr))) + return attr; + + constexpr unsigned maxDepth = 8; + if (depth >= maxDepth) + return {}; + + // C conditions such as `while (1)` or `x || 1` convert between int and + // bool, which the cast folder leaves alone. + if (auto cast = value.getDefiningOp<CastOp>()) { + if (cast.getKind() == CastKind::int_to_bool) { + if (auto intAttr = mlir::dyn_cast_if_present<IntAttr>( + foldToConstant(cast.getSrc(), depth + 1))) + return BoolAttr::get(value.getContext(), !intAttr.getValue().isZero()); + return {}; + } + if (cast.getKind() == CastKind::bool_to_int) { + if (auto boolAttr = mlir::dyn_cast_if_present<BoolAttr>( + foldToConstant(cast.getSrc(), depth + 1))) + return IntAttr::get(cast.getType(), boolAttr.getValue() ? 1 : 0); + return {}; + } + } + + // `x || 1` and `x && 0` become a cir.ternary whose arms yield the same + // constant, which the CFG check folds too. + if (auto ternary = value.getDefiningOp<TernaryOp>()) { + auto foldArm = [&](mlir::Region &arm) -> mlir::Attribute { + if (!arm.hasOneBlock() || !arm.front().mightHaveTerminator()) + return {}; + auto yield = mlir::dyn_cast<YieldOp>(arm.front().getTerminator()); + if (!yield || yield.getNumOperands() != 1) + return {}; + return foldToConstant(yield.getOperand(0), depth + 1); + }; + mlir::Attribute trueValue = foldArm(ternary.getTrueRegion()); + mlir::Attribute falseValue = foldArm(ternary.getFalseRegion()); + if (auto cond = mlir::dyn_cast_if_present<BoolAttr>( + foldToConstant(ternary.getCond(), depth + 1))) + return cond.getValue() ? trueValue : falseValue; + return trueValue == falseValue ? trueValue : mlir::Attribute(); + } + + mlir::Operation *def = value.getDefiningOp(); + if (!def || def->getNumResults() != 1 || def->getNumRegions() != 0 || + !mlir::isMemoryEffectFree(def)) + return {}; + llvm::SmallVector<mlir::Attribute> operands; + for (mlir::Value operand : def->getOperands()) { + operands.push_back(foldToConstant(operand, depth + 1)); + if (!operands.back()) + return {}; + } + llvm::SmallVector<mlir::OpFoldResult> results; + if (mlir::failed(def->fold(operands, results)) || results.size() != 1) + return {}; + return mlir::dyn_cast_if_present<mlir::Attribute>(results.front()); +} + +static std::optional<bool> getConstantBool(mlir::Value value) { + mlir::Attribute attr = foldToConstant(value); + if (auto boolAttr = mlir::dyn_cast_if_present<BoolAttr>(attr)) + return boolAttr.getValue(); + return std::nullopt; +} + +static bool isNoReturnCall(mlir::Operation *op) { + return mlir::isa<CallOp>(op) && + op->hasAttr(CIRDialect::getNoReturnAttrName()); +} + +/// `__builtin_assume(0)` is noreturn for the CFG check. +static bool isAssumeFalse(mlir::Operation *op) { + auto assume = mlir::dyn_cast<AssumeOp>(op); + return assume && getConstantBool(assume.getPredicate()) == false; +} + +/// The only operation with regions in a single-block \p region, if any. +static mlir::Operation *getOnlyRegionOp(mlir::Region ®ion) { + if (!region.hasOneBlock()) + return nullptr; + mlir::Operation *found = nullptr; + for (mlir::Operation &op : region.front()) { + if (op.getNumRegions() == 0) + continue; + if (found) + return nullptr; + found = &op; + } + return found; +} + +/// The code written in a coroutine's body, without the implicit `try` (and the +/// `if` around it) CIRGen adds with exceptions: leaving those is not fall-off. +static mlir::Region &getCoroutineUserBody(CoroutineOp coro) { + mlir::Operation *op = getOnlyRegionOp(coro.getBody()); + if (auto ifOp = mlir::dyn_cast_if_present<IfOp>(op); + ifOp && ifOp.getElseRegion().empty()) + op = getOnlyRegionOp(ifOp.getThenRegion()); + if (auto scope = mlir::dyn_cast_if_present<ScopeOp>(op)) + op = getOnlyRegionOp(scope.getScopeRegion()); + if (auto tryOp = mlir::dyn_cast_if_present<TryOp>(op)) + return tryOp.getTryRegion(); + return coro.getBody(); +} + +FallOffKind FallOffAnalyzer::run() { + // For a coroutine, the end is that of the code written in its body, and + // co_return is its return. + mlir::Region *body = &func.getBody(); + if (func.getCoroutineKind().has_value()) { + CoroutineOp coro; + func.walk<mlir::WalkOrder::PreOrder>([&](CoroutineOp op) { + coro = op; + return mlir::WalkResult::interrupt(); + }); + if (!coro) + return FallOffKind::Unknown; + body = &getCoroutineUserBody(coro); + } + + // A reached goto may target a label in a region already walked as dead, so + // walk again until no new label is targeted; without gotos, once. + Exits exits; + while (true) { + abnormalEdge = fakeEdge = reachedIndirectGoto = false; + reachedGotoTargets.clear(); + exits = visitRegion(*body, /*entered=*/true); + + size_t numTargeted = targetedLabels.size(); + targetedLabels.insert_range(reachedGotoTargets); + if (reachedIndirectGoto) + addAddressTakenLabels(); + if (targetedLabels.size() == numTargeted) + break; + updateLabelAncestors(); + } + + bool plainEdge = exits.implicitReturn || exits.normal; + if (!plainEdge) + return exits.explicitReturn ? FallOffKind::Never + : FallOffKind::NeverAndNoReturn; + if (abnormalEdge || fakeEdge || exits.explicitReturn) + return FallOffKind::Maybe; + return FallOffKind::Always; +} + +void FallOffAnalyzer::addAddressTakenLabels() { + if (addedAddressTakenLabels) + return; + addedAddressTakenLabels = true; + mlir::StringAttr funcName = func.getSymNameAttr(); + auto addFromAttr = [&](mlir::Attribute attr) { + attr.walk( + [&](BlockAddrInfoAttr info) { + if (info.getFunc().getAttr() == funcName) + targetedLabels.insert(info.getLabel()); + }, + [&](BlockAddrDiffAttr diff) { + if (diff.getFunc().getAttr() == funcName) { + targetedLabels.insert(diff.getLhsLabel()); + targetedLabels.insert(diff.getRhsLabel()); + } + }); + }; + auto addFromOp = [&](mlir::Operation *op) { + if (auto blockAddr = mlir::dyn_cast<BlockAddressOp>(op)) + targetedLabels.insert(blockAddr.getBlockAddrInfo().getLabel()); + else if (mlir::isa<ConstantOp, GlobalOp>(op)) + for (mlir::NamedAttribute attr : op->getAttrs()) + addFromAttr(attr.getValue()); + }; + // As in the CFG, addresses taken in static initializers count too. + func.getBody().walk(addFromOp); + if (auto module = func->getParentOfType<mlir::ModuleOp>()) + for (GlobalOp global : module.getOps<GlobalOp>()) + global->walk(addFromOp); +} + +void FallOffAnalyzer::updateLabelAncestors() { + if (!labels) { + labels.emplace(); + func.getBody().walk([&](LabelOp label) { labels->push_back(label); }); + } + labelAncestors.clear(); + for (LabelOp label : *labels) { + if (!targetedLabels.contains(label.getLabelAttr())) + continue; + for (mlir::Operation *parent = label->getParentOp(); parent != func; + parent = parent->getParentOp()) + if (!labelAncestors.insert(parent).second) + break; + } +} + +Exits FallOffAnalyzer::visitRegion(mlir::Region ®ion, bool entered) { + Exits exits; + if (region.empty()) { + exits.normal = entered; + return exits; + } + + // Dead code is still walked when a goto or a switch dispatch may enter it, + // and walked again if it turns out live. + bool mayHideCase = inEnteredSwitch(); + auto mustVisitDead = [&](mlir::Operation &op) { + return (mayHideCase && op.getNumRegions() != 0) || + containsTargetedLabel(&op); + }; + // Most regions have a single block, which an inline map holds without + // allocating. + llvm::SmallDenseMap<mlir::Block *, bool, 4> visited; + llvm::SmallVector<std::pair<mlir::Block *, bool>> worklist; + worklist.push_back({®ion.front(), entered}); + if (!region.hasOneBlock() && (mayHideCase || !targetedLabels.empty())) + for (mlir::Block &block : llvm::drop_begin(region)) + if (llvm::any_of(block, [&](mlir::Operation &op) { + return isTargetedLabel(&op) || mustVisitDead(op); + })) + worklist.push_back({&block, false}); + + while (!worklist.empty()) { + auto [block, live] = worklist.pop_back_val(); + auto [it, inserted] = visited.try_emplace(block, live); + if (!inserted) { + if (it->second || !live) + continue; + it->second = true; + } + + // Querying the terminator trait once per block rather than per operation + // is measurably faster. + mlir::Operation *terminator = + block->mightHaveTerminator() ? &block->back() : nullptr; + llvm::SmallVector<mlir::Block *> liveSuccessors; + for (mlir::Operation &op : *block) { + if (!live) { + if (isTargetedLabel(&op)) { + live = true; + continue; + } + if (!mustVisitDead(op)) { + if (tailOnly && (op.getNumRegions() != 0 || mlir::isa<LabelOp>(op))) + unsure = true; + continue; + } + } + + if (op.getNumRegions() != 0) { + Exits opExits = visitStructured(&op, live); + exits.mergeEscaping(opExits); + live = opExits.normal; + continue; + } + + if (!live) + continue; + + if (isNoReturnCall(&op) || isAssumeFalse(&op)) { + abnormalEdge = true; + live = false; + } else if (mlir::isa<ThrowOp>(op)) { + fakeEdge = true; + live = false; + } else if (&op == terminator) { + visitTerminator(&op, exits, liveSuccessors); + live = false; + } else if (tailOnly && mlir::isa<LabelOp>(op)) { + unsure = true; + } + } + + // A block without a terminator falls through to the region's parent. + if (live) + exits.normal = true; + + for (mlir::Block *succ : liveSuccessors) + worklist.push_back({succ, true}); + } + if (tailOnly && visited.size() != llvm::range_size(region)) + unsure = true; + return exits; +} + +void FallOffAnalyzer::visitTerminator( + mlir::Operation *op, Exits &exits, + llvm::SmallVectorImpl<mlir::Block *> &liveSuccessors) { + if (mlir::isa<YieldOp>(op)) { + exits.normal = true; + } else if (auto condOp = mlir::dyn_cast<ConditionOp>(op)) { + std::optional<bool> cond = getConstantBool(condOp.getCondition()); + exits.condTrue |= cond.value_or(true); + exits.condFalse |= !cond.value_or(false); + } else if (mlir::isa<CoReturnOp>(op)) { + exits.explicitReturn = true; + } else if (auto retOp = mlir::dyn_cast<ReturnOp>(op)) { + if (retOp.getImplicit()) + exits.implicitReturn = true; + else + exits.explicitReturn = true; + } else if (mlir::isa<TrapOp, UnreachableOp>(op)) { + // User traps and __builtin_unreachable are noreturn, like in the CFG. + auto trapOp = mlir::dyn_cast<TrapOp>(op); + bool isImplicit = trapOp ? trapOp.getImplicit() + : mlir::cast<UnreachableOp>(op).getImplicit(); + if (isImplicit) + exits.implicitReturn = true; + else + abnormalEdge = true; + } else if (mlir::isa<BreakOp>(op)) { + exits.breaks = true; + } else if (mlir::isa<ContinueOp>(op)) { + exits.continues = true; + } else if (auto brCond = mlir::dyn_cast<BrCondOp>(op)) { + std::optional<bool> cond = getConstantBool(brCond.getCond()); + if (cond.value_or(true)) + liveSuccessors.push_back(brCond.getDestTrue()); + if (!cond.value_or(false)) + liveSuccessors.push_back(brCond.getDestFalse()); + } else if (auto gotoOp = mlir::dyn_cast<GotoOp>(op)) { + reachedGotoTargets.insert(gotoOp.getLabelAttr()); + } else if (mlir::isa<IndirectGotoOp>(op)) { + reachedIndirectGoto = true; + } else { + // Everything else with successors (cir.br, cir.switch.flat, ...) + // reaches all of them. + llvm::append_range(liveSuccessors, op->getSuccessors()); + } +} + +Exits FallOffAnalyzer::visitStructured(mlir::Operation *op, bool entered) { + if (auto loop = mlir::dyn_cast<LoopOpInterface>(op)) + return visitLoop(loop, entered); + if (auto switchOp = mlir::dyn_cast<SwitchOp>(op)) + return visitSwitch(switchOp, entered); + if (auto cleanupScope = mlir::dyn_cast<CleanupScopeOp>(op)) + return visitCleanupScope(cleanupScope, entered); + + if (auto caseOp = mlir::dyn_cast<CaseOp>(op)) { + // A case is entered by falling through from the previous one or by the + // switch dispatching to it. + bool dispatched = inEnteredSwitch(); + if (dispatched && caseOp.getKind() == CaseOpKind::Default) + switches.back().hasDefault = true; + return visitRegion(caseOp.getCaseRegion(), entered || dispatched); + } + + if (auto ifOp = mlir::dyn_cast<IfOp>(op)) { + std::optional<bool> cond = getConstantBool(ifOp.getCondition()); + Exits thenExits = + visitRegion(ifOp.getThenRegion(), entered && cond.value_or(true)); + Exits elseExits = + visitRegion(ifOp.getElseRegion(), entered && !cond.value_or(false)); + Exits exits; + exits.normal = thenExits.normal || elseExits.normal; + exits.mergeEscaping(thenExits); + exits.mergeEscaping(elseExits); + return exits; + } + + if (auto tryOp = mlir::dyn_cast<TryOp>(op)) { + // Like the CFG check, treat every handler as reachable when the try is. + Exits exits = visitRegion(tryOp.getTryRegion(), entered); + for (mlir::Region &handler : tryOp.getHandlerRegions()) { + Exits handlerExits = visitRegion(handler, entered); + exits.normal |= handlerExits.normal; + exits.mergeEscaping(handlerExits); + } + return exits; + } + + // Any region may run. Scopes and ternaries complete if a region does; ops + // whose regions do not yield control complete whenever reached. + Exits exits; + bool yieldsControl = mlir::isa<ScopeOp, TernaryOp>(op); + exits.normal = entered && !yieldsControl; + for (mlir::Region ®ion : op->getRegions()) { + Exits regionExits = visitRegion(region, entered); + if (yieldsControl) + exits.normal |= regionExits.normal; + exits.mergeEscaping(regionExits); + } + return exits; +} + +Exits FallOffAnalyzer::visitLoop(LoopOpInterface loop, bool entered) { + bool isDoWhile = &loop.getEntry() == &loop.getBody(); + bool condEntered = entered && !isDoWhile; + bool bodyEntered = entered && isDoWhile; + mlir::Region *step = loop.maybeGetStep(); + + // Visit the regions in execution order. Another round is only needed when + // the loop was not entered from the top but through a goto into it. + Exits condExits, bodyExits, stepExits; + auto visitBodyAndStep = [&]() { + bodyExits = visitRegion(loop.getBody(), bodyEntered); + bool reachesLatch = bodyExits.normal || bodyExits.continues; + if (step) { + stepExits = visitRegion(*step, reachesLatch); + reachesLatch = stepExits.normal; + } + return reachesLatch; + }; + while (true) { + if (isDoWhile) { + condEntered |= visitBodyAndStep(); + condExits = visitRegion(loop.getCond(), condEntered); + if (!condExits.condTrue || bodyEntered) + break; + bodyEntered = true; + } else { + condExits = visitRegion(loop.getCond(), condEntered); + bodyEntered |= condExits.condTrue; + if (!visitBodyAndStep() || condEntered) + break; + condEntered = true; + } + } + + Exits exits; + exits.normal = condExits.condFalse || bodyExits.breaks; + for (const Exits ®ionExits : {condExits, bodyExits, stepExits}) { + exits.explicitReturn |= regionExits.explicitReturn; + exits.implicitReturn |= regionExits.implicitReturn; + } + return exits; +} + +Exits FallOffAnalyzer::visitSwitch(SwitchOp op, bool entered) { + // The switch body is entered through its cases only, so code ahead of the + // first case is dead. + switches.push_back({entered, /*hasDefault=*/false}); + Exits bodyExits = visitRegion(op.getBody(), /*entered=*/false); + bool hasDefault = switches.pop_back_val().hasDefault; + + // As in the CFG check, a switch listing every enumerator has no implicit + // default edge. + Exits exits; + exits.normal = bodyExits.normal || bodyExits.breaks || + (entered && !hasDefault && !op.getAllEnumCasesCovered()); + exits.continues = bodyExits.continues; + exits.explicitReturn = bodyExits.explicitReturn; + exits.implicitReturn = bodyExits.implicitReturn; + return exits; +} + +Exits FallOffAnalyzer::visitCleanupScope(CleanupScopeOp op, bool entered) { + Exits bodyExits = visitRegion(op.getBodyRegion(), entered); + if (op.getCleanupKind() == CleanupKind::EH) + return bodyExits; + + // A cleanup that cannot complete (e.g. a noreturn destructor) stops every + // path leaving the body. + Exits cleanupExits = visitRegion(op.getCleanupRegion(), bodyExits.any()); + if (!bodyExits.any() || cleanupExits.normal) + return bodyExits; + abnormalEdge = true; + return Exits(); +} + +llvm::StringRef cir::stringifyFallOffKind(FallOffKind kind) { + switch (kind) { + case FallOffKind::Unknown: + return "unknown"; + case FallOffKind::Never: + return "never"; + case FallOffKind::NeverAndNoReturn: + return "never-and-no-return"; + case FallOffKind::Maybe: + return "maybe"; + case FallOffKind::Always: + return "always"; + } + llvm_unreachable("unknown FallOffKind"); +} + +static bool mayComplete(FuncOp func, mlir::Operation *op); + +static bool isImplicitTerminator(mlir::Operation *op) { + if (auto ret = mlir::dyn_cast<ReturnOp>(op)) + return ret.getImplicit(); + if (auto trap = mlir::dyn_cast<TrapOp>(op)) + return trap.getImplicit(); + if (auto unreachable = mlir::dyn_cast<UnreachableOp>(op)) + return unreachable.getImplicit(); + return false; +} + +/// Conservatively, whether control may get past `last` in `block` (the whole +/// block when null). Only the closest region-holding op before it matters. +static bool mayReachPast(FuncOp func, mlir::Block &block, + mlir::Operation *last) { + for (mlir::Operation *op = last; op; op = op->getPrevNode()) { + // A goto may enter here, past anything before the label. + if (mlir::isa<LabelOp>(op)) + return true; + if (op->getNumRegions() != 0) + return mayComplete(func, op); + } + return block.isEntryBlock() || !block.hasNoPredecessors(); +} + +/// Conservatively, whether `op` may complete normally: a scope when a block of +/// its body may reach its end, anything else analyzed on its own. +static bool mayComplete(FuncOp func, mlir::Operation *op) { + mlir::Region *body = nullptr; + if (auto scope = mlir::dyn_cast<ScopeOp>(op)) + body = &scope.getScopeRegion(); + else if (auto cleanupScope = mlir::dyn_cast<CleanupScopeOp>(op)) + body = &cleanupScope.getBodyRegion(); + if (!body) + return FallOffAnalyzer(func, /*tailOnly=*/true).mayCompleteFromTop(op); + if (body->empty()) + return true; + return llvm::any_of(*body, [&](mlir::Block &block) { + if (block.empty()) + return mayReachPast(func, block, nullptr); + if (!block.mightHaveTerminator()) + return mayReachPast(func, block, &block.back()); + mlir::Operation *terminator = &block.back(); + return mlir::isa<YieldOp>(terminator) && + mayReachPast(func, block, terminator->getPrevNode()); + }); +} + +bool cir::mayFallOff(FuncOp func) { + // A coroutine ends where the code in its body does, not at an implicit + // terminator. + if (func.getCoroutineKind().has_value()) + return true; + // CIRGen emits the implicit terminator only in the function's top-level + // region; it is reached if what precedes it may complete. + return llvm::any_of(func.getBody(), [&](mlir::Block &block) { + if (block.empty()) + return mayReachPast(func, block, nullptr); + if (!block.mightHaveTerminator()) + return mayReachPast(func, block, &block.back()); + mlir::Operation *terminator = &block.back(); + return isImplicitTerminator(terminator) && + mayReachPast(func, block, terminator->getPrevNode()); + }); +} + +FallOffKind cir::analyzeFallOff(FuncOp func) { + // Declarations and aliases have no body to analyze. + if (func.getBody().empty()) + return FallOffKind::Unknown; + FallOffKind kind = FallOffAnalyzer(func).run(); +#ifdef EXPENSIVE_CHECKS + assert(((kind != FallOffKind::Maybe && kind != FallOffKind::Always) || + mayFallOff(func)) && + "mayFallOff rejected a function that falls off"); +#endif + return kind; +} + +llvm::SmallVector<FallOffResult> +cir::analyzeFallOff(mlir::ModuleOp module, + llvm::function_ref<bool(FuncOp)> filter) { + llvm::TimeTraceScope timeScope("CIRFallOffAnalysis"); + auto accept = [&](FuncOp func) { + return !func.getBody().empty() && (!filter || filter(func)); + }; + llvm::SmallVector<FallOffResult> results; + mlir::MLIRContext *context = module.getContext(); + if (!context->isMultithreadingEnabled()) { + for (FuncOp func : module.getOps<FuncOp>()) + if (accept(func)) + results.push_back({func, analyzeFallOff(func)}); + return results; + } + + // Filtering costs about as much as analyzing the few functions that pass, + // so both run in parallel; each task writes only its own slot. + llvm::SmallVector<FuncOp> funcs; + for (FuncOp func : module.getOps<FuncOp>()) + funcs.push_back(func); + llvm::SmallVector<std::optional<FallOffKind>> kinds(funcs.size()); + mlir::parallelFor(context, 0, funcs.size(), [&](size_t i) { + if (accept(funcs[i])) + kinds[i] = analyzeFallOff(funcs[i]); + }); + for (auto [func, kind] : llvm::zip_equal(funcs, kinds)) + if (kind) + results.push_back({func, *kind}); + return results; +} diff --git a/clang/lib/CIR/Dialect/Analysis/CMakeLists.txt b/clang/lib/CIR/Dialect/Analysis/CMakeLists.txt index 45ecc00c7d20e0..52870160efc63a 100644 --- a/clang/lib/CIR/Dialect/Analysis/CMakeLists.txt +++ b/clang/lib/CIR/Dialect/Analysis/CMakeLists.txt @@ -1,6 +1,7 @@ add_clang_library(MLIRCIRAnalysis CIRAliasAnalysis.cpp CIRBasicAliasAnalysis.cpp + CIRFallOffAnalysis.cpp DEPENDS mlir-headers diff --git a/clang/lib/CIR/Dialect/Transforms/CMakeLists.txt b/clang/lib/CIR/Dialect/Transforms/CMakeLists.txt index c379da7d64794c..669ec964eaea33 100644 --- a/clang/lib/CIR/Dialect/Transforms/CMakeLists.txt +++ b/clang/lib/CIR/Dialect/Transforms/CMakeLists.txt @@ -13,6 +13,7 @@ add_clang_library(MLIRCIRTransforms HoistAllocas.cpp LoweringPrepare.cpp GotoSolver.cpp + FallOffAnalysisPass.cpp IdiomRecognizer.cpp LibOpt.cpp RecordTypeConverter.cpp @@ -38,6 +39,7 @@ add_clang_library(MLIRCIRTransforms MLIRTransformUtils MLIRCIR + MLIRCIRAnalysis MLIRCIRInterfaces MLIRCIRTargetLowering MLIROpenACCDialect diff --git a/clang/lib/CIR/Dialect/Transforms/FallOffAnalysisPass.cpp b/clang/lib/CIR/Dialect/Transforms/FallOffAnalysisPass.cpp new file mode 100644 index 00000000000000..3b76af9c94b811 --- /dev/null +++ b/clang/lib/CIR/Dialect/Transforms/FallOffAnalysisPass.cpp @@ -0,0 +1,36 @@ +//===----------------------------------------------------------------------===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#include "PassDetail.h" +#include "clang/CIR/Dialect/Analysis/CIRFallOffAnalysis.h" +#include "clang/CIR/Dialect/Passes.h" + +using namespace mlir; + +namespace mlir { +#define GEN_PASS_DEF_FALLOFFANALYSIS +#include "clang/CIR/Dialect/Passes.h.inc" +} // namespace mlir + +namespace { + +struct FallOffAnalysisPass + : public impl::FallOffAnalysisBase<FallOffAnalysisPass> { + void runOnOperation() override { + for (cir::FallOffResult result : cir::analyzeFallOff(getOperation())) + emitRemark(result.func.getLoc()) + << "fall-off: " << cir::stringifyFallOffKind(result.kind); + markAllAnalysesPreserved(); + } +}; + +} // namespace + +std::unique_ptr<Pass> mlir::createFallOffAnalysisPass() { + return std::make_unique<FallOffAnalysisPass>(); +} diff --git a/clang/test/CIR/Analysis/fall-off-coroutine.cpp b/clang/test/CIR/Analysis/fall-off-coroutine.cpp new file mode 100644 index 00000000000000..b12dca09fec44c --- /dev/null +++ b/clang/test/CIR/Analysis/fall-off-coroutine.cpp @@ -0,0 +1,182 @@ +// RUN: %clang_cc1 -std=c++20 -triple x86_64-unknown-linux-gnu -I %S/../../SemaCXX -fclangir -emit-cir -clangir-disable-passes -Wno-return-type %s -o %t.cir +// RUN: cir-opt %t.cir -cir-fall-off-analysis -o /dev/null 2>&1 | FileCheck %s + +// With exceptions, the coroutine body is wrapped in an implicit try whose +// handler calls unhandled_exception(); leaving it is not flowing off. +// RUN: %clang_cc1 -std=c++20 -triple x86_64-unknown-linux-gnu -I %S/../../SemaCXX -fcxx-exceptions -fexceptions -fclangir -emit-cir -clangir-disable-passes -Wno-return-type %s -o %t-eh.cir +// RUN: cir-opt %t-eh.cir -cir-fall-off-analysis -o /dev/null 2>&1 | FileCheck %s --check-prefixes=CHECK,EH + +// RUN: %clang_cc1 -std=c++20 -triple x86_64-unknown-linux-gnu -I %S/../../SemaCXX -fsyntax-only -Wreturn-type -verify %s +// RUN: %clang_cc1 -std=c++20 -triple x86_64-unknown-linux-gnu -I %S/../../SemaCXX -fcxx-exceptions -fexceptions -fsyntax-only -Wreturn-type -verify %s + +#include "Inputs/std-coroutine.h" + +using std::suspend_always; + +struct awaitable { + bool await_ready(); + void await_suspend(std::coroutine_handle<>); + void await_resume(); +} a; + +// await_resume of the initial suspend may throw, so with exceptions the +// implicit try is also nested in an `if` that skips the body. +struct throwing_suspend { + bool await_ready(); + void await_suspend(std::coroutine_handle<>); + void await_resume(); +}; + +struct promise_int { + int get_return_object(); + suspend_always initial_suspend(); + suspend_always final_suspend() noexcept; + void return_value(int); + void unhandled_exception(); +}; + +struct promise_long { + long get_return_object(); + throwing_suspend initial_suspend(); + suspend_always final_suspend() noexcept; + void return_value(int); + void unhandled_exception(); +}; + +struct promise_float { + float get_return_object(); + suspend_always initial_suspend(); + suspend_always final_suspend() noexcept; + void return_void(); + void unhandled_exception(); +}; + +struct promise_void_return_value { + void get_return_object(); + suspend_always initial_suspend(); + suspend_always final_suspend() noexcept; + void return_value(int); + void unhandled_exception(); +}; + +template <typename... T> +struct std::coroutine_traits<int, T...> { using promise_type = promise_int; }; +template <typename... T> +struct std::coroutine_traits<long, T...> { using promise_type = promise_long; }; +template <typename... T> +struct std::coroutine_traits<float, T...> { using promise_type = promise_float; }; +template <typename... T> +struct std::coroutine_traits<void, T...> { + using promise_type = promise_void_return_value; +}; + +[[noreturn]] void die(); + +// CHECK-DAG: fall-off-coroutine.cpp:[[@LINE+1]]:1: remark: fall-off: always +int always() { + co_await a; +} // expected-warning {{non-void coroutine does not return a value}} + +// CHECK-DAG: fall-off-coroutine.cpp:[[@LINE+1]]:1: remark: fall-off: maybe +int maybe(bool b) { + if (b) + co_return 1; +} // expected-warning {{non-void coroutine does not return a value in all control paths}} + +// CHECK-DAG: fall-off-coroutine.cpp:[[@LINE+1]]:1: remark: fall-off: never +int never(bool b) { + if (b) + co_return 1; + co_await a; + co_return 2; +} + +// CHECK-DAG: fall-off-coroutine.cpp:[[@LINE+1]]:1: remark: fall-off: never +int never_if_else(bool b) { + if (b) + co_return 1; + else + co_return 2; +} + +// CHECK-DAG: fall-off-coroutine.cpp:[[@LINE+1]]:1: remark: fall-off: never-and-no-return +int ends_in_noreturn() { + co_await a; + die(); +} + +// CHECK-DAG: fall-off-coroutine.cpp:[[@LINE+1]]:1: remark: fall-off: never-and-no-return +int infinite_loop() { + for (;;) + co_await a; +} + +// CHECK-DAG: fall-off-coroutine.cpp:[[@LINE+1]]:1: remark: fall-off: maybe +int loop_breaks(int n) { + while (n--) { + if (n == 3) + break; + co_return n; + } +} // expected-warning {{non-void coroutine does not return a value in all control paths}} + +// CHECK-DAG: fall-off-coroutine.cpp:[[@LINE+1]]:1: remark: fall-off: always +long throwing_initial_resume() { + co_await a; +} // expected-warning {{non-void coroutine does not return a value}} + +// CHECK-DAG: fall-off-coroutine.cpp:[[@LINE+1]]:1: remark: fall-off: never +long throwing_initial_resume_returns(bool b) { + if (b) + co_return 1; + co_return 2; +} + +// The fall-through handler, return_void(), is the implicit co_return. +// CHECK-DAG: fall-off-coroutine.cpp:[[@LINE+1]]:1: remark: fall-off: never +float return_void() { + co_await a; +} + +// Without return_void(), flowing off is undefined whatever the return type. +// CHECK-DAG: fall-off-coroutine.cpp:[[@LINE+1]]:1: remark: fall-off: always +void void_without_return_void(int) { + co_await a; +} // expected-warning {{non-void coroutine does not return a value}} + +// CHECK-DAG: fall-off-coroutine.cpp:[[@LINE+1]]:1: remark: fall-off: never +int use_lambda() { + // CHECK-DAG: fall-off-coroutine.cpp:[[@LINE+1]]:{{[0-9]+}}: remark: fall-off: maybe + auto l = [](bool b) -> int { + if (b) + co_return 1; + }; // expected-warning {{non-void lambda does not return a value in all control paths}} + (void)l(true); + co_return 0; +} + +#ifdef __EXCEPTIONS +// A try written in the body is not the implicit one. +// EH-DAG: fall-off-coroutine.cpp:[[@LINE+1]]:1: remark: fall-off: maybe +int user_try() { + try { + co_return 1; + } catch (...) { + } +} // expected-warning {{non-void coroutine does not return a value in all control paths}} + +// EH-DAG: fall-off-coroutine.cpp:[[@LINE+1]]:1: remark: fall-off: never +int user_try_returns() { + try { + co_return 1; + } catch (...) { + co_return 2; + } +} + +// EH-DAG: fall-off-coroutine.cpp:[[@LINE+1]]:1: remark: fall-off: never-and-no-return +int ends_in_throw() { + co_await a; + throw 1; +} +#endif diff --git a/clang/test/CIR/Analysis/fall-off.c b/clang/test/CIR/Analysis/fall-off.c new file mode 100644 index 00000000000000..bf3afa77a33196 --- /dev/null +++ b/clang/test/CIR/Analysis/fall-off.c @@ -0,0 +1,180 @@ +// RUN: %clang_cc1 -triple x86_64-unknown-linux-gnu -fclangir -emit-cir -clangir-disable-passes -Wno-return-type %s -o %t.cir +// RUN: cir-opt %t.cir -cir-fall-off-analysis -o /dev/null 2>&1 | FileCheck %s +// RUN: cir-opt %t.cir -cir-fall-off-analysis --mlir-disable-threading -o /dev/null 2>&1 | FileCheck %s +// RUN: cir-opt %t.cir -cir-fall-off-analysis -o /dev/null 2>&1 | FileCheck %s --check-prefix=ALIAS + +// The warning annotations are what Sema's CFG-based check reports for the +// same code, so both classifications are pinned to each other. +// RUN: %clang_cc1 -triple x86_64-unknown-linux-gnu -fsyntax-only -Wreturn-type -verify %s + +_Noreturn void stop(void); + +// CHECK: fall-off.c:[[@LINE+1]]:1: remark: fall-off: maybe +int maybe(int x) { + if (x) + return 1; +} // expected-warning {{non-void function does not return a value in all control paths}} + +// CHECK: fall-off.c:[[@LINE+1]]:1: remark: fall-off: never +int while_one(int x) { + while (1) { + if (x) + return 1; + } +} + +// CHECK: fall-off.c:[[@LINE+1]]:1: remark: fall-off: always +int do_while_zero(int x) { + do { + if (x) + break; + } while (0); +} // expected-warning {{non-void function does not return a value}} + +// CHECK: fall-off.c:[[@LINE+1]]:1: remark: fall-off: never-and-no-return +int only_noreturn_call(void) { + stop(); +} + +// CHECK: fall-off.c:[[@LINE+1]]:1: remark: fall-off: never-and-no-return +int goto_loop(void) { +loop: + goto loop; +} + +// CHECK: fall-off.c:[[@LINE+1]]:1: remark: fall-off: never +int computed_goto(int x) { + void *target = x ? &&one : &&two; + goto *target; +one: + return 1; +two: + return 2; +} + +// CHECK: fall-off.c:[[@LINE+1]]:1: remark: fall-off: maybe +int computed_goto_to_end(int x) { + void *target = x ? &&one : &&two; + goto *target; +one: + return 1; +two:; +} // expected-warning {{non-void function does not return a value in all control paths}} + +// Like in the CFG, a label whose address is taken is reached only through a +// reachable indirect goto, including addresses taken in static initializers. +// CHECK: fall-off.c:[[@LINE+1]]:1: remark: fall-off: never +int address_taken_without_indirect_goto(void) { + void *p = &&l; + (void)p; + return 0; +l:; +} + +// CHECK: fall-off.c:[[@LINE+1]]:1: remark: fall-off: never +int dead_indirect_goto(void) { + return 0; + void *p = &&l; + goto *p; +l:; +} + +// CHECK: fall-off.c:[[@LINE+1]]:1: remark: fall-off: maybe +int static_table_indirect_goto(int i) { + static void *table[] = {&&one, &&two}; + goto *table[i]; +one: + return 1; +two:; +} // expected-warning {{non-void function does not return a value in all control paths}} + +// CHECK: fall-off.c:[[@LINE+1]]:1: remark: fall-off: never +int dead_goto(int x) { + while (0) { + goto out; + } + return 1; +out:; +} + +// CHECK: fall-off.c:[[@LINE+1]]:1: remark: fall-off: never +int constant_or(int x) { + if (x == 1) + return 1; + else if (x == 2 || 1) + return 2; +} + +// CHECK: fall-off.c:[[@LINE+1]]:1: remark: fall-off: maybe +int nonconstant_or(int x) { + if (x == 1 || x == 2) + return 1; +} // expected-warning {{non-void function does not return a value in all control paths}} + +// CHECK: fall-off.c:[[@LINE+1]]:1: remark: fall-off: never +int assume_false(int x) { + if (x) + return 1; + __builtin_assume(0); +} + +// A goto into the tail of the last scope reaches the end past its return. +// CHECK: fall-off.c:[[@LINE+1]]:1: remark: fall-off: maybe +int goto_into_trailing_scope(int x) { + if (x) + goto inside; + { + return 1; + inside:; + } +} // expected-warning {{non-void function does not return a value in all control paths}} + +// A goto into the last statement reaches its end past the returns before. +// CHECK: fall-off.c:[[@LINE+1]]:1: remark: fall-off: maybe +int goto_into_trailing_switch(int x) { + if (x > 1) + goto inside; + switch (x) { + case 0: + return 0; + default: + return 1; + inside:; + } +} // expected-warning {{non-void function does not return a value in all control paths}} + +// CHECK: fall-off.c:[[@LINE+1]]:1: remark: fall-off: maybe +int goto_past_noreturn_in_trailing_if(int x) { + if (x > 1) + goto inside; + if (x) { + stop(); + { + inside:; + } + } else { + return 0; + } +} // expected-warning {{non-void function does not return a value in all control paths}} + +// CHECK: fall-off.c:[[@LINE+1]]:1: remark: fall-off: never +int trailing_if_else_returns(int x) { + if (x) + return 1; + else + return 2; +} + +// CHECK: fall-off.c:[[@LINE+1]]:1: remark: fall-off: maybe +int trailing_loop_breaks(int x) { + while (1) { + if (x) + return 1; + if (x < 0) + break; + } +} // expected-warning {{non-void function does not return a value in all control paths}} + +// An alias has no body of its own to classify. +// ALIAS-NOT: fall-off.c:[[@LINE+1]]:{{.*}}remark +int alias_of_maybe(int x) __attribute__((alias("maybe"))); diff --git a/clang/test/CIR/Analysis/fall-off.cpp b/clang/test/CIR/Analysis/fall-off.cpp new file mode 100644 index 00000000000000..f70ab57a58a115 --- /dev/null +++ b/clang/test/CIR/Analysis/fall-off.cpp @@ -0,0 +1,281 @@ +// RUN: %clang_cc1 -std=c++20 -triple x86_64-unknown-linux-gnu -fcxx-exceptions -fexceptions -fclangir -emit-cir -clangir-disable-passes -Wno-return-type %s -o %t.cir +// RUN: cir-opt %t.cir -cir-fall-off-analysis -o /dev/null 2>&1 | FileCheck %s + +// At -O1 the fall-off terminator is cir.unreachable rather than cir.trap. +// RUN: %clang_cc1 -std=c++20 -triple x86_64-unknown-linux-gnu -fcxx-exceptions -fexceptions -O1 -fclangir -emit-cir -clangir-disable-passes -Wno-return-type %s -o %t-O1.cir +// RUN: cir-opt %t-O1.cir -cir-fall-off-analysis -o /dev/null 2>&1 | FileCheck %s + +// The warning annotations are what Sema's CFG-based check reports +// for the same code, so both classifications are pinned to each other. +// RUN: %clang_cc1 -std=c++20 -triple x86_64-unknown-linux-gnu -fcxx-exceptions -fexceptions -fsyntax-only -Wreturn-type -verify %s + +[[noreturn]] void die(); +int g(); + +// CHECK-DAG: fall-off.cpp:[[@LINE+1]]:1: remark: fall-off: always +int always(int x) { + x++; +} // expected-warning {{non-void function does not return a value}} + +// CHECK-DAG: fall-off.cpp:[[@LINE+1]]:1: remark: fall-off: maybe +int maybe(int x) { + if (x) + return 1; +} // expected-warning {{non-void function does not return a value in all control paths}} + +// CHECK-DAG: fall-off.cpp:[[@LINE+1]]:1: remark: fall-off: never +int never(int x) { + if (x) + return 1; + return 0; +} + +// CHECK-DAG: fall-off.cpp:[[@LINE+1]]:1: remark: fall-off: never +int noreturn_call(int x) { + if (x) + return 1; + die(); +} + +// CHECK-DAG: fall-off.cpp:[[@LINE+1]]:1: remark: fall-off: never-and-no-return +int only_noreturn_call() { + die(); +} + +// CHECK-DAG: fall-off.cpp:[[@LINE+1]]:1: remark: fall-off: never +int user_unreachable(int x) { + if (x) + return 1; + __builtin_unreachable(); +} + +// CHECK-DAG: fall-off.cpp:[[@LINE+1]]:1: remark: fall-off: never +int user_trap(int x) { + if (x) + return 1; + __builtin_trap(); +} + +// CHECK-DAG: fall-off.cpp:[[@LINE+1]]:1: remark: fall-off: maybe +int noreturn_on_some_path(int x) { + if (x) + die(); +} // expected-warning {{non-void function does not return a value in all control paths}} + +// CHECK-DAG: fall-off.cpp:[[@LINE+1]]:1: remark: fall-off: never +int constant_condition() { + if (true) + return 1; +} + +// CHECK-DAG: fall-off.cpp:[[@LINE+1]]:1: remark: fall-off: never-and-no-return +int infinite_loop() { + while (true) { + } +} + +// CHECK-DAG: fall-off.cpp:[[@LINE+1]]:1: remark: fall-off: always +int infinite_loop_with_break(int x) { + while (true) { + if (x) + break; + } +} // expected-warning {{non-void function does not return a value}} + +// CHECK-DAG: fall-off.cpp:[[@LINE+1]]:1: remark: fall-off: never +int for_ever(int x) { + for (;;) { + if (x) + return 1; + } +} + +// CHECK-DAG: fall-off.cpp:[[@LINE+1]]:1: remark: fall-off: maybe +int while_may_not_run(int x) { + while (x) + return 1; +} // expected-warning {{non-void function does not return a value in all control paths}} + +// CHECK-DAG: fall-off.cpp:[[@LINE+1]]:1: remark: fall-off: never +int do_while_runs_once(int x) { + do { + return 1; + } while (x); +} + +// CHECK-DAG: fall-off.cpp:[[@LINE+1]]:1: remark: fall-off: maybe +int continue_reaches_exit(int x) { + for (int i = 0; i < x; ++i) { + if (i == 3) + continue; + return i; + } +} // expected-warning {{non-void function does not return a value in all control paths}} + +// CHECK-DAG: fall-off.cpp:[[@LINE+1]]:1: remark: fall-off: never +int switch_with_default(int x) { + switch (x) { + case 0: + return 0; + default: + return 1; + } +} + +// CHECK-DAG: fall-off.cpp:[[@LINE+1]]:1: remark: fall-off: maybe +int switch_without_default(int x) { + switch (x) { + case 0: + return 0; + case 1: + return 1; + } +} // expected-warning {{non-void function does not return a value in all control paths}} + +enum E { A, B }; + +// CHECK-DAG: fall-off.cpp:[[@LINE+1]]:1: remark: fall-off: never +int switch_covers_enum(E e) { + switch (e) { + case A: + return 0; + case B: + return 1; + } +} + +// CHECK-DAG: fall-off.cpp:[[@LINE+1]]:1: remark: fall-off: maybe +int switch_break(int x) { + switch (x) { + case 0: + break; + default: + return 1; + } +} // expected-warning {{non-void function does not return a value in all control paths}} + +// A switch dispatches to cases nested anywhere in its body, even after dead +// code. +// CHECK-DAG: fall-off.cpp:[[@LINE+1]]:1: remark: fall-off: maybe +int switch_nested_case_after_dead_code(int x) { + switch (x) { + return 0; + { + case 1: + return 1; + } + } +} // expected-warning {{non-void function does not return a value in all control paths}} + +// CHECK-DAG: fall-off.cpp:[[@LINE+1]]:1: remark: fall-off: never +int switch_nested_default_after_dead_code(int x) { + switch (x) { + return 5; + { + default: + return 1; + } + } +} + +// CHECK-DAG: fall-off.cpp:[[@LINE+1]]:1: remark: fall-off: maybe +int switch_case_in_loop(int x, int n) { + switch (x) { + case 0: + do { + n--; + case 1: + n--; + } while (n > 0); + return n; + } +} // expected-warning {{non-void function does not return a value in all control paths}} + +// CHECK-DAG: fall-off.cpp:[[@LINE+1]]:1: remark: fall-off: never +int switch_fallthrough(int x) { + switch (x) { + case 0: + x++; + [[fallthrough]]; + default: + return x; + } +} + +// CHECK-DAG: fall-off.cpp:[[@LINE+1]]:1: remark: fall-off: never +int throw_on_some_path(int x) { + if (x) + return 1; + throw 0; +} + +// CHECK-DAG: fall-off.cpp:[[@LINE+1]]:1: remark: fall-off: never-and-no-return +int only_throw() { + throw 1; +} + +// CHECK-DAG: fall-off.cpp:[[@LINE+1]]:1: remark: fall-off: maybe +int catch_falls_off() { + try { + return g(); + } catch (...) { + } +} // expected-warning {{non-void function does not return a value in all control paths}} + +struct NoReturnDtor { + [[noreturn]] ~NoReturnDtor(); +}; + +// CHECK-DAG: fall-off.cpp:[[@LINE+1]]:1: remark: fall-off: never-and-no-return +int noreturn_destructor() { + NoReturnDtor d; +} + +struct Dtor { + ~Dtor(); +}; + +// The body of a function with a destructor to run is a cleanup scope. +// CHECK-DAG: fall-off.cpp:[[@LINE+1]]:1: remark: fall-off: maybe +int cleanup_scope_falls_off(int x) { + Dtor d; + if (x) + return 1; +} // expected-warning {{non-void function does not return a value in all control paths}} + +// CHECK-DAG: fall-off.cpp:[[@LINE+1]]:1: remark: fall-off: never +int cleanup_scope_returns() { + Dtor d; + return 1; + g(); +} + +// CHECK-DAG: fall-off.cpp:[[@LINE+1]]:1: remark: fall-off: never +int goto_to_return(int x) { + if (x) + goto out; + return 0; +out: + return 1; +} + +// CHECK-DAG: fall-off.cpp:[[@LINE+1]]:1: remark: fall-off: maybe +int goto_to_end(int x) { + if (x) + goto out; + return 0; +out:; +} // expected-warning {{non-void function does not return a value in all control paths}} + +// CHECK-DAG: fall-off.cpp:[[@LINE+1]]:1: remark: fall-off: always +void void_function() {} + +// CHECK-DAG: fall-off.cpp:[[@LINE+1]]:1: remark: fall-off: never +int use_lambda(int x) { + // CHECK-DAG: fall-off.cpp:[[@LINE+1]]:{{[0-9]+}}: remark: fall-off: maybe + auto l = [](int y) -> int { + if (y) + return 1; + }; // expected-warning {{non-void lambda does not return a value in all control paths}} + return l(x); +} diff --git a/clang/tools/cir-opt/cir-opt.cpp b/clang/tools/cir-opt/cir-opt.cpp index 92c607247f1e73..240321ce4e2e2c 100644 --- a/clang/tools/cir-opt/cir-opt.cpp +++ b/clang/tools/cir-opt/cir-opt.cpp @@ -81,6 +81,10 @@ int main(int argc, char **argv) { return mlir::createGotoSolverPass(); }); + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return mlir::createFallOffAnalysisPass(); + }); + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { return mlir::createCXXABILoweringPass(); }); _______________________________________________ cfe-commits mailing list [email protected] https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
