diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td b/clang/include/clang/Basic/DiagnosticSemaKinds.td index e50138dccf1e..235c6abdaee3 100644 --- a/clang/include/clang/Basic/DiagnosticSemaKinds.td +++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td @@ -1469,6 +1469,10 @@ def warn_cxx98_compat_unicode_type : Warning< // Objective-C++ def err_objc_decls_may_only_appear_in_global_scope : Error< "Objective-C declarations may only appear in global scope">; +def warn_auto_var_is_id : Warning< + "'auto' deduced as 'id' in declaration of %0">, + InGroup>; + // Attributes def err_nsobject_attribute : Error< "__attribute ((NSObject)) is for pointer types only">; diff --git a/clang/lib/Sema/SemaDecl.cpp b/clang/lib/Sema/SemaDecl.cpp index 68f74694577b..40cc35117c8c 100644 --- a/clang/lib/Sema/SemaDecl.cpp +++ b/clang/lib/Sema/SemaDecl.cpp @@ -6303,6 +6303,17 @@ void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl)) VDecl->setInvalidDecl(); + // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using + // 'id' instead of a specific object type prevents most of our usual checks. + // We only want to warn outside of template instantiations, though: + // inside a template, the 'id' could have come from a parameter. + if (ActiveTemplateInstantiations.empty() && + DeducedType->getType()->isObjCIdType()) { + SourceLocation Loc = DeducedType->getTypeLoc().getBeginLoc(); + Diag(Loc, diag::warn_auto_var_is_id) + << VDecl->getDeclName() << DeduceInit->getSourceRange(); + } + // If this is a redeclaration, check that the type we just deduced matches // the previously declared type. if (VarDecl *Old = VDecl->getPreviousDecl()) diff --git a/clang/test/SemaObjCXX/arc-0x.mm b/clang/test/SemaObjCXX/arc-0x.mm index 28eec51775bd..88b3ab117864 100644 --- a/clang/test/SemaObjCXX/arc-0x.mm +++ b/clang/test/SemaObjCXX/arc-0x.mm @@ -22,7 +22,7 @@ void deduction(id obj) { __strong id *idp = new auto(obj); __strong id array[17]; - for (auto x : array) { + for (auto x : array) { // expected-warning{{'auto' deduced as 'id' in declaration of 'x'}} __strong id *xPtr = &x; } @@ -51,3 +51,24 @@ void test1c() { (void) ^{ (void) p; }; (void) ^{ (void) v; }; // expected-error {{cannot capture __autoreleasing variable in a block}} } + + +// +// warn when initializing an 'auto' variable with an 'id' initializer expression + +void testAutoId(id obj) { + auto x = obj; // expected-warning{{'auto' deduced as 'id' in declaration of 'x'}} +} + +// ...but don't warn if it's coming from a template parameter. +template +void autoTemplateFunction(T param, id obj) { + auto x = param; // no-warning + auto y = obj; // expected-warning{{'auto' deduced as 'id' in declaration of 'y'}} +} + +void testAutoIdTemplate(id obj) { + autoTemplateFunction(obj, obj); // no-warning +} + +