blob: a6aa4c74024f2e5eac8d1b98c2b782d4ba49c355 [file] [log] [blame]
Ted Kremenekf7639e12012-03-06 20:06:33 +00001//===--- ObjCMT.cpp - ObjC Migrate Tool -----------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
Fariborz Jahanian85e988b2013-07-18 22:17:33 +000010#include "Transforms.h"
Ted Kremenekf7639e12012-03-06 20:06:33 +000011#include "clang/ARCMigrate/ARCMTActions.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000012#include "clang/AST/ASTConsumer.h"
13#include "clang/AST/ASTContext.h"
14#include "clang/AST/NSAPI.h"
Argyrios Kyrtzidis6b4f3412013-01-16 23:54:48 +000015#include "clang/AST/ParentMap.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000016#include "clang/AST/RecursiveASTVisitor.h"
17#include "clang/Basic/FileManager.h"
18#include "clang/Edit/Commit.h"
19#include "clang/Edit/EditedSource.h"
20#include "clang/Edit/EditsReceiver.h"
21#include "clang/Edit/Rewriters.h"
Ted Kremenekf7639e12012-03-06 20:06:33 +000022#include "clang/Frontend/CompilerInstance.h"
23#include "clang/Frontend/MultiplexConsumer.h"
Argyrios Kyrtzidisf3d587e2012-12-04 07:27:05 +000024#include "clang/Lex/PPConditionalDirectiveRecord.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000025#include "clang/Lex/Preprocessor.h"
26#include "clang/Rewrite/Core/Rewriter.h"
Fariborz Jahanian9ef4a262013-08-19 19:13:34 +000027#include "clang/Analysis/DomainSpecific/CocoaConventions.h"
Fariborz Jahanian84ac1de2013-08-15 21:44:38 +000028#include "clang/StaticAnalyzer/Checkers/ObjCRetainCount.h"
Fariborz Jahaniandfe6ed92013-08-12 23:17:13 +000029#include "clang/AST/Attr.h"
Ted Kremenekf7639e12012-03-06 20:06:33 +000030#include "llvm/ADT/SmallString.h"
31
32using namespace clang;
33using namespace arcmt;
Fariborz Jahanian84ac1de2013-08-15 21:44:38 +000034using namespace ento::objc_retain;
Ted Kremenekf7639e12012-03-06 20:06:33 +000035
36namespace {
37
38class ObjCMigrateASTConsumer : public ASTConsumer {
Fariborz Jahanian63ffce22013-08-27 22:42:30 +000039 enum CF_BRIDGING_KIND {
40 CF_BRIDGING_NONE,
41 CF_BRIDGING_ENABLE,
42 CF_BRIDGING_MAY_INCLUDE
43 };
44
Ted Kremenekf7639e12012-03-06 20:06:33 +000045 void migrateDecl(Decl *D);
Fariborz Jahanian92f72422013-09-17 19:00:30 +000046 void migrateObjCInterfaceDecl(ASTContext &Ctx, ObjCContainerDecl *D);
Fariborz Jahanian1be01532013-07-12 22:32:19 +000047 void migrateProtocolConformance(ASTContext &Ctx,
48 const ObjCImplementationDecl *ImpDecl);
Fariborz Jahanian92463272013-07-18 20:11:45 +000049 void migrateNSEnumDecl(ASTContext &Ctx, const EnumDecl *EnumDcl,
50 const TypedefDecl *TypedefDcl);
Fariborz Jahaniand0fbf6c2013-08-30 23:52:08 +000051 void migrateMethods(ASTContext &Ctx, ObjCContainerDecl *CDecl);
Fariborz Jahanian670ef262013-07-23 23:34:42 +000052 void migrateMethodInstanceType(ASTContext &Ctx, ObjCContainerDecl *CDecl,
53 ObjCMethodDecl *OM);
Fariborz Jahanian92f72422013-09-17 19:00:30 +000054 bool migrateProperty(ASTContext &Ctx, ObjCContainerDecl *D, ObjCMethodDecl *OM);
Fariborz Jahaniand0fbf6c2013-08-30 23:52:08 +000055 void migrateNsReturnsInnerPointer(ASTContext &Ctx, ObjCMethodDecl *OM);
Fariborz Jahanian10b74352013-09-24 20:20:52 +000056 void migratePropertyNsReturnsInnerPointer(ASTContext &Ctx, ObjCPropertyDecl *P);
Fariborz Jahanianc4291852013-08-02 18:00:53 +000057 void migrateFactoryMethod(ASTContext &Ctx, ObjCContainerDecl *CDecl,
Fariborz Jahanian9275c682013-08-02 20:54:18 +000058 ObjCMethodDecl *OM,
59 ObjCInstanceTypeFamily OIT_Family = OIT_None);
Fariborz Jahaniandfe6ed92013-08-12 23:17:13 +000060
Fariborz Jahanian4f64dd22013-08-22 21:40:15 +000061 void migrateCFAnnotation(ASTContext &Ctx, const Decl *Decl);
Fariborz Jahanian63ffce22013-08-27 22:42:30 +000062 void AddCFAnnotations(ASTContext &Ctx, const CallEffects &CE,
Fariborz Jahanian7ca1d302013-08-27 23:56:54 +000063 const FunctionDecl *FuncDecl, bool ResultAnnotated);
Fariborz Jahanian63ffce22013-08-27 22:42:30 +000064 void AddCFAnnotations(ASTContext &Ctx, const CallEffects &CE,
Fariborz Jahanian7ca1d302013-08-27 23:56:54 +000065 const ObjCMethodDecl *MethodDecl, bool ResultAnnotated);
Fariborz Jahanian2ec4d7b2013-08-16 23:35:05 +000066
Fariborz Jahanian301b5212013-08-20 22:42:13 +000067 void AnnotateImplicitBridging(ASTContext &Ctx);
68
Fariborz Jahanian63ffce22013-08-27 22:42:30 +000069 CF_BRIDGING_KIND migrateAddFunctionAnnotation(ASTContext &Ctx,
70 const FunctionDecl *FuncDecl);
Fariborz Jahaniandfe6ed92013-08-12 23:17:13 +000071
Fariborz Jahanian926fafb2013-08-22 18:35:27 +000072 void migrateARCSafeAnnotation(ASTContext &Ctx, ObjCContainerDecl *CDecl);
73
Fariborz Jahanian89f6d102013-09-04 00:10:06 +000074 void migrateAddMethodAnnotation(ASTContext &Ctx,
75 const ObjCMethodDecl *MethodDecl);
Ted Kremenekf7639e12012-03-06 20:06:33 +000076public:
77 std::string MigrateDir;
Fariborz Jahanian182486c2013-10-02 17:08:12 +000078 unsigned ASTMigrateActions;
Fariborz Jahanianb8343522013-08-20 23:35:26 +000079 unsigned FileId;
Dmitri Gribenkof8579502013-01-12 19:30:44 +000080 OwningPtr<NSAPI> NSAPIObj;
81 OwningPtr<edit::EditedSource> Editor;
Ted Kremenekf7639e12012-03-06 20:06:33 +000082 FileRemapper &Remapper;
83 FileManager &FileMgr;
Argyrios Kyrtzidisf3d587e2012-12-04 07:27:05 +000084 const PPConditionalDirectiveRecord *PPRec;
Fariborz Jahaniana7437f02013-07-03 23:05:00 +000085 Preprocessor &PP;
Ted Kremenekf7639e12012-03-06 20:06:33 +000086 bool IsOutputFile;
Fariborz Jahanian1be01532013-07-12 22:32:19 +000087 llvm::SmallPtrSet<ObjCProtocolDecl *, 32> ObjCProtocolDecls;
Fariborz Jahanian926fafb2013-08-22 18:35:27 +000088 llvm::SmallVector<const Decl *, 8> CFFunctionIBCandidates;
Fariborz Jahanian1be01532013-07-12 22:32:19 +000089
Ted Kremenekf7639e12012-03-06 20:06:33 +000090 ObjCMigrateASTConsumer(StringRef migrateDir,
Fariborz Jahanian182486c2013-10-02 17:08:12 +000091 unsigned astMigrateActions,
Ted Kremenekf7639e12012-03-06 20:06:33 +000092 FileRemapper &remapper,
93 FileManager &fileMgr,
Argyrios Kyrtzidisf3d587e2012-12-04 07:27:05 +000094 const PPConditionalDirectiveRecord *PPRec,
Fariborz Jahaniana7437f02013-07-03 23:05:00 +000095 Preprocessor &PP,
Ted Kremenekf7639e12012-03-06 20:06:33 +000096 bool isOutputFile = false)
97 : MigrateDir(migrateDir),
Fariborz Jahanian182486c2013-10-02 17:08:12 +000098 ASTMigrateActions(astMigrateActions),
Fariborz Jahanian55d6e6c2013-08-28 23:22:46 +000099 FileId(0), Remapper(remapper), FileMgr(fileMgr), PPRec(PPRec), PP(PP),
Ted Kremenekf7639e12012-03-06 20:06:33 +0000100 IsOutputFile(isOutputFile) { }
101
102protected:
103 virtual void Initialize(ASTContext &Context) {
104 NSAPIObj.reset(new NSAPI(Context));
105 Editor.reset(new edit::EditedSource(Context.getSourceManager(),
David Blaikiebbafb8a2012-03-11 07:00:24 +0000106 Context.getLangOpts(),
Fariborz Jahanian8f5225b2013-10-01 21:16:29 +0000107 PPRec, false));
Ted Kremenekf7639e12012-03-06 20:06:33 +0000108 }
109
110 virtual bool HandleTopLevelDecl(DeclGroupRef DG) {
111 for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I)
112 migrateDecl(*I);
113 return true;
114 }
115 virtual void HandleInterestingDecl(DeclGroupRef DG) {
116 // Ignore decls from the PCH.
117 }
118 virtual void HandleTopLevelDeclInObjCContainer(DeclGroupRef DG) {
119 ObjCMigrateASTConsumer::HandleTopLevelDecl(DG);
120 }
121
122 virtual void HandleTranslationUnit(ASTContext &Ctx);
123};
124
125}
126
127ObjCMigrateAction::ObjCMigrateAction(FrontendAction *WrappedAction,
Fariborz Jahanian182486c2013-10-02 17:08:12 +0000128 StringRef migrateDir,
129 unsigned migrateAction)
Ted Kremenekf7639e12012-03-06 20:06:33 +0000130 : WrapperFrontendAction(WrappedAction), MigrateDir(migrateDir),
Fariborz Jahanian182486c2013-10-02 17:08:12 +0000131 ObjCMigAction(migrateAction),
Ted Kremenekf7639e12012-03-06 20:06:33 +0000132 CompInst(0) {
133 if (MigrateDir.empty())
134 MigrateDir = "."; // user current directory if none is given.
135}
136
137ASTConsumer *ObjCMigrateAction::CreateASTConsumer(CompilerInstance &CI,
138 StringRef InFile) {
Argyrios Kyrtzidisf3d587e2012-12-04 07:27:05 +0000139 PPConditionalDirectiveRecord *
140 PPRec = new PPConditionalDirectiveRecord(CompInst->getSourceManager());
141 CompInst->getPreprocessor().addPPCallbacks(PPRec);
Ted Kremenekf7639e12012-03-06 20:06:33 +0000142 ASTConsumer *
143 WrappedConsumer = WrapperFrontendAction::CreateASTConsumer(CI, InFile);
144 ASTConsumer *MTConsumer = new ObjCMigrateASTConsumer(MigrateDir,
Fariborz Jahanian182486c2013-10-02 17:08:12 +0000145 ObjCMigAction,
Ted Kremenekf7639e12012-03-06 20:06:33 +0000146 Remapper,
147 CompInst->getFileManager(),
Fariborz Jahaniana7437f02013-07-03 23:05:00 +0000148 PPRec,
149 CompInst->getPreprocessor());
Ted Kremenekf7639e12012-03-06 20:06:33 +0000150 ASTConsumer *Consumers[] = { MTConsumer, WrappedConsumer };
151 return new MultiplexConsumer(Consumers);
152}
153
154bool ObjCMigrateAction::BeginInvocation(CompilerInstance &CI) {
155 Remapper.initFromDisk(MigrateDir, CI.getDiagnostics(),
156 /*ignoreIfFilesChanges=*/true);
157 CompInst = &CI;
158 CI.getDiagnostics().setIgnoreAllWarnings(true);
Ted Kremenekf7639e12012-03-06 20:06:33 +0000159 return true;
160}
161
162namespace {
163class ObjCMigrator : public RecursiveASTVisitor<ObjCMigrator> {
164 ObjCMigrateASTConsumer &Consumer;
Argyrios Kyrtzidis6b4f3412013-01-16 23:54:48 +0000165 ParentMap &PMap;
Ted Kremenekf7639e12012-03-06 20:06:33 +0000166
167public:
Argyrios Kyrtzidis6b4f3412013-01-16 23:54:48 +0000168 ObjCMigrator(ObjCMigrateASTConsumer &consumer, ParentMap &PMap)
169 : Consumer(consumer), PMap(PMap) { }
Ted Kremenekf7639e12012-03-06 20:06:33 +0000170
171 bool shouldVisitTemplateInstantiations() const { return false; }
172 bool shouldWalkTypesOfTypeLocs() const { return false; }
173
174 bool VisitObjCMessageExpr(ObjCMessageExpr *E) {
Fariborz Jahanian182486c2013-10-02 17:08:12 +0000175 if (Consumer.ASTMigrateActions & FrontendOptions::ObjCMT_Literals) {
Ted Kremenekf7639e12012-03-06 20:06:33 +0000176 edit::Commit commit(*Consumer.Editor);
Argyrios Kyrtzidis6b4f3412013-01-16 23:54:48 +0000177 edit::rewriteToObjCLiteralSyntax(E, *Consumer.NSAPIObj, commit, &PMap);
Ted Kremenekf7639e12012-03-06 20:06:33 +0000178 Consumer.Editor->commit(commit);
179 }
180
Fariborz Jahanian182486c2013-10-02 17:08:12 +0000181 if (Consumer.ASTMigrateActions & FrontendOptions::ObjCMT_Subscripting) {
Ted Kremenekf7639e12012-03-06 20:06:33 +0000182 edit::Commit commit(*Consumer.Editor);
183 edit::rewriteToObjCSubscriptSyntax(E, *Consumer.NSAPIObj, commit);
184 Consumer.Editor->commit(commit);
185 }
186
187 return true;
188 }
189
190 bool TraverseObjCMessageExpr(ObjCMessageExpr *E) {
191 // Do depth first; we want to rewrite the subexpressions first so that if
192 // we have to move expressions we will move them already rewritten.
193 for (Stmt::child_range range = E->children(); range; ++range)
194 if (!TraverseStmt(*range))
195 return false;
196
197 return WalkUpFromObjCMessageExpr(E);
198 }
199};
Argyrios Kyrtzidis6b4f3412013-01-16 23:54:48 +0000200
201class BodyMigrator : public RecursiveASTVisitor<BodyMigrator> {
202 ObjCMigrateASTConsumer &Consumer;
203 OwningPtr<ParentMap> PMap;
204
205public:
206 BodyMigrator(ObjCMigrateASTConsumer &consumer) : Consumer(consumer) { }
207
208 bool shouldVisitTemplateInstantiations() const { return false; }
209 bool shouldWalkTypesOfTypeLocs() const { return false; }
210
211 bool TraverseStmt(Stmt *S) {
212 PMap.reset(new ParentMap(S));
213 ObjCMigrator(Consumer, *PMap).TraverseStmt(S);
214 return true;
215 }
216};
Ted Kremenekf7639e12012-03-06 20:06:33 +0000217}
218
219void ObjCMigrateASTConsumer::migrateDecl(Decl *D) {
220 if (!D)
221 return;
222 if (isa<ObjCMethodDecl>(D))
223 return; // Wait for the ObjC container declaration.
224
Argyrios Kyrtzidis6b4f3412013-01-16 23:54:48 +0000225 BodyMigrator(*this).TraverseDecl(D);
Ted Kremenekf7639e12012-03-06 20:06:33 +0000226}
227
Fariborz Jahanian447b15e2013-08-21 18:49:03 +0000228static void append_attr(std::string &PropertyString, const char *attr) {
229 PropertyString += ", ";
Fariborz Jahaniancf2ff9b2013-08-08 20:51:58 +0000230 PropertyString += attr;
Fariborz Jahaniancf2ff9b2013-08-08 20:51:58 +0000231}
232
Fariborz Jahanian85e988b2013-07-18 22:17:33 +0000233static bool rewriteToObjCProperty(const ObjCMethodDecl *Getter,
234 const ObjCMethodDecl *Setter,
Fariborz Jahaniancf2ff9b2013-08-08 20:51:58 +0000235 const NSAPI &NS, edit::Commit &commit,
Fariborz Jahanianca399602013-09-11 17:05:15 +0000236 unsigned LengthOfPrefix) {
Fariborz Jahanian85e988b2013-07-18 22:17:33 +0000237 ASTContext &Context = NS.getASTContext();
Fariborz Jahanian7797c0d2013-09-24 21:27:58 +0000238 std::string PropertyString = "@property (nonatomic";
Fariborz Jahaniancf387c62013-08-06 18:06:23 +0000239 std::string PropertyNameString = Getter->getNameAsString();
240 StringRef PropertyName(PropertyNameString);
Fariborz Jahanianca399602013-09-11 17:05:15 +0000241 if (LengthOfPrefix > 0) {
Fariborz Jahanian447b15e2013-08-21 18:49:03 +0000242 PropertyString += ", getter=";
Fariborz Jahaniancf2ff9b2013-08-08 20:51:58 +0000243 PropertyString += PropertyNameString;
244 }
Fariborz Jahanian55d6e6c2013-08-28 23:22:46 +0000245 // Property with no setter may be suggested as a 'readonly' property.
246 if (!Setter)
247 append_attr(PropertyString, "readonly");
248
Fariborz Jahaniancf387c62013-08-06 18:06:23 +0000249 // Short circuit properties that contain the name "delegate" or "dataSource",
250 // or have exact name "target" to have unsafe_unretained attribute.
251 if (PropertyName.equals("target") ||
252 (PropertyName.find("delegate") != StringRef::npos) ||
253 (PropertyName.find("dataSource") != StringRef::npos))
Fariborz Jahanian447b15e2013-08-21 18:49:03 +0000254 append_attr(PropertyString, "unsafe_unretained");
Fariborz Jahanian55d6e6c2013-08-28 23:22:46 +0000255 else if (Setter) {
Fariborz Jahaniancf387c62013-08-06 18:06:23 +0000256 const ParmVarDecl *argDecl = *Setter->param_begin();
257 QualType ArgType = Context.getCanonicalType(argDecl->getType());
258 Qualifiers::ObjCLifetime propertyLifetime = ArgType.getObjCLifetime();
259 bool RetainableObject = ArgType->isObjCRetainableType();
260 if (RetainableObject && propertyLifetime == Qualifiers::OCL_Strong) {
261 if (const ObjCObjectPointerType *ObjPtrTy =
262 ArgType->getAs<ObjCObjectPointerType>()) {
263 ObjCInterfaceDecl *IDecl = ObjPtrTy->getObjectType()->getInterface();
264 if (IDecl &&
265 IDecl->lookupNestedProtocol(&Context.Idents.get("NSCopying")))
Fariborz Jahanian447b15e2013-08-21 18:49:03 +0000266 append_attr(PropertyString, "copy");
Fariborz Jahaniancf387c62013-08-06 18:06:23 +0000267 else
Fariborz Jahanian447b15e2013-08-21 18:49:03 +0000268 append_attr(PropertyString, "retain");
269 }
Fariborz Jahaniancf387c62013-08-06 18:06:23 +0000270 } else if (propertyLifetime == Qualifiers::OCL_Weak)
271 // TODO. More precise determination of 'weak' attribute requires
272 // looking into setter's implementation for backing weak ivar.
Fariborz Jahanian447b15e2013-08-21 18:49:03 +0000273 append_attr(PropertyString, "weak");
Fariborz Jahaniancf387c62013-08-06 18:06:23 +0000274 else if (RetainableObject)
Fariborz Jahanian447b15e2013-08-21 18:49:03 +0000275 append_attr(PropertyString, "retain");
Fariborz Jahaniancf387c62013-08-06 18:06:23 +0000276 }
Fariborz Jahanian447b15e2013-08-21 18:49:03 +0000277 PropertyString += ')';
Fariborz Jahanian85e988b2013-07-18 22:17:33 +0000278
Fariborz Jahaniancf2ff9b2013-08-08 20:51:58 +0000279 QualType RT = Getter->getResultType();
280 if (!isa<TypedefType>(RT)) {
281 // strip off any ARC lifetime qualifier.
282 QualType CanResultTy = Context.getCanonicalType(RT);
283 if (CanResultTy.getQualifiers().hasObjCLifetime()) {
284 Qualifiers Qs = CanResultTy.getQualifiers();
285 Qs.removeObjCLifetime();
286 RT = Context.getQualifiedType(CanResultTy.getUnqualifiedType(), Qs);
287 }
Fariborz Jahanian85e988b2013-07-18 22:17:33 +0000288 }
289 PropertyString += " ";
Fariborz Jahaniancf2ff9b2013-08-08 20:51:58 +0000290 PropertyString += RT.getAsString(Context.getPrintingPolicy());
Fariborz Jahanian1a73b8f2013-09-23 23:48:04 +0000291 char LastChar = PropertyString[PropertyString.size()-1];
Fariborz Jahanianc71eb6a2013-09-23 23:18:46 +0000292 if (LastChar != '*')
293 PropertyString += " ";
Fariborz Jahanianca399602013-09-11 17:05:15 +0000294 if (LengthOfPrefix > 0) {
Fariborz Jahaniancf2ff9b2013-08-08 20:51:58 +0000295 // property name must strip off "is" and lower case the first character
296 // after that; e.g. isContinuous will become continuous.
297 StringRef PropertyNameStringRef(PropertyNameString);
Fariborz Jahanianca399602013-09-11 17:05:15 +0000298 PropertyNameStringRef = PropertyNameStringRef.drop_front(LengthOfPrefix);
Fariborz Jahaniancf2ff9b2013-08-08 20:51:58 +0000299 PropertyNameString = PropertyNameStringRef;
300 std::string NewPropertyNameString = PropertyNameString;
Fariborz Jahanian34fea362013-09-11 18:27:16 +0000301 bool NoLowering = (isUppercase(NewPropertyNameString[0]) &&
302 NewPropertyNameString.size() > 1 &&
303 isUppercase(NewPropertyNameString[1]));
304 if (!NoLowering)
305 NewPropertyNameString[0] = toLowercase(NewPropertyNameString[0]);
Fariborz Jahaniancf2ff9b2013-08-08 20:51:58 +0000306 PropertyString += NewPropertyNameString;
307 }
308 else
309 PropertyString += PropertyNameString;
Fariborz Jahanian215f96c2013-09-06 23:45:20 +0000310 SourceLocation StartGetterSelectorLoc = Getter->getSelectorStartLoc();
311 Selector GetterSelector = Getter->getSelector();
312
313 SourceLocation EndGetterSelectorLoc =
314 StartGetterSelectorLoc.getLocWithOffset(GetterSelector.getNameForSlot(0).size());
Fariborz Jahanian85e988b2013-07-18 22:17:33 +0000315 commit.replace(CharSourceRange::getCharRange(Getter->getLocStart(),
Fariborz Jahanian215f96c2013-09-06 23:45:20 +0000316 EndGetterSelectorLoc),
Fariborz Jahanian85e988b2013-07-18 22:17:33 +0000317 PropertyString);
Fariborz Jahanian55d6e6c2013-08-28 23:22:46 +0000318 if (Setter) {
319 SourceLocation EndLoc = Setter->getDeclaratorEndLoc();
320 // Get location past ';'
321 EndLoc = EndLoc.getLocWithOffset(1);
322 commit.remove(CharSourceRange::getCharRange(Setter->getLocStart(), EndLoc));
323 }
Fariborz Jahanian85e988b2013-07-18 22:17:33 +0000324 return true;
325}
326
Fariborz Jahaniana7437f02013-07-03 23:05:00 +0000327void ObjCMigrateASTConsumer::migrateObjCInterfaceDecl(ASTContext &Ctx,
Fariborz Jahanian92f72422013-09-17 19:00:30 +0000328 ObjCContainerDecl *D) {
Fariborz Jahanian75226d52013-09-17 21:56:04 +0000329 if (D->isDeprecated())
330 return;
331
Fariborz Jahaniana7437f02013-07-03 23:05:00 +0000332 for (ObjCContainerDecl::method_iterator M = D->meth_begin(), MEnd = D->meth_end();
333 M != MEnd; ++M) {
334 ObjCMethodDecl *Method = (*M);
Fariborz Jahanian75226d52013-09-17 21:56:04 +0000335 if (Method->isDeprecated())
336 continue;
Fariborz Jahanian10b74352013-09-24 20:20:52 +0000337 migrateProperty(Ctx, D, Method);
338 migrateNsReturnsInnerPointer(Ctx, Method);
339 }
340 for (ObjCContainerDecl::prop_iterator P = D->prop_begin(),
341 E = D->prop_end(); P != E; ++P) {
342 ObjCPropertyDecl *Prop = *P;
343 if (!P->isDeprecated())
344 migratePropertyNsReturnsInnerPointer(Ctx, Prop);
Fariborz Jahaniana7437f02013-07-03 23:05:00 +0000345 }
346}
347
Fariborz Jahanian9eabf452013-07-13 00:04:20 +0000348static bool
Fariborz Jahanian9a3512b2013-07-13 17:16:41 +0000349ClassImplementsAllMethodsAndProperties(ASTContext &Ctx,
Fariborz Jahanian9eabf452013-07-13 00:04:20 +0000350 const ObjCImplementationDecl *ImpDecl,
Fariborz Jahaniand36150d2013-07-15 21:22:08 +0000351 const ObjCInterfaceDecl *IDecl,
Fariborz Jahanian9eabf452013-07-13 00:04:20 +0000352 ObjCProtocolDecl *Protocol) {
Fariborz Jahaniand36150d2013-07-15 21:22:08 +0000353 // In auto-synthesis, protocol properties are not synthesized. So,
354 // a conforming protocol must have its required properties declared
355 // in class interface.
Fariborz Jahanian9e543af2013-07-22 23:50:04 +0000356 bool HasAtleastOneRequiredProperty = false;
Fariborz Jahaniand36150d2013-07-15 21:22:08 +0000357 if (const ObjCProtocolDecl *PDecl = Protocol->getDefinition())
358 for (ObjCProtocolDecl::prop_iterator P = PDecl->prop_begin(),
359 E = PDecl->prop_end(); P != E; ++P) {
360 ObjCPropertyDecl *Property = *P;
361 if (Property->getPropertyImplementation() == ObjCPropertyDecl::Optional)
362 continue;
Fariborz Jahanian9e543af2013-07-22 23:50:04 +0000363 HasAtleastOneRequiredProperty = true;
Fariborz Jahaniand36150d2013-07-15 21:22:08 +0000364 DeclContext::lookup_const_result R = IDecl->lookup(Property->getDeclName());
Fariborz Jahanian2bc3dda2013-07-16 21:59:42 +0000365 if (R.size() == 0) {
366 // Relax the rule and look into class's implementation for a synthesize
367 // or dynamic declaration. Class is implementing a property coming from
368 // another protocol. This still makes the target protocol as conforming.
369 if (!ImpDecl->FindPropertyImplDecl(
370 Property->getDeclName().getAsIdentifierInfo()))
371 return false;
Fariborz Jahaniand36150d2013-07-15 21:22:08 +0000372 }
Fariborz Jahanian2bc3dda2013-07-16 21:59:42 +0000373 else if (ObjCPropertyDecl *ClassProperty = dyn_cast<ObjCPropertyDecl>(R[0])) {
374 if ((ClassProperty->getPropertyAttributes()
375 != Property->getPropertyAttributes()) ||
376 !Ctx.hasSameType(ClassProperty->getType(), Property->getType()))
377 return false;
378 }
379 else
380 return false;
Fariborz Jahaniand36150d2013-07-15 21:22:08 +0000381 }
Fariborz Jahanian9e543af2013-07-22 23:50:04 +0000382
Fariborz Jahaniand36150d2013-07-15 21:22:08 +0000383 // At this point, all required properties in this protocol conform to those
384 // declared in the class.
385 // Check that class implements the required methods of the protocol too.
Fariborz Jahanian9e543af2013-07-22 23:50:04 +0000386 bool HasAtleastOneRequiredMethod = false;
Fariborz Jahanian5bd5aff2013-07-16 00:20:21 +0000387 if (const ObjCProtocolDecl *PDecl = Protocol->getDefinition()) {
388 if (PDecl->meth_begin() == PDecl->meth_end())
Fariborz Jahanian9e543af2013-07-22 23:50:04 +0000389 return HasAtleastOneRequiredProperty;
Fariborz Jahaniand36150d2013-07-15 21:22:08 +0000390 for (ObjCContainerDecl::method_iterator M = PDecl->meth_begin(),
391 MEnd = PDecl->meth_end(); M != MEnd; ++M) {
392 ObjCMethodDecl *MD = (*M);
Fariborz Jahanian5bd5aff2013-07-16 00:20:21 +0000393 if (MD->isImplicit())
394 continue;
Fariborz Jahaniand36150d2013-07-15 21:22:08 +0000395 if (MD->getImplementationControl() == ObjCMethodDecl::Optional)
396 continue;
Fariborz Jahaniand36150d2013-07-15 21:22:08 +0000397 DeclContext::lookup_const_result R = ImpDecl->lookup(MD->getDeclName());
Fariborz Jahanian5bd5aff2013-07-16 00:20:21 +0000398 if (R.size() == 0)
399 return false;
Fariborz Jahanian9e543af2013-07-22 23:50:04 +0000400 bool match = false;
401 HasAtleastOneRequiredMethod = true;
Fariborz Jahaniand36150d2013-07-15 21:22:08 +0000402 for (unsigned I = 0, N = R.size(); I != N; ++I)
403 if (ObjCMethodDecl *ImpMD = dyn_cast<ObjCMethodDecl>(R[0]))
404 if (Ctx.ObjCMethodsAreEqual(MD, ImpMD)) {
405 match = true;
406 break;
407 }
408 if (!match)
409 return false;
410 }
Fariborz Jahanian5bd5aff2013-07-16 00:20:21 +0000411 }
Fariborz Jahanian9e543af2013-07-22 23:50:04 +0000412 if (HasAtleastOneRequiredProperty || HasAtleastOneRequiredMethod)
413 return true;
414 return false;
Fariborz Jahanian9eabf452013-07-13 00:04:20 +0000415}
416
Fariborz Jahanian85e988b2013-07-18 22:17:33 +0000417static bool rewriteToObjCInterfaceDecl(const ObjCInterfaceDecl *IDecl,
418 llvm::SmallVectorImpl<ObjCProtocolDecl*> &ConformingProtocols,
419 const NSAPI &NS, edit::Commit &commit) {
420 const ObjCList<ObjCProtocolDecl> &Protocols = IDecl->getReferencedProtocols();
421 std::string ClassString;
422 SourceLocation EndLoc =
423 IDecl->getSuperClass() ? IDecl->getSuperClassLoc() : IDecl->getLocation();
424
425 if (Protocols.empty()) {
426 ClassString = '<';
427 for (unsigned i = 0, e = ConformingProtocols.size(); i != e; i++) {
428 ClassString += ConformingProtocols[i]->getNameAsString();
429 if (i != (e-1))
430 ClassString += ", ";
431 }
432 ClassString += "> ";
433 }
434 else {
435 ClassString = ", ";
436 for (unsigned i = 0, e = ConformingProtocols.size(); i != e; i++) {
437 ClassString += ConformingProtocols[i]->getNameAsString();
438 if (i != (e-1))
439 ClassString += ", ";
440 }
441 ObjCInterfaceDecl::protocol_loc_iterator PL = IDecl->protocol_loc_end() - 1;
442 EndLoc = *PL;
443 }
444
445 commit.insertAfterToken(EndLoc, ClassString);
446 return true;
447}
448
449static bool rewriteToNSEnumDecl(const EnumDecl *EnumDcl,
450 const TypedefDecl *TypedefDcl,
Fariborz Jahanianb0057bb2013-07-19 01:05:49 +0000451 const NSAPI &NS, edit::Commit &commit,
Fariborz Jahanianff3476e2013-08-30 17:46:01 +0000452 bool IsNSIntegerType,
453 bool NSOptions) {
454 std::string ClassString;
455 if (NSOptions)
456 ClassString = "typedef NS_OPTIONS(NSUInteger, ";
457 else
458 ClassString =
459 IsNSIntegerType ? "typedef NS_ENUM(NSInteger, "
460 : "typedef NS_ENUM(NSUInteger, ";
461
Fariborz Jahanian85e988b2013-07-18 22:17:33 +0000462 ClassString += TypedefDcl->getIdentifier()->getName();
463 ClassString += ')';
464 SourceRange R(EnumDcl->getLocStart(), EnumDcl->getLocStart());
465 commit.replace(R, ClassString);
466 SourceLocation EndOfTypedefLoc = TypedefDcl->getLocEnd();
467 EndOfTypedefLoc = trans::findLocationAfterSemi(EndOfTypedefLoc, NS.getASTContext());
468 if (!EndOfTypedefLoc.isInvalid()) {
469 commit.remove(SourceRange(TypedefDcl->getLocStart(), EndOfTypedefLoc));
470 return true;
471 }
472 return false;
473}
474
Fariborz Jahaniand0f6f792013-07-22 18:53:45 +0000475static bool rewriteToNSMacroDecl(const EnumDecl *EnumDcl,
Fariborz Jahanianc1c44f62013-07-19 20:18:36 +0000476 const TypedefDecl *TypedefDcl,
Fariborz Jahaniand0f6f792013-07-22 18:53:45 +0000477 const NSAPI &NS, edit::Commit &commit,
478 bool IsNSIntegerType) {
479 std::string ClassString =
480 IsNSIntegerType ? "NS_ENUM(NSInteger, " : "NS_OPTIONS(NSUInteger, ";
Fariborz Jahanianc1c44f62013-07-19 20:18:36 +0000481 ClassString += TypedefDcl->getIdentifier()->getName();
482 ClassString += ')';
483 SourceRange R(EnumDcl->getLocStart(), EnumDcl->getLocStart());
484 commit.replace(R, ClassString);
485 SourceLocation TypedefLoc = TypedefDcl->getLocEnd();
486 commit.remove(SourceRange(TypedefLoc, TypedefLoc));
487 return true;
488}
489
Fariborz Jahaniana23f4fb2013-08-30 00:10:37 +0000490static bool UseNSOptionsMacro(Preprocessor &PP, ASTContext &Ctx,
Fariborz Jahaniand0f6f792013-07-22 18:53:45 +0000491 const EnumDecl *EnumDcl) {
492 bool PowerOfTwo = true;
Fariborz Jahanian02bdb162013-09-23 20:27:06 +0000493 bool AllHexdecimalEnumerator = true;
Fariborz Jahanianbe7bc112013-08-15 18:46:37 +0000494 uint64_t MaxPowerOfTwoVal = 0;
Fariborz Jahaniand0f6f792013-07-22 18:53:45 +0000495 for (EnumDecl::enumerator_iterator EI = EnumDcl->enumerator_begin(),
496 EE = EnumDcl->enumerator_end(); EI != EE; ++EI) {
497 EnumConstantDecl *Enumerator = (*EI);
498 const Expr *InitExpr = Enumerator->getInitExpr();
499 if (!InitExpr) {
500 PowerOfTwo = false;
Fariborz Jahanian02bdb162013-09-23 20:27:06 +0000501 AllHexdecimalEnumerator = false;
Fariborz Jahaniand0f6f792013-07-22 18:53:45 +0000502 continue;
503 }
Fariborz Jahanian6e1798e2013-09-17 23:32:51 +0000504 InitExpr = InitExpr->IgnoreParenCasts();
Fariborz Jahaniand0f6f792013-07-22 18:53:45 +0000505 if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr))
506 if (BO->isShiftOp() || BO->isBitwiseOp())
507 return true;
508
509 uint64_t EnumVal = Enumerator->getInitVal().getZExtValue();
Fariborz Jahanianbe7bc112013-08-15 18:46:37 +0000510 if (PowerOfTwo && EnumVal) {
511 if (!llvm::isPowerOf2_64(EnumVal))
512 PowerOfTwo = false;
513 else if (EnumVal > MaxPowerOfTwoVal)
514 MaxPowerOfTwoVal = EnumVal;
515 }
Fariborz Jahanian02bdb162013-09-23 20:27:06 +0000516 if (AllHexdecimalEnumerator && EnumVal) {
517 bool FoundHexdecimalEnumerator = false;
Fariborz Jahaniana23f4fb2013-08-30 00:10:37 +0000518 SourceLocation EndLoc = Enumerator->getLocEnd();
519 Token Tok;
520 if (!PP.getRawToken(EndLoc, Tok, /*IgnoreWhiteSpace=*/true))
521 if (Tok.isLiteral() && Tok.getLength() > 2) {
522 if (const char *StringLit = Tok.getLiteralData())
523 FoundHexdecimalEnumerator =
524 (StringLit[0] == '0' && (toLowercase(StringLit[1]) == 'x'));
525 }
Fariborz Jahanian02bdb162013-09-23 20:27:06 +0000526 if (!FoundHexdecimalEnumerator)
527 AllHexdecimalEnumerator = false;
Fariborz Jahaniana23f4fb2013-08-30 00:10:37 +0000528 }
Fariborz Jahaniand0f6f792013-07-22 18:53:45 +0000529 }
Fariborz Jahanian02bdb162013-09-23 20:27:06 +0000530 return AllHexdecimalEnumerator || (PowerOfTwo && (MaxPowerOfTwoVal > 2));
Fariborz Jahaniand0f6f792013-07-22 18:53:45 +0000531}
532
Fariborz Jahanian008ef722013-07-19 17:44:32 +0000533void ObjCMigrateASTConsumer::migrateProtocolConformance(ASTContext &Ctx,
Fariborz Jahanian1be01532013-07-12 22:32:19 +0000534 const ObjCImplementationDecl *ImpDecl) {
535 const ObjCInterfaceDecl *IDecl = ImpDecl->getClassInterface();
Fariborz Jahanian75226d52013-09-17 21:56:04 +0000536 if (!IDecl || ObjCProtocolDecls.empty() || IDecl->isDeprecated())
Fariborz Jahanian1be01532013-07-12 22:32:19 +0000537 return;
538 // Find all implicit conforming protocols for this class
539 // and make them explicit.
540 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> ExplicitProtocols;
541 Ctx.CollectInheritedProtocols(IDecl, ExplicitProtocols);
Fariborz Jahanian9eabf452013-07-13 00:04:20 +0000542 llvm::SmallVector<ObjCProtocolDecl *, 8> PotentialImplicitProtocols;
Fariborz Jahanian1be01532013-07-12 22:32:19 +0000543
Fariborz Jahanian9eabf452013-07-13 00:04:20 +0000544 for (llvm::SmallPtrSet<ObjCProtocolDecl*, 32>::iterator I =
Fariborz Jahanian1be01532013-07-12 22:32:19 +0000545 ObjCProtocolDecls.begin(),
546 E = ObjCProtocolDecls.end(); I != E; ++I)
547 if (!ExplicitProtocols.count(*I))
Fariborz Jahanian9eabf452013-07-13 00:04:20 +0000548 PotentialImplicitProtocols.push_back(*I);
Fariborz Jahanian1be01532013-07-12 22:32:19 +0000549
550 if (PotentialImplicitProtocols.empty())
551 return;
Fariborz Jahanian9eabf452013-07-13 00:04:20 +0000552
553 // go through list of non-optional methods and properties in each protocol
554 // in the PotentialImplicitProtocols list. If class implements every one of the
555 // methods and properties, then this class conforms to this protocol.
556 llvm::SmallVector<ObjCProtocolDecl*, 8> ConformingProtocols;
557 for (unsigned i = 0, e = PotentialImplicitProtocols.size(); i != e; i++)
Fariborz Jahaniand36150d2013-07-15 21:22:08 +0000558 if (ClassImplementsAllMethodsAndProperties(Ctx, ImpDecl, IDecl,
Fariborz Jahanian9eabf452013-07-13 00:04:20 +0000559 PotentialImplicitProtocols[i]))
560 ConformingProtocols.push_back(PotentialImplicitProtocols[i]);
Fariborz Jahanian5bd5aff2013-07-16 00:20:21 +0000561
562 if (ConformingProtocols.empty())
563 return;
Fariborz Jahaniancb7b8de2013-07-17 00:02:22 +0000564
565 // Further reduce number of conforming protocols. If protocol P1 is in the list
566 // protocol P2 (P2<P1>), No need to include P1.
567 llvm::SmallVector<ObjCProtocolDecl*, 8> MinimalConformingProtocols;
568 for (unsigned i = 0, e = ConformingProtocols.size(); i != e; i++) {
569 bool DropIt = false;
570 ObjCProtocolDecl *TargetPDecl = ConformingProtocols[i];
571 for (unsigned i1 = 0, e1 = ConformingProtocols.size(); i1 != e1; i1++) {
572 ObjCProtocolDecl *PDecl = ConformingProtocols[i1];
573 if (PDecl == TargetPDecl)
574 continue;
575 if (PDecl->lookupProtocolNamed(
576 TargetPDecl->getDeclName().getAsIdentifierInfo())) {
577 DropIt = true;
578 break;
579 }
580 }
581 if (!DropIt)
582 MinimalConformingProtocols.push_back(TargetPDecl);
583 }
Fariborz Jahanian5bd5aff2013-07-16 00:20:21 +0000584 edit::Commit commit(*Editor);
Fariborz Jahanian85e988b2013-07-18 22:17:33 +0000585 rewriteToObjCInterfaceDecl(IDecl, MinimalConformingProtocols,
586 *NSAPIObj, commit);
Fariborz Jahanian5bd5aff2013-07-16 00:20:21 +0000587 Editor->commit(commit);
Fariborz Jahanian1be01532013-07-12 22:32:19 +0000588}
589
Fariborz Jahanian92463272013-07-18 20:11:45 +0000590void ObjCMigrateASTConsumer::migrateNSEnumDecl(ASTContext &Ctx,
591 const EnumDecl *EnumDcl,
592 const TypedefDecl *TypedefDcl) {
593 if (!EnumDcl->isCompleteDefinition() || EnumDcl->getIdentifier() ||
Fariborz Jahanian75226d52013-09-17 21:56:04 +0000594 !TypedefDcl->getIdentifier() ||
595 EnumDcl->isDeprecated() || TypedefDcl->isDeprecated())
Fariborz Jahanian92463272013-07-18 20:11:45 +0000596 return;
597
598 QualType qt = TypedefDcl->getTypeSourceInfo()->getType();
Fariborz Jahanianb0057bb2013-07-19 01:05:49 +0000599 bool IsNSIntegerType = NSAPIObj->isObjCNSIntegerType(qt);
600 bool IsNSUIntegerType = !IsNSIntegerType && NSAPIObj->isObjCNSUIntegerType(qt);
Fariborz Jahaniand0f6f792013-07-22 18:53:45 +0000601
Fariborz Jahanianc1c44f62013-07-19 20:18:36 +0000602 if (!IsNSIntegerType && !IsNSUIntegerType) {
603 // Also check for typedef enum {...} TD;
604 if (const EnumType *EnumTy = qt->getAs<EnumType>()) {
605 if (EnumTy->getDecl() == EnumDcl) {
Fariborz Jahaniana23f4fb2013-08-30 00:10:37 +0000606 bool NSOptions = UseNSOptionsMacro(PP, Ctx, EnumDcl);
Fariborz Jahaniand0f6f792013-07-22 18:53:45 +0000607 if (NSOptions) {
608 if (!Ctx.Idents.get("NS_OPTIONS").hasMacroDefinition())
609 return;
610 }
611 else if (!Ctx.Idents.get("NS_ENUM").hasMacroDefinition())
Fariborz Jahanianc1c44f62013-07-19 20:18:36 +0000612 return;
613 edit::Commit commit(*Editor);
Fariborz Jahaniand0f6f792013-07-22 18:53:45 +0000614 rewriteToNSMacroDecl(EnumDcl, TypedefDcl, *NSAPIObj, commit, !NSOptions);
Fariborz Jahanianc1c44f62013-07-19 20:18:36 +0000615 Editor->commit(commit);
Fariborz Jahanianc1c44f62013-07-19 20:18:36 +0000616 }
Fariborz Jahanianc1c44f62013-07-19 20:18:36 +0000617 }
Fariborz Jahaniand0f6f792013-07-22 18:53:45 +0000618 return;
619 }
Fariborz Jahanian92463272013-07-18 20:11:45 +0000620
Fariborz Jahanianff3476e2013-08-30 17:46:01 +0000621 // We may still use NS_OPTIONS based on what we find in the enumertor list.
622 bool NSOptions = UseNSOptionsMacro(PP, Ctx, EnumDcl);
Fariborz Jahanian92463272013-07-18 20:11:45 +0000623 // NS_ENUM must be available.
Fariborz Jahanianb0057bb2013-07-19 01:05:49 +0000624 if (IsNSIntegerType && !Ctx.Idents.get("NS_ENUM").hasMacroDefinition())
625 return;
626 // NS_OPTIONS must be available.
627 if (IsNSUIntegerType && !Ctx.Idents.get("NS_OPTIONS").hasMacroDefinition())
Fariborz Jahanian92463272013-07-18 20:11:45 +0000628 return;
629 edit::Commit commit(*Editor);
Fariborz Jahanianff3476e2013-08-30 17:46:01 +0000630 rewriteToNSEnumDecl(EnumDcl, TypedefDcl, *NSAPIObj, commit, IsNSIntegerType, NSOptions);
Fariborz Jahanian92463272013-07-18 20:11:45 +0000631 Editor->commit(commit);
632}
633
Fariborz Jahanianc4291852013-08-02 18:00:53 +0000634static void ReplaceWithInstancetype(const ObjCMigrateASTConsumer &ASTC,
635 ObjCMethodDecl *OM) {
636 SourceRange R;
637 std::string ClassString;
638 if (TypeSourceInfo *TSInfo = OM->getResultTypeSourceInfo()) {
639 TypeLoc TL = TSInfo->getTypeLoc();
640 R = SourceRange(TL.getBeginLoc(), TL.getEndLoc());
641 ClassString = "instancetype";
642 }
643 else {
644 R = SourceRange(OM->getLocStart(), OM->getLocStart());
645 ClassString = OM->isInstanceMethod() ? '-' : '+';
646 ClassString += " (instancetype)";
647 }
648 edit::Commit commit(*ASTC.Editor);
649 commit.replace(R, ClassString);
650 ASTC.Editor->commit(commit);
651}
652
Fariborz Jahanian670ef262013-07-23 23:34:42 +0000653void ObjCMigrateASTConsumer::migrateMethodInstanceType(ASTContext &Ctx,
654 ObjCContainerDecl *CDecl,
655 ObjCMethodDecl *OM) {
Fariborz Jahanian71221352013-07-23 22:42:28 +0000656 ObjCInstanceTypeFamily OIT_Family =
657 Selector::getInstTypeMethodFamily(OM->getSelector());
Fariborz Jahanian9275c682013-08-02 20:54:18 +0000658
Fariborz Jahanian267bae32013-07-24 19:18:37 +0000659 std::string ClassName;
Fariborz Jahanian631925f2013-07-23 23:55:55 +0000660 switch (OIT_Family) {
Fariborz Jahanian9275c682013-08-02 20:54:18 +0000661 case OIT_None:
662 migrateFactoryMethod(Ctx, CDecl, OM);
663 return;
Fariborz Jahanian7dd71432013-08-28 21:23:00 +0000664 case OIT_Array:
665 ClassName = "NSArray";
666 break;
667 case OIT_Dictionary:
668 ClassName = "NSDictionary";
669 break;
Fariborz Jahanian9275c682013-08-02 20:54:18 +0000670 case OIT_Singleton:
671 migrateFactoryMethod(Ctx, CDecl, OM, OIT_Singleton);
Fariborz Jahanian631925f2013-07-23 23:55:55 +0000672 return;
Fariborz Jahanian1c900bc2013-09-18 20:35:47 +0000673 case OIT_Init:
674 if (OM->getResultType()->isObjCIdType())
675 ReplaceWithInstancetype(*this, OM);
676 return;
Fariborz Jahanian631925f2013-07-23 23:55:55 +0000677 }
Fariborz Jahanian71221352013-07-23 22:42:28 +0000678 if (!OM->getResultType()->isObjCIdType())
679 return;
680
681 ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(CDecl);
682 if (!IDecl) {
683 if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(CDecl))
684 IDecl = CatDecl->getClassInterface();
685 else if (ObjCImplDecl *ImpDecl = dyn_cast<ObjCImplDecl>(CDecl))
686 IDecl = ImpDecl->getClassInterface();
687 }
Fariborz Jahanian267bae32013-07-24 19:18:37 +0000688 if (!IDecl ||
Fariborz Jahanianc4291852013-08-02 18:00:53 +0000689 !IDecl->lookupInheritedClass(&Ctx.Idents.get(ClassName))) {
690 migrateFactoryMethod(Ctx, CDecl, OM);
Fariborz Jahanian71221352013-07-23 22:42:28 +0000691 return;
Fariborz Jahanian280954a2013-07-24 18:31:42 +0000692 }
Fariborz Jahanianc4291852013-08-02 18:00:53 +0000693 ReplaceWithInstancetype(*this, OM);
Fariborz Jahanian71221352013-07-23 22:42:28 +0000694}
695
Fariborz Jahaniand0fbf6c2013-08-30 23:52:08 +0000696static bool TypeIsInnerPointer(QualType T) {
697 if (!T->isAnyPointerType())
698 return false;
699 if (T->isObjCObjectPointerType() || T->isObjCBuiltinType() ||
Fariborz Jahanian73466ca2013-09-26 21:43:47 +0000700 T->isBlockPointerType() || T->isFunctionPointerType() ||
701 ento::coreFoundation::isCFObjectRef(T))
Fariborz Jahaniand0fbf6c2013-08-30 23:52:08 +0000702 return false;
Fariborz Jahanian9d5fffb2013-09-09 23:56:14 +0000703 // Also, typedef-of-pointer-to-incomplete-struct is something that we assume
704 // is not an innter pointer type.
705 QualType OrigT = T;
706 while (const TypedefType *TD = dyn_cast<TypedefType>(T.getTypePtr()))
707 T = TD->getDecl()->getUnderlyingType();
708 if (OrigT == T || !T->isPointerType())
709 return true;
710 const PointerType* PT = T->getAs<PointerType>();
711 QualType UPointeeT = PT->getPointeeType().getUnqualifiedType();
712 if (UPointeeT->isRecordType()) {
713 const RecordType *RecordTy = UPointeeT->getAs<RecordType>();
714 if (!RecordTy->getDecl()->isCompleteDefinition())
715 return false;
716 }
Fariborz Jahaniand0fbf6c2013-08-30 23:52:08 +0000717 return true;
718}
719
Fariborz Jahanian2ba62a72013-09-18 17:22:25 +0000720static bool AttributesMatch(const Decl *Decl1, const Decl *Decl2) {
721 if (Decl1->hasAttrs() != Decl2->hasAttrs())
722 return false;
723
724 if (!Decl1->hasAttrs())
725 return true;
726
727 const AttrVec &Attrs1 = Decl1->getAttrs();
728 const AttrVec &Attrs2 = Decl2->getAttrs();
729 // This list is very small, so this need not be optimized.
730 for (unsigned i = 0, e = Attrs1.size(); i != e; i++) {
731 bool match = false;
732 for (unsigned j = 0, f = Attrs2.size(); j != f; j++) {
733 // Matching attribute kind only. We are not getting into
734 // details of the attributes. For all practical purposes
735 // this is sufficient.
736 if (Attrs1[i]->getKind() == Attrs2[j]->getKind()) {
737 match = true;
738 break;
739 }
740 }
741 if (!match)
742 return false;
743 }
744 return true;
745}
746
Fariborz Jahanian5d783df2013-09-27 22:55:54 +0000747static bool IsValidIdentifier(ASTContext &Ctx,
748 const char *Name) {
749 if (!isIdentifierHead(Name[0]))
750 return false;
751 std::string NameString = Name;
752 NameString[0] = toLowercase(NameString[0]);
753 IdentifierInfo *II = &Ctx.Idents.get(NameString);
754 return II->getTokenID() == tok::identifier;
755}
756
Fariborz Jahanian215f96c2013-09-06 23:45:20 +0000757bool ObjCMigrateASTConsumer::migrateProperty(ASTContext &Ctx,
Fariborz Jahanian92f72422013-09-17 19:00:30 +0000758 ObjCContainerDecl *D,
Fariborz Jahanian215f96c2013-09-06 23:45:20 +0000759 ObjCMethodDecl *Method) {
760 if (Method->isPropertyAccessor() || !Method->isInstanceMethod() ||
761 Method->param_size() != 0)
762 return false;
763 // Is this method candidate to be a getter?
764 QualType GRT = Method->getResultType();
765 if (GRT->isVoidType())
766 return false;
Fariborz Jahanian215f96c2013-09-06 23:45:20 +0000767
768 Selector GetterSelector = Method->getSelector();
Fariborz Jahanian7391a7b5a2013-09-25 00:17:07 +0000769 ObjCInstanceTypeFamily OIT_Family =
770 Selector::getInstTypeMethodFamily(GetterSelector);
771
772 if (OIT_Family != OIT_None)
773 return false;
774
Fariborz Jahanian215f96c2013-09-06 23:45:20 +0000775 IdentifierInfo *getterName = GetterSelector.getIdentifierInfoForSlot(0);
776 Selector SetterSelector =
777 SelectorTable::constructSetterSelector(PP.getIdentifierTable(),
778 PP.getSelectorTable(),
779 getterName);
Fariborz Jahanian92f72422013-09-17 19:00:30 +0000780 ObjCMethodDecl *SetterMethod = D->getInstanceMethod(SetterSelector);
Fariborz Jahanianca399602013-09-11 17:05:15 +0000781 unsigned LengthOfPrefix = 0;
Fariborz Jahanian215f96c2013-09-06 23:45:20 +0000782 if (!SetterMethod) {
783 // try a different naming convention for getter: isXxxxx
784 StringRef getterNameString = getterName->getName();
Fariborz Jahanianca399602013-09-11 17:05:15 +0000785 bool IsPrefix = getterNameString.startswith("is");
Fariborz Jahanian4c3d9c52013-09-17 19:38:55 +0000786 // Note that we don't want to change an isXXX method of retainable object
787 // type to property (readonly or otherwise).
788 if (IsPrefix && GRT->isObjCRetainableType())
789 return false;
790 if (IsPrefix || getterNameString.startswith("get")) {
Fariborz Jahanianca399602013-09-11 17:05:15 +0000791 LengthOfPrefix = (IsPrefix ? 2 : 3);
792 const char *CGetterName = getterNameString.data() + LengthOfPrefix;
793 // Make sure that first character after "is" or "get" prefix can
794 // start an identifier.
Fariborz Jahanian5d783df2013-09-27 22:55:54 +0000795 if (!IsValidIdentifier(Ctx, CGetterName))
Fariborz Jahanianca399602013-09-11 17:05:15 +0000796 return false;
Fariborz Jahanian215f96c2013-09-06 23:45:20 +0000797 if (CGetterName[0] && isUppercase(CGetterName[0])) {
798 getterName = &Ctx.Idents.get(CGetterName);
799 SetterSelector =
800 SelectorTable::constructSetterSelector(PP.getIdentifierTable(),
801 PP.getSelectorTable(),
802 getterName);
Fariborz Jahanian92f72422013-09-17 19:00:30 +0000803 SetterMethod = D->getInstanceMethod(SetterSelector);
Fariborz Jahanian215f96c2013-09-06 23:45:20 +0000804 }
805 }
806 }
Fariborz Jahanian4c3d9c52013-09-17 19:38:55 +0000807
Fariborz Jahanian215f96c2013-09-06 23:45:20 +0000808 if (SetterMethod) {
Fariborz Jahanianc1213862013-10-02 21:32:39 +0000809 if ((ASTMigrateActions & FrontendOptions::ObjCMT_ReadwriteProperty) == 0)
810 return false;
Fariborz Jahanian2ba62a72013-09-18 17:22:25 +0000811 if (SetterMethod->isDeprecated() ||
812 !AttributesMatch(Method, SetterMethod))
Fariborz Jahanianf6c65052013-09-17 22:41:25 +0000813 return false;
Fariborz Jahanian2ba62a72013-09-18 17:22:25 +0000814
Fariborz Jahanian215f96c2013-09-06 23:45:20 +0000815 // Is this a valid setter, matching the target getter?
816 QualType SRT = SetterMethod->getResultType();
817 if (!SRT->isVoidType())
818 return false;
819 const ParmVarDecl *argDecl = *SetterMethod->param_begin();
820 QualType ArgType = argDecl->getType();
Fariborz Jahanian2ba62a72013-09-18 17:22:25 +0000821 if (!Ctx.hasSameUnqualifiedType(ArgType, GRT))
Fariborz Jahanian215f96c2013-09-06 23:45:20 +0000822 return false;
823 edit::Commit commit(*Editor);
824 rewriteToObjCProperty(Method, SetterMethod, *NSAPIObj, commit,
Fariborz Jahanianca399602013-09-11 17:05:15 +0000825 LengthOfPrefix);
Fariborz Jahanian215f96c2013-09-06 23:45:20 +0000826 Editor->commit(commit);
827 return true;
828 }
Fariborz Jahanian182486c2013-10-02 17:08:12 +0000829 else if (ASTMigrateActions & FrontendOptions::ObjCMT_ReadonlyProperty) {
Fariborz Jahanian215f96c2013-09-06 23:45:20 +0000830 // Try a non-void method with no argument (and no setter or property of same name
831 // as a 'readonly' property.
832 edit::Commit commit(*Editor);
833 rewriteToObjCProperty(Method, 0 /*SetterMethod*/, *NSAPIObj, commit,
Fariborz Jahanianca399602013-09-11 17:05:15 +0000834 LengthOfPrefix);
Fariborz Jahanian215f96c2013-09-06 23:45:20 +0000835 Editor->commit(commit);
836 return true;
837 }
838 return false;
839}
840
Fariborz Jahaniand0fbf6c2013-08-30 23:52:08 +0000841void ObjCMigrateASTConsumer::migrateNsReturnsInnerPointer(ASTContext &Ctx,
842 ObjCMethodDecl *OM) {
Fariborz Jahanian10b74352013-09-24 20:20:52 +0000843 if (OM->isImplicit() ||
Fariborz Jahanian7c1a4452013-09-26 22:43:41 +0000844 !OM->isInstanceMethod() ||
Fariborz Jahanian10b74352013-09-24 20:20:52 +0000845 OM->hasAttr<ObjCReturnsInnerPointerAttr>())
Fariborz Jahaniand0fbf6c2013-08-30 23:52:08 +0000846 return;
847
848 QualType RT = OM->getResultType();
849 if (!TypeIsInnerPointer(RT) ||
850 !Ctx.Idents.get("NS_RETURNS_INNER_POINTER").hasMacroDefinition())
851 return;
852
853 edit::Commit commit(*Editor);
854 commit.insertBefore(OM->getLocEnd(), " NS_RETURNS_INNER_POINTER");
855 Editor->commit(commit);
856}
857
Fariborz Jahanian10b74352013-09-24 20:20:52 +0000858void ObjCMigrateASTConsumer::migratePropertyNsReturnsInnerPointer(ASTContext &Ctx,
859 ObjCPropertyDecl *P) {
860 QualType T = P->getType();
861
862 if (!TypeIsInnerPointer(T) ||
863 !Ctx.Idents.get("NS_RETURNS_INNER_POINTER").hasMacroDefinition())
864 return;
865 edit::Commit commit(*Editor);
866 commit.insertBefore(P->getLocEnd(), " NS_RETURNS_INNER_POINTER ");
867 Editor->commit(commit);
868}
869
Fariborz Jahaniand0fbf6c2013-08-30 23:52:08 +0000870void ObjCMigrateASTConsumer::migrateMethods(ASTContext &Ctx,
Fariborz Jahanian71221352013-07-23 22:42:28 +0000871 ObjCContainerDecl *CDecl) {
Fariborz Jahaniane47a14a2013-09-18 15:43:52 +0000872 if (CDecl->isDeprecated())
873 return;
874
Fariborz Jahanian71221352013-07-23 22:42:28 +0000875 // migrate methods which can have instancetype as their result type.
876 for (ObjCContainerDecl::method_iterator M = CDecl->meth_begin(),
877 MEnd = CDecl->meth_end();
878 M != MEnd; ++M) {
879 ObjCMethodDecl *Method = (*M);
Fariborz Jahanian75226d52013-09-17 21:56:04 +0000880 if (Method->isDeprecated())
881 continue;
Fariborz Jahanian71221352013-07-23 22:42:28 +0000882 migrateMethodInstanceType(Ctx, CDecl, Method);
883 }
884}
885
Fariborz Jahanianc4291852013-08-02 18:00:53 +0000886void ObjCMigrateASTConsumer::migrateFactoryMethod(ASTContext &Ctx,
887 ObjCContainerDecl *CDecl,
Fariborz Jahanian9275c682013-08-02 20:54:18 +0000888 ObjCMethodDecl *OM,
889 ObjCInstanceTypeFamily OIT_Family) {
Fariborz Jahanian3bfc35e2013-08-02 22:34:18 +0000890 if (OM->isInstanceMethod() ||
891 OM->getResultType() == Ctx.getObjCInstanceType() ||
892 !OM->getResultType()->isObjCIdType())
Fariborz Jahanianc4291852013-08-02 18:00:53 +0000893 return;
894
895 // Candidate factory methods are + (id) NaMeXXX : ... which belong to a class
896 // NSYYYNamE with matching names be at least 3 characters long.
897 ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(CDecl);
898 if (!IDecl) {
899 if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(CDecl))
900 IDecl = CatDecl->getClassInterface();
901 else if (ObjCImplDecl *ImpDecl = dyn_cast<ObjCImplDecl>(CDecl))
902 IDecl = ImpDecl->getClassInterface();
903 }
904 if (!IDecl)
905 return;
906
907 std::string StringClassName = IDecl->getName();
908 StringRef LoweredClassName(StringClassName);
909 std::string StringLoweredClassName = LoweredClassName.lower();
910 LoweredClassName = StringLoweredClassName;
911
912 IdentifierInfo *MethodIdName = OM->getSelector().getIdentifierInfoForSlot(0);
Fariborz Jahanianc13c1b02013-08-13 18:01:42 +0000913 // Handle method with no name at its first selector slot; e.g. + (id):(int)x.
914 if (!MethodIdName)
915 return;
916
Fariborz Jahanianc4291852013-08-02 18:00:53 +0000917 std::string MethodName = MethodIdName->getName();
Fariborz Jahanian9275c682013-08-02 20:54:18 +0000918 if (OIT_Family == OIT_Singleton) {
919 StringRef STRefMethodName(MethodName);
920 size_t len = 0;
921 if (STRefMethodName.startswith("standard"))
922 len = strlen("standard");
923 else if (STRefMethodName.startswith("shared"))
924 len = strlen("shared");
925 else if (STRefMethodName.startswith("default"))
926 len = strlen("default");
927 else
928 return;
929 MethodName = STRefMethodName.substr(len);
930 }
Fariborz Jahanianc4291852013-08-02 18:00:53 +0000931 std::string MethodNameSubStr = MethodName.substr(0, 3);
932 StringRef MethodNamePrefix(MethodNameSubStr);
933 std::string StringLoweredMethodNamePrefix = MethodNamePrefix.lower();
934 MethodNamePrefix = StringLoweredMethodNamePrefix;
935 size_t Ix = LoweredClassName.rfind(MethodNamePrefix);
936 if (Ix == StringRef::npos)
937 return;
938 std::string ClassNamePostfix = LoweredClassName.substr(Ix);
939 StringRef LoweredMethodName(MethodName);
940 std::string StringLoweredMethodName = LoweredMethodName.lower();
941 LoweredMethodName = StringLoweredMethodName;
942 if (!LoweredMethodName.startswith(ClassNamePostfix))
943 return;
944 ReplaceWithInstancetype(*this, OM);
945}
946
Fariborz Jahanian2ec4d7b2013-08-16 23:35:05 +0000947static bool IsVoidStarType(QualType Ty) {
948 if (!Ty->isPointerType())
949 return false;
950
951 while (const TypedefType *TD = dyn_cast<TypedefType>(Ty.getTypePtr()))
952 Ty = TD->getDecl()->getUnderlyingType();
953
954 // Is the type void*?
955 const PointerType* PT = Ty->getAs<PointerType>();
956 if (PT->getPointeeType().getUnqualifiedType()->isVoidType())
957 return true;
958 return IsVoidStarType(PT->getPointeeType());
959}
960
Fariborz Jahanian94279392013-08-20 18:54:39 +0000961/// AuditedType - This routine audits the type AT and returns false if it is one of known
962/// CF object types or of the "void *" variety. It returns true if we don't care about the type
963/// such as a non-pointer or pointers which have no ownership issues (such as "int *").
Fariborz Jahanian63ffce22013-08-27 22:42:30 +0000964static bool AuditedType (QualType AT) {
965 if (!AT->isAnyPointerType() && !AT->isBlockPointerType())
Fariborz Jahanian9ef4a262013-08-19 19:13:34 +0000966 return true;
Fariborz Jahanian9ef4a262013-08-19 19:13:34 +0000967 // FIXME. There isn't much we can say about CF pointer type; or is there?
Fariborz Jahanian94279392013-08-20 18:54:39 +0000968 if (ento::coreFoundation::isCFObjectRef(AT) ||
969 IsVoidStarType(AT) ||
970 // If an ObjC object is type, assuming that it is not a CF function and
971 // that it is an un-audited function.
Fariborz Jahanian2e9c19c2013-08-22 22:27:36 +0000972 AT->isObjCObjectPointerType() || AT->isObjCBuiltinType())
Fariborz Jahanian9ef4a262013-08-19 19:13:34 +0000973 return false;
Fariborz Jahanian94279392013-08-20 18:54:39 +0000974 // All other pointers are assumed audited as harmless.
Fariborz Jahanian9ef4a262013-08-19 19:13:34 +0000975 return true;
Fariborz Jahanian2ec4d7b2013-08-16 23:35:05 +0000976}
977
Fariborz Jahanian301b5212013-08-20 22:42:13 +0000978void ObjCMigrateASTConsumer::AnnotateImplicitBridging(ASTContext &Ctx) {
Fariborz Jahanian926fafb2013-08-22 18:35:27 +0000979 if (CFFunctionIBCandidates.empty())
980 return;
Fariborz Jahanian301b5212013-08-20 22:42:13 +0000981 if (!Ctx.Idents.get("CF_IMPLICIT_BRIDGING_ENABLED").hasMacroDefinition()) {
982 CFFunctionIBCandidates.clear();
Fariborz Jahanianb8343522013-08-20 23:35:26 +0000983 FileId = 0;
Fariborz Jahanian301b5212013-08-20 22:42:13 +0000984 return;
985 }
986 // Insert CF_IMPLICIT_BRIDGING_ENABLE/CF_IMPLICIT_BRIDGING_DISABLED
Fariborz Jahanian926fafb2013-08-22 18:35:27 +0000987 const Decl *FirstFD = CFFunctionIBCandidates[0];
988 const Decl *LastFD =
989 CFFunctionIBCandidates[CFFunctionIBCandidates.size()-1];
Fariborz Jahanian301b5212013-08-20 22:42:13 +0000990 const char *PragmaString = "\nCF_IMPLICIT_BRIDGING_ENABLED\n\n";
991 edit::Commit commit(*Editor);
992 commit.insertBefore(FirstFD->getLocStart(), PragmaString);
993 PragmaString = "\n\nCF_IMPLICIT_BRIDGING_DISABLED\n";
994 SourceLocation EndLoc = LastFD->getLocEnd();
995 // get location just past end of function location.
996 EndLoc = PP.getLocForEndOfToken(EndLoc);
Fariborz Jahanian926fafb2013-08-22 18:35:27 +0000997 if (isa<FunctionDecl>(LastFD)) {
998 // For Methods, EndLoc points to the ending semcolon. So,
999 // not of these extra work is needed.
1000 Token Tok;
1001 // get locaiton of token that comes after end of function.
1002 bool Failed = PP.getRawToken(EndLoc, Tok, /*IgnoreWhiteSpace=*/true);
1003 if (!Failed)
1004 EndLoc = Tok.getLocation();
1005 }
Fariborz Jahanian301b5212013-08-20 22:42:13 +00001006 commit.insertAfterToken(EndLoc, PragmaString);
1007 Editor->commit(commit);
Fariborz Jahanianb8343522013-08-20 23:35:26 +00001008 FileId = 0;
Fariborz Jahanian301b5212013-08-20 22:42:13 +00001009 CFFunctionIBCandidates.clear();
1010}
1011
Fariborz Jahanian4f64dd22013-08-22 21:40:15 +00001012void ObjCMigrateASTConsumer::migrateCFAnnotation(ASTContext &Ctx, const Decl *Decl) {
Fariborz Jahanian75226d52013-09-17 21:56:04 +00001013 if (Decl->isDeprecated())
1014 return;
1015
Fariborz Jahanian4f64dd22013-08-22 21:40:15 +00001016 if (Decl->hasAttr<CFAuditedTransferAttr>()) {
Fariborz Jahanianc6dfd3f2013-08-19 22:00:50 +00001017 assert(CFFunctionIBCandidates.empty() &&
Fariborz Jahanian4f64dd22013-08-22 21:40:15 +00001018 "Cannot have audited functions/methods inside user "
Fariborz Jahanianc6dfd3f2013-08-19 22:00:50 +00001019 "provided CF_IMPLICIT_BRIDGING_ENABLE");
1020 return;
1021 }
1022
Fariborz Jahanian2ec4d7b2013-08-16 23:35:05 +00001023 // Finction must be annotated first.
Fariborz Jahanian89f6d102013-09-04 00:10:06 +00001024 if (const FunctionDecl *FuncDecl = dyn_cast<FunctionDecl>(Decl)) {
1025 CF_BRIDGING_KIND AuditKind = migrateAddFunctionAnnotation(Ctx, FuncDecl);
1026 if (AuditKind == CF_BRIDGING_ENABLE) {
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001027 CFFunctionIBCandidates.push_back(Decl);
1028 if (!FileId)
1029 FileId = PP.getSourceManager().getFileID(Decl->getLocation()).getHashValue();
1030 }
Fariborz Jahanian89f6d102013-09-04 00:10:06 +00001031 else if (AuditKind == CF_BRIDGING_MAY_INCLUDE) {
1032 if (!CFFunctionIBCandidates.empty()) {
1033 CFFunctionIBCandidates.push_back(Decl);
1034 if (!FileId)
1035 FileId = PP.getSourceManager().getFileID(Decl->getLocation()).getHashValue();
1036 }
1037 }
1038 else
1039 AnnotateImplicitBridging(Ctx);
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001040 }
Fariborz Jahanian89f6d102013-09-04 00:10:06 +00001041 else {
1042 migrateAddMethodAnnotation(Ctx, cast<ObjCMethodDecl>(Decl));
Fariborz Jahanian301b5212013-08-20 22:42:13 +00001043 AnnotateImplicitBridging(Ctx);
Fariborz Jahanian89f6d102013-09-04 00:10:06 +00001044 }
Fariborz Jahanian2ec4d7b2013-08-16 23:35:05 +00001045}
1046
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001047void ObjCMigrateASTConsumer::AddCFAnnotations(ASTContext &Ctx,
1048 const CallEffects &CE,
Fariborz Jahanian7ca1d302013-08-27 23:56:54 +00001049 const FunctionDecl *FuncDecl,
1050 bool ResultAnnotated) {
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001051 // Annotate function.
Fariborz Jahanian7ca1d302013-08-27 23:56:54 +00001052 if (!ResultAnnotated) {
Fariborz Jahanian9ef4a262013-08-19 19:13:34 +00001053 RetEffect Ret = CE.getReturnValue();
1054 const char *AnnotationString = 0;
Fariborz Jahanian1a269272013-09-04 22:49:19 +00001055 if (Ret.getObjKind() == RetEffect::CF) {
1056 if (Ret.isOwned() &&
1057 Ctx.Idents.get("CF_RETURNS_RETAINED").hasMacroDefinition())
Fariborz Jahanian9ef4a262013-08-19 19:13:34 +00001058 AnnotationString = " CF_RETURNS_RETAINED";
Fariborz Jahanian1a269272013-09-04 22:49:19 +00001059 else if (Ret.notOwned() &&
1060 Ctx.Idents.get("CF_RETURNS_NOT_RETAINED").hasMacroDefinition())
Fariborz Jahanian9ef4a262013-08-19 19:13:34 +00001061 AnnotationString = " CF_RETURNS_NOT_RETAINED";
1062 }
Fariborz Jahanian1a269272013-09-04 22:49:19 +00001063 else if (Ret.getObjKind() == RetEffect::ObjC) {
1064 if (Ret.isOwned() &&
1065 Ctx.Idents.get("NS_RETURNS_RETAINED").hasMacroDefinition())
1066 AnnotationString = " NS_RETURNS_RETAINED";
Fariborz Jahanian1a269272013-09-04 22:49:19 +00001067 }
1068
Fariborz Jahanian9ef4a262013-08-19 19:13:34 +00001069 if (AnnotationString) {
1070 edit::Commit commit(*Editor);
1071 commit.insertAfterToken(FuncDecl->getLocEnd(), AnnotationString);
1072 Editor->commit(commit);
1073 }
Fariborz Jahanian84ac1de2013-08-15 21:44:38 +00001074 }
Fariborz Jahanian9ef4a262013-08-19 19:13:34 +00001075 llvm::ArrayRef<ArgEffect> AEArgs = CE.getArgs();
1076 unsigned i = 0;
1077 for (FunctionDecl::param_const_iterator pi = FuncDecl->param_begin(),
1078 pe = FuncDecl->param_end(); pi != pe; ++pi, ++i) {
Fariborz Jahanianb918d7a2013-08-21 19:37:47 +00001079 const ParmVarDecl *pd = *pi;
Fariborz Jahanian9ef4a262013-08-19 19:13:34 +00001080 ArgEffect AE = AEArgs[i];
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001081 if (AE == DecRef && !pd->getAttr<CFConsumedAttr>() &&
1082 Ctx.Idents.get("CF_CONSUMED").hasMacroDefinition()) {
1083 edit::Commit commit(*Editor);
1084 commit.insertBefore(pd->getLocation(), "CF_CONSUMED ");
1085 Editor->commit(commit);
Fariborz Jahanian94279392013-08-20 18:54:39 +00001086 }
Fariborz Jahanian1a269272013-09-04 22:49:19 +00001087 else if (AE == DecRefMsg && !pd->getAttr<NSConsumedAttr>() &&
1088 Ctx.Idents.get("NS_CONSUMED").hasMacroDefinition()) {
1089 edit::Commit commit(*Editor);
1090 commit.insertBefore(pd->getLocation(), "NS_CONSUMED ");
1091 Editor->commit(commit);
1092 }
Fariborz Jahanian84ac1de2013-08-15 21:44:38 +00001093 }
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001094}
1095
1096
1097ObjCMigrateASTConsumer::CF_BRIDGING_KIND
1098 ObjCMigrateASTConsumer::migrateAddFunctionAnnotation(
1099 ASTContext &Ctx,
1100 const FunctionDecl *FuncDecl) {
1101 if (FuncDecl->hasBody())
1102 return CF_BRIDGING_NONE;
1103
1104 CallEffects CE = CallEffects::getEffect(FuncDecl);
1105 bool FuncIsReturnAnnotated = (FuncDecl->getAttr<CFReturnsRetainedAttr>() ||
Fariborz Jahanian1a269272013-09-04 22:49:19 +00001106 FuncDecl->getAttr<CFReturnsNotRetainedAttr>() ||
1107 FuncDecl->getAttr<NSReturnsRetainedAttr>() ||
Fariborz Jahanianc24879e2013-09-05 23:04:33 +00001108 FuncDecl->getAttr<NSReturnsNotRetainedAttr>() ||
1109 FuncDecl->getAttr<NSReturnsAutoreleasedAttr>());
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001110
1111 // Trivial case of when funciton is annotated and has no argument.
1112 if (FuncIsReturnAnnotated && FuncDecl->getNumParams() == 0)
1113 return CF_BRIDGING_NONE;
1114
1115 bool ReturnCFAudited = false;
1116 if (!FuncIsReturnAnnotated) {
1117 RetEffect Ret = CE.getReturnValue();
1118 if (Ret.getObjKind() == RetEffect::CF &&
Fariborz Jahanian89f6d102013-09-04 00:10:06 +00001119 (Ret.isOwned() || Ret.notOwned()))
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001120 ReturnCFAudited = true;
1121 else if (!AuditedType(FuncDecl->getResultType()))
1122 return CF_BRIDGING_NONE;
1123 }
1124
1125 // At this point result type is audited for potential inclusion.
1126 // Now, how about argument types.
1127 llvm::ArrayRef<ArgEffect> AEArgs = CE.getArgs();
1128 unsigned i = 0;
1129 bool ArgCFAudited = false;
1130 for (FunctionDecl::param_const_iterator pi = FuncDecl->param_begin(),
1131 pe = FuncDecl->param_end(); pi != pe; ++pi, ++i) {
1132 const ParmVarDecl *pd = *pi;
1133 ArgEffect AE = AEArgs[i];
1134 if (AE == DecRef /*CFConsumed annotated*/ || AE == IncRef) {
1135 if (AE == DecRef && !pd->getAttr<CFConsumedAttr>())
1136 ArgCFAudited = true;
1137 else if (AE == IncRef)
1138 ArgCFAudited = true;
1139 }
1140 else {
1141 QualType AT = pd->getType();
1142 if (!AuditedType(AT)) {
Fariborz Jahanian7ca1d302013-08-27 23:56:54 +00001143 AddCFAnnotations(Ctx, CE, FuncDecl, FuncIsReturnAnnotated);
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001144 return CF_BRIDGING_NONE;
1145 }
1146 }
1147 }
1148 if (ReturnCFAudited || ArgCFAudited)
1149 return CF_BRIDGING_ENABLE;
1150
1151 return CF_BRIDGING_MAY_INCLUDE;
Fariborz Jahaniandfe6ed92013-08-12 23:17:13 +00001152}
1153
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001154void ObjCMigrateASTConsumer::migrateARCSafeAnnotation(ASTContext &Ctx,
1155 ObjCContainerDecl *CDecl) {
Fariborz Jahanian75226d52013-09-17 21:56:04 +00001156 if (!isa<ObjCInterfaceDecl>(CDecl) || CDecl->isDeprecated())
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001157 return;
1158
1159 // migrate methods which can have instancetype as their result type.
1160 for (ObjCContainerDecl::method_iterator M = CDecl->meth_begin(),
1161 MEnd = CDecl->meth_end();
1162 M != MEnd; ++M) {
1163 ObjCMethodDecl *Method = (*M);
Fariborz Jahanian4f64dd22013-08-22 21:40:15 +00001164 migrateCFAnnotation(Ctx, Method);
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001165 }
1166}
1167
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001168void ObjCMigrateASTConsumer::AddCFAnnotations(ASTContext &Ctx,
1169 const CallEffects &CE,
Fariborz Jahanian7ca1d302013-08-27 23:56:54 +00001170 const ObjCMethodDecl *MethodDecl,
1171 bool ResultAnnotated) {
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001172 // Annotate function.
Fariborz Jahanian7ca1d302013-08-27 23:56:54 +00001173 if (!ResultAnnotated) {
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001174 RetEffect Ret = CE.getReturnValue();
1175 const char *AnnotationString = 0;
Fariborz Jahanian1a269272013-09-04 22:49:19 +00001176 if (Ret.getObjKind() == RetEffect::CF) {
1177 if (Ret.isOwned() &&
1178 Ctx.Idents.get("CF_RETURNS_RETAINED").hasMacroDefinition())
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001179 AnnotationString = " CF_RETURNS_RETAINED";
Fariborz Jahanian1a269272013-09-04 22:49:19 +00001180 else if (Ret.notOwned() &&
1181 Ctx.Idents.get("CF_RETURNS_NOT_RETAINED").hasMacroDefinition())
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001182 AnnotationString = " CF_RETURNS_NOT_RETAINED";
1183 }
Fariborz Jahanian1a269272013-09-04 22:49:19 +00001184 else if (Ret.getObjKind() == RetEffect::ObjC) {
Fariborz Jahanianc24879e2013-09-05 23:04:33 +00001185 ObjCMethodFamily OMF = MethodDecl->getMethodFamily();
1186 switch (OMF) {
1187 case clang::OMF_alloc:
1188 case clang::OMF_new:
1189 case clang::OMF_copy:
1190 case clang::OMF_init:
1191 case clang::OMF_mutableCopy:
1192 break;
1193
1194 default:
1195 if (Ret.isOwned() &&
1196 Ctx.Idents.get("NS_RETURNS_RETAINED").hasMacroDefinition())
1197 AnnotationString = " NS_RETURNS_RETAINED";
Fariborz Jahanianc24879e2013-09-05 23:04:33 +00001198 break;
1199 }
Fariborz Jahanian1a269272013-09-04 22:49:19 +00001200 }
1201
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001202 if (AnnotationString) {
1203 edit::Commit commit(*Editor);
1204 commit.insertBefore(MethodDecl->getLocEnd(), AnnotationString);
1205 Editor->commit(commit);
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001206 }
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001207 }
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001208 llvm::ArrayRef<ArgEffect> AEArgs = CE.getArgs();
1209 unsigned i = 0;
1210 for (ObjCMethodDecl::param_const_iterator pi = MethodDecl->param_begin(),
1211 pe = MethodDecl->param_end(); pi != pe; ++pi, ++i) {
1212 const ParmVarDecl *pd = *pi;
1213 ArgEffect AE = AEArgs[i];
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001214 if (AE == DecRef && !pd->getAttr<CFConsumedAttr>() &&
1215 Ctx.Idents.get("CF_CONSUMED").hasMacroDefinition()) {
1216 edit::Commit commit(*Editor);
1217 commit.insertBefore(pd->getLocation(), "CF_CONSUMED ");
1218 Editor->commit(commit);
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001219 }
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001220 }
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001221}
1222
Fariborz Jahanian89f6d102013-09-04 00:10:06 +00001223void ObjCMigrateASTConsumer::migrateAddMethodAnnotation(
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001224 ASTContext &Ctx,
1225 const ObjCMethodDecl *MethodDecl) {
Fariborz Jahanian1a269272013-09-04 22:49:19 +00001226 if (MethodDecl->hasBody() || MethodDecl->isImplicit())
Fariborz Jahanian89f6d102013-09-04 00:10:06 +00001227 return;
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001228
1229 CallEffects CE = CallEffects::getEffect(MethodDecl);
1230 bool MethodIsReturnAnnotated = (MethodDecl->getAttr<CFReturnsRetainedAttr>() ||
Fariborz Jahanian1a269272013-09-04 22:49:19 +00001231 MethodDecl->getAttr<CFReturnsNotRetainedAttr>() ||
1232 MethodDecl->getAttr<NSReturnsRetainedAttr>() ||
Fariborz Jahanianc24879e2013-09-05 23:04:33 +00001233 MethodDecl->getAttr<NSReturnsNotRetainedAttr>() ||
1234 MethodDecl->getAttr<NSReturnsAutoreleasedAttr>());
1235
1236 if (CE.getReceiver() == DecRefMsg &&
1237 !MethodDecl->getAttr<NSConsumesSelfAttr>() &&
1238 MethodDecl->getMethodFamily() != OMF_init &&
1239 MethodDecl->getMethodFamily() != OMF_release &&
1240 Ctx.Idents.get("NS_CONSUMES_SELF").hasMacroDefinition()) {
1241 edit::Commit commit(*Editor);
1242 commit.insertBefore(MethodDecl->getLocEnd(), " NS_CONSUMES_SELF");
1243 Editor->commit(commit);
1244 }
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001245
1246 // Trivial case of when funciton is annotated and has no argument.
1247 if (MethodIsReturnAnnotated &&
1248 (MethodDecl->param_begin() == MethodDecl->param_end()))
Fariborz Jahanian89f6d102013-09-04 00:10:06 +00001249 return;
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001250
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001251 if (!MethodIsReturnAnnotated) {
1252 RetEffect Ret = CE.getReturnValue();
Fariborz Jahanian1a269272013-09-04 22:49:19 +00001253 if ((Ret.getObjKind() == RetEffect::CF ||
1254 Ret.getObjKind() == RetEffect::ObjC) &&
1255 (Ret.isOwned() || Ret.notOwned())) {
Fariborz Jahanian8b102302013-09-04 16:43:57 +00001256 AddCFAnnotations(Ctx, CE, MethodDecl, false);
1257 return;
1258 }
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001259 else if (!AuditedType(MethodDecl->getResultType()))
Fariborz Jahanian89f6d102013-09-04 00:10:06 +00001260 return;
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001261 }
1262
1263 // At this point result type is either annotated or audited.
1264 // Now, how about argument types.
1265 llvm::ArrayRef<ArgEffect> AEArgs = CE.getArgs();
1266 unsigned i = 0;
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001267 for (ObjCMethodDecl::param_const_iterator pi = MethodDecl->param_begin(),
1268 pe = MethodDecl->param_end(); pi != pe; ++pi, ++i) {
1269 const ParmVarDecl *pd = *pi;
1270 ArgEffect AE = AEArgs[i];
Fariborz Jahanian8b102302013-09-04 16:43:57 +00001271 if ((AE == DecRef && !pd->getAttr<CFConsumedAttr>()) || AE == IncRef ||
1272 !AuditedType(pd->getType())) {
1273 AddCFAnnotations(Ctx, CE, MethodDecl, MethodIsReturnAnnotated);
1274 return;
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001275 }
1276 }
Fariborz Jahanian89f6d102013-09-04 00:10:06 +00001277 return;
Fariborz Jahaniandfe6ed92013-08-12 23:17:13 +00001278}
1279
Ted Kremenekf7639e12012-03-06 20:06:33 +00001280namespace {
1281
1282class RewritesReceiver : public edit::EditsReceiver {
1283 Rewriter &Rewrite;
1284
1285public:
1286 RewritesReceiver(Rewriter &Rewrite) : Rewrite(Rewrite) { }
1287
1288 virtual void insert(SourceLocation loc, StringRef text) {
1289 Rewrite.InsertText(loc, text);
1290 }
1291 virtual void replace(CharSourceRange range, StringRef text) {
1292 Rewrite.ReplaceText(range.getBegin(), Rewrite.getRangeSize(range), text);
1293 }
1294};
1295
1296}
1297
Fariborz Jahanian8f5225b2013-10-01 21:16:29 +00001298static bool
1299IsReallyASystemHeader(ASTContext &Ctx, const FileEntry *file, FileID FID) {
1300 bool Invalid = false;
1301 const SrcMgr::SLocEntry &SEntry =
1302 Ctx.getSourceManager().getSLocEntry(FID, &Invalid);
1303 if (!Invalid && SEntry.isFile()) {
1304 const SrcMgr::FileInfo &FI = SEntry.getFile();
1305 if (!FI.hasLineDirectives()) {
1306 if (FI.getFileCharacteristic() == SrcMgr::C_ExternCSystem)
1307 return true;
1308 if (FI.getFileCharacteristic() == SrcMgr::C_System) {
1309 // This file is in a system header directory. Continue with commiting change
1310 // only if it is a user specified system directory because user put a
1311 // .system_framework file in the framework directory.
1312 StringRef Directory(file->getDir()->getName());
1313 size_t Ix = Directory.rfind(".framework");
1314 if (Ix == StringRef::npos)
1315 return true;
1316 std::string PatchToSystemFramework = Directory.slice(0, Ix+sizeof(".framework"));
1317 PatchToSystemFramework += ".system_framework";
1318 if (!llvm::sys::fs::exists(PatchToSystemFramework.data()))
1319 return true;
1320 }
1321 }
1322 }
1323 return false;
1324}
1325
Ted Kremenekf7639e12012-03-06 20:06:33 +00001326void ObjCMigrateASTConsumer::HandleTranslationUnit(ASTContext &Ctx) {
Fariborz Jahaniana7437f02013-07-03 23:05:00 +00001327
1328 TranslationUnitDecl *TU = Ctx.getTranslationUnitDecl();
Fariborz Jahanianc1213862013-10-02 21:32:39 +00001329 if (ASTMigrateActions & FrontendOptions::ObjCMT_MigrateDecls) {
Fariborz Jahaniand83ef842013-07-09 16:59:14 +00001330 for (DeclContext::decl_iterator D = TU->decls_begin(), DEnd = TU->decls_end();
1331 D != DEnd; ++D) {
Fariborz Jahanianb8343522013-08-20 23:35:26 +00001332 if (unsigned FID =
1333 PP.getSourceManager().getFileID((*D)->getLocation()).getHashValue())
Fariborz Jahanian75226d52013-09-17 21:56:04 +00001334 if (FileId && FileId != FID)
Fariborz Jahanianb8343522013-08-20 23:35:26 +00001335 AnnotateImplicitBridging(Ctx);
Fariborz Jahanianb8343522013-08-20 23:35:26 +00001336
Fariborz Jahaniand83ef842013-07-09 16:59:14 +00001337 if (ObjCInterfaceDecl *CDecl = dyn_cast<ObjCInterfaceDecl>(*D))
1338 migrateObjCInterfaceDecl(Ctx, CDecl);
Fariborz Jahanian92f72422013-09-17 19:00:30 +00001339 if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(*D))
1340 migrateObjCInterfaceDecl(Ctx, CatDecl);
Fariborz Jahanian1be01532013-07-12 22:32:19 +00001341 else if (ObjCProtocolDecl *PDecl = dyn_cast<ObjCProtocolDecl>(*D))
1342 ObjCProtocolDecls.insert(PDecl);
1343 else if (const ObjCImplementationDecl *ImpDecl =
1344 dyn_cast<ObjCImplementationDecl>(*D))
1345 migrateProtocolConformance(Ctx, ImpDecl);
Fariborz Jahanian92463272013-07-18 20:11:45 +00001346 else if (const EnumDecl *ED = dyn_cast<EnumDecl>(*D)) {
1347 DeclContext::decl_iterator N = D;
1348 ++N;
Fariborz Jahanian008ef722013-07-19 17:44:32 +00001349 if (N != DEnd)
1350 if (const TypedefDecl *TD = dyn_cast<TypedefDecl>(*N))
1351 migrateNSEnumDecl(Ctx, ED, TD);
Fariborz Jahanian92463272013-07-18 20:11:45 +00001352 }
Fariborz Jahanianc13c1b02013-08-13 18:01:42 +00001353 else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(*D))
Fariborz Jahanian4f64dd22013-08-22 21:40:15 +00001354 migrateCFAnnotation(Ctx, FD);
Fariborz Jahanianc13c1b02013-08-13 18:01:42 +00001355
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001356 if (ObjCContainerDecl *CDecl = dyn_cast<ObjCContainerDecl>(*D)) {
1357 // migrate methods which can have instancetype as their result type.
Fariborz Jahaniand0fbf6c2013-08-30 23:52:08 +00001358 migrateMethods(Ctx, CDecl);
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001359 // annotate methods with CF annotations.
1360 migrateARCSafeAnnotation(Ctx, CDecl);
1361 }
Fariborz Jahaniand83ef842013-07-09 16:59:14 +00001362 }
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001363 AnnotateImplicitBridging(Ctx);
Fariborz Jahanian301b5212013-08-20 22:42:13 +00001364 }
Fariborz Jahaniana7437f02013-07-03 23:05:00 +00001365
David Blaikiebbafb8a2012-03-11 07:00:24 +00001366 Rewriter rewriter(Ctx.getSourceManager(), Ctx.getLangOpts());
Ted Kremenekf7639e12012-03-06 20:06:33 +00001367 RewritesReceiver Rec(rewriter);
1368 Editor->applyRewrites(Rec);
1369
1370 for (Rewriter::buffer_iterator
1371 I = rewriter.buffer_begin(), E = rewriter.buffer_end(); I != E; ++I) {
1372 FileID FID = I->first;
1373 RewriteBuffer &buf = I->second;
1374 const FileEntry *file = Ctx.getSourceManager().getFileEntryForID(FID);
1375 assert(file);
Fariborz Jahanian8f5225b2013-10-01 21:16:29 +00001376 if (IsReallyASystemHeader(Ctx, file, FID))
1377 continue;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001378 SmallString<512> newText;
Ted Kremenekf7639e12012-03-06 20:06:33 +00001379 llvm::raw_svector_ostream vecOS(newText);
1380 buf.write(vecOS);
1381 vecOS.flush();
1382 llvm::MemoryBuffer *memBuf = llvm::MemoryBuffer::getMemBufferCopy(
1383 StringRef(newText.data(), newText.size()), file->getName());
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001384 SmallString<64> filePath(file->getName());
Ted Kremenekf7639e12012-03-06 20:06:33 +00001385 FileMgr.FixupRelativePath(filePath);
1386 Remapper.remap(filePath.str(), memBuf);
1387 }
1388
1389 if (IsOutputFile) {
1390 Remapper.flushToFile(MigrateDir, Ctx.getDiagnostics());
1391 } else {
1392 Remapper.flushToDisk(MigrateDir, Ctx.getDiagnostics());
1393 }
1394}
1395
1396bool MigrateSourceAction::BeginInvocation(CompilerInstance &CI) {
Argyrios Kyrtzidisb4822602012-05-24 16:48:23 +00001397 CI.getDiagnostics().setIgnoreAllWarnings(true);
Ted Kremenekf7639e12012-03-06 20:06:33 +00001398 return true;
1399}
1400
1401ASTConsumer *MigrateSourceAction::CreateASTConsumer(CompilerInstance &CI,
1402 StringRef InFile) {
Argyrios Kyrtzidisf3d587e2012-12-04 07:27:05 +00001403 PPConditionalDirectiveRecord *
1404 PPRec = new PPConditionalDirectiveRecord(CI.getSourceManager());
1405 CI.getPreprocessor().addPPCallbacks(PPRec);
Ted Kremenekf7639e12012-03-06 20:06:33 +00001406 return new ObjCMigrateASTConsumer(CI.getFrontendOpts().OutputFile,
Fariborz Jahanianc1213862013-10-02 21:32:39 +00001407 FrontendOptions::ObjCMT_MigrateAll,
Ted Kremenekf7639e12012-03-06 20:06:33 +00001408 Remapper,
1409 CI.getFileManager(),
Argyrios Kyrtzidisf3d587e2012-12-04 07:27:05 +00001410 PPRec,
Fariborz Jahaniana7437f02013-07-03 23:05:00 +00001411 CI.getPreprocessor(),
Ted Kremenekf7639e12012-03-06 20:06:33 +00001412 /*isOutputFile=*/true);
1413}