Skip to content

[NFC] Refactor parameter counting #10271

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
79 changes: 40 additions & 39 deletions include/swift/AST/Types.h
Original file line number Diff line number Diff line change
Expand Up @@ -2282,7 +2282,35 @@ getSILFunctionLanguage(SILFunctionTypeRepresentation rep) {

llvm_unreachable("Unhandled SILFunctionTypeRepresentation in switch.");
}


/// A call argument or parameter.
struct CallArgParam {
/// The type of the argument or parameter. For a variadic parameter,
/// this is the element type.
Type Ty;

// The label associated with the argument or parameter, if any.
Identifier Label;

/// Whether the parameter has a default argument. Not valid for arguments.
bool HasDefaultArgument = false;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

HasDefaultArgument doesn't belong in the type. I think you will need to use something other than CallArgParam for your storage.


/// Parameter specific flags, not valid for arguments
ParameterTypeFlags parameterFlags = {};

/// Whether the argument or parameter has a label.
bool hasLabel() const { return !Label.empty(); }

/// Whether the parameter is varargs
bool isVariadic() const { return parameterFlags.isVariadic(); }

/// Whether the parameter is autoclosure
bool isAutoClosure() const { return parameterFlags.isAutoClosure(); }

/// Whether the parameter is escaping
bool isEscaping() const { return parameterFlags.isEscaping(); }
};

/// AnyFunctionType - A function type has a single input and result, but
/// these types may be tuples, for example:
/// "(int) -> int" or "(a : int, b : int) -> (int, int)".
Expand All @@ -2295,7 +2323,8 @@ getSILFunctionLanguage(SILFunctionTypeRepresentation rep) {
/// be 'thin', indicating that a function value has no capture context and can be
/// represented at the binary level as a single function pointer.
class AnyFunctionType : public TypeBase {
const Type Input;
const ArrayRef<CallArgParam> Input;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'd prefer to tail-allocate the parameters in the subclasses, so we don't pay for this extra pointer in such a common type.

const Type RawInput;
const Type Output;

public:
Expand Down Expand Up @@ -2441,15 +2470,14 @@ class AnyFunctionType : public TypeBase {

protected:
AnyFunctionType(TypeKind Kind, const ASTContext *CanTypeContext,
Type Input, Type Output, RecursiveTypeProperties properties,
const ExtInfo &Info)
: TypeBase(Kind, CanTypeContext, properties), Input(Input), Output(Output) {
AnyFunctionTypeBits.ExtInfo = Info.Bits;
}
ArrayRef<CallArgParam> Input, Type RawInput, Type Output,
RecursiveTypeProperties properties,
const ExtInfo &Info);

public:

Type getInput() const { return Input; }

const ArrayRef<CallArgParam> getParams() const { return Input; }
Type getInput() const { return RawInput; }
Type getResult() const { return Output; }

ExtInfo getExtInfo() const {
Expand Down Expand Up @@ -2533,41 +2561,14 @@ BEGIN_CAN_TYPE_WRAPPER(FunctionType, AnyFunctionType)
return CanFunctionType(cast<FunctionType>(getPointer()->withExtInfo(info)));
}
END_CAN_TYPE_WRAPPER(FunctionType, AnyFunctionType)

/// A call argument or parameter.
struct CallArgParam {
/// The type of the argument or parameter. For a variadic parameter,
/// this is the element type.
Type Ty;

// The label associated with the argument or parameter, if any.
Identifier Label;

/// Whether the parameter has a default argument. Not valid for arguments.
bool HasDefaultArgument = false;

/// Parameter specific flags, not valid for arguments
ParameterTypeFlags parameterFlags = {};

/// Whether the argument or parameter has a label.
bool hasLabel() const { return !Label.empty(); }

/// Whether the parameter is varargs
bool isVariadic() const { return parameterFlags.isVariadic(); }

/// Whether the parameter is autoclosure
bool isAutoClosure() const { return parameterFlags.isAutoClosure(); }

/// Whether the parameter is escaping
bool isEscaping() const { return parameterFlags.isEscaping(); }
};


/// Break an argument type into an array of \c CallArgParams.
///
/// \param type The type to decompose.
/// \param argumentLabels The argument labels to use.
SmallVector<CallArgParam, 4>
decomposeArgType(Type type, ArrayRef<Identifier> argumentLabels);
decomposeArgType(Type type, ArrayRef<Identifier> argumentLabels,
bool inAnyFunctionType = false);

/// Break a parameter type into an array of \c CallArgParams.
///
Expand Down
27 changes: 24 additions & 3 deletions lib/AST/ASTContext.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -3136,6 +3136,16 @@ getGenericFunctionRecursiveProperties(Type Input, Type Result) {
return properties;
}

AnyFunctionType::AnyFunctionType(TypeKind Kind, const ASTContext *CanTypeContext,
ArrayRef<CallArgParam> Input, Type RawInput, Type Output,
RecursiveTypeProperties properties,
const ExtInfo &Info)
: TypeBase(Kind, CanTypeContext, properties),
Input((CanTypeContext ?: &RawInput->getASTContext())->AllocateCopy(Input)),
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hmm... I'm confused why we're doing the CanTypeContext null check dance here. If we do the tail allocation thing, then don't need to do the AllocateCopy dance here... we just copy over the data we get.

RawInput(RawInput), Output(Output) {
AnyFunctionTypeBits.ExtInfo = Info.Bits;
}

AnyFunctionType *AnyFunctionType::withExtInfo(ExtInfo info) const {
if (isa<FunctionType>(this))
return FunctionType::get(getInput(), getResult(), info);
Expand Down Expand Up @@ -3167,6 +3177,17 @@ FunctionType *FunctionType::get(Type Input, Type Result,
Info);
}

static SmallVector<CallArgParam, 4> decomposeInput(Type ty) {
if (auto *TTy = dyn_cast<TupleType>(ty.getPointer())) {
SmallVector<Identifier, 4> labels;
for (auto &ttyElt : TTy->getElements()) {
labels.push_back(ttyElt.getName());
}
return decomposeArgType(TTy, labels, /*inAnyFunctionType*/true);
}
return decomposeArgType(ty, { Identifier() }, /*inAnyFunctionType*/true);
}

// If the input and result types are canonical, then so is the result.
FunctionType::FunctionType(Type input, Type output,
RecursiveTypeProperties properties,
Expand All @@ -3175,7 +3196,7 @@ FunctionType::FunctionType(Type input, Type output,
(input->isCanonical() && output->isCanonical())
? &input->getASTContext()
: nullptr,
input, output, properties, Info) {}
decomposeInput(input), input, output, properties, Info) {}

void GenericFunctionType::Profile(llvm::FoldingSetNodeID &ID,
GenericSignature *sig,
Expand Down Expand Up @@ -3242,8 +3263,8 @@ GenericFunctionType::GenericFunctionType(
const ExtInfo &info,
const ASTContext *ctx,
RecursiveTypeProperties properties)
: AnyFunctionType(TypeKind::GenericFunction, ctx, input, result,
properties, info),
: AnyFunctionType(TypeKind::GenericFunction, ctx, decomposeInput(input),
input, result, properties, info),
Signature(sig)
{}

Expand Down
11 changes: 7 additions & 4 deletions lib/AST/Type.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -710,7 +710,8 @@ Type TypeBase::replaceCovariantResultType(Type newResultType,
}

SmallVector<CallArgParam, 4>
swift::decomposeArgType(Type type, ArrayRef<Identifier> argumentLabels) {
swift::decomposeArgType(Type type, ArrayRef<Identifier> argumentLabels,
bool inAnyFunctionType) {
SmallVector<CallArgParam, 4> result;
switch (type->getKind()) {
case TypeKind::Tuple: {
Expand All @@ -727,9 +728,11 @@ swift::decomposeArgType(Type type, ArrayRef<Identifier> argumentLabels) {

for (auto i : range(0, tupleTy->getNumElements())) {
const auto &elt = tupleTy->getElement(i);
assert(elt.getParameterFlags().isNone() &&
"Vararg, autoclosure, or escaping argument tuple"
"doesn't make sense");
if (!inAnyFunctionType) {
assert(elt.getParameterFlags().isNone() &&
"Vararg, autoclosure, or escaping argument tuple"
"doesn't make sense");
}
CallArgParam argParam;
argParam.Ty = elt.getType();
argParam.Label = argumentLabels[i];
Expand Down
63 changes: 36 additions & 27 deletions lib/Sema/CSGen.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -690,25 +690,34 @@ namespace {
return nOperands;
}

/// Return a pair, containing the total parameter count of a function, coupled
/// with the number of non-default parameters.
std::pair<size_t, size_t> getParamCount(ValueDecl *VD) {
auto fTy = VD->getInterfaceType()->getAs<AnyFunctionType>();
assert(fTy && "attempting to count parameters of a non-function type");
/// Return a pair, containing the total parameter count of a function and
/// the number of non-default parameters.
std::pair<size_t, size_t> getParamCount(AnyFunctionType *fTy) {
auto inputTy = fTy->getParams();
size_t nOperands = 0;
if (inputTy.size() == 1
&& !inputTy.front().hasLabel()
&& inputTy.front().Ty->isTypeVariableOrMember()) {
nOperands = 1;
} else {
nOperands = inputTy.size();
}

auto inputTy = fTy->getInput();
size_t nOperands = getOperandCount(inputTy);
size_t nNoDefault = 0;
if (auto AFD = dyn_cast<AbstractFunctionDecl>(VD)) {
for (auto params : AFD->getParameterLists()) {
for (auto param : *params) {
if (!param->isDefaultArgument())
nNoDefault++;

ArrayRef<CallArgParam> params = fTy->getParams();
while (true) {
for (auto &param : params) {
if (!param.HasDefaultArgument) {
nNoDefault++;
}
}
} else {
nNoDefault = nOperands;

if (auto *nextFn = fTy->getResult()->getAs<AnyFunctionType>()) {
params = nextFn->getParams();
} else {
break;
}
}

return { nOperands, nNoDefault };
Expand Down Expand Up @@ -759,27 +768,27 @@ namespace {
bool haveMultipleApplicableOverloads = false;

for (auto VD : ODR->getDecls()) {
if (VD->getInterfaceType()->is<AnyFunctionType>()) {
auto nParams = getParamCount(VD);
if (nArgs == nParams.first) {
if (haveMultipleApplicableOverloads) {
return;
} else {
haveMultipleApplicableOverloads = true;
}
auto *vTy = VD->getInterfaceType()->getAs<AnyFunctionType>();
if (!vTy) continue;

auto nParams = getParamCount(vTy);
if (nArgs == nParams.first) {
if (haveMultipleApplicableOverloads) {
return;
} else {
haveMultipleApplicableOverloads = true;
}
}
}

// Determine whether the given declaration is favored.
auto isFavoredDecl = [&](ValueDecl *value) -> bool {
auto valueTy = value->getInterfaceType();
auto valueTy = value->getInterfaceType()->getAs<AnyFunctionType>();

if (!valueTy->is<AnyFunctionType>())
if (!valueTy)
return false;

auto paramCount = getParamCount(value);
auto paramCount = getParamCount(valueTy);

return nArgs == paramCount.first ||
nArgs == paramCount.second;
Expand Down