module clice; import :compile.compilation; import :compile.directive; import :feature.code_actions.body; namespace clice::feature::action { namespace { /// Whether evaluating `stmt` writes something itself, not through a call. bool writes(const clang::Stmt* stmt) { if(auto* op = llvm::dyn_cast(stmt); op && op->isAssignmentOp()) { return true; } if(auto* op = llvm::dyn_cast(stmt); op && op->isIncrementDecrementOp()) { return true; } if(auto* call = llvm::dyn_cast(stmt)) { auto kind = call->getOperator(); if(clang::CXXOperatorCallExpr::isAssignmentOp(kind) || kind == clang::OO_PlusPlus || kind == clang::OO_MinusMinus) { return true; } } if(llvm::isa(stmt)) { return true; } // A lambda's body runs when it is called, its captures where it is // written. if(auto* lambda = llvm::dyn_cast(stmt)) { return ranges::any_of(lambda->capture_inits(), [](const clang::Expr* init) { return init && writes(init); }); } return ranges::any_of(stmt->children(), [](const clang::Stmt* child) { return child && writes(child); }); } /// The operands of `parent` evaluated around its operand `child`, by the /// language's sequencing rules (C++17's, which order the operands of /// `<<`, `=`, `[]` and a call's callee before the rest): those it /// evaluates first, and those in no order with `child`. An overloaded /// operator is sequenced as the built-in one it spells. struct Around { llvm::SmallVector before; llvm::SmallVector unordered; /// `operands` in their order: those ahead of `child` before it. template void ordered(const Range& operands, const clang::Stmt* child) { for(const auto* operand: operands) { if(operand == child) { break; } if(operand) { before.push_back(operand); } } } /// `operands` in no order with `child`. template void alongside(const Range& operands, const clang::Stmt* child) { for(const auto* operand: operands) { if(operand && operand != child) { unordered.push_back(operand); } } } }; /// Whether `parent` evaluates its operand `child` exactly once each time /// it is evaluated itself, noting in `around` what it evaluates around it. bool evaluates_once(const clang::Stmt* parent, const clang::Stmt* child, Around& around) { auto& before = around.before; if(auto* op = llvm::dyn_cast(parent)) { if(op->isLogicalOp()) { return child == op->getLHS(); } auto opcode = op->getOpcode(); if(op->isAssignmentOp()) { if(child == op->getLHS()) { before.push_back(op->getRHS()); } } else if(opcode == clang::BO_Comma || op->isShiftOp() || opcode == clang::BO_PtrMemD || opcode == clang::BO_PtrMemI) { if(child == op->getRHS()) { before.push_back(op->getLHS()); } } else { around.alongside(std::array{op->getLHS(), op->getRHS()}, child); } return true; } if(auto* call = llvm::dyn_cast(parent)) { if(child == call->getCallee()) { return true; } auto arguments = llvm::ArrayRef(call->getArgs(), call->getNumArgs()); auto kind = call->getOperator(); if(clang::CXXOperatorCallExpr::isAssignmentOp(kind)) { if(!arguments.empty() && child == arguments.front()) { before.append(arguments.begin() + 1, arguments.end()); } } else if(ranges::contains(std::array{clang::OO_AmpAmp, clang::OO_PipePipe, clang::OO_Comma, clang::OO_LessLess, clang::OO_GreaterGreater, clang::OO_ArrowStar, clang::OO_Subscript}, kind)) { around.ordered(arguments, child); } else if(kind == clang::OO_Call && !arguments.empty()) { if(child != arguments.front()) { before.push_back(arguments.front()); around.alongside(arguments.drop_front(), child); } } else { around.alongside(arguments, child); } return true; } if(auto* call = llvm::dyn_cast(parent)) { // Neither operand is evaluated at run time. auto builtin = call->getBuiltinCallee(); if(builtin == clang::Builtin::BI__builtin_constant_p || builtin == clang::Builtin::BI__builtin_assume) { return false; } if(child != call->getCallee()) { before.push_back(call->getCallee()); around.alongside(llvm::ArrayRef(call->getArgs(), call->getNumArgs()), child); } return true; } if(auto* subscript = llvm::dyn_cast(parent)) { if(child == subscript->getRHS()) { before.push_back(subscript->getLHS()); } return true; } if(auto* conditional = llvm::dyn_cast(parent)) { return child == conditional->getCond(); } if(auto* conditional = llvm::dyn_cast(parent)) { return child == conditional->getCommon(); } if(auto* list = llvm::dyn_cast(parent)) { around.ordered(list->inits(), child); return true; } if(auto* construct = llvm::dyn_cast(parent)) { if(construct->isListInitialization()) { around.ordered(construct->arguments(), child); } else { around.alongside(construct->arguments(), child); } return true; } if(auto* list = llvm::dyn_cast(parent)) { around.ordered(list->getInitExprs(), child); return true; } if(auto* lambda = llvm::dyn_cast(parent)) { around.ordered(lambda->capture_inits(), child); return true; } // Operands evaluated never, only at compile time, more than once or // through a node standing for another. if(llvm::isa(parent)) { return false; } if(llvm::isa(parent)) { around.alongside(parent->children(), child); return true; } if(auto* declaration = llvm::dyn_cast(parent)) { for(const auto* decl: declaration->decls()) { auto* var = llvm::dyn_cast(decl); if(!var || !var->getInit()) { continue; } if(var->getInit() == child) { // A static local is initialized once, a constexpr one at // compile time. return var->getStorageDuration() == clang::SD_Automatic && !var->isConstexpr(); } before.push_back(var->getInit()); } return false; } if(llvm::isa(parent)) { return true; } if(auto* branch = llvm::dyn_cast(parent)) { if(branch->isConstexpr() || branch->isConsteval()) { return false; } if(child == branch->getInit()) { return true; } if(child != branch->getConditionVariableDeclStmt() && child != branch->getCond()) { return false; } if(branch->getInit()) { before.push_back(branch->getInit()); } return true; } if(auto* selection = llvm::dyn_cast(parent)) { if(child == selection->getInit()) { return true; } if(child != selection->getConditionVariableDeclStmt() && child != selection->getCond()) { return false; } if(selection->getInit()) { before.push_back(selection->getInit()); } return true; } if(auto* loop = llvm::dyn_cast(parent)) { return child == loop->getInit(); } if(auto* loop = llvm::dyn_cast(parent)) { if(child == loop->getInit()) { return true; } if(child != loop->getRangeStmt()) { return false; } if(loop->getInit()) { before.push_back(loop->getInit()); } return true; } // Loops evaluate their condition again and again; a label is jumped // to past what precedes it. return false; } /// Whether the function type of `callee` takes argument `index` by /// reference to non-const, or may: a call through no prototype, a /// template's call not resolved yet. bool binds_mutable(clang::QualType callee, std::size_t index) { if(auto* pointer = callee->getAs()) { callee = pointer->getPointeeType(); } else if(auto* reference = callee->getAs()) { callee = reference->getPointeeType(); } auto* prototype = callee->getAs(); if(!prototype) { return true; } if(index >= prototype->getNumParams()) { return false; } auto parameter = prototype->getParamType(static_cast(index)); return parameter->isReferenceType() && !parameter.getNonReferenceType().isConstQualified(); } /// Whether a const member function or a reference to const may still /// write an object of `type`: its class has mutable fields. bool mutable_fields(clang::QualType type) { const auto* record = type->getAsCXXRecordDecl(); record = record ? record->getDefinition() : nullptr; return record && record->hasMutableFields(); } } // namespace Effects effects(clang::ASTContext& context, const clang::Stmt* stmt) { if(auto* expr = llvm::dyn_cast(stmt)) { if(!expr->HasSideEffects(context)) { return Effects::None; } return writes(expr) ? Effects::Definite : Effects::Possible; } auto result = Effects::None; for(const auto* child: stmt->children()) { if(child) { result = std::max(result, effects(context, child)); } } // A declaration constructs, and later destroys, what it declares. if(auto* declaration = llvm::dyn_cast(stmt)) { for(const auto* decl: declaration->decls()) { auto* var = llvm::dyn_cast(decl); if(var && var->getType()->getAsCXXRecordDecl()) { result = std::max(result, Effects::Possible); } } } return result; } Body::Body(const clang::Stmt* body) : body(body) { llvm::SmallVector pending{body}; while(!pending.empty()) { const auto* stmt = pending.pop_back_val(); for(const auto* child: stmt->children()) { if(child) { parents[child] = stmt; pending.push_back(child); } } } } std::optional Body::hoisting(clang::ASTContext& context, const clang::Expr* at, const clang::Expr* computed, bool sinking) const { // Moved past them, the expression sees nothing they write, they see // nothing it writes, and what it calls cannot run on the other side of // what they call; past a call, either may read only what no call // reaches. Computed in place of `at` rather than before its statement, // it meets also what the statement evaluates in no order with `at`. auto own = effects(context, computed); // An lvalue naming a variable reads nothing of it (`std::cout` of // `std::cout << f()`). auto stable = [&](const clang::Expr* expr) { if(expr->isGLValue() && llvm::isa(expr->IgnoreParenNoopCasts(context))) { return true; } auto locals = local_reads(expr, false); return locals && unchanged(*locals, {}); }; auto apart = [&](const clang::Stmt* other) { auto theirs = effects(context, other); if(own == Effects::Definite || theirs == Effects::Definite || (own == Effects::Possible && theirs == Effects::Possible)) { return false; } auto* expr = llvm::dyn_cast(other); if(own == Effects::Possible) { return expr && stable(expr); } return theirs == Effects::None || stable(computed); }; Around around; const clang::Stmt* child = at; for(const auto* holder = parent(child); holder; child = holder, holder = parent(holder)) { if(auto* block = llvm::dyn_cast(holder)) { if(!ranges::all_of(around.before, apart) || (sinking && !ranges::all_of(around.unordered, apart))) { return std::nullopt; } return Hoisting{block, child}; } if(!evaluates_once(holder, child, around)) { return std::nullopt; } } return std::nullopt; } Use Body::use(const clang::DeclRefExpr* name) const { const clang::Expr* expr = name; while(true) { const auto* holder = parent(expr); if(!holder) { return Use::Address; } if(llvm::isa(holder)) { expr = llvm::cast(holder); continue; } if(auto* cast = llvm::dyn_cast(holder)) { switch(cast->getCastKind()) { case clang::CK_LValueToRValue: case clang::CK_ToVoid: return Use::Read; case clang::CK_NoOp: if(cast->getType().isConstQualified()) { return mutable_fields(cast->getType()) ? Use::Bind : Use::Read; } break; case clang::CK_DerivedToBase: case clang::CK_UncheckedDerivedToBase: break; case clang::CK_ArrayToPointerDecay: { // Indexing an array reaches an element of it. auto* subscript = llvm::dyn_cast_or_null(parent(cast)); if(!subscript || subscript->getBase() != cast) { return Use::Address; } expr = subscript; continue; } default: return Use::Address; } expr = cast; continue; } if(auto* member = llvm::dyn_cast(holder)) { if(auto* method = llvm::dyn_cast(member->getMemberDecl())) { if(method->isStatic()) { return Use::Read; } return method->isConst() && !mutable_fields(member->getBase()->getType()) ? Use::Read : Use::Bind; } expr = member; continue; } if(auto* op = llvm::dyn_cast(holder)) { if(op->isIncrementDecrementOp()) { return Use::Write; } if(op->getOpcode() == clang::UO_AddrOf) { return Use::Address; } if(op->getOpcode() == clang::UO_Real || op->getOpcode() == clang::UO_Imag || op->getOpcode() == clang::UO_Extension) { expr = op; continue; } return Use::Address; } if(auto* op = llvm::dyn_cast(holder)) { if(op->isAssignmentOp()) { return op->getLHS() == expr ? Use::Write : Use::Read; } if(op->getOpcode() == clang::BO_Comma && op->getRHS() == expr) { expr = op; continue; } if(op->isPtrMemOp() && op->getLHS() == expr) { expr = op; continue; } return Use::Address; } if(auto* conditional = llvm::dyn_cast(holder)) { if(conditional->getCond() == expr) { return Use::Read; } expr = conditional; continue; } if(auto* call = llvm::dyn_cast(holder)) { auto arguments = llvm::ArrayRef(call->getArgs(), call->getNumArgs()); auto index = static_cast(ranges::find(arguments, expr) - arguments.begin()); auto kind = call->getOperator(); if(index == arguments.size()) { return Use::Address; } if(clang::CXXOperatorCallExpr::isAssignmentOp(kind) && index == 0) { return Use::Write; } if((kind == clang::OO_PlusPlus || kind == clang::OO_MinusMinus) && index == 0) { return Use::Write; } if(auto* method = llvm::dyn_cast_or_null(call->getDirectCallee())) { if(index == 0) { return method->isConst() && !mutable_fields(expr->getType()) ? Use::Read : Use::Bind; } index -= 1; } auto* callee = call->getDirectCallee(); return !callee || binds_mutable(callee->getType(), index) ? Use::Bind : Use::Read; } if(auto* call = llvm::dyn_cast(holder)) { auto arguments = llvm::ArrayRef(call->getArgs(), call->getNumArgs()); auto index = static_cast(ranges::find(arguments, expr) - arguments.begin()); if(index == arguments.size()) { return Use::Address; } // A member call's callee has no function type of its own. auto* callee = call->getDirectCallee(); auto type = callee ? callee->getType() : call->getCallee()->getType(); return binds_mutable(type, index) ? Use::Bind : Use::Read; } // A capture by reference; one by copy reads through a conversion // or a constructor. if(llvm::isa(holder)) { return Use::Address; } if(auto* construct = llvm::dyn_cast(holder)) { auto arguments = construct->arguments(); auto index = static_cast(ranges::find(arguments, expr) - arguments.begin()); return binds_mutable(construct->getConstructor()->getType(), index) ? Use::Bind : Use::Read; } if(auto* declaration = llvm::dyn_cast(holder)) { for(const auto* decl: declaration->decls()) { auto* var = llvm::dyn_cast(decl); if(var && var->getInit() == expr) { auto type = var->getType(); return type->isReferenceType() && !type.getNonReferenceType().isConstQualified() ? Use::Bind : Use::Read; } } return Use::Address; } // Bound to a reference: a reference member an initializer list // initializes, a function returning one. return Use::Bind; } } const clang::Stmt* Body::outer_implicit(const clang::Stmt* stmt) const { while(auto* holder = parent(stmt)) { if(!llvm::isa(holder)) { break; } stmt = holder; } return stmt; } bool Body::constant_needed(const clang::Expr* expr) const { bool converted = false; const clang::Stmt* node = expr; while(auto* cast = llvm::dyn_cast_or_null(parent(node))) { switch(cast->getCastKind()) { case clang::CK_NullToPointer: case clang::CK_NullToMemberPointer: return true; case clang::CK_IntegralCast: case clang::CK_FloatingCast: case clang::CK_IntegralToFloating: case clang::CK_FloatingToIntegral: case clang::CK_IntegralToBoolean: case clang::CK_FloatingToBoolean: converted = true; break; default: break; } node = cast; } const auto* holder = parent(node); auto* construct = llvm::dyn_cast_or_null(holder); return converted && (llvm::isa_and_present(holder) || (construct && construct->isListInitialization())); } bool Body::dangles(const clang::Expr* expr, clang::QualType kept) const { // LIMITATION: a class owning what it holds may still hold views into // a temporary (a vector of `std::string_view` into a temporary string), // which then dangle the same. const auto* record = kept->getAsCXXRecordDecl(); record = record ? record->getDefinition() : nullptr; if(record ? !record->hasTrivialDestructor() && !record->hasAttr() : kept->isArithmeticType() || kept->isEnumeralType() || kept->isNullPtrType()) { return false; } bool found = false; for_each_expr(expr, [&](const clang::Expr* node) { if(!llvm::isa(node)) { return; } for(const clang::Stmt* up = node; up != expr; up = parent(up)) { if(llvm::isa(up)) { return; } } found = true; }); return found; } bool Body::evaluated(const clang::Expr* expr) const { const clang::Stmt* node = expr; for(const auto* holder = parent(node); holder; node = holder, holder = parent(holder)) { if(llvm::isa(holder)) { return false; } if(auto* declaration = llvm::dyn_cast(holder)) { for(const auto* decl: declaration->decls()) { auto* var = llvm::dyn_cast(decl); if(var && var->getInit() == node && var->isConstexpr()) { return false; } } } } return node == body; } bool Body::unchanged(llvm::ArrayRef locals, llvm::ArrayRef region) const { auto in_region = [&](const clang::Stmt* stmt) { for(const auto* node = stmt; node; node = parent(node)) { if(ranges::contains(region, node)) { return true; } } return false; }; bool kept = true; for_each_expr(body, [&](const clang::Expr* node) { auto* name = llvm::dyn_cast(node); if(!name || !ranges::contains(locals, name->getDecl())) { return; } auto kind = use(name); kept &= kind == Use::Read || (kind == Use::Write && !in_region(name)); }); return kept; } void Body::for_each_expr(const clang::Stmt* stmt, llvm::function_ref visit) { llvm::SmallVector pending{stmt}; while(!pending.empty()) { const auto* next = pending.pop_back_val(); if(auto* expr = llvm::dyn_cast(next)) { visit(expr); } auto first = pending.size(); for(const auto* child: next->children()) { if(child) { pending.push_back(child); } } ranges::reverse(pending.begin() + static_cast(first), pending.end()); } } std::optional> local_reads(const clang::Expr* expr, bool designates) { // The variable at the root of the lvalue: through `.`, the subscripts // of an array, parentheses and conversions to a base. const clang::DeclRefExpr* designated = nullptr; for(const auto* node = expr; designates && node;) { node = node->IgnoreParens(); if(auto* member = llvm::dyn_cast(node); member && !member->isArrow()) { node = member->getBase(); } else if(auto* subscript = llvm::dyn_cast(node)) { auto* base = subscript->getBase()->IgnoreParenImpCasts(); node = base->getType()->isArrayType() ? base : nullptr; } else if(auto* cast = llvm::dyn_cast(node); cast && (cast->getCastKind() == clang::CK_DerivedToBase || cast->getCastKind() == clang::CK_UncheckedDerivedToBase || cast->getCastKind() == clang::CK_NoOp)) { node = cast->getSubExpr(); } else { designated = llvm::dyn_cast(node); break; } } llvm::SmallVector locals; bool stable = true; Body::for_each_expr(expr, [&](const clang::Expr* node) { if(auto* op = llvm::dyn_cast(node); op && op->getOpcode() == clang::UO_Deref) { stable = false; } else if(auto* member = llvm::dyn_cast(node); member && member->isArrow()) { stable = false; } else if(auto* subscript = llvm::dyn_cast(node); subscript && !subscript->getBase()->IgnoreParenImpCasts()->getType()->isArrayType()) { stable = false; } else if(llvm::isa(node)) { stable = false; } else if(auto* name = llvm::dyn_cast(node)) { const auto* decl = name->getDecl(); auto* var = llvm::dyn_cast(decl); if(name == designated && var && var->isLocalVarDeclOrParm()) { return; } if(var) { auto type = var->getType(); if(var->isLocalVarDeclOrParm() && !var->isStaticLocal() && !type->isReferenceType() && !type.isVolatileQualified()) { locals.push_back(var); } else if(!var->isConstexpr()) { stable = false; } } else if(!llvm::isa(decl)) { stable = false; } } }); if(!stable) { return std::nullopt; } return locals; } bool entered_by_jump(llvm::ArrayRef statements) { bool entered = false; auto find = [&](this auto& self, const clang::Stmt* stmt, bool own_switch) -> void { entered |= llvm::isa(stmt) || (!own_switch && llvm::isa(stmt)); for(const auto* child: stmt->children()) { if(child && !llvm::isa(child)) { self(child, own_switch || llvm::isa(stmt)); } } }; for(const auto* statement: statements) { find(statement, false); } return entered; } const clang::FunctionDecl* outermost_function(const clang::DeclContext* context) { const clang::FunctionDecl* function = nullptr; for(; context; context = context->getLexicalParent()) { if(auto* found = llvm::dyn_cast(context)) { function = found; continue; } auto* record = llvm::dyn_cast(context); if(!record || !record->isLambda()) { break; } } return function; } std::optional replaceable_range(CompilationUnit& unit, const Body& body, const clang::Expr* expr) { auto focus = unit.focus_file(); auto source = expr->getSourceRange(); auto written = focus.written_range(source); if(!written || (source.getBegin().isFileID() && source.getEnd().isFileID())) { return written; } auto& tokens = focus.tokens(); auto spelled = tokens.spelled(); auto first = tokens.spelled_at_or_after(written->begin); auto last = tokens.spelled_at_or_after(written->end); auto expansions = tokens.expansions_overlapping(spelled.slice(first, last - first)); if(expansions.size() != 1) { return std::nullopt; } const auto& expansion = expansions.front(); LocalSourceRange invocation{expansion.spelled.front().range.begin, expansion.spelled.back().range.end}; if(*written == invocation) { return written; } if(written->begin <= invocation.begin || written->end >= invocation.end || ranges::any_of(expansion.expanded, [&](const clang::syntax::Token& token) { return unit.concatenated(token.location()); })) { return std::nullopt; } // Another expansion of the argument is another expression written // there; the casts around this one share its location. auto begin = expr->getBeginLoc(); auto at = unit.written_location(begin); bool again = false; Body::for_each_expr(body.root(), [&](const clang::Expr* other) { again |= other->getBeginLoc() != begin && other->getBeginLoc().isMacroID() && unit.written_location(other->getBeginLoc()) == at; }); if(again) { return std::nullopt; } return written; } std::string fresh_name(CompilationUnit& unit, llvm::StringRef base, LocalSourceRange within, llvm::function_ref taken) { auto focus = unit.focus_file(); auto content = focus.content(); llvm::StringSet<> spelled; for(const auto& token: focus.lexical().code_from(within.begin)) { if(token.range.begin >= within.end) { break; } if(token.is_identifier()) { spelled.insert(token.text(content)); } } auto& identifiers = unit.context().Idents; std::string name = base.str(); for(std::uint32_t suffix = 2; spelled.contains(name) || identifiers.get(name).hadMacroDefinition() || (taken && taken(name)); suffix += 1) { name = std::format("{}{}", base, suffix); } return name; } bool same_macros(CompilationUnit& unit, LocalSourceRange moved, std::uint32_t to) { auto focus = unit.focus_file(); LocalSourceRange between = to < moved.begin ? LocalSourceRange{to, moved.begin} : LocalSourceRange{moved.end, to}; const auto& macros = unit.directives()[focus.file()].macros; llvm::StringSet<> invoked; for(const auto& reference: macros) { auto at = unit.produced_at(reference.loc); if(reference.kind == MacroRef::Ref && at.file == focus.file() && moved.contains(at.offset)) { invoked.insert(unit.token_spelling(reference.loc)); } } return ranges::none_of(macros, [&](const MacroRef& reference) { auto at = unit.produced_at(reference.loc); return reference.kind != MacroRef::Ref && at.file == focus.file() && between.contains(at.offset) && invoked.contains(unit.token_spelling(reference.loc)); }); } std::string separated(llvm::StringRef content, LocalSourceRange range, std::string text) { auto identifier = [](char c) { return clang::isAsciiIdentifierContinue(c); }; if(!text.empty() && range.begin > 0 && identifier(content[range.begin - 1]) && identifier(text.front())) { text.insert(text.begin(), ' '); } if(!text.empty() && range.end < content.size() && identifier(content[range.end]) && identifier(text.back())) { text += ' '; } return text; } } // namespace clice::feature::action