本文整理汇总了C++中CanType类的典型用法代码示例。如果您正苦于以下问题:C++ CanType类的具体用法?C++ CanType怎么用?C++ CanType使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了CanType类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1: classifyDynamicCastFromProtocol
static DynamicCastFeasibility
classifyDynamicCastFromProtocol(ModuleDecl *M, CanType source, CanType target,
bool isWholeModuleOpts) {
assert(source.isExistentialType() &&
"source should be an existential type");
if (source == target)
return DynamicCastFeasibility::WillSucceed;
// Casts from class existential into a non-class can never succeed.
if (source->isClassExistentialType() &&
!target.isAnyExistentialType() &&
!target.getClassOrBoundGenericClass() &&
!isa<ArchetypeType>(target) &&
!mayBridgeToObjectiveC(M, target)) {
assert((target.getEnumOrBoundGenericEnum() ||
target.getStructOrBoundGenericStruct() ||
isa<TupleType>(target) ||
isa<SILFunctionType>(target) ||
isa<FunctionType>(target) ||
isa<MetatypeType>(target)) &&
"Target should be an enum, struct, tuple, metatype or function type");
return DynamicCastFeasibility::WillFail;
}
// TODO: maybe prove that certain conformances are impossible?
return DynamicCastFeasibility::MaySucceed;
}
示例2: SubstitutionMap
/// Build an interface type substitution map for the given generic signature
/// from a type substitution function and conformance lookup function.
SubstitutionMap SubstitutionMap::get(GenericSignature *genericSig,
TypeSubstitutionFn subs,
LookupConformanceFn lookupConformance) {
if (!genericSig) {
return SubstitutionMap();
}
// Form the replacement types.
SmallVector<Type, 4> replacementTypes;
replacementTypes.reserve(genericSig->getGenericParams().size());
for (auto gp : genericSig->getGenericParams()) {
// Don't eagerly form replacements for non-canonical generic parameters.
if (!genericSig->isCanonicalTypeInContext(gp->getCanonicalType())) {
replacementTypes.push_back(Type());
continue;
}
// Record the replacement.
Type replacement = Type(gp).subst(subs, lookupConformance,
SubstFlags::UseErrorType);
replacementTypes.push_back(replacement);
}
// Form the stored conformances.
SmallVector<ProtocolConformanceRef, 4> conformances;
for (const auto &req : genericSig->getRequirements()) {
if (req.getKind() != RequirementKind::Conformance) continue;
CanType depTy = req.getFirstType()->getCanonicalType();
auto replacement = depTy.subst(subs, lookupConformance,
SubstFlags::UseErrorType);
auto protoType = req.getSecondType()->castTo<ProtocolType>();
auto proto = protoType->getDecl();
auto conformance = lookupConformance(depTy, replacement, proto)
.getValueOr(ProtocolConformanceRef(proto));
conformances.push_back(conformance);
}
return SubstitutionMap(genericSig, replacementTypes, conformances);
}
示例3: addBuiltinTypeRefs
// Collect any builtin types referenced from this type.
void addBuiltinTypeRefs(CanType type) {
type.visit([&](Type t) {
if (t->is<BuiltinType>())
BuiltinTypes.insert(CanType(t));
// We need at least size/alignment information for types imported by
// clang, so we'll treat them as a builtin type, essentially an
// opaque blob.
if (auto Nominal = t->getAnyNominal())
if (Nominal->hasClangNode())
BuiltinTypes.insert(CanType(t));
});
}
示例4: emitResultIsZeroErrorCheck
/// Perform a foreign error check by testing whether the call result is zero.
/// The call result is otherwise ignored.
static void
emitResultIsZeroErrorCheck(SILGenFunction &gen, SILLocation loc,
ManagedValue result, ManagedValue errorSlot,
bool suppressErrorCheck, bool zeroIsError) {
// Just ignore the call result if we're suppressing the error check.
if (suppressErrorCheck) {
return;
}
SILValue resultValue =
emitUnwrapIntegerResult(gen, loc, result.getUnmanagedValue());
CanType resultType = resultValue->getType().getSwiftRValueType();
if (!resultType->isBuiltinIntegerType(1)) {
SILValue zero =
gen.B.createIntegerLiteral(loc, resultValue->getType(), 0);
ASTContext &ctx = gen.getASTContext();
resultValue =
gen.B.createBuiltinBinaryFunction(loc,
"cmp_ne",
resultValue->getType(),
SILType::getBuiltinIntegerType(1, ctx),
{resultValue, zero});
}
SILBasicBlock *errorBB = gen.createBasicBlock(FunctionSection::Postmatter);
SILBasicBlock *contBB = gen.createBasicBlock();
if (zeroIsError)
gen.B.createCondBranch(loc, resultValue, contBB, errorBB);
else
gen.B.createCondBranch(loc, resultValue, errorBB, contBB);
gen.emitForeignErrorBlock(loc, errorBB, errorSlot);
gen.B.emitBlock(contBB);
}
示例5: CanType
FormalLinkage swift::getTypeLinkage(CanType type) {
FormalLinkage result = FormalLinkage::Top;
// Merge all nominal types from the structural type.
(void) type.findIf([&](Type _type) {
CanType type = CanType(_type);
// For any nominal type reference, look at the type declaration.
if (auto nominal = type->getAnyNominal()) {
result ^= getDeclLinkage(nominal);
// For polymorphic function types, look at the generic parameters.
// FIXME: findIf should do this, once polymorphic function types can be
// canonicalized and re-formed properly.
} else if (auto polyFn = dyn_cast<PolymorphicFunctionType>(type)) {
result ^= getGenericClauseLinkage(polyFn->getGenericParameters());
}
return false; // continue searching
});
return result;
}
示例6: getOptionalSomeValue
/// Return a value for an optional ".Some(x)" of the specified type. This only
/// works for loadable enum types.
ManagedValue SILGenFunction::
getOptionalSomeValue(SILLocation loc, ManagedValue value,
const TypeLowering &optTL) {
assert(optTL.isLoadable() && "Address-only optionals cannot use this");
SILType optType = optTL.getLoweredType();
CanType formalOptType = optType.getSwiftRValueType();
OptionalTypeKind OTK;
auto formalObjectType = formalOptType->getAnyOptionalObjectType(OTK)
->getCanonicalType();
assert(OTK != OTK_None);
auto someDecl = getASTContext().getOptionalSomeDecl(OTK);
AbstractionPattern origType = AbstractionPattern::getOpaque();
// Reabstract input value to the type expected by the enum.
value = emitSubstToOrigValue(loc, value, origType, formalObjectType);
SILValue result =
B.createEnum(loc, value.forward(*this), someDecl,
optTL.getLoweredType());
return emitManagedRValueWithCleanup(result, optTL);
}
示例7: isSafeType
bool DestructorAnalysis::isSafeType(CanType Ty) {
// Don't visit types twice.
auto CachedRes = Cached.find(Ty);
if (CachedRes != Cached.end()) {
return CachedRes->second;
}
// Before we recurse mark the type as safe i.e if we see it in a recursive
// position it is safe in the absence of another fact that proves otherwise.
// We will reset this value to the correct value once we return from the
// recursion below.
cacheResult(Ty, true);
// Trivial value types.
if (Ty->is<BuiltinIntegerType>())
return cacheResult(Ty, true);
if (Ty->is<BuiltinFloatType>())
return cacheResult(Ty, true);
// A struct is safe if
// * either it implements the _DestructorSafeContainer protocol and
// all the type parameters are safe types.
// * or all stored properties are safe types.
if (auto *Struct = Ty->getStructOrBoundGenericStruct()) {
if (implementsDestructorSafeContainerProtocol(Struct) &&
areTypeParametersSafe(Ty))
return cacheResult(Ty, true);
// Check the stored properties.
for (auto SP : Struct->getStoredProperties())
if (!isSafeType(SP->getInterfaceType()->getCanonicalType()))
return cacheResult(Ty, false);
return cacheResult(Ty, true);
}
// A tuple type is safe if its elements are safe.
if (auto Tuple = dyn_cast<TupleType>(Ty)) {
for (auto &Elt : Tuple->getElements())
if (!isSafeType(Elt.getType()->getCanonicalType()))
return cacheResult(Ty, false);
return cacheResult(Ty, true);
}
// TODO: enum types.
return cacheResult(Ty, false);
}
示例8: CanType
CanType swift::getNSBridgedClassOfCFClass(ModuleDecl *M, CanType type) {
if (auto classDecl = type->getClassOrBoundGenericClass()) {
if (classDecl->getForeignClassKind() == ClassDecl::ForeignKind::CFType) {
if (auto bridgedAttr =
classDecl->getAttrs().getAttribute<ObjCBridgedAttr>()) {
auto bridgedClass = bridgedAttr->getObjCClass();
// TODO: this should handle generic classes properly.
if (!bridgedClass->isGenericContext()) {
return bridgedClass->getDeclaredInterfaceType()->getCanonicalType();
}
}
}
}
return CanType();
}
示例9: addTypeRef
/// Add a 32-bit relative offset to a mangled typeref string
/// in the typeref reflection section.
void addTypeRef(Module *ModuleContext, CanType type) {
assert(type);
// Generic parameters should be written in terms of interface types
// for the purposes of reflection metadata
assert(!type->hasArchetype() && "Forgot to map typeref out of context");
Mangle::Mangler mangler(/*DWARFMangling*/false,
/*usePunyCode*/ true,
/*OptimizeProtocolNames*/ false);
mangler.setModuleContext(ModuleContext);
mangler.mangleType(type, 0);
auto mangledName = IGM.getAddrOfStringForTypeRef(mangler.finalize());
addRelativeAddress(mangledName);
}
示例10: getLoweredBridgedType
CanType TypeConverter::getBridgedInputType(SILFunctionTypeRepresentation rep,
AbstractionPattern pattern,
CanType input) {
if (auto tuple = dyn_cast<TupleType>(input)) {
SmallVector<TupleTypeElt, 4> bridgedFields;
bool changed = false;
for (unsigned i : indices(tuple->getElements())) {
auto &elt = tuple->getElement(i);
Type bridged = getLoweredBridgedType(pattern.getTupleElementType(i),
elt.getType(), rep,
TypeConverter::ForArgument);
if (!bridged) {
Context.Diags.diagnose(SourceLoc(), diag::could_not_find_bridge_type,
elt.getType());
llvm::report_fatal_error("unable to set up the ObjC bridge!");
}
CanType canBridged = bridged->getCanonicalType();
if (canBridged != CanType(elt.getType())) {
changed = true;
bridgedFields.push_back(elt.getWithType(canBridged));
} else {
bridgedFields.push_back(elt);
}
}
if (!changed)
return input;
return CanType(TupleType::get(bridgedFields, input->getASTContext()));
}
auto loweredBridgedType = getLoweredBridgedType(pattern, input, rep,
TypeConverter::ForArgument);
if (!loweredBridgedType) {
Context.Diags.diagnose(SourceLoc(), diag::could_not_find_bridge_type,
input);
llvm::report_fatal_error("unable to set up the ObjC bridge!");
}
return loweredBridgedType->getCanonicalType();
}
示例11: fn
Optional<ProtocolConformanceRef>
SubstitutionMap::forEachParent(CanType type, Fn fn) const {
auto foundParents = parentMap.find(type.getPointer());
if (foundParents != parentMap.end()) {
for (auto parent : foundParents->second) {
if (auto result = fn(parent.first, parent.second))
return result;
}
}
if (auto archetypeType = dyn_cast<ArchetypeType>(type))
if (auto *parent = archetypeType->getParent())
return fn(CanType(parent), archetypeType->getAssocType());
if (auto memberType = dyn_cast<DependentMemberType>(type))
return fn(CanType(memberType->getBase()), memberType->getAssocType());
return None;
}
示例12: getLoweredType
// FIXME: With some changes to their callers, all of the below functions
// could be re-worked to use emitInjectEnum().
ManagedValue
SILGenFunction::emitInjectOptional(SILLocation loc,
ManagedValue v,
CanType inputFormalType,
CanType substFormalType,
const TypeLowering &expectedTL,
SGFContext ctxt) {
// Optional's payload is currently maximally abstracted. FIXME: Eventually
// it shouldn't be.
auto opaque = AbstractionPattern::getOpaque();
OptionalTypeKind substOTK;
auto substObjectType = substFormalType.getAnyOptionalObjectType(substOTK);
auto loweredTy = getLoweredType(opaque, substObjectType);
if (v.getType() != loweredTy)
v = emitTransformedValue(loc, v,
AbstractionPattern(inputFormalType), inputFormalType,
opaque, substObjectType);
auto someDecl = getASTContext().getOptionalSomeDecl(substOTK);
SILType optTy = getLoweredType(substFormalType);
if (v.getType().isAddress()) {
auto buf = getBufferForExprResult(loc, optTy.getObjectType(), ctxt);
auto payload = B.createInitEnumDataAddr(loc, buf, someDecl,
v.getType());
// FIXME: Is it correct to use IsTake here even if v doesn't have a cleanup?
B.createCopyAddr(loc, v.forward(*this), payload,
IsTake, IsInitialization);
B.createInjectEnumAddr(loc, buf, someDecl);
v = manageBufferForExprResult(buf, expectedTL, ctxt);
} else {
auto some = B.createEnum(loc, v.getValue(), someDecl, optTy);
v = ManagedValue(some, v.getCleanup());
}
return v;
}
示例13: addTypeRef
/// Add a 32-bit relative offset to a mangled typeref string
/// in the typeref reflection section.
void addTypeRef(ModuleDecl *ModuleContext, CanType type,
CanGenericSignature Context = {}) {
assert(type);
// Generic parameters should be written in terms of interface types
// for the purposes of reflection metadata
assert(!type->hasArchetype() && "Forgot to map typeref out of context");
// TODO: As a compatibility hack, mangle single-field boxes with the legacy
// mangling in reflection metadata.
bool isSingleFieldOfBox = false;
auto boxTy = dyn_cast<SILBoxType>(type);
if (boxTy && boxTy->getLayout()->getFields().size() == 1) {
GenericContextScope scope(IGM, Context);
type = boxTy->getFieldLoweredType(IGM.getSILModule(), 0);
isSingleFieldOfBox = true;
}
IRGenMangler mangler;
std::string MangledStr = mangler.mangleTypeForReflection(type,
ModuleContext, isSingleFieldOfBox);
auto mangledName = IGM.getAddrOfStringForTypeRef(MangledStr);
addRelativeAddress(mangledName);
}
示例14: addBuiltinTypeRefs
// Collect any builtin types referenced from this type.
void addBuiltinTypeRefs(CanType type) {
type.visit([&](Type t) {
if (t->is<BuiltinType>())
IGM.BuiltinTypes.insert(CanType(t));
// We need size/alignment information for imported value types,
// so emit builtin descriptors for them.
//
// In effect they're treated like an opaque blob, which is OK
// for now, at least until we want to import C++ types or
// something like that.
//
// Classes and protocols go down a different path.
if (auto Nominal = t->getAnyNominal())
if (Nominal->hasClangNode()) {
if (auto CD = dyn_cast<ClassDecl>(Nominal))
IGM.ImportedClasses.insert(CD);
else if (auto PD = dyn_cast<ProtocolDecl>(Nominal))
IGM.ImportedProtocols.insert(PD);
else
IGM.BuiltinTypes.insert(CanType(t));
}
});
}
示例15: isLeafTypeMetadata
/// Is metadata for the given type kind a "leaf", or does it possibly
/// store any other type metadata that we can statically extract?
///
/// It's okay to conservatively answer "no". It's more important for this
/// to be quick than for it to be accurate; don't recurse.
static bool isLeafTypeMetadata(CanType type) {
switch (type->getKind()) {
#define SUGARED_TYPE(ID, SUPER) \
case TypeKind::ID:
#define UNCHECKED_TYPE(ID, SUPER) \
case TypeKind::ID:
#define TYPE(ID, SUPER)
#include "swift/AST/TypeNodes.def"
llvm_unreachable("kind is invalid for a canonical type");
#define ARTIFICIAL_TYPE(ID, SUPER) \
case TypeKind::ID:
#define TYPE(ID, SUPER)
#include "swift/AST/TypeNodes.def"
case TypeKind::LValue:
case TypeKind::InOut:
case TypeKind::DynamicSelf:
llvm_unreachable("these types do not have metadata");
// All the builtin types are leaves.
#define BUILTIN_TYPE(ID, SUPER) \
case TypeKind::ID:
#define TYPE(ID, SUPER)
#include "swift/AST/TypeNodes.def"
case TypeKind::Module:
return true;
// Type parameters are statically opaque.
case TypeKind::Archetype:
case TypeKind::GenericTypeParam:
case TypeKind::DependentMember:
return true;
// Only the empty tuple is a leaf.
case TypeKind::Tuple:
return cast<TupleType>(type)->getNumElements() == 0;
// Nominal types might have parents.
case TypeKind::Class:
case TypeKind::Enum:
case TypeKind::Protocol:
case TypeKind::Struct:
return !cast<NominalType>(type)->getParent();
// Bound generic types have type arguments.
case TypeKind::BoundGenericClass:
case TypeKind::BoundGenericEnum:
case TypeKind::BoundGenericStruct:
return false;
// Functions have component types.
case TypeKind::Function:
case TypeKind::PolymorphicFunction:
case TypeKind::GenericFunction: // included for future-proofing
return false;
// Protocol compositions have component types.
case TypeKind::ProtocolComposition:
return false;
// Metatypes have instance types.
case TypeKind::Metatype:
case TypeKind::ExistentialMetatype:
return false;
}
llvm_unreachable("bad type kind");
}