本文整理汇总了C++中SmallVector::front方法的典型用法代码示例。如果您正苦于以下问题:C++ SmallVector::front方法的具体用法?C++ SmallVector::front怎么用?C++ SmallVector::front使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类SmallVector
的用法示例。
在下文中一共展示了SmallVector::front方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1: getImportDecls
void ModuleFile::getImportDecls(SmallVectorImpl<Decl *> &Results) {
if (!Bits.ComputedImportDecls) {
ASTContext &Ctx = getContext();
for (auto &Dep : Dependencies) {
// FIXME: We need a better way to show headers, since they usually /are/
// re-exported. This isn't likely to come up much, though.
if (Dep.isHeader())
continue;
StringRef ModulePathStr = Dep.RawPath;
StringRef ScopePath;
if (Dep.isScoped())
std::tie(ModulePathStr, ScopePath) = ModulePathStr.rsplit('\0');
SmallVector<std::pair<swift::Identifier, swift::SourceLoc>, 1> AccessPath;
while (!ModulePathStr.empty()) {
StringRef NextComponent;
std::tie(NextComponent, ModulePathStr) = ModulePathStr.split('\0');
AccessPath.push_back({Ctx.getIdentifier(NextComponent), SourceLoc()});
}
if (AccessPath.size() == 1 && AccessPath[0].first == Ctx.StdlibModuleName)
continue;
Module *M = Ctx.getModule(AccessPath);
auto Kind = ImportKind::Module;
if (!ScopePath.empty()) {
auto ScopeID = Ctx.getIdentifier(ScopePath);
assert(!ScopeID.empty() &&
"invalid decl name (non-top-level decls not supported)");
if (!M) {
// The dependency module could not be loaded. Just make a guess
// about the import kind, we cannot do better.
Kind = ImportKind::Func;
} else {
// Lookup the decl in the top-level module.
Module *TopLevelModule = M;
if (AccessPath.size() > 1)
TopLevelModule = Ctx.getLoadedModule(AccessPath.front().first);
SmallVector<ValueDecl *, 8> Decls;
TopLevelModule->lookupQualified(
ModuleType::get(TopLevelModule), ScopeID,
NL_QualifiedDefault | NL_KnownNoDependency, nullptr, Decls);
Optional<ImportKind> FoundKind = ImportDecl::findBestImportKind(Decls);
assert(FoundKind.hasValue() &&
"deserialized imports should not be ambiguous");
Kind = *FoundKind;
}
AccessPath.push_back({ ScopeID, SourceLoc() });
}
auto *ID = ImportDecl::create(Ctx, FileContext, SourceLoc(), Kind,
SourceLoc(), AccessPath);
ID->setModule(M);
if (Dep.isExported())
ID->getAttrs().add(
new (Ctx) ExportedAttr(/*IsImplicit=*/false));
ImportDecls.push_back(ID);
}
Bits.ComputedImportDecls = true;
}
Results.append(ImportDecls.begin(), ImportDecls.end());
}
示例2: InsertUnwindResumeCalls
/// InsertUnwindResumeCalls - Convert the ResumeInsts that are still present
/// into calls to the appropriate _Unwind_Resume function.
bool DwarfEHPrepare::InsertUnwindResumeCalls(Function &Fn) {
SmallVector<ResumeInst*, 16> Resumes;
for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I) {
TerminatorInst *TI = I->getTerminator();
if (ResumeInst *RI = dyn_cast<ResumeInst>(TI))
Resumes.push_back(RI);
}
if (Resumes.empty())
return false;
// Find the rewind function if we didn't already.
const TargetLowering *TLI = TM->getTargetLowering();
if (!RewindFunction) {
LLVMContext &Ctx = Resumes[0]->getContext();
FunctionType *FTy = FunctionType::get(Type::getVoidTy(Ctx),
Type::getInt8PtrTy(Ctx), false);
const char *RewindName = TLI->getLibcallName(RTLIB::UNWIND_RESUME);
RewindFunction = Fn.getParent()->getOrInsertFunction(RewindName, FTy);
}
// Create the basic block where the _Unwind_Resume call will live.
LLVMContext &Ctx = Fn.getContext();
unsigned ResumesSize = Resumes.size();
if (ResumesSize == 1) {
// Instead of creating a new BB and PHI node, just append the call to
// _Unwind_Resume to the end of the single resume block.
ResumeInst *RI = Resumes.front();
BasicBlock *UnwindBB = RI->getParent();
Value *ExnObj = GetExceptionObject(RI);
// Call the _Unwind_Resume function.
CallInst *CI = CallInst::Create(RewindFunction, ExnObj, "", UnwindBB);
CI->setCallingConv(TLI->getLibcallCallingConv(RTLIB::UNWIND_RESUME));
// We never expect _Unwind_Resume to return.
new UnreachableInst(Ctx, UnwindBB);
return true;
}
BasicBlock *UnwindBB = BasicBlock::Create(Ctx, "unwind_resume", &Fn);
PHINode *PN = PHINode::Create(Type::getInt8PtrTy(Ctx), ResumesSize,
"exn.obj", UnwindBB);
// Extract the exception object from the ResumeInst and add it to the PHI node
// that feeds the _Unwind_Resume call.
for (SmallVectorImpl<ResumeInst*>::iterator
I = Resumes.begin(), E = Resumes.end(); I != E; ++I) {
ResumeInst *RI = *I;
BasicBlock *Parent = RI->getParent();
BranchInst::Create(UnwindBB, Parent);
Value *ExnObj = GetExceptionObject(RI);
PN->addIncoming(ExnObj, Parent);
++NumResumesLowered;
}
// Call the function.
CallInst *CI = CallInst::Create(RewindFunction, PN, "", UnwindBB);
CI->setCallingConv(TLI->getLibcallCallingConv(RTLIB::UNWIND_RESUME));
// We never expect _Unwind_Resume to return.
new UnreachableInst(Ctx, UnwindBB);
return true;
}
示例3: associateWithFileContext
Status ModuleFile::associateWithFileContext(FileUnit *file,
SourceLoc diagLoc) {
PrettyModuleFileDeserialization stackEntry(*this);
assert(getStatus() == Status::Valid && "invalid module file");
assert(!FileContext && "already associated with an AST module");
FileContext = file;
if (file->getParentModule()->getName().str() != Name)
return error(Status::NameMismatch);
ASTContext &ctx = getContext();
llvm::Triple moduleTarget(llvm::Triple::normalize(TargetTriple));
if (!areCompatibleArchitectures(moduleTarget, ctx.LangOpts.Target) ||
!areCompatibleOSs(moduleTarget, ctx.LangOpts.Target)) {
return error(Status::TargetIncompatible);
}
if (ctx.LangOpts.EnableTargetOSChecking &&
isTargetTooNew(moduleTarget, ctx.LangOpts.Target)) {
return error(Status::TargetTooNew);
}
for (const auto &searchPathPair : SearchPaths)
ctx.addSearchPath(searchPathPair.first, searchPathPair.second);
auto clangImporter = static_cast<ClangImporter *>(ctx.getClangModuleLoader());
bool missingDependency = false;
for (auto &dependency : Dependencies) {
assert(!dependency.isLoaded() && "already loaded?");
if (dependency.isHeader()) {
// The path may be empty if the file being loaded is a partial AST,
// and the current compiler invocation is a merge-modules step.
if (!dependency.RawPath.empty()) {
bool hadError =
clangImporter->importHeader(dependency.RawPath,
file->getParentModule(),
importedHeaderInfo.fileSize,
importedHeaderInfo.fileModTime,
importedHeaderInfo.contents,
diagLoc);
if (hadError)
return error(Status::FailedToLoadBridgingHeader);
}
Module *importedHeaderModule = clangImporter->getImportedHeaderModule();
dependency.Import = { {}, importedHeaderModule };
continue;
}
StringRef modulePathStr = dependency.RawPath;
StringRef scopePath;
if (dependency.isScoped()) {
auto splitPoint = modulePathStr.find_last_of('\0');
assert(splitPoint != StringRef::npos);
scopePath = modulePathStr.substr(splitPoint+1);
modulePathStr = modulePathStr.slice(0, splitPoint);
}
SmallVector<Identifier, 4> modulePath;
while (!modulePathStr.empty()) {
StringRef nextComponent;
std::tie(nextComponent, modulePathStr) = modulePathStr.split('\0');
modulePath.push_back(ctx.getIdentifier(nextComponent));
assert(!modulePath.back().empty() &&
"invalid module name (submodules not yet supported)");
}
auto module = getModule(modulePath);
if (!module) {
// If we're missing the module we're shadowing, treat that specially.
if (modulePath.size() == 1 &&
modulePath.front() == file->getParentModule()->getName()) {
return error(Status::MissingShadowedModule);
}
// Otherwise, continue trying to load dependencies, so that we can list
// everything that's missing.
missingDependency = true;
continue;
}
// This is for backwards-compatibility with modules that still rely on the
// "HasUnderlyingModule" flag.
if (Bits.HasUnderlyingModule && module == ShadowedModule)
dependency.forceExported();
if (scopePath.empty()) {
dependency.Import = { {}, module };
} else {
auto scopeID = ctx.getIdentifier(scopePath);
assert(!scopeID.empty() &&
"invalid decl name (non-top-level decls not supported)");
auto path = Module::AccessPathTy({scopeID, SourceLoc()});
dependency.Import = { ctx.AllocateCopy(path), module };
}
}
if (missingDependency) {
return error(Status::MissingDependency);
//.........这里部分代码省略.........
示例4: addImport
void NameBinder::addImport(
SmallVectorImpl<std::pair<ImportedModule, ImportOptions>> &imports,
ImportDecl *ID) {
if (ID->getModulePath().front().first == SF.getParentModule()->getName() &&
ID->getModulePath().size() == 1 && !shouldImportSelfImportClang(ID, SF)) {
// If the imported module name is the same as the current module,
// produce a diagnostic.
StringRef filename = llvm::sys::path::filename(SF.getFilename());
if (filename.empty())
Context.Diags.diagnose(ID, diag::sema_import_current_module,
ID->getModulePath().front().first);
else
Context.Diags.diagnose(ID, diag::sema_import_current_module_with_file,
filename, ID->getModulePath().front().first);
ID->setModule(SF.getParentModule());
return;
}
Module *M = getModule(ID->getModulePath());
if (!M) {
SmallString<64> modulePathStr;
interleave(ID->getModulePath(),
[&](ImportDecl::AccessPathElement elem) {
modulePathStr += elem.first.str();
},
[&] { modulePathStr += "."; });
auto diagKind = diag::sema_no_import;
if (SF.Kind == SourceFileKind::REPL || Context.LangOpts.DebuggerSupport)
diagKind = diag::sema_no_import_repl;
diagnose(ID->getLoc(), diagKind, modulePathStr);
if (Context.SearchPathOpts.SDKPath.empty() &&
llvm::Triple(llvm::sys::getProcessTriple()).isMacOSX()) {
diagnose(SourceLoc(), diag::sema_no_import_no_sdk);
diagnose(SourceLoc(), diag::sema_no_import_no_sdk_xcrun);
}
return;
}
ID->setModule(M);
Module *topLevelModule;
if (ID->getModulePath().size() == 1) {
topLevelModule = M;
} else {
// If we imported a submodule, import the top-level module as well.
Identifier topLevelName = ID->getModulePath().front().first;
topLevelModule = Context.getLoadedModule(topLevelName);
assert(topLevelModule && "top-level module missing");
}
auto *testableAttr = ID->getAttrs().getAttribute<TestableAttr>();
if (testableAttr && !topLevelModule->isTestingEnabled() &&
Context.LangOpts.EnableTestableAttrRequiresTestableModule) {
diagnose(ID->getModulePath().front().second, diag::module_not_testable,
topLevelModule->getName());
testableAttr->setInvalid();
}
ImportOptions options;
if (ID->isExported())
options |= SourceFile::ImportFlags::Exported;
if (testableAttr)
options |= SourceFile::ImportFlags::Testable;
imports.push_back({ { ID->getDeclPath(), M }, options });
if (topLevelModule != M)
imports.push_back({ { ID->getDeclPath(), topLevelModule }, options });
if (ID->getImportKind() != ImportKind::Module) {
// If we're importing a specific decl, validate the import kind.
using namespace namelookup;
auto declPath = ID->getDeclPath();
// FIXME: Doesn't handle scoped testable imports correctly.
assert(declPath.size() == 1 && "can't handle sub-decl imports");
SmallVector<ValueDecl *, 8> decls;
lookupInModule(topLevelModule, declPath, declPath.front().first, decls,
NLKind::QualifiedLookup, ResolutionKind::Overloadable,
/*resolver*/nullptr, &SF);
if (decls.empty()) {
diagnose(ID, diag::no_decl_in_module)
.highlight(SourceRange(declPath.front().second,
declPath.back().second));
return;
}
ID->setDecls(Context.AllocateCopy(decls));
Optional<ImportKind> actualKind = ImportDecl::findBestImportKind(decls);
if (!actualKind.hasValue()) {
// FIXME: print entire module name?
diagnose(ID, diag::ambiguous_decl_in_module,
declPath.front().first, M->getName());
for (auto next : decls)
diagnose(next, diag::found_candidate);
} else if (!isCompatibleImportKind(ID->getImportKind(), *actualKind)) {
//.........这里部分代码省略.........
示例5: emitArtificialTopLevel
void SILGenFunction::emitArtificialTopLevel(ClassDecl *mainClass) {
// Load argc and argv from the entry point arguments.
SILValue argc = F.begin()->getBBArg(0);
SILValue argv = F.begin()->getBBArg(1);
switch (mainClass->getArtificialMainKind()) {
case ArtificialMainKind::UIApplicationMain: {
// Emit a UIKit main.
// return UIApplicationMain(C_ARGC, C_ARGV, nil, ClassName);
CanType NSStringTy = SGM.Types.getNSStringType();
CanType OptNSStringTy
= OptionalType::get(NSStringTy)->getCanonicalType();
CanType IUOptNSStringTy
= ImplicitlyUnwrappedOptionalType::get(NSStringTy)->getCanonicalType();
// Look up UIApplicationMain.
// FIXME: Doing an AST lookup here is gross and not entirely sound;
// we're getting away with it because the types are guaranteed to already
// be imported.
ASTContext &ctx = getASTContext();
Module *UIKit = ctx.getLoadedModule(ctx.getIdentifier("UIKit"));
SmallVector<ValueDecl *, 1> results;
UIKit->lookupQualified(UIKit->getDeclaredType(),
ctx.getIdentifier("UIApplicationMain"),
NL_QualifiedDefault,
/*resolver*/nullptr,
results);
assert(!results.empty() && "couldn't find UIApplicationMain in UIKit");
assert(results.size() == 1 && "more than one UIApplicationMain?");
SILDeclRef mainRef{results.front(), ResilienceExpansion::Minimal,
SILDeclRef::ConstructAtNaturalUncurryLevel,
/*isForeign*/true};
auto UIApplicationMainFn = SGM.M.getOrCreateFunction(mainClass, mainRef,
NotForDefinition);
auto fnTy = UIApplicationMainFn->getLoweredFunctionType();
// Get the class name as a string using NSStringFromClass.
CanType mainClassTy = mainClass->getDeclaredTypeInContext()->getCanonicalType();
CanType mainClassMetaty = CanMetatypeType::get(mainClassTy,
MetatypeRepresentation::ObjC);
ProtocolDecl *anyObjectProtocol =
ctx.getProtocol(KnownProtocolKind::AnyObject);
auto mainClassAnyObjectConformance = ProtocolConformanceRef(
*SGM.M.getSwiftModule()->lookupConformance(mainClassTy, anyObjectProtocol,
nullptr));
CanType anyObjectTy = anyObjectProtocol
->getDeclaredTypeInContext()
->getCanonicalType();
CanType anyObjectMetaTy = CanExistentialMetatypeType::get(anyObjectTy,
MetatypeRepresentation::ObjC);
auto NSStringFromClassType = SILFunctionType::get(nullptr,
SILFunctionType::ExtInfo()
.withRepresentation(SILFunctionType::Representation::
CFunctionPointer),
ParameterConvention::Direct_Unowned,
SILParameterInfo(anyObjectMetaTy,
ParameterConvention::Direct_Unowned),
SILResultInfo(OptNSStringTy,
ResultConvention::Autoreleased),
/*error result*/ None,
ctx);
auto NSStringFromClassFn
= SGM.M.getOrCreateFunction(mainClass, "NSStringFromClass",
SILLinkage::PublicExternal,
NSStringFromClassType,
IsBare, IsTransparent, IsNotFragile);
auto NSStringFromClass = B.createFunctionRef(mainClass, NSStringFromClassFn);
SILValue metaTy = B.createMetatype(mainClass,
SILType::getPrimitiveObjectType(mainClassMetaty));
metaTy = B.createInitExistentialMetatype(mainClass, metaTy,
SILType::getPrimitiveObjectType(anyObjectMetaTy),
ctx.AllocateCopy(
llvm::makeArrayRef(mainClassAnyObjectConformance)));
SILValue optName = B.createApply(mainClass,
NSStringFromClass,
NSStringFromClass->getType(),
SILType::getPrimitiveObjectType(OptNSStringTy),
{}, metaTy);
// Fix up the string parameters to have the right type.
SILType nameArgTy = fnTy->getSILArgumentType(3);
assert(nameArgTy == fnTy->getSILArgumentType(2));
auto managedName = ManagedValue::forUnmanaged(optName);
SILValue nilValue;
if (optName->getType() == nameArgTy) {
nilValue = getOptionalNoneValue(mainClass,
getTypeLowering(OptNSStringTy));
} else {
assert(nameArgTy.getSwiftRValueType() == IUOptNSStringTy);
nilValue = getOptionalNoneValue(mainClass,
getTypeLowering(IUOptNSStringTy));
managedName = emitOptionalToOptional(
mainClass, managedName,
SILType::getPrimitiveObjectType(IUOptNSStringTy),
[](SILGenFunction &, SILLocation, ManagedValue input, SILType) {
return input;
});
//.........这里部分代码省略.........
示例6: RegularCommentPrinter
//.........这里部分代码省略.........
auto PrintDecl = [&](Decl *D) -> bool {
ASTPrinter &Printer = *PrinterToUse;
if (!shouldPrint(D, AdjustedOptions)) {
Printer.callAvoidPrintDeclPost(D);
return false;
}
if (auto Ext = dyn_cast<ExtensionDecl>(D)) {
// Clang extensions (categories) are always printed in source order.
// Swift extensions are printed with their associated type unless it's
// a cross-module extension.
if (!Ext->hasClangNode()) {
auto ExtendedNominal = Ext->getExtendedType()->getAnyNominal();
if (Ext->getModuleContext() == ExtendedNominal->getModuleContext())
return false;
}
}
std::unique_ptr<SynthesizedExtensionAnalyzer> pAnalyzer;
if (auto NTD = dyn_cast<NominalTypeDecl>(D)) {
if (PrintSynthesizedExtensions) {
pAnalyzer.reset(new SynthesizedExtensionAnalyzer(NTD, AdjustedOptions));
AdjustedOptions.shouldCloseNominal = !pAnalyzer->hasMergeGroup(
SynthesizedExtensionAnalyzer::MergeGroupKind::MergableWithTypeDef);
}
}
if (D->print(Printer, AdjustedOptions)) {
if (AdjustedOptions.shouldCloseNominal)
Printer << "\n";
AdjustedOptions.shouldCloseNominal = true;
if (auto NTD = dyn_cast<NominalTypeDecl>(D)) {
std::queue<NominalTypeDecl *> SubDecls{{NTD}};
while (!SubDecls.empty()) {
auto NTD = SubDecls.front();
SubDecls.pop();
// Add sub-types of NTD.
for (auto Sub : NTD->getMembers())
if (auto N = dyn_cast<NominalTypeDecl>(Sub))
SubDecls.push(N);
if (!PrintSynthesizedExtensions) {
// Print Ext and add sub-types of Ext.
for (auto Ext : NTD->getExtensions()) {
if (!shouldPrint(Ext, AdjustedOptions)) {
Printer.callAvoidPrintDeclPost(Ext);
continue;
}
if (Ext->hasClangNode())
continue; // will be printed in its source location, see above.
Printer << "\n";
Ext->print(Printer, AdjustedOptions);
Printer << "\n";
for (auto Sub : Ext->getMembers())
if (auto N = dyn_cast<NominalTypeDecl>(Sub))
SubDecls.push(N);
}
continue;
}
bool IsTopLevelDecl = D == NTD;
// If printed Decl is the top-level, merge the constraint-free extensions
// into the main body.
if (IsTopLevelDecl) {
// Print the part that should be merged with the type decl.
示例7: subst
Substitution Substitution::subst(Module *module,
ArrayRef<Substitution> subs,
TypeSubstitutionMap &subMap,
ArchetypeConformanceMap &conformanceMap) const {
// Substitute the replacement.
Type substReplacement = Replacement.subst(module, subMap, None);
assert(substReplacement && "substitution replacement failed");
if (substReplacement->isEqual(Replacement))
return *this;
if (Conformance.empty()) {
return {substReplacement, Conformance};
}
bool conformancesChanged = false;
SmallVector<ProtocolConformanceRef, 4> substConformances;
substConformances.reserve(Conformance.size());
for (auto c : Conformance) {
// If we have a concrete conformance, we need to substitute the
// conformance to apply to the new type.
if (c.isConcrete()) {
auto substC = c.getConcrete()->subst(module, substReplacement, subs,
subMap, conformanceMap);
substConformances.push_back(ProtocolConformanceRef(substC));
if (c != substConformances.back())
conformancesChanged = true;
continue;
}
// Otherwise, we may need to fill in the conformance.
ProtocolDecl *proto = c.getAbstract();
Optional<ProtocolConformanceRef> conformance;
// If the original type was an archetype, check the conformance map.
if (auto replacementArch = Replacement->getAs<ArchetypeType>()) {
// Check for conformances for the type that apply to the original
// substituted archetype.
auto it = conformanceMap.find(replacementArch);
assert(it != conformanceMap.end());
for (ProtocolConformanceRef found : it->second) {
auto foundProto = found.getRequirement();
if (foundProto == proto) {
conformance = found;
break;
} else if (foundProto->inheritsFrom(proto)) {
if (found.isConcrete()) {
conformance = ProtocolConformanceRef(
found.getConcrete()->getInheritedConformance(proto));
} else {
conformance = found;
}
break;
}
}
}
// If that didn't find anything, we can still synthesize AnyObject
// conformances from thin air. FIXME: gross.
if (!conformance &&
proto->isSpecificProtocol(KnownProtocolKind::AnyObject)) {
auto classDecl
= substReplacement->getClassOrBoundGenericClass();
SmallVector<ProtocolConformance *, 1> lookupResults;
classDecl->lookupConformance(classDecl->getParentModule(),
proto, lookupResults);
conformance = ProtocolConformanceRef(lookupResults.front());
}
if (conformance) {
if (conformance->isConcrete())
conformancesChanged = true;
substConformances.push_back(*conformance);
} else {
assert(substReplacement->hasDependentProtocolConformances() &&
"couldn't find concrete conformance for concrete type?");
substConformances.push_back(ProtocolConformanceRef(proto));
}
}
assert(substConformances.size() == Conformance.size());
ArrayRef<ProtocolConformanceRef> substConfs;
if (conformancesChanged)
substConfs = module->getASTContext().AllocateCopy(substConformances);
else
substConfs = Conformance;
return Substitution{substReplacement, substConfs};
}
示例8: InsertUnwindResumeCalls
/// InsertUnwindResumeCalls - Convert the ResumeInsts that are still present
/// into calls to the appropriate _Unwind_Resume function.
bool DwarfEHPrepare::InsertUnwindResumeCalls(Function &Fn) {
SmallVector<ResumeInst*, 16> Resumes;
SmallVector<LandingPadInst*, 16> CleanupLPads;
for (BasicBlock &BB : Fn) {
if (auto *RI = dyn_cast<ResumeInst>(BB.getTerminator()))
Resumes.push_back(RI);
if (auto *LP = BB.getLandingPadInst())
if (LP->isCleanup())
CleanupLPads.push_back(LP);
}
if (Resumes.empty())
return false;
// Check the personality, don't do anything if it's funclet-based.
EHPersonality Pers = classifyEHPersonality(Fn.getPersonalityFn());
if (isFuncletEHPersonality(Pers))
return false;
LLVMContext &Ctx = Fn.getContext();
size_t ResumesLeft = pruneUnreachableResumes(Fn, Resumes, CleanupLPads);
if (ResumesLeft == 0)
return true; // We pruned them all.
// Find the rewind function if we didn't already.
if (!RewindFunction) {
FunctionType *FTy = FunctionType::get(Type::getVoidTy(Ctx),
Type::getInt8PtrTy(Ctx), false);
const char *RewindName = TLI->getLibcallName(RTLIB::UNWIND_RESUME);
RewindFunction = Fn.getParent()->getOrInsertFunction(RewindName, FTy);
}
// Create the basic block where the _Unwind_Resume call will live.
if (ResumesLeft == 1) {
// Instead of creating a new BB and PHI node, just append the call to
// _Unwind_Resume to the end of the single resume block.
ResumeInst *RI = Resumes.front();
BasicBlock *UnwindBB = RI->getParent();
Value *ExnObj = GetExceptionObject(RI);
// Call the _Unwind_Resume function.
CallInst *CI = CallInst::Create(RewindFunction, ExnObj, "", UnwindBB);
CI->setCallingConv(TLI->getLibcallCallingConv(RTLIB::UNWIND_RESUME));
// We never expect _Unwind_Resume to return.
new UnreachableInst(Ctx, UnwindBB);
return true;
}
BasicBlock *UnwindBB = BasicBlock::Create(Ctx, "unwind_resume", &Fn);
PHINode *PN = PHINode::Create(Type::getInt8PtrTy(Ctx), ResumesLeft,
"exn.obj", UnwindBB);
// Extract the exception object from the ResumeInst and add it to the PHI node
// that feeds the _Unwind_Resume call.
for (ResumeInst *RI : Resumes) {
BasicBlock *Parent = RI->getParent();
BranchInst::Create(UnwindBB, Parent);
Value *ExnObj = GetExceptionObject(RI);
PN->addIncoming(ExnObj, Parent);
++NumResumesLowered;
}
// Call the function.
CallInst *CI = CallInst::Create(RewindFunction, PN, "", UnwindBB);
CI->setCallingConv(TLI->getLibcallCallingConv(RTLIB::UNWIND_RESUME));
// We never expect _Unwind_Resume to return.
new UnreachableInst(Ctx, UnwindBB);
return true;
}
示例9: assert
TypeIndex llvm::codeview::getModifiedType(const CVType &CVT) {
assert(CVT.kind() == LF_MODIFIER);
SmallVector<TypeIndex, 1> Refs;
discoverTypeIndices(CVT, Refs);
return Refs.front();
}
示例10: check
void NamedParameterCheck::check(const MatchFinder::MatchResult &Result) {
const SourceManager &SM = *Result.SourceManager;
const auto *Function = Result.Nodes.getNodeAs<FunctionDecl>("decl");
SmallVector<std::pair<const FunctionDecl *, unsigned>, 4> UnnamedParams;
// Ignore implicitly generated members.
if (Function->isImplicit())
return;
// Ignore declarations without a definition if we're not dealing with an
// overriden method.
const FunctionDecl *Definition = nullptr;
if ((!Function->isDefined(Definition) || Function->isDefaulted() ||
Function->isDeleted()) &&
(!isa<CXXMethodDecl>(Function) ||
cast<CXXMethodDecl>(Function)->size_overridden_methods() == 0))
return;
// TODO: Handle overloads.
// TODO: We could check that all redeclarations use the same name for
// arguments in the same position.
for (unsigned I = 0, E = Function->getNumParams(); I != E; ++I) {
const ParmVarDecl *Parm = Function->getParamDecl(I);
// Look for unnamed parameters.
if (!Parm->getName().empty())
continue;
// Don't warn on the dummy argument on post-inc and post-dec operators.
if ((Function->getOverloadedOperator() == OO_PlusPlus ||
Function->getOverloadedOperator() == OO_MinusMinus) &&
Parm->getType()->isSpecificBuiltinType(BuiltinType::Int))
continue;
// Sanity check the source locations.
if (!Parm->getLocation().isValid() || Parm->getLocation().isMacroID() ||
!SM.isWrittenInSameFile(Parm->getLocStart(), Parm->getLocation()))
continue;
// Skip gmock testing::Unused parameters.
if (auto Typedef = Parm->getType()->getAs<clang::TypedefType>())
if (Typedef->getDecl()->getQualifiedNameAsString() == "testing::Unused")
continue;
// Skip std::nullptr_t.
if (Parm->getType().getCanonicalType()->isNullPtrType())
continue;
// Look for comments. We explicitly want to allow idioms like
// void foo(int /*unused*/)
const char *Begin = SM.getCharacterData(Parm->getLocStart());
const char *End = SM.getCharacterData(Parm->getLocation());
StringRef Data(Begin, End - Begin);
if (Data.find("/*") != StringRef::npos)
continue;
UnnamedParams.push_back(std::make_pair(Function, I));
}
// Emit only one warning per function but fixits for all unnamed parameters.
if (!UnnamedParams.empty()) {
const ParmVarDecl *FirstParm =
UnnamedParams.front().first->getParamDecl(UnnamedParams.front().second);
auto D = diag(FirstParm->getLocation(),
"all parameters should be named in a function");
for (auto P : UnnamedParams) {
// Fallback to an unused marker.
StringRef NewName = "unused";
// If the method is overridden, try to copy the name from the base method
// into the overrider.
const auto *M = dyn_cast<CXXMethodDecl>(P.first);
if (M && M->size_overridden_methods() > 0) {
const ParmVarDecl *OtherParm =
(*M->begin_overridden_methods())->getParamDecl(P.second);
StringRef Name = OtherParm->getName();
if (!Name.empty())
NewName = Name;
}
// If the definition has a named parameter use that name.
if (Definition) {
const ParmVarDecl *DefParm = Definition->getParamDecl(P.second);
StringRef Name = DefParm->getName();
if (!Name.empty())
NewName = Name;
}
// Now insert the comment. Note that getLocation() points to the place
// where the name would be, this allows us to also get complex cases like
// function pointers right.
const ParmVarDecl *Parm = P.first->getParamDecl(P.second);
D << FixItHint::CreateInsertion(Parm->getLocation(),
" /*" + NewName.str() + "*/");
}
}
}
示例11: subst
Substitution Substitution::subst(Module *module,
ArrayRef<Substitution> subs,
TypeSubstitutionMap &subMap,
ArchetypeConformanceMap &conformanceMap) const {
// Substitute the replacement.
Type substReplacement = Replacement.subst(module, subMap, None);
assert(substReplacement && "substitution replacement failed");
if (substReplacement->isEqual(Replacement))
return *this;
bool conformancesChanged = false;
SmallVector<ProtocolConformance *, 4> substConformance;
substConformance.reserve(Conformance.size());
// When substituting a concrete type for an archetype, we need to fill in the
// conformances.
if (auto replacementArch = Replacement->getAs<ArchetypeType>()) {
if (!substReplacement->hasDependentProtocolConformances()) {
// Find the conformances mapped to the archetype.
auto found = conformanceMap.find(replacementArch);
assert(found != conformanceMap.end()
&& "no conformances for replaced archetype?!");
auto &foundConformances = found->second;
// If the substituted replacement archetype has no conformances,
// then there are no conformances to substitute.
if (foundConformances.empty())
return Substitution{Archetype, substReplacement, Conformance};
conformancesChanged = true;
// Get the conformances for the type that apply to the original
// substituted archetype.
for (auto proto : Archetype->getConformsTo()) {
for (auto c : foundConformances) {
if (c->getProtocol() == proto) {
substConformance.push_back(c);
goto found_conformance;
}
if (c->getProtocol()->inheritsFrom(proto)) {
substConformance.push_back(c->getInheritedConformance(proto));
goto found_conformance;
}
}
// FIXME: AnyObject conformances can be synthesized from
// thin air. Gross.
if (proto->isSpecificProtocol(KnownProtocolKind::AnyObject)) {
auto classDecl
= substReplacement->getClassOrBoundGenericClass();
SmallVector<ProtocolConformance *, 1> conformances;
classDecl->lookupConformance(classDecl->getParentModule(),
proto, conformances);
substConformance.push_back(conformances.front());
goto found_conformance;
}
assert(false && "did not find conformance for archetype requirement?!");
found_conformance:;
}
}
} else {
// If we substituted a concrete type for another, we need to substitute the
// conformance to apply to the new type.
for (auto c : Conformance) {
auto substC = c->subst(module, substReplacement, subs,
subMap, conformanceMap);
if (c != substC)
conformancesChanged = true;
substConformance.push_back(substC);
}
}
ArrayRef<ProtocolConformance *> substConformanceRef;
if (conformancesChanged)
substConformanceRef = module->getASTContext().AllocateCopy(substConformance);
else
substConformanceRef = Conformance;
assert(substReplacement->hasDependentProtocolConformances()
|| substConformanceRef.size() == Archetype->getConformsTo().size());
return Substitution{Archetype, substReplacement, substConformanceRef};
}
示例12: fixupWithCase
static std::string fixupWithCase(StringRef Name,
IdentifierNamingCheck::CaseType Case) {
static llvm::Regex Splitter(
"([a-z0-9A-Z]*)(_+)|([A-Z]?[a-z0-9]+)([A-Z]|$)|([A-Z]+)([A-Z]|$)");
SmallVector<StringRef, 8> Substrs;
Name.split(Substrs, "_", -1, false);
SmallVector<StringRef, 8> Words;
for (auto Substr : Substrs) {
while (!Substr.empty()) {
SmallVector<StringRef, 8> Groups;
if (!Splitter.match(Substr, &Groups))
break;
if (Groups[2].size() > 0) {
Words.push_back(Groups[1]);
Substr = Substr.substr(Groups[0].size());
} else if (Groups[3].size() > 0) {
Words.push_back(Groups[3]);
Substr = Substr.substr(Groups[0].size() - Groups[4].size());
} else if (Groups[5].size() > 0) {
Words.push_back(Groups[5]);
Substr = Substr.substr(Groups[0].size() - Groups[6].size());
}
}
}
if (Words.empty())
return Name;
std::string Fixup;
switch (Case) {
case IdentifierNamingCheck::CT_AnyCase:
Fixup += Name;
break;
case IdentifierNamingCheck::CT_LowerCase:
for (auto const &Word : Words) {
if (&Word != &Words.front())
Fixup += "_";
Fixup += Word.lower();
}
break;
case IdentifierNamingCheck::CT_UpperCase:
for (auto const &Word : Words) {
if (&Word != &Words.front())
Fixup += "_";
Fixup += Word.upper();
}
break;
case IdentifierNamingCheck::CT_CamelCase:
for (auto const &Word : Words) {
Fixup += Word.substr(0, 1).upper();
Fixup += Word.substr(1).lower();
}
break;
case IdentifierNamingCheck::CT_CamelBack:
for (auto const &Word : Words) {
if (&Word == &Words.front()) {
Fixup += Word.lower();
} else {
Fixup += Word.substr(0, 1).upper();
Fixup += Word.substr(1).lower();
}
}
break;
case IdentifierNamingCheck::CT_CamelSnakeCase:
for (auto const &Word : Words) {
if (&Word != &Words.front())
Fixup += "_";
Fixup += Word.substr(0, 1).upper();
Fixup += Word.substr(1).lower();
}
break;
case IdentifierNamingCheck::CT_CamelSnakeBack:
for (auto const &Word : Words) {
if (&Word != &Words.front()) {
Fixup += "_";
Fixup += Word.substr(0, 1).upper();
} else {
Fixup += Word.substr(0, 1).lower();
}
Fixup += Word.substr(1).lower();
}
break;
}
return Fixup;
}
示例13: emitArtificialTopLevel
void SILGenFunction::emitArtificialTopLevel(ClassDecl *mainClass) {
// Load argc and argv from the entry point arguments.
SILValue argc = F.begin()->getArgument(0);
SILValue argv = F.begin()->getArgument(1);
switch (mainClass->getArtificialMainKind()) {
case ArtificialMainKind::UIApplicationMain: {
// Emit a UIKit main.
// return UIApplicationMain(C_ARGC, C_ARGV, nil, ClassName);
CanType NSStringTy = SGM.Types.getNSStringType();
CanType OptNSStringTy
= OptionalType::get(NSStringTy)->getCanonicalType();
// Look up UIApplicationMain.
// FIXME: Doing an AST lookup here is gross and not entirely sound;
// we're getting away with it because the types are guaranteed to already
// be imported.
ASTContext &ctx = getASTContext();
std::pair<Identifier, SourceLoc> UIKitName =
{ctx.getIdentifier("UIKit"), SourceLoc()};
ModuleDecl *UIKit = ctx
.getClangModuleLoader()
->loadModule(SourceLoc(), UIKitName);
assert(UIKit && "couldn't find UIKit objc module?!");
SmallVector<ValueDecl *, 1> results;
UIKit->lookupQualified(UIKit,
ctx.getIdentifier("UIApplicationMain"),
NL_QualifiedDefault,
results);
assert(results.size() == 1
&& "couldn't find a unique UIApplicationMain in the UIKit ObjC "
"module?!");
ValueDecl *UIApplicationMainDecl = results.front();
auto mainRef = SILDeclRef(UIApplicationMainDecl).asForeign();
SILGenFunctionBuilder builder(SGM);
auto UIApplicationMainFn =
builder.getOrCreateFunction(mainClass, mainRef, NotForDefinition);
auto fnTy = UIApplicationMainFn->getLoweredFunctionType();
SILFunctionConventions fnConv(fnTy, SGM.M);
// Get the class name as a string using NSStringFromClass.
CanType mainClassTy = mainClass->getDeclaredInterfaceType()
->getCanonicalType();
CanType mainClassMetaty = CanMetatypeType::get(mainClassTy,
MetatypeRepresentation::ObjC);
CanType anyObjectTy = ctx.getAnyObjectType();
CanType anyObjectMetaTy = CanExistentialMetatypeType::get(anyObjectTy,
MetatypeRepresentation::ObjC);
auto NSStringFromClassType = SILFunctionType::get(nullptr,
SILFunctionType::ExtInfo()
.withRepresentation(SILFunctionType::Representation::
CFunctionPointer),
SILCoroutineKind::None,
ParameterConvention::Direct_Unowned,
SILParameterInfo(anyObjectMetaTy,
ParameterConvention::Direct_Unowned),
/*yields*/ {},
SILResultInfo(OptNSStringTy,
ResultConvention::Autoreleased),
/*error result*/ None,
ctx);
auto NSStringFromClassFn = builder.getOrCreateFunction(
mainClass, "NSStringFromClass", SILLinkage::PublicExternal,
NSStringFromClassType, IsBare, IsTransparent, IsNotSerialized);
auto NSStringFromClass = B.createFunctionRef(mainClass, NSStringFromClassFn);
SILValue metaTy = B.createMetatype(mainClass,
SILType::getPrimitiveObjectType(mainClassMetaty));
metaTy = B.createInitExistentialMetatype(mainClass, metaTy,
SILType::getPrimitiveObjectType(anyObjectMetaTy), {});
SILValue optName = B.createApply(mainClass,
NSStringFromClass,
NSStringFromClass->getType(),
SILType::getPrimitiveObjectType(OptNSStringTy),
{}, metaTy);
// Fix up the string parameters to have the right type.
SILType nameArgTy = fnConv.getSILArgumentType(3);
assert(nameArgTy == fnConv.getSILArgumentType(2));
(void)nameArgTy;
auto managedName = ManagedValue::forUnmanaged(optName);
SILValue nilValue;
assert(optName->getType() == nameArgTy);
nilValue = getOptionalNoneValue(mainClass,
getTypeLowering(OptNSStringTy));
// Fix up argv to have the right type.
auto argvTy = fnConv.getSILArgumentType(1);
SILType unwrappedTy = argvTy;
if (Type innerTy = argvTy.getASTType()->getOptionalObjectType()) {
auto canInnerTy = innerTy->getCanonicalType();
unwrappedTy = SILType::getPrimitiveObjectType(canInnerTy);
}
//.........这里部分代码省略.........
示例14: addImport
void NameBinder::addImport(
SmallVectorImpl<SourceFile::ImportedModuleDesc> &imports, ImportDecl *ID) {
if (ID->getModulePath().front().first == SF.getParentModule()->getName() &&
ID->getModulePath().size() == 1 && !shouldImportSelfImportClang(ID, SF)) {
// If the imported module name is the same as the current module,
// produce a diagnostic.
StringRef filename = llvm::sys::path::filename(SF.getFilename());
if (filename.empty())
Context.Diags.diagnose(ID, diag::sema_import_current_module,
ID->getModulePath().front().first);
else
Context.Diags.diagnose(ID, diag::sema_import_current_module_with_file,
filename, ID->getModulePath().front().first);
ID->setModule(SF.getParentModule());
return;
}
ModuleDecl *M = getModule(ID->getModulePath());
if (!M) {
SmallString<64> modulePathStr;
interleave(ID->getModulePath(),
[&](ImportDecl::AccessPathElement elem) {
modulePathStr += elem.first.str();
},
[&] { modulePathStr += "."; });
auto diagKind = diag::sema_no_import;
if (SF.Kind == SourceFileKind::REPL || Context.LangOpts.DebuggerSupport)
diagKind = diag::sema_no_import_repl;
diagnose(ID->getLoc(), diagKind, modulePathStr);
if (Context.SearchPathOpts.SDKPath.empty() &&
llvm::Triple(llvm::sys::getProcessTriple()).isMacOSX()) {
diagnose(SourceLoc(), diag::sema_no_import_no_sdk);
diagnose(SourceLoc(), diag::sema_no_import_no_sdk_xcrun);
}
return;
}
ID->setModule(M);
ModuleDecl *topLevelModule;
if (ID->getModulePath().size() == 1) {
topLevelModule = M;
} else {
// If we imported a submodule, import the top-level module as well.
Identifier topLevelName = ID->getModulePath().front().first;
topLevelModule = Context.getLoadedModule(topLevelName);
if (!topLevelModule) {
// Clang can sometimes import top-level modules as if they were
// submodules.
assert(!M->getFiles().empty() &&
isa<ClangModuleUnit>(M->getFiles().front()));
topLevelModule = M;
}
}
auto *testableAttr = ID->getAttrs().getAttribute<TestableAttr>();
if (testableAttr && !topLevelModule->isTestingEnabled() &&
Context.LangOpts.EnableTestableAttrRequiresTestableModule) {
diagnose(ID->getModulePath().front().second, diag::module_not_testable,
topLevelModule->getName());
testableAttr->setInvalid();
}
auto *privateImportAttr = ID->getAttrs().getAttribute<PrivateImportAttr>();
StringRef privateImportFileName;
if (privateImportAttr) {
if (!topLevelModule->arePrivateImportsEnabled()) {
diagnose(ID->getModulePath().front().second,
diag::module_not_compiled_for_private_import,
topLevelModule->getName());
privateImportAttr->setInvalid();
} else {
privateImportFileName = privateImportAttr->getSourceFile();
}
}
ImportOptions options;
if (ID->isExported())
options |= SourceFile::ImportFlags::Exported;
if (testableAttr)
options |= SourceFile::ImportFlags::Testable;
if (privateImportAttr)
options |= SourceFile::ImportFlags::PrivateImport;
auto *implementationOnlyAttr =
ID->getAttrs().getAttribute<ImplementationOnlyAttr>();
if (implementationOnlyAttr) {
if (options.contains(SourceFile::ImportFlags::Exported)) {
diagnose(ID, diag::import_implementation_cannot_be_exported,
topLevelModule->getName())
.fixItRemove(implementationOnlyAttr->getRangeWithAt());
} else {
options |= SourceFile::ImportFlags::ImplementationOnly;
}
}
imports.push_back(SourceFile::ImportedModuleDesc(
{ID->getDeclPath(), M}, options, privateImportFileName));
//.........这里部分代码省略.........
示例15: readIndexBlock
bool ModuleFile::readIndexBlock(llvm::BitstreamCursor &cursor) {
cursor.EnterSubBlock(INDEX_BLOCK_ID);
SmallVector<uint64_t, 4> scratch;
StringRef blobData;
while (true) {
auto next = cursor.advance();
switch (next.Kind) {
case llvm::BitstreamEntry::EndBlock:
return true;
case llvm::BitstreamEntry::Error:
return false;
case llvm::BitstreamEntry::SubBlock:
// Unknown sub-block, which this version of the compiler won't use.
if (cursor.SkipBlock())
return false;
break;
case llvm::BitstreamEntry::Record:
scratch.clear();
blobData = {};
unsigned kind = cursor.readRecord(next.ID, scratch, &blobData);
switch (kind) {
case index_block::DECL_OFFSETS:
assert(blobData.empty());
Decls.assign(scratch.begin(), scratch.end());
break;
case index_block::DECL_CONTEXT_OFFSETS:
assert(blobData.empty());
DeclContexts.assign(scratch.begin(), scratch.end());
break;
case index_block::TYPE_OFFSETS:
assert(blobData.empty());
Types.assign(scratch.begin(), scratch.end());
break;
case index_block::IDENTIFIER_OFFSETS:
assert(blobData.empty());
Identifiers.assign(scratch.begin(), scratch.end());
break;
case index_block::TOP_LEVEL_DECLS:
TopLevelDecls = readDeclTable(scratch, blobData);
break;
case index_block::OPERATORS:
OperatorDecls = readDeclTable(scratch, blobData);
break;
case index_block::EXTENSIONS:
ExtensionDecls = readDeclTable(scratch, blobData);
break;
case index_block::CLASS_MEMBERS:
ClassMembersByName = readDeclTable(scratch, blobData);
break;
case index_block::OPERATOR_METHODS:
OperatorMethodDecls = readDeclTable(scratch, blobData);
break;
case index_block::OBJC_METHODS:
ObjCMethods = readObjCMethodTable(scratch, blobData);
break;
case index_block::ENTRY_POINT:
assert(blobData.empty());
setEntryPointClassID(scratch.front());
break;
case index_block::LOCAL_TYPE_DECLS:
LocalTypeDecls = readLocalDeclTable(scratch, blobData);
break;
case index_block::LOCAL_DECL_CONTEXT_OFFSETS:
assert(blobData.empty());
LocalDeclContexts.assign(scratch.begin(), scratch.end());
break;
case index_block::NORMAL_CONFORMANCE_OFFSETS:
assert(blobData.empty());
NormalConformances.assign(scratch.begin(), scratch.end());
break;
default:
// Unknown index kind, which this version of the compiler won't use.
break;
}
break;
}
}
}