1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365
|
//===--- ExistentialSpecializer.cpp - Specialization of functions -----===//
//===--- with existential arguments -----===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// Specialize functions with existential parameters to generic ones.
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "sil-existential-specializer"
#include "ExistentialTransform.h"
#include "swift/SIL/SILFunction.h"
#include "swift/SIL/SILInstruction.h"
#include "swift/SILOptimizer/Analysis/ProtocolConformanceAnalysis.h"
#include "swift/SILOptimizer/PassManager/Transforms.h"
#include "swift/SILOptimizer/Utils/Existential.h"
#include "swift/SILOptimizer/Utils/InstOptUtils.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/Statistic.h"
using namespace swift;
static llvm::cl::opt<bool>
EnableExistentialSpecializer("enable-existential-specializer",
llvm::cl::Hidden,
llvm::cl::init(true));
STATISTIC(NumFunctionsWithExistentialArgsSpecialized,
"Number of functions with existential args specialized");
namespace {
/// ExistentialSpecializer class.
class ExistentialSpecializer : public SILFunctionTransform {
/// Determine if the current function is a target for existential
/// specialization of args.
bool canSpecializeExistentialArgsInFunction(
FullApplySite &Apply,
llvm::SmallDenseMap<int, ExistentialTransformArgumentDescriptor>
&ExistentialArgDescriptor);
/// Can Callee be specialized?
bool canSpecializeCalleeFunction(FullApplySite &Apply);
/// Specialize existential args in function F.
void specializeExistentialArgsInAppliesWithinFunction(SILFunction &F);
/// Find concrete type using protocolconformance analysis.
bool findConcreteTypeFromSoleConformingType(
SILFunctionArgument *Arg, CanType &ConcreteType);
/// CallerAnalysis information.
CallerAnalysis *CA;
// Determine the set of types a protocol conforms to in whole-module
// compilation mode.
ProtocolConformanceAnalysis *PCA;
ClassHierarchyAnalysis *CHA;
public:
void run() override {
auto *F = getFunction();
/// Don't optimize functions that should not be optimized.
if (!F->shouldOptimize() || !EnableExistentialSpecializer) {
return;
}
/// Get CallerAnalysis information handy.
CA = PM->getAnalysis<CallerAnalysis>();
/// Get ProtocolConformanceAnalysis.
PCA = PM->getAnalysis<ProtocolConformanceAnalysis>();
/// Get ClassHierarchyAnalysis.
CHA = PM->getAnalysis<ClassHierarchyAnalysis>();
/// Perform specialization.
specializeExistentialArgsInAppliesWithinFunction(*F);
}
};
} // namespace
/// Find concrete type from Sole Conforming Type.
bool ExistentialSpecializer::findConcreteTypeFromSoleConformingType(
SILFunctionArgument *Arg, CanType &ConcreteType) {
auto ArgType = Arg->getType();
auto SwiftArgType = ArgType.getASTType();
CanType constraint = SwiftArgType;
if (auto existential = constraint->getAs<ExistentialType>())
constraint = existential->getConstraintType()->getCanonicalType();
/// Do not handle composition types yet.
if (isa<ProtocolCompositionType>(constraint))
return false;
assert(ArgType.isExistentialType());
/// Find the protocol decl.
auto *PD = dyn_cast<ProtocolDecl>(constraint->getAnyNominal());
if (!PD)
return false;
// Get SoleConformingType in ConcreteType using ProtocolConformanceAnalysis
// and ClassHierarchyAnalysis.
if (!PCA->getSoleConformingType(PD, CHA, ConcreteType))
return false;
return true;
}
/// Helper function to ensure that the argument is not InOut or InOut_Aliasable
static bool isNonInoutIndirectArgument(SILValue Arg,
SILArgumentConvention ArgConvention) {
return !Arg->getType().isObject() && ArgConvention.isIndirectConvention() &&
ArgConvention != SILArgumentConvention::Indirect_Inout &&
ArgConvention != SILArgumentConvention::Indirect_InoutAliasable;
}
/// Check if any apply argument meets the criteria for existential
/// specialization.
bool ExistentialSpecializer::canSpecializeExistentialArgsInFunction(
FullApplySite &Apply,
llvm::SmallDenseMap<int, ExistentialTransformArgumentDescriptor>
&ExistentialArgDescriptor) {
auto *F = Apply.getReferencedFunctionOrNull();
auto CalleeArgs = F->begin()->getSILFunctionArguments();
bool returnFlag = false;
/// Analyze the argument for protocol conformance. Iterator over the callee's
/// function arguments. The same SIL argument index is used for both caller
/// and callee side arguments.
auto origCalleeConv = Apply.getOrigCalleeConv();
assert(Apply.getCalleeArgIndexOfFirstAppliedArg() == 0);
for (unsigned Idx = 0, Num = CalleeArgs.size(); Idx < Num; ++Idx) {
auto CalleeArg = CalleeArgs[Idx];
auto ArgType = CalleeArg->getType();
auto SwiftArgType = ArgType.getASTType();
/// Checking for AnyObject and Any is added to ensure that we do not blow up
/// the code size by specializing to every type that conforms to Any or
/// AnyObject. In future, we may want to lift these two restrictions in a
/// controlled way.
if (!ArgType.isExistentialType() || ArgType.isAnyObject() ||
SwiftArgType->isAny())
continue;
auto ExistentialRepr =
CalleeArg->getType().getPreferredExistentialRepresentation();
if (ExistentialRepr != ExistentialRepresentation::Opaque &&
ExistentialRepr != ExistentialRepresentation::Class)
continue;
/// Find the concrete type.
Operand &ArgOper = Apply.getArgumentRef(Idx);
CanType ConcreteType =
ConcreteExistentialInfo(ArgOper.get(), ArgOper.getUser()).ConcreteType;
auto ArgConvention = F->getConventions().getSILArgumentConvention(Idx);
/// Find the concrete type, either via sole type or via
/// findInitExistential..
CanType SoleConcreteType;
if (!((F->getModule().isWholeModule() &&
isNonInoutIndirectArgument(CalleeArg, ArgConvention) &&
findConcreteTypeFromSoleConformingType(CalleeArg, SoleConcreteType)) ||
ConcreteType)) {
LLVM_DEBUG(
llvm::dbgs()
<< "ExistentialSpecializer Pass: Bail! cannot find ConcreteType "
"for call argument to:"
<< F->getName() << " in caller:"
<< Apply.getInstruction()->getParent()->getParent()->getName()
<< "\n";);
continue;
}
/// Determine attributes of the existential addr argument.
ExistentialTransformArgumentDescriptor ETAD;
auto paramInfo = origCalleeConv.getParamInfoForSILArg(Idx);
// The ExistentialSpecializerCloner copies the incoming generic argument
// into an existential. This won't work if the original argument is
// mutated. Furthermore, SILCombine would not be able to replace a mutated
// existential with a concrete value, so the specialization thunk could not
// be optimized away.
if (paramInfo.isIndirectMutating())
continue;
// The ExistentialSpecializerCloner copies the incoming generic argument
// into an existential if it is non-consuming (if it's consuming, it's
// moved into the existential via `copy_addr [take]`). Introducing a copy
// of a move-only value isn't legal.
if (!paramInfo.isConsumed() &&
paramInfo.getSILStorageInterfaceType().isMoveOnly())
continue;
ETAD.AccessType = paramInfo.isConsumed()
? OpenedExistentialAccess::Mutable
: OpenedExistentialAccess::Immutable;
ETAD.isConsumed = paramInfo.isConsumed();
/// Save the attributes
ExistentialArgDescriptor[Idx] = ETAD;
LLVM_DEBUG(llvm::dbgs()
<< "ExistentialSpecializer Pass:Function: " << F->getName()
<< " Arg:" << Idx << " has a concrete type.\n");
returnFlag |= true;
}
return returnFlag;
}
/// Determine if this callee function can be specialized or not.
bool ExistentialSpecializer::canSpecializeCalleeFunction(FullApplySite &Apply) {
/// Determine the caller of the apply.
auto *Callee = Apply.getReferencedFunctionOrNull();
if (!Callee)
return false;
/// Callee should be optimizable.
if (!Callee->shouldOptimize())
return false;
/// External function definitions.
if (!Callee->isDefinition())
return false;
// Ignore generic functions. Generic functions should be fully specialized
// before attempting to introduce new generic parameters for existential
// arguments. Otherwise, there's no guarantee that the generic specializer
// will be able to specialize the new generic parameter created by this pass.
//
// Enabling this would require additional implementation work to correctly
// substitute the original archetypes into the new generic signature.
if (Callee->getLoweredFunctionType()->getSubstGenericSignature())
return false;
/// Ignore functions with indirect results.
if (Callee->getConventions().hasIndirectSILResults())
return false;
/// Ignore error returning functions.
if (Callee->getLoweredFunctionType()->hasErrorResult())
return false;
/// Do not optimize always_inlinable functions.
if (Callee->getInlineStrategy() == Inline_t::AlwaysInline)
return false;
/// Ignore externally linked functions with public_external or higher
/// linkage.
if (isAvailableExternally(Callee->getLinkage())) {
return false;
}
/// Only choose a select few function representations for specialization.
switch (Callee->getRepresentation()) {
case SILFunctionTypeRepresentation::ObjCMethod:
case SILFunctionTypeRepresentation::Block:
return false;
default: break;
}
return true;
}
/// Specialize existential args passed as arguments to callees. Iterate over all
/// call sites of the caller F and check for legality to apply existential
/// specialization.
void ExistentialSpecializer::specializeExistentialArgsInAppliesWithinFunction(
SILFunction &F) {
bool Changed = false;
for (auto &BB : F) {
for (auto It = BB.begin(), End = BB.end(); It != End; ++It) {
auto *I = &*It;
/// Is it an apply site?
FullApplySite Apply = FullApplySite::isa(I);
if (!Apply)
continue;
/// Can the callee be specialized?
if (!canSpecializeCalleeFunction(Apply)) {
LLVM_DEBUG(llvm::dbgs() << "ExistentialSpecializer Pass: Bail! Due to "
"canSpecializeCalleeFunction.\n";
I->dump(););
continue;
}
auto *Callee = Apply.getReferencedFunctionOrNull();
/// Handle recursion! Do not modify F right now.
if (Callee == &F) {
LLVM_DEBUG(llvm::dbgs() << "ExistentialSpecializer Pass: Bail! Due to "
"recursion.\n";
I->dump(););
continue;
}
/// Determine the arguments that can be specialized.
llvm::SmallDenseMap<int, ExistentialTransformArgumentDescriptor>
ExistentialArgDescriptor;
if (!canSpecializeExistentialArgsInFunction(Apply,
ExistentialArgDescriptor)) {
LLVM_DEBUG(llvm::dbgs()
<< "ExistentialSpecializer Pass: Bail! Due to "
"canSpecializeExistentialArgsInFunction in function: "
<< Callee->getName() << " -> abort\n");
continue;
}
LLVM_DEBUG(llvm::dbgs()
<< "ExistentialSpecializer Pass: Function::"
<< Callee->getName()
<< " has an existential argument and can be optimized "
"via ExistentialSpecializer\n");
/// Name Mangler for naming the protocol constrained generic method.
auto P = Demangle::SpecializationPass::FunctionSignatureOpts;
Mangle::FunctionSignatureSpecializationMangler Mangler(
P, Callee->getSerializedKind(), Callee);
/// Save the arguments in a descriptor.
llvm::SpecificBumpPtrAllocator<ProjectionTreeNode> Allocator;
llvm::SmallVector<ArgumentDescriptor, 4> ArgumentDescList;
auto Args = Callee->begin()->getSILFunctionArguments();
for (unsigned i : indices(Args)) {
ArgumentDescList.emplace_back(Args[i], Allocator);
}
/// This is the function to optimize for existential specilizer.
LLVM_DEBUG(llvm::dbgs()
<< "*** Running ExistentialSpecializer Pass on function: "
<< Callee->getName() << " ***\n");
/// Instantiate the ExistentialSpecializerTransform pass.
SILOptFunctionBuilder FuncBuilder(*this);
ExistentialTransform ET(FuncBuilder, Callee, Mangler, ArgumentDescList,
ExistentialArgDescriptor);
/// Run the existential specializer pass.
Changed = ET.run();
if (Changed) {
/// Update statistics on the number of functions specialized.
++NumFunctionsWithExistentialArgsSpecialized;
/// Make sure the PM knows about the new specialized inner function.
addFunctionToPassManagerWorklist(ET.getExistentialSpecializedFunction(),
Callee);
/// Invalidate analysis results of Callee.
PM->invalidateAnalysis(Callee,
SILAnalysis::InvalidationKind::FunctionBody);
}
}
}
return;
}
SILTransform *swift::createExistentialSpecializer() {
return new ExistentialSpecializer();
}
|