Support more types in MapConstantToAPValue by refactoring code out of ConvertArgToTemplateArg (#6923)

This doesn't change any of the current tests, but will be useful for
calling constexpr functions with bool/float params.
This commit is contained in:
Nicholas Bishop
2026-03-18 16:11:42 +00:00
committed by GitHub
parent 98e2567524
commit 0482b27c6b
3 changed files with 34 additions and 41 deletions
+7 -32
View File
@@ -8,6 +8,7 @@
#include "clang/Sema/Template.h"
#include "toolchain/base/kind_switch.h"
#include "toolchain/check/call.h"
#include "toolchain/check/cpp/constant.h"
#include "toolchain/check/cpp/import.h"
#include "toolchain/check/cpp/location.h"
#include "toolchain/check/cpp/operators.h"
@@ -227,38 +228,7 @@ static auto ConvertArgToTemplateArg(
auto const_inst_id =
context.constant_values().GetConstantInstId(converted_inst_id);
if (const_inst_id.has_value()) {
if (param_type->isIntegerType()) {
const bool is_signed = param_type->isSignedIntegerOrEnumerationType();
if (auto int_value =
context.insts().TryGetAs<SemIR::IntValue>(const_inst_id)) {
const auto& ap_int = context.ints().Get(int_value->int_id);
auto aps_int =
llvm::APSInt(ap_int, !is_signed)
.extOrTrunc(context.ast_context().getIntWidth(param_type));
clang::TemplateArgument template_arg(context.ast_context(), aps_int,
param_type);
return clang::TemplateArgumentLoc(template_arg, template_loc);
} else if (auto bool_value =
context.insts().TryGetAs<SemIR::BoolLiteral>(
const_inst_id)) {
llvm::APInt ap_int(context.ast_context().getIntWidth(param_type),
bool_value->value.ToBool(), is_signed);
auto aps_int =
llvm::APSInt(ap_int, !is_signed)
.extOrTrunc(context.ast_context().getIntWidth(param_type));
auto template_arg = clang::TemplateArgument(context.ast_context(),
aps_int, param_type);
return clang::TemplateArgumentLoc(template_arg, template_loc);
}
} else if (param_type->isFloatingType()) {
if (auto float_value =
context.insts().TryGetAs<SemIR::FloatValue>(const_inst_id)) {
const auto& ap_float = context.floats().Get(float_value->float_id);
clang::TemplateArgument template_arg(
context.ast_context(), param_type, clang::APValue(ap_float));
return clang::TemplateArgumentLoc(template_arg, template_loc);
}
} else if (param_type->isPointerType()) {
if (param_type->isPointerType()) {
if (auto addr_of =
context.insts().TryGetAs<SemIR::AddrOf>(const_inst_id)) {
if (auto* var_decl = GetAsClangVarDecl(context, addr_of->lvalue_id)) {
@@ -268,6 +238,11 @@ static auto ConvertArgToTemplateArg(
// TODO: support pointers to variables declared in Carbon.
}
} else if (auto ap_value =
MapConstantToAPValue(context, const_inst_id, param_type)) {
clang::TemplateArgument template_arg(context.ast_context(), param_type,
*ap_value);
return clang::TemplateArgumentLoc(template_arg, template_loc);
}
}