blob: 5d36fa7b8ab20bb98f1309ea2c317702752529a6 [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 Jahanianc4291852013-08-02 18:00:53 +000056 void migrateFactoryMethod(ASTContext &Ctx, ObjCContainerDecl *CDecl,
Fariborz Jahanian9275c682013-08-02 20:54:18 +000057 ObjCMethodDecl *OM,
58 ObjCInstanceTypeFamily OIT_Family = OIT_None);
Fariborz Jahaniandfe6ed92013-08-12 23:17:13 +000059
Fariborz Jahanian4f64dd22013-08-22 21:40:15 +000060 void migrateCFAnnotation(ASTContext &Ctx, const Decl *Decl);
Fariborz Jahanian63ffce22013-08-27 22:42:30 +000061 void AddCFAnnotations(ASTContext &Ctx, const CallEffects &CE,
Fariborz Jahanian7ca1d302013-08-27 23:56:54 +000062 const FunctionDecl *FuncDecl, bool ResultAnnotated);
Fariborz Jahanian63ffce22013-08-27 22:42:30 +000063 void AddCFAnnotations(ASTContext &Ctx, const CallEffects &CE,
Fariborz Jahanian7ca1d302013-08-27 23:56:54 +000064 const ObjCMethodDecl *MethodDecl, bool ResultAnnotated);
Fariborz Jahanian2ec4d7b2013-08-16 23:35:05 +000065
Fariborz Jahanian301b5212013-08-20 22:42:13 +000066 void AnnotateImplicitBridging(ASTContext &Ctx);
67
Fariborz Jahanian63ffce22013-08-27 22:42:30 +000068 CF_BRIDGING_KIND migrateAddFunctionAnnotation(ASTContext &Ctx,
69 const FunctionDecl *FuncDecl);
Fariborz Jahaniandfe6ed92013-08-12 23:17:13 +000070
Fariborz Jahanian926fafb2013-08-22 18:35:27 +000071 void migrateARCSafeAnnotation(ASTContext &Ctx, ObjCContainerDecl *CDecl);
72
Fariborz Jahanian89f6d102013-09-04 00:10:06 +000073 void migrateAddMethodAnnotation(ASTContext &Ctx,
74 const ObjCMethodDecl *MethodDecl);
Ted Kremenekf7639e12012-03-06 20:06:33 +000075public:
76 std::string MigrateDir;
77 bool MigrateLiterals;
78 bool MigrateSubscripting;
Fariborz Jahaniand83ef842013-07-09 16:59:14 +000079 bool MigrateProperty;
Fariborz Jahanian55d6e6c2013-08-28 23:22:46 +000080 bool MigrateReadonlyProperty;
Fariborz Jahanianb8343522013-08-20 23:35:26 +000081 unsigned FileId;
Dmitri Gribenkof8579502013-01-12 19:30:44 +000082 OwningPtr<NSAPI> NSAPIObj;
83 OwningPtr<edit::EditedSource> Editor;
Ted Kremenekf7639e12012-03-06 20:06:33 +000084 FileRemapper &Remapper;
85 FileManager &FileMgr;
Argyrios Kyrtzidisf3d587e2012-12-04 07:27:05 +000086 const PPConditionalDirectiveRecord *PPRec;
Fariborz Jahaniana7437f02013-07-03 23:05:00 +000087 Preprocessor &PP;
Ted Kremenekf7639e12012-03-06 20:06:33 +000088 bool IsOutputFile;
Fariborz Jahanian1be01532013-07-12 22:32:19 +000089 llvm::SmallPtrSet<ObjCProtocolDecl *, 32> ObjCProtocolDecls;
Fariborz Jahanian926fafb2013-08-22 18:35:27 +000090 llvm::SmallVector<const Decl *, 8> CFFunctionIBCandidates;
Fariborz Jahanian1be01532013-07-12 22:32:19 +000091
Ted Kremenekf7639e12012-03-06 20:06:33 +000092 ObjCMigrateASTConsumer(StringRef migrateDir,
93 bool migrateLiterals,
94 bool migrateSubscripting,
Fariborz Jahaniand83ef842013-07-09 16:59:14 +000095 bool migrateProperty,
Fariborz Jahanian55d6e6c2013-08-28 23:22:46 +000096 bool migrateReadonlyProperty,
Ted Kremenekf7639e12012-03-06 20:06:33 +000097 FileRemapper &remapper,
98 FileManager &fileMgr,
Argyrios Kyrtzidisf3d587e2012-12-04 07:27:05 +000099 const PPConditionalDirectiveRecord *PPRec,
Fariborz Jahaniana7437f02013-07-03 23:05:00 +0000100 Preprocessor &PP,
Ted Kremenekf7639e12012-03-06 20:06:33 +0000101 bool isOutputFile = false)
102 : MigrateDir(migrateDir),
103 MigrateLiterals(migrateLiterals),
104 MigrateSubscripting(migrateSubscripting),
Fariborz Jahanian55d6e6c2013-08-28 23:22:46 +0000105 MigrateProperty(migrateProperty),
106 MigrateReadonlyProperty(migrateReadonlyProperty),
107 FileId(0), Remapper(remapper), FileMgr(fileMgr), PPRec(PPRec), PP(PP),
Ted Kremenekf7639e12012-03-06 20:06:33 +0000108 IsOutputFile(isOutputFile) { }
109
110protected:
111 virtual void Initialize(ASTContext &Context) {
112 NSAPIObj.reset(new NSAPI(Context));
113 Editor.reset(new edit::EditedSource(Context.getSourceManager(),
David Blaikiebbafb8a2012-03-11 07:00:24 +0000114 Context.getLangOpts(),
Ted Kremenekf7639e12012-03-06 20:06:33 +0000115 PPRec));
116 }
117
118 virtual bool HandleTopLevelDecl(DeclGroupRef DG) {
119 for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I)
120 migrateDecl(*I);
121 return true;
122 }
123 virtual void HandleInterestingDecl(DeclGroupRef DG) {
124 // Ignore decls from the PCH.
125 }
126 virtual void HandleTopLevelDeclInObjCContainer(DeclGroupRef DG) {
127 ObjCMigrateASTConsumer::HandleTopLevelDecl(DG);
128 }
129
130 virtual void HandleTranslationUnit(ASTContext &Ctx);
131};
132
133}
134
135ObjCMigrateAction::ObjCMigrateAction(FrontendAction *WrappedAction,
136 StringRef migrateDir,
137 bool migrateLiterals,
Fariborz Jahaniand83ef842013-07-09 16:59:14 +0000138 bool migrateSubscripting,
Fariborz Jahanian55d6e6c2013-08-28 23:22:46 +0000139 bool migrateProperty,
140 bool migrateReadonlyProperty)
Ted Kremenekf7639e12012-03-06 20:06:33 +0000141 : WrapperFrontendAction(WrappedAction), MigrateDir(migrateDir),
142 MigrateLiterals(migrateLiterals), MigrateSubscripting(migrateSubscripting),
Fariborz Jahaniand83ef842013-07-09 16:59:14 +0000143 MigrateProperty(migrateProperty),
Fariborz Jahanian55d6e6c2013-08-28 23:22:46 +0000144 MigrateReadonlyProperty(migrateReadonlyProperty),
Ted Kremenekf7639e12012-03-06 20:06:33 +0000145 CompInst(0) {
146 if (MigrateDir.empty())
147 MigrateDir = "."; // user current directory if none is given.
148}
149
150ASTConsumer *ObjCMigrateAction::CreateASTConsumer(CompilerInstance &CI,
151 StringRef InFile) {
Argyrios Kyrtzidisf3d587e2012-12-04 07:27:05 +0000152 PPConditionalDirectiveRecord *
153 PPRec = new PPConditionalDirectiveRecord(CompInst->getSourceManager());
154 CompInst->getPreprocessor().addPPCallbacks(PPRec);
Ted Kremenekf7639e12012-03-06 20:06:33 +0000155 ASTConsumer *
156 WrappedConsumer = WrapperFrontendAction::CreateASTConsumer(CI, InFile);
157 ASTConsumer *MTConsumer = new ObjCMigrateASTConsumer(MigrateDir,
158 MigrateLiterals,
159 MigrateSubscripting,
Fariborz Jahaniand83ef842013-07-09 16:59:14 +0000160 MigrateProperty,
Fariborz Jahanian55d6e6c2013-08-28 23:22:46 +0000161 MigrateReadonlyProperty,
Ted Kremenekf7639e12012-03-06 20:06:33 +0000162 Remapper,
163 CompInst->getFileManager(),
Fariborz Jahaniana7437f02013-07-03 23:05:00 +0000164 PPRec,
165 CompInst->getPreprocessor());
Ted Kremenekf7639e12012-03-06 20:06:33 +0000166 ASTConsumer *Consumers[] = { MTConsumer, WrappedConsumer };
167 return new MultiplexConsumer(Consumers);
168}
169
170bool ObjCMigrateAction::BeginInvocation(CompilerInstance &CI) {
171 Remapper.initFromDisk(MigrateDir, CI.getDiagnostics(),
172 /*ignoreIfFilesChanges=*/true);
173 CompInst = &CI;
174 CI.getDiagnostics().setIgnoreAllWarnings(true);
Ted Kremenekf7639e12012-03-06 20:06:33 +0000175 return true;
176}
177
178namespace {
179class ObjCMigrator : public RecursiveASTVisitor<ObjCMigrator> {
180 ObjCMigrateASTConsumer &Consumer;
Argyrios Kyrtzidis6b4f3412013-01-16 23:54:48 +0000181 ParentMap &PMap;
Ted Kremenekf7639e12012-03-06 20:06:33 +0000182
183public:
Argyrios Kyrtzidis6b4f3412013-01-16 23:54:48 +0000184 ObjCMigrator(ObjCMigrateASTConsumer &consumer, ParentMap &PMap)
185 : Consumer(consumer), PMap(PMap) { }
Ted Kremenekf7639e12012-03-06 20:06:33 +0000186
187 bool shouldVisitTemplateInstantiations() const { return false; }
188 bool shouldWalkTypesOfTypeLocs() const { return false; }
189
190 bool VisitObjCMessageExpr(ObjCMessageExpr *E) {
191 if (Consumer.MigrateLiterals) {
192 edit::Commit commit(*Consumer.Editor);
Argyrios Kyrtzidis6b4f3412013-01-16 23:54:48 +0000193 edit::rewriteToObjCLiteralSyntax(E, *Consumer.NSAPIObj, commit, &PMap);
Ted Kremenekf7639e12012-03-06 20:06:33 +0000194 Consumer.Editor->commit(commit);
195 }
196
197 if (Consumer.MigrateSubscripting) {
198 edit::Commit commit(*Consumer.Editor);
199 edit::rewriteToObjCSubscriptSyntax(E, *Consumer.NSAPIObj, commit);
200 Consumer.Editor->commit(commit);
201 }
202
203 return true;
204 }
205
206 bool TraverseObjCMessageExpr(ObjCMessageExpr *E) {
207 // Do depth first; we want to rewrite the subexpressions first so that if
208 // we have to move expressions we will move them already rewritten.
209 for (Stmt::child_range range = E->children(); range; ++range)
210 if (!TraverseStmt(*range))
211 return false;
212
213 return WalkUpFromObjCMessageExpr(E);
214 }
215};
Argyrios Kyrtzidis6b4f3412013-01-16 23:54:48 +0000216
217class BodyMigrator : public RecursiveASTVisitor<BodyMigrator> {
218 ObjCMigrateASTConsumer &Consumer;
219 OwningPtr<ParentMap> PMap;
220
221public:
222 BodyMigrator(ObjCMigrateASTConsumer &consumer) : Consumer(consumer) { }
223
224 bool shouldVisitTemplateInstantiations() const { return false; }
225 bool shouldWalkTypesOfTypeLocs() const { return false; }
226
227 bool TraverseStmt(Stmt *S) {
228 PMap.reset(new ParentMap(S));
229 ObjCMigrator(Consumer, *PMap).TraverseStmt(S);
230 return true;
231 }
232};
Ted Kremenekf7639e12012-03-06 20:06:33 +0000233}
234
235void ObjCMigrateASTConsumer::migrateDecl(Decl *D) {
236 if (!D)
237 return;
238 if (isa<ObjCMethodDecl>(D))
239 return; // Wait for the ObjC container declaration.
240
Argyrios Kyrtzidis6b4f3412013-01-16 23:54:48 +0000241 BodyMigrator(*this).TraverseDecl(D);
Ted Kremenekf7639e12012-03-06 20:06:33 +0000242}
243
Fariborz Jahanian447b15e2013-08-21 18:49:03 +0000244static void append_attr(std::string &PropertyString, const char *attr) {
245 PropertyString += ", ";
Fariborz Jahaniancf2ff9b2013-08-08 20:51:58 +0000246 PropertyString += attr;
Fariborz Jahaniancf2ff9b2013-08-08 20:51:58 +0000247}
248
Fariborz Jahanian85e988b2013-07-18 22:17:33 +0000249static bool rewriteToObjCProperty(const ObjCMethodDecl *Getter,
250 const ObjCMethodDecl *Setter,
Fariborz Jahaniancf2ff9b2013-08-08 20:51:58 +0000251 const NSAPI &NS, edit::Commit &commit,
Fariborz Jahanianca399602013-09-11 17:05:15 +0000252 unsigned LengthOfPrefix) {
Fariborz Jahanian85e988b2013-07-18 22:17:33 +0000253 ASTContext &Context = NS.getASTContext();
Fariborz Jahanian447b15e2013-08-21 18:49:03 +0000254 std::string PropertyString = "@property(nonatomic";
Fariborz Jahaniancf387c62013-08-06 18:06:23 +0000255 std::string PropertyNameString = Getter->getNameAsString();
256 StringRef PropertyName(PropertyNameString);
Fariborz Jahanianca399602013-09-11 17:05:15 +0000257 if (LengthOfPrefix > 0) {
Fariborz Jahanian447b15e2013-08-21 18:49:03 +0000258 PropertyString += ", getter=";
Fariborz Jahaniancf2ff9b2013-08-08 20:51:58 +0000259 PropertyString += PropertyNameString;
260 }
Fariborz Jahanian55d6e6c2013-08-28 23:22:46 +0000261 // Property with no setter may be suggested as a 'readonly' property.
262 if (!Setter)
263 append_attr(PropertyString, "readonly");
264
Fariborz Jahaniancf387c62013-08-06 18:06:23 +0000265 // Short circuit properties that contain the name "delegate" or "dataSource",
266 // or have exact name "target" to have unsafe_unretained attribute.
267 if (PropertyName.equals("target") ||
268 (PropertyName.find("delegate") != StringRef::npos) ||
269 (PropertyName.find("dataSource") != StringRef::npos))
Fariborz Jahanian447b15e2013-08-21 18:49:03 +0000270 append_attr(PropertyString, "unsafe_unretained");
Fariborz Jahanian55d6e6c2013-08-28 23:22:46 +0000271 else if (Setter) {
Fariborz Jahaniancf387c62013-08-06 18:06:23 +0000272 const ParmVarDecl *argDecl = *Setter->param_begin();
273 QualType ArgType = Context.getCanonicalType(argDecl->getType());
274 Qualifiers::ObjCLifetime propertyLifetime = ArgType.getObjCLifetime();
275 bool RetainableObject = ArgType->isObjCRetainableType();
276 if (RetainableObject && propertyLifetime == Qualifiers::OCL_Strong) {
277 if (const ObjCObjectPointerType *ObjPtrTy =
278 ArgType->getAs<ObjCObjectPointerType>()) {
279 ObjCInterfaceDecl *IDecl = ObjPtrTy->getObjectType()->getInterface();
280 if (IDecl &&
281 IDecl->lookupNestedProtocol(&Context.Idents.get("NSCopying")))
Fariborz Jahanian447b15e2013-08-21 18:49:03 +0000282 append_attr(PropertyString, "copy");
Fariborz Jahaniancf387c62013-08-06 18:06:23 +0000283 else
Fariborz Jahanian447b15e2013-08-21 18:49:03 +0000284 append_attr(PropertyString, "retain");
285 }
Fariborz Jahaniancf387c62013-08-06 18:06:23 +0000286 } else if (propertyLifetime == Qualifiers::OCL_Weak)
287 // TODO. More precise determination of 'weak' attribute requires
288 // looking into setter's implementation for backing weak ivar.
Fariborz Jahanian447b15e2013-08-21 18:49:03 +0000289 append_attr(PropertyString, "weak");
Fariborz Jahaniancf387c62013-08-06 18:06:23 +0000290 else if (RetainableObject)
Fariborz Jahanian447b15e2013-08-21 18:49:03 +0000291 append_attr(PropertyString, "retain");
Fariborz Jahaniancf387c62013-08-06 18:06:23 +0000292 }
Fariborz Jahanian447b15e2013-08-21 18:49:03 +0000293 PropertyString += ')';
Fariborz Jahanian85e988b2013-07-18 22:17:33 +0000294
Fariborz Jahaniancf2ff9b2013-08-08 20:51:58 +0000295 QualType RT = Getter->getResultType();
296 if (!isa<TypedefType>(RT)) {
297 // strip off any ARC lifetime qualifier.
298 QualType CanResultTy = Context.getCanonicalType(RT);
299 if (CanResultTy.getQualifiers().hasObjCLifetime()) {
300 Qualifiers Qs = CanResultTy.getQualifiers();
301 Qs.removeObjCLifetime();
302 RT = Context.getQualifiedType(CanResultTy.getUnqualifiedType(), Qs);
303 }
Fariborz Jahanian85e988b2013-07-18 22:17:33 +0000304 }
305 PropertyString += " ";
Fariborz Jahaniancf2ff9b2013-08-08 20:51:58 +0000306 PropertyString += RT.getAsString(Context.getPrintingPolicy());
Fariborz Jahanian85e988b2013-07-18 22:17:33 +0000307 PropertyString += " ";
Fariborz Jahanianca399602013-09-11 17:05:15 +0000308 if (LengthOfPrefix > 0) {
Fariborz Jahaniancf2ff9b2013-08-08 20:51:58 +0000309 // property name must strip off "is" and lower case the first character
310 // after that; e.g. isContinuous will become continuous.
311 StringRef PropertyNameStringRef(PropertyNameString);
Fariborz Jahanianca399602013-09-11 17:05:15 +0000312 PropertyNameStringRef = PropertyNameStringRef.drop_front(LengthOfPrefix);
Fariborz Jahaniancf2ff9b2013-08-08 20:51:58 +0000313 PropertyNameString = PropertyNameStringRef;
314 std::string NewPropertyNameString = PropertyNameString;
Fariborz Jahanian34fea362013-09-11 18:27:16 +0000315 bool NoLowering = (isUppercase(NewPropertyNameString[0]) &&
316 NewPropertyNameString.size() > 1 &&
317 isUppercase(NewPropertyNameString[1]));
318 if (!NoLowering)
319 NewPropertyNameString[0] = toLowercase(NewPropertyNameString[0]);
Fariborz Jahaniancf2ff9b2013-08-08 20:51:58 +0000320 PropertyString += NewPropertyNameString;
321 }
322 else
323 PropertyString += PropertyNameString;
Fariborz Jahanian215f96c2013-09-06 23:45:20 +0000324 SourceLocation StartGetterSelectorLoc = Getter->getSelectorStartLoc();
325 Selector GetterSelector = Getter->getSelector();
326
327 SourceLocation EndGetterSelectorLoc =
328 StartGetterSelectorLoc.getLocWithOffset(GetterSelector.getNameForSlot(0).size());
Fariborz Jahanian85e988b2013-07-18 22:17:33 +0000329 commit.replace(CharSourceRange::getCharRange(Getter->getLocStart(),
Fariborz Jahanian215f96c2013-09-06 23:45:20 +0000330 EndGetterSelectorLoc),
Fariborz Jahanian85e988b2013-07-18 22:17:33 +0000331 PropertyString);
Fariborz Jahanian55d6e6c2013-08-28 23:22:46 +0000332 if (Setter) {
333 SourceLocation EndLoc = Setter->getDeclaratorEndLoc();
334 // Get location past ';'
335 EndLoc = EndLoc.getLocWithOffset(1);
336 commit.remove(CharSourceRange::getCharRange(Setter->getLocStart(), EndLoc));
337 }
Fariborz Jahanian85e988b2013-07-18 22:17:33 +0000338 return true;
339}
340
Fariborz Jahaniana7437f02013-07-03 23:05:00 +0000341void ObjCMigrateASTConsumer::migrateObjCInterfaceDecl(ASTContext &Ctx,
Fariborz Jahanian92f72422013-09-17 19:00:30 +0000342 ObjCContainerDecl *D) {
Fariborz Jahanian75226d52013-09-17 21:56:04 +0000343 if (D->isDeprecated())
344 return;
345
Fariborz Jahaniana7437f02013-07-03 23:05:00 +0000346 for (ObjCContainerDecl::method_iterator M = D->meth_begin(), MEnd = D->meth_end();
347 M != MEnd; ++M) {
348 ObjCMethodDecl *Method = (*M);
Fariborz Jahanian75226d52013-09-17 21:56:04 +0000349 if (Method->isDeprecated())
350 continue;
Fariborz Jahanian215f96c2013-09-06 23:45:20 +0000351 if (!migrateProperty(Ctx, D, Method))
352 migrateNsReturnsInnerPointer(Ctx, Method);
Fariborz Jahaniana7437f02013-07-03 23:05:00 +0000353 }
354}
355
Fariborz Jahanian9eabf452013-07-13 00:04:20 +0000356static bool
Fariborz Jahanian9a3512b2013-07-13 17:16:41 +0000357ClassImplementsAllMethodsAndProperties(ASTContext &Ctx,
Fariborz Jahanian9eabf452013-07-13 00:04:20 +0000358 const ObjCImplementationDecl *ImpDecl,
Fariborz Jahaniand36150d2013-07-15 21:22:08 +0000359 const ObjCInterfaceDecl *IDecl,
Fariborz Jahanian9eabf452013-07-13 00:04:20 +0000360 ObjCProtocolDecl *Protocol) {
Fariborz Jahaniand36150d2013-07-15 21:22:08 +0000361 // In auto-synthesis, protocol properties are not synthesized. So,
362 // a conforming protocol must have its required properties declared
363 // in class interface.
Fariborz Jahanian9e543af2013-07-22 23:50:04 +0000364 bool HasAtleastOneRequiredProperty = false;
Fariborz Jahaniand36150d2013-07-15 21:22:08 +0000365 if (const ObjCProtocolDecl *PDecl = Protocol->getDefinition())
366 for (ObjCProtocolDecl::prop_iterator P = PDecl->prop_begin(),
367 E = PDecl->prop_end(); P != E; ++P) {
368 ObjCPropertyDecl *Property = *P;
369 if (Property->getPropertyImplementation() == ObjCPropertyDecl::Optional)
370 continue;
Fariborz Jahanian9e543af2013-07-22 23:50:04 +0000371 HasAtleastOneRequiredProperty = true;
Fariborz Jahaniand36150d2013-07-15 21:22:08 +0000372 DeclContext::lookup_const_result R = IDecl->lookup(Property->getDeclName());
Fariborz Jahanian2bc3dda2013-07-16 21:59:42 +0000373 if (R.size() == 0) {
374 // Relax the rule and look into class's implementation for a synthesize
375 // or dynamic declaration. Class is implementing a property coming from
376 // another protocol. This still makes the target protocol as conforming.
377 if (!ImpDecl->FindPropertyImplDecl(
378 Property->getDeclName().getAsIdentifierInfo()))
379 return false;
Fariborz Jahaniand36150d2013-07-15 21:22:08 +0000380 }
Fariborz Jahanian2bc3dda2013-07-16 21:59:42 +0000381 else if (ObjCPropertyDecl *ClassProperty = dyn_cast<ObjCPropertyDecl>(R[0])) {
382 if ((ClassProperty->getPropertyAttributes()
383 != Property->getPropertyAttributes()) ||
384 !Ctx.hasSameType(ClassProperty->getType(), Property->getType()))
385 return false;
386 }
387 else
388 return false;
Fariborz Jahaniand36150d2013-07-15 21:22:08 +0000389 }
Fariborz Jahanian9e543af2013-07-22 23:50:04 +0000390
Fariborz Jahaniand36150d2013-07-15 21:22:08 +0000391 // At this point, all required properties in this protocol conform to those
392 // declared in the class.
393 // Check that class implements the required methods of the protocol too.
Fariborz Jahanian9e543af2013-07-22 23:50:04 +0000394 bool HasAtleastOneRequiredMethod = false;
Fariborz Jahanian5bd5aff2013-07-16 00:20:21 +0000395 if (const ObjCProtocolDecl *PDecl = Protocol->getDefinition()) {
396 if (PDecl->meth_begin() == PDecl->meth_end())
Fariborz Jahanian9e543af2013-07-22 23:50:04 +0000397 return HasAtleastOneRequiredProperty;
Fariborz Jahaniand36150d2013-07-15 21:22:08 +0000398 for (ObjCContainerDecl::method_iterator M = PDecl->meth_begin(),
399 MEnd = PDecl->meth_end(); M != MEnd; ++M) {
400 ObjCMethodDecl *MD = (*M);
Fariborz Jahanian5bd5aff2013-07-16 00:20:21 +0000401 if (MD->isImplicit())
402 continue;
Fariborz Jahaniand36150d2013-07-15 21:22:08 +0000403 if (MD->getImplementationControl() == ObjCMethodDecl::Optional)
404 continue;
Fariborz Jahaniand36150d2013-07-15 21:22:08 +0000405 DeclContext::lookup_const_result R = ImpDecl->lookup(MD->getDeclName());
Fariborz Jahanian5bd5aff2013-07-16 00:20:21 +0000406 if (R.size() == 0)
407 return false;
Fariborz Jahanian9e543af2013-07-22 23:50:04 +0000408 bool match = false;
409 HasAtleastOneRequiredMethod = true;
Fariborz Jahaniand36150d2013-07-15 21:22:08 +0000410 for (unsigned I = 0, N = R.size(); I != N; ++I)
411 if (ObjCMethodDecl *ImpMD = dyn_cast<ObjCMethodDecl>(R[0]))
412 if (Ctx.ObjCMethodsAreEqual(MD, ImpMD)) {
413 match = true;
414 break;
415 }
416 if (!match)
417 return false;
418 }
Fariborz Jahanian5bd5aff2013-07-16 00:20:21 +0000419 }
Fariborz Jahanian9e543af2013-07-22 23:50:04 +0000420 if (HasAtleastOneRequiredProperty || HasAtleastOneRequiredMethod)
421 return true;
422 return false;
Fariborz Jahanian9eabf452013-07-13 00:04:20 +0000423}
424
Fariborz Jahanian85e988b2013-07-18 22:17:33 +0000425static bool rewriteToObjCInterfaceDecl(const ObjCInterfaceDecl *IDecl,
426 llvm::SmallVectorImpl<ObjCProtocolDecl*> &ConformingProtocols,
427 const NSAPI &NS, edit::Commit &commit) {
428 const ObjCList<ObjCProtocolDecl> &Protocols = IDecl->getReferencedProtocols();
429 std::string ClassString;
430 SourceLocation EndLoc =
431 IDecl->getSuperClass() ? IDecl->getSuperClassLoc() : IDecl->getLocation();
432
433 if (Protocols.empty()) {
434 ClassString = '<';
435 for (unsigned i = 0, e = ConformingProtocols.size(); i != e; i++) {
436 ClassString += ConformingProtocols[i]->getNameAsString();
437 if (i != (e-1))
438 ClassString += ", ";
439 }
440 ClassString += "> ";
441 }
442 else {
443 ClassString = ", ";
444 for (unsigned i = 0, e = ConformingProtocols.size(); i != e; i++) {
445 ClassString += ConformingProtocols[i]->getNameAsString();
446 if (i != (e-1))
447 ClassString += ", ";
448 }
449 ObjCInterfaceDecl::protocol_loc_iterator PL = IDecl->protocol_loc_end() - 1;
450 EndLoc = *PL;
451 }
452
453 commit.insertAfterToken(EndLoc, ClassString);
454 return true;
455}
456
457static bool rewriteToNSEnumDecl(const EnumDecl *EnumDcl,
458 const TypedefDecl *TypedefDcl,
Fariborz Jahanianb0057bb2013-07-19 01:05:49 +0000459 const NSAPI &NS, edit::Commit &commit,
Fariborz Jahanianff3476e2013-08-30 17:46:01 +0000460 bool IsNSIntegerType,
461 bool NSOptions) {
462 std::string ClassString;
463 if (NSOptions)
464 ClassString = "typedef NS_OPTIONS(NSUInteger, ";
465 else
466 ClassString =
467 IsNSIntegerType ? "typedef NS_ENUM(NSInteger, "
468 : "typedef NS_ENUM(NSUInteger, ";
469
Fariborz Jahanian85e988b2013-07-18 22:17:33 +0000470 ClassString += TypedefDcl->getIdentifier()->getName();
471 ClassString += ')';
472 SourceRange R(EnumDcl->getLocStart(), EnumDcl->getLocStart());
473 commit.replace(R, ClassString);
474 SourceLocation EndOfTypedefLoc = TypedefDcl->getLocEnd();
475 EndOfTypedefLoc = trans::findLocationAfterSemi(EndOfTypedefLoc, NS.getASTContext());
476 if (!EndOfTypedefLoc.isInvalid()) {
477 commit.remove(SourceRange(TypedefDcl->getLocStart(), EndOfTypedefLoc));
478 return true;
479 }
480 return false;
481}
482
Fariborz Jahaniand0f6f792013-07-22 18:53:45 +0000483static bool rewriteToNSMacroDecl(const EnumDecl *EnumDcl,
Fariborz Jahanianc1c44f62013-07-19 20:18:36 +0000484 const TypedefDecl *TypedefDcl,
Fariborz Jahaniand0f6f792013-07-22 18:53:45 +0000485 const NSAPI &NS, edit::Commit &commit,
486 bool IsNSIntegerType) {
487 std::string ClassString =
488 IsNSIntegerType ? "NS_ENUM(NSInteger, " : "NS_OPTIONS(NSUInteger, ";
Fariborz Jahanianc1c44f62013-07-19 20:18:36 +0000489 ClassString += TypedefDcl->getIdentifier()->getName();
490 ClassString += ')';
491 SourceRange R(EnumDcl->getLocStart(), EnumDcl->getLocStart());
492 commit.replace(R, ClassString);
493 SourceLocation TypedefLoc = TypedefDcl->getLocEnd();
494 commit.remove(SourceRange(TypedefLoc, TypedefLoc));
495 return true;
496}
497
Fariborz Jahaniana23f4fb2013-08-30 00:10:37 +0000498static bool UseNSOptionsMacro(Preprocessor &PP, ASTContext &Ctx,
Fariborz Jahaniand0f6f792013-07-22 18:53:45 +0000499 const EnumDecl *EnumDcl) {
500 bool PowerOfTwo = true;
Fariborz Jahaniana23f4fb2013-08-30 00:10:37 +0000501 bool FoundHexdecimalEnumerator = false;
Fariborz Jahanianbe7bc112013-08-15 18:46:37 +0000502 uint64_t MaxPowerOfTwoVal = 0;
Fariborz Jahaniand0f6f792013-07-22 18:53:45 +0000503 for (EnumDecl::enumerator_iterator EI = EnumDcl->enumerator_begin(),
504 EE = EnumDcl->enumerator_end(); EI != EE; ++EI) {
505 EnumConstantDecl *Enumerator = (*EI);
506 const Expr *InitExpr = Enumerator->getInitExpr();
507 if (!InitExpr) {
508 PowerOfTwo = false;
509 continue;
510 }
Fariborz Jahanian6e1798e2013-09-17 23:32:51 +0000511 InitExpr = InitExpr->IgnoreParenCasts();
Fariborz Jahaniand0f6f792013-07-22 18:53:45 +0000512 if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr))
513 if (BO->isShiftOp() || BO->isBitwiseOp())
514 return true;
515
516 uint64_t EnumVal = Enumerator->getInitVal().getZExtValue();
Fariborz Jahanianbe7bc112013-08-15 18:46:37 +0000517 if (PowerOfTwo && EnumVal) {
518 if (!llvm::isPowerOf2_64(EnumVal))
519 PowerOfTwo = false;
520 else if (EnumVal > MaxPowerOfTwoVal)
521 MaxPowerOfTwoVal = EnumVal;
522 }
Fariborz Jahaniana23f4fb2013-08-30 00:10:37 +0000523 if (!FoundHexdecimalEnumerator) {
524 SourceLocation EndLoc = Enumerator->getLocEnd();
525 Token Tok;
526 if (!PP.getRawToken(EndLoc, Tok, /*IgnoreWhiteSpace=*/true))
527 if (Tok.isLiteral() && Tok.getLength() > 2) {
528 if (const char *StringLit = Tok.getLiteralData())
529 FoundHexdecimalEnumerator =
530 (StringLit[0] == '0' && (toLowercase(StringLit[1]) == 'x'));
531 }
532 }
Fariborz Jahaniand0f6f792013-07-22 18:53:45 +0000533 }
Fariborz Jahaniana23f4fb2013-08-30 00:10:37 +0000534 return FoundHexdecimalEnumerator || (PowerOfTwo && (MaxPowerOfTwoVal > 2));
Fariborz Jahaniand0f6f792013-07-22 18:53:45 +0000535}
536
Fariborz Jahanian008ef722013-07-19 17:44:32 +0000537void ObjCMigrateASTConsumer::migrateProtocolConformance(ASTContext &Ctx,
Fariborz Jahanian1be01532013-07-12 22:32:19 +0000538 const ObjCImplementationDecl *ImpDecl) {
539 const ObjCInterfaceDecl *IDecl = ImpDecl->getClassInterface();
Fariborz Jahanian75226d52013-09-17 21:56:04 +0000540 if (!IDecl || ObjCProtocolDecls.empty() || IDecl->isDeprecated())
Fariborz Jahanian1be01532013-07-12 22:32:19 +0000541 return;
542 // Find all implicit conforming protocols for this class
543 // and make them explicit.
544 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> ExplicitProtocols;
545 Ctx.CollectInheritedProtocols(IDecl, ExplicitProtocols);
Fariborz Jahanian9eabf452013-07-13 00:04:20 +0000546 llvm::SmallVector<ObjCProtocolDecl *, 8> PotentialImplicitProtocols;
Fariborz Jahanian1be01532013-07-12 22:32:19 +0000547
Fariborz Jahanian9eabf452013-07-13 00:04:20 +0000548 for (llvm::SmallPtrSet<ObjCProtocolDecl*, 32>::iterator I =
Fariborz Jahanian1be01532013-07-12 22:32:19 +0000549 ObjCProtocolDecls.begin(),
550 E = ObjCProtocolDecls.end(); I != E; ++I)
551 if (!ExplicitProtocols.count(*I))
Fariborz Jahanian9eabf452013-07-13 00:04:20 +0000552 PotentialImplicitProtocols.push_back(*I);
Fariborz Jahanian1be01532013-07-12 22:32:19 +0000553
554 if (PotentialImplicitProtocols.empty())
555 return;
Fariborz Jahanian9eabf452013-07-13 00:04:20 +0000556
557 // go through list of non-optional methods and properties in each protocol
558 // in the PotentialImplicitProtocols list. If class implements every one of the
559 // methods and properties, then this class conforms to this protocol.
560 llvm::SmallVector<ObjCProtocolDecl*, 8> ConformingProtocols;
561 for (unsigned i = 0, e = PotentialImplicitProtocols.size(); i != e; i++)
Fariborz Jahaniand36150d2013-07-15 21:22:08 +0000562 if (ClassImplementsAllMethodsAndProperties(Ctx, ImpDecl, IDecl,
Fariborz Jahanian9eabf452013-07-13 00:04:20 +0000563 PotentialImplicitProtocols[i]))
564 ConformingProtocols.push_back(PotentialImplicitProtocols[i]);
Fariborz Jahanian5bd5aff2013-07-16 00:20:21 +0000565
566 if (ConformingProtocols.empty())
567 return;
Fariborz Jahaniancb7b8de2013-07-17 00:02:22 +0000568
569 // Further reduce number of conforming protocols. If protocol P1 is in the list
570 // protocol P2 (P2<P1>), No need to include P1.
571 llvm::SmallVector<ObjCProtocolDecl*, 8> MinimalConformingProtocols;
572 for (unsigned i = 0, e = ConformingProtocols.size(); i != e; i++) {
573 bool DropIt = false;
574 ObjCProtocolDecl *TargetPDecl = ConformingProtocols[i];
575 for (unsigned i1 = 0, e1 = ConformingProtocols.size(); i1 != e1; i1++) {
576 ObjCProtocolDecl *PDecl = ConformingProtocols[i1];
577 if (PDecl == TargetPDecl)
578 continue;
579 if (PDecl->lookupProtocolNamed(
580 TargetPDecl->getDeclName().getAsIdentifierInfo())) {
581 DropIt = true;
582 break;
583 }
584 }
585 if (!DropIt)
586 MinimalConformingProtocols.push_back(TargetPDecl);
587 }
Fariborz Jahanian5bd5aff2013-07-16 00:20:21 +0000588 edit::Commit commit(*Editor);
Fariborz Jahanian85e988b2013-07-18 22:17:33 +0000589 rewriteToObjCInterfaceDecl(IDecl, MinimalConformingProtocols,
590 *NSAPIObj, commit);
Fariborz Jahanian5bd5aff2013-07-16 00:20:21 +0000591 Editor->commit(commit);
Fariborz Jahanian1be01532013-07-12 22:32:19 +0000592}
593
Fariborz Jahanian92463272013-07-18 20:11:45 +0000594void ObjCMigrateASTConsumer::migrateNSEnumDecl(ASTContext &Ctx,
595 const EnumDecl *EnumDcl,
596 const TypedefDecl *TypedefDcl) {
597 if (!EnumDcl->isCompleteDefinition() || EnumDcl->getIdentifier() ||
Fariborz Jahanian75226d52013-09-17 21:56:04 +0000598 !TypedefDcl->getIdentifier() ||
599 EnumDcl->isDeprecated() || TypedefDcl->isDeprecated())
Fariborz Jahanian92463272013-07-18 20:11:45 +0000600 return;
601
602 QualType qt = TypedefDcl->getTypeSourceInfo()->getType();
Fariborz Jahanianb0057bb2013-07-19 01:05:49 +0000603 bool IsNSIntegerType = NSAPIObj->isObjCNSIntegerType(qt);
604 bool IsNSUIntegerType = !IsNSIntegerType && NSAPIObj->isObjCNSUIntegerType(qt);
Fariborz Jahaniand0f6f792013-07-22 18:53:45 +0000605
Fariborz Jahanianc1c44f62013-07-19 20:18:36 +0000606 if (!IsNSIntegerType && !IsNSUIntegerType) {
607 // Also check for typedef enum {...} TD;
608 if (const EnumType *EnumTy = qt->getAs<EnumType>()) {
609 if (EnumTy->getDecl() == EnumDcl) {
Fariborz Jahaniana23f4fb2013-08-30 00:10:37 +0000610 bool NSOptions = UseNSOptionsMacro(PP, Ctx, EnumDcl);
Fariborz Jahaniand0f6f792013-07-22 18:53:45 +0000611 if (NSOptions) {
612 if (!Ctx.Idents.get("NS_OPTIONS").hasMacroDefinition())
613 return;
614 }
615 else if (!Ctx.Idents.get("NS_ENUM").hasMacroDefinition())
Fariborz Jahanianc1c44f62013-07-19 20:18:36 +0000616 return;
617 edit::Commit commit(*Editor);
Fariborz Jahaniand0f6f792013-07-22 18:53:45 +0000618 rewriteToNSMacroDecl(EnumDcl, TypedefDcl, *NSAPIObj, commit, !NSOptions);
Fariborz Jahanianc1c44f62013-07-19 20:18:36 +0000619 Editor->commit(commit);
Fariborz Jahanianc1c44f62013-07-19 20:18:36 +0000620 }
Fariborz Jahanianc1c44f62013-07-19 20:18:36 +0000621 }
Fariborz Jahaniand0f6f792013-07-22 18:53:45 +0000622 return;
623 }
Fariborz Jahanian92463272013-07-18 20:11:45 +0000624
Fariborz Jahanianff3476e2013-08-30 17:46:01 +0000625 // We may still use NS_OPTIONS based on what we find in the enumertor list.
626 bool NSOptions = UseNSOptionsMacro(PP, Ctx, EnumDcl);
Fariborz Jahanian92463272013-07-18 20:11:45 +0000627 // NS_ENUM must be available.
Fariborz Jahanianb0057bb2013-07-19 01:05:49 +0000628 if (IsNSIntegerType && !Ctx.Idents.get("NS_ENUM").hasMacroDefinition())
629 return;
630 // NS_OPTIONS must be available.
631 if (IsNSUIntegerType && !Ctx.Idents.get("NS_OPTIONS").hasMacroDefinition())
Fariborz Jahanian92463272013-07-18 20:11:45 +0000632 return;
633 edit::Commit commit(*Editor);
Fariborz Jahanianff3476e2013-08-30 17:46:01 +0000634 rewriteToNSEnumDecl(EnumDcl, TypedefDcl, *NSAPIObj, commit, IsNSIntegerType, NSOptions);
Fariborz Jahanian92463272013-07-18 20:11:45 +0000635 Editor->commit(commit);
636}
637
Fariborz Jahanianc4291852013-08-02 18:00:53 +0000638static void ReplaceWithInstancetype(const ObjCMigrateASTConsumer &ASTC,
639 ObjCMethodDecl *OM) {
640 SourceRange R;
641 std::string ClassString;
642 if (TypeSourceInfo *TSInfo = OM->getResultTypeSourceInfo()) {
643 TypeLoc TL = TSInfo->getTypeLoc();
644 R = SourceRange(TL.getBeginLoc(), TL.getEndLoc());
645 ClassString = "instancetype";
646 }
647 else {
648 R = SourceRange(OM->getLocStart(), OM->getLocStart());
649 ClassString = OM->isInstanceMethod() ? '-' : '+';
650 ClassString += " (instancetype)";
651 }
652 edit::Commit commit(*ASTC.Editor);
653 commit.replace(R, ClassString);
654 ASTC.Editor->commit(commit);
655}
656
Fariborz Jahanian670ef262013-07-23 23:34:42 +0000657void ObjCMigrateASTConsumer::migrateMethodInstanceType(ASTContext &Ctx,
658 ObjCContainerDecl *CDecl,
659 ObjCMethodDecl *OM) {
Fariborz Jahanian7dd71432013-08-28 21:23:00 +0000660 // bail out early and do not suggest 'instancetype' when the method already
661 // has a related result type,
662 if (OM->hasRelatedResultType())
663 return;
664
Fariborz Jahanian71221352013-07-23 22:42:28 +0000665 ObjCInstanceTypeFamily OIT_Family =
666 Selector::getInstTypeMethodFamily(OM->getSelector());
Fariborz Jahanian9275c682013-08-02 20:54:18 +0000667
Fariborz Jahanian267bae32013-07-24 19:18:37 +0000668 std::string ClassName;
Fariborz Jahanian631925f2013-07-23 23:55:55 +0000669 switch (OIT_Family) {
Fariborz Jahanian9275c682013-08-02 20:54:18 +0000670 case OIT_None:
671 migrateFactoryMethod(Ctx, CDecl, OM);
672 return;
Fariborz Jahanian7dd71432013-08-28 21:23:00 +0000673 case OIT_Array:
674 ClassName = "NSArray";
675 break;
676 case OIT_Dictionary:
677 ClassName = "NSDictionary";
678 break;
Fariborz Jahanian9275c682013-08-02 20:54:18 +0000679 case OIT_Singleton:
680 migrateFactoryMethod(Ctx, CDecl, OM, OIT_Singleton);
Fariborz Jahanian631925f2013-07-23 23:55:55 +0000681 return;
682 }
Fariborz Jahanian71221352013-07-23 22:42:28 +0000683 if (!OM->getResultType()->isObjCIdType())
684 return;
685
686 ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(CDecl);
687 if (!IDecl) {
688 if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(CDecl))
689 IDecl = CatDecl->getClassInterface();
690 else if (ObjCImplDecl *ImpDecl = dyn_cast<ObjCImplDecl>(CDecl))
691 IDecl = ImpDecl->getClassInterface();
692 }
Fariborz Jahanian267bae32013-07-24 19:18:37 +0000693 if (!IDecl ||
Fariborz Jahanianc4291852013-08-02 18:00:53 +0000694 !IDecl->lookupInheritedClass(&Ctx.Idents.get(ClassName))) {
695 migrateFactoryMethod(Ctx, CDecl, OM);
Fariborz Jahanian71221352013-07-23 22:42:28 +0000696 return;
Fariborz Jahanian280954a2013-07-24 18:31:42 +0000697 }
Fariborz Jahanianc4291852013-08-02 18:00:53 +0000698 ReplaceWithInstancetype(*this, OM);
Fariborz Jahanian71221352013-07-23 22:42:28 +0000699}
700
Fariborz Jahaniand0fbf6c2013-08-30 23:52:08 +0000701static bool TypeIsInnerPointer(QualType T) {
702 if (!T->isAnyPointerType())
703 return false;
704 if (T->isObjCObjectPointerType() || T->isObjCBuiltinType() ||
705 T->isBlockPointerType() || ento::coreFoundation::isCFObjectRef(T))
706 return false;
Fariborz Jahanian9d5fffb2013-09-09 23:56:14 +0000707 // Also, typedef-of-pointer-to-incomplete-struct is something that we assume
708 // is not an innter pointer type.
709 QualType OrigT = T;
710 while (const TypedefType *TD = dyn_cast<TypedefType>(T.getTypePtr()))
711 T = TD->getDecl()->getUnderlyingType();
712 if (OrigT == T || !T->isPointerType())
713 return true;
714 const PointerType* PT = T->getAs<PointerType>();
715 QualType UPointeeT = PT->getPointeeType().getUnqualifiedType();
716 if (UPointeeT->isRecordType()) {
717 const RecordType *RecordTy = UPointeeT->getAs<RecordType>();
718 if (!RecordTy->getDecl()->isCompleteDefinition())
719 return false;
720 }
Fariborz Jahaniand0fbf6c2013-08-30 23:52:08 +0000721 return true;
722}
723
Fariborz Jahanian215f96c2013-09-06 23:45:20 +0000724bool ObjCMigrateASTConsumer::migrateProperty(ASTContext &Ctx,
Fariborz Jahanian92f72422013-09-17 19:00:30 +0000725 ObjCContainerDecl *D,
Fariborz Jahanian215f96c2013-09-06 23:45:20 +0000726 ObjCMethodDecl *Method) {
727 if (Method->isPropertyAccessor() || !Method->isInstanceMethod() ||
728 Method->param_size() != 0)
729 return false;
730 // Is this method candidate to be a getter?
731 QualType GRT = Method->getResultType();
732 if (GRT->isVoidType())
733 return false;
734 // FIXME. Don't know what todo with attributes, skip for now.
735 if (Method->hasAttrs())
736 return false;
737
738 Selector GetterSelector = Method->getSelector();
739 IdentifierInfo *getterName = GetterSelector.getIdentifierInfoForSlot(0);
740 Selector SetterSelector =
741 SelectorTable::constructSetterSelector(PP.getIdentifierTable(),
742 PP.getSelectorTable(),
743 getterName);
Fariborz Jahanian92f72422013-09-17 19:00:30 +0000744 ObjCMethodDecl *SetterMethod = D->getInstanceMethod(SetterSelector);
Fariborz Jahanianca399602013-09-11 17:05:15 +0000745 unsigned LengthOfPrefix = 0;
Fariborz Jahanian215f96c2013-09-06 23:45:20 +0000746 if (!SetterMethod) {
747 // try a different naming convention for getter: isXxxxx
748 StringRef getterNameString = getterName->getName();
Fariborz Jahanianca399602013-09-11 17:05:15 +0000749 bool IsPrefix = getterNameString.startswith("is");
Fariborz Jahanian4c3d9c52013-09-17 19:38:55 +0000750 // Note that we don't want to change an isXXX method of retainable object
751 // type to property (readonly or otherwise).
752 if (IsPrefix && GRT->isObjCRetainableType())
753 return false;
754 if (IsPrefix || getterNameString.startswith("get")) {
Fariborz Jahanianca399602013-09-11 17:05:15 +0000755 LengthOfPrefix = (IsPrefix ? 2 : 3);
756 const char *CGetterName = getterNameString.data() + LengthOfPrefix;
757 // Make sure that first character after "is" or "get" prefix can
758 // start an identifier.
759 if (!isIdentifierHead(CGetterName[0]))
760 return false;
Fariborz Jahanian215f96c2013-09-06 23:45:20 +0000761 if (CGetterName[0] && isUppercase(CGetterName[0])) {
762 getterName = &Ctx.Idents.get(CGetterName);
763 SetterSelector =
764 SelectorTable::constructSetterSelector(PP.getIdentifierTable(),
765 PP.getSelectorTable(),
766 getterName);
Fariborz Jahanian92f72422013-09-17 19:00:30 +0000767 SetterMethod = D->getInstanceMethod(SetterSelector);
Fariborz Jahanian215f96c2013-09-06 23:45:20 +0000768 }
769 }
770 }
Fariborz Jahanian4c3d9c52013-09-17 19:38:55 +0000771
Fariborz Jahanian215f96c2013-09-06 23:45:20 +0000772 if (SetterMethod) {
Fariborz Jahanianf6c65052013-09-17 22:41:25 +0000773 if (SetterMethod->isDeprecated())
774 return false;
Fariborz Jahanian215f96c2013-09-06 23:45:20 +0000775 // Is this a valid setter, matching the target getter?
776 QualType SRT = SetterMethod->getResultType();
777 if (!SRT->isVoidType())
778 return false;
779 const ParmVarDecl *argDecl = *SetterMethod->param_begin();
780 QualType ArgType = argDecl->getType();
781 if (!Ctx.hasSameUnqualifiedType(ArgType, GRT) ||
782 SetterMethod->hasAttrs())
783 return false;
784 edit::Commit commit(*Editor);
785 rewriteToObjCProperty(Method, SetterMethod, *NSAPIObj, commit,
Fariborz Jahanianca399602013-09-11 17:05:15 +0000786 LengthOfPrefix);
Fariborz Jahanian215f96c2013-09-06 23:45:20 +0000787 Editor->commit(commit);
788 return true;
789 }
790 else if (MigrateReadonlyProperty) {
791 // Try a non-void method with no argument (and no setter or property of same name
792 // as a 'readonly' property.
793 edit::Commit commit(*Editor);
794 rewriteToObjCProperty(Method, 0 /*SetterMethod*/, *NSAPIObj, commit,
Fariborz Jahanianca399602013-09-11 17:05:15 +0000795 LengthOfPrefix);
Fariborz Jahanian215f96c2013-09-06 23:45:20 +0000796 Editor->commit(commit);
797 return true;
798 }
799 return false;
800}
801
Fariborz Jahaniand0fbf6c2013-08-30 23:52:08 +0000802void ObjCMigrateASTConsumer::migrateNsReturnsInnerPointer(ASTContext &Ctx,
803 ObjCMethodDecl *OM) {
804 if (OM->hasAttr<ObjCReturnsInnerPointerAttr>())
805 return;
806
807 QualType RT = OM->getResultType();
808 if (!TypeIsInnerPointer(RT) ||
809 !Ctx.Idents.get("NS_RETURNS_INNER_POINTER").hasMacroDefinition())
810 return;
811
812 edit::Commit commit(*Editor);
813 commit.insertBefore(OM->getLocEnd(), " NS_RETURNS_INNER_POINTER");
814 Editor->commit(commit);
815}
816
817void ObjCMigrateASTConsumer::migrateMethods(ASTContext &Ctx,
Fariborz Jahanian71221352013-07-23 22:42:28 +0000818 ObjCContainerDecl *CDecl) {
819 // migrate methods which can have instancetype as their result type.
820 for (ObjCContainerDecl::method_iterator M = CDecl->meth_begin(),
821 MEnd = CDecl->meth_end();
822 M != MEnd; ++M) {
823 ObjCMethodDecl *Method = (*M);
Fariborz Jahanian75226d52013-09-17 21:56:04 +0000824 if (Method->isDeprecated())
825 continue;
Fariborz Jahanian71221352013-07-23 22:42:28 +0000826 migrateMethodInstanceType(Ctx, CDecl, Method);
827 }
828}
829
Fariborz Jahanianc4291852013-08-02 18:00:53 +0000830void ObjCMigrateASTConsumer::migrateFactoryMethod(ASTContext &Ctx,
831 ObjCContainerDecl *CDecl,
Fariborz Jahanian9275c682013-08-02 20:54:18 +0000832 ObjCMethodDecl *OM,
833 ObjCInstanceTypeFamily OIT_Family) {
Fariborz Jahanian3bfc35e2013-08-02 22:34:18 +0000834 if (OM->isInstanceMethod() ||
835 OM->getResultType() == Ctx.getObjCInstanceType() ||
836 !OM->getResultType()->isObjCIdType())
Fariborz Jahanianc4291852013-08-02 18:00:53 +0000837 return;
838
839 // Candidate factory methods are + (id) NaMeXXX : ... which belong to a class
840 // NSYYYNamE with matching names be at least 3 characters long.
841 ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(CDecl);
842 if (!IDecl) {
843 if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(CDecl))
844 IDecl = CatDecl->getClassInterface();
845 else if (ObjCImplDecl *ImpDecl = dyn_cast<ObjCImplDecl>(CDecl))
846 IDecl = ImpDecl->getClassInterface();
847 }
848 if (!IDecl)
849 return;
850
851 std::string StringClassName = IDecl->getName();
852 StringRef LoweredClassName(StringClassName);
853 std::string StringLoweredClassName = LoweredClassName.lower();
854 LoweredClassName = StringLoweredClassName;
855
856 IdentifierInfo *MethodIdName = OM->getSelector().getIdentifierInfoForSlot(0);
Fariborz Jahanianc13c1b02013-08-13 18:01:42 +0000857 // Handle method with no name at its first selector slot; e.g. + (id):(int)x.
858 if (!MethodIdName)
859 return;
860
Fariborz Jahanianc4291852013-08-02 18:00:53 +0000861 std::string MethodName = MethodIdName->getName();
Fariborz Jahanian9275c682013-08-02 20:54:18 +0000862 if (OIT_Family == OIT_Singleton) {
863 StringRef STRefMethodName(MethodName);
864 size_t len = 0;
865 if (STRefMethodName.startswith("standard"))
866 len = strlen("standard");
867 else if (STRefMethodName.startswith("shared"))
868 len = strlen("shared");
869 else if (STRefMethodName.startswith("default"))
870 len = strlen("default");
871 else
872 return;
873 MethodName = STRefMethodName.substr(len);
874 }
Fariborz Jahanianc4291852013-08-02 18:00:53 +0000875 std::string MethodNameSubStr = MethodName.substr(0, 3);
876 StringRef MethodNamePrefix(MethodNameSubStr);
877 std::string StringLoweredMethodNamePrefix = MethodNamePrefix.lower();
878 MethodNamePrefix = StringLoweredMethodNamePrefix;
879 size_t Ix = LoweredClassName.rfind(MethodNamePrefix);
880 if (Ix == StringRef::npos)
881 return;
882 std::string ClassNamePostfix = LoweredClassName.substr(Ix);
883 StringRef LoweredMethodName(MethodName);
884 std::string StringLoweredMethodName = LoweredMethodName.lower();
885 LoweredMethodName = StringLoweredMethodName;
886 if (!LoweredMethodName.startswith(ClassNamePostfix))
887 return;
888 ReplaceWithInstancetype(*this, OM);
889}
890
Fariborz Jahanian2ec4d7b2013-08-16 23:35:05 +0000891static bool IsVoidStarType(QualType Ty) {
892 if (!Ty->isPointerType())
893 return false;
894
895 while (const TypedefType *TD = dyn_cast<TypedefType>(Ty.getTypePtr()))
896 Ty = TD->getDecl()->getUnderlyingType();
897
898 // Is the type void*?
899 const PointerType* PT = Ty->getAs<PointerType>();
900 if (PT->getPointeeType().getUnqualifiedType()->isVoidType())
901 return true;
902 return IsVoidStarType(PT->getPointeeType());
903}
904
Fariborz Jahanian94279392013-08-20 18:54:39 +0000905/// AuditedType - This routine audits the type AT and returns false if it is one of known
906/// CF object types or of the "void *" variety. It returns true if we don't care about the type
907/// such as a non-pointer or pointers which have no ownership issues (such as "int *").
Fariborz Jahanian63ffce22013-08-27 22:42:30 +0000908static bool AuditedType (QualType AT) {
909 if (!AT->isAnyPointerType() && !AT->isBlockPointerType())
Fariborz Jahanian9ef4a262013-08-19 19:13:34 +0000910 return true;
Fariborz Jahanian9ef4a262013-08-19 19:13:34 +0000911 // FIXME. There isn't much we can say about CF pointer type; or is there?
Fariborz Jahanian94279392013-08-20 18:54:39 +0000912 if (ento::coreFoundation::isCFObjectRef(AT) ||
913 IsVoidStarType(AT) ||
914 // If an ObjC object is type, assuming that it is not a CF function and
915 // that it is an un-audited function.
Fariborz Jahanian2e9c19c2013-08-22 22:27:36 +0000916 AT->isObjCObjectPointerType() || AT->isObjCBuiltinType())
Fariborz Jahanian9ef4a262013-08-19 19:13:34 +0000917 return false;
Fariborz Jahanian94279392013-08-20 18:54:39 +0000918 // All other pointers are assumed audited as harmless.
Fariborz Jahanian9ef4a262013-08-19 19:13:34 +0000919 return true;
Fariborz Jahanian2ec4d7b2013-08-16 23:35:05 +0000920}
921
Fariborz Jahanian301b5212013-08-20 22:42:13 +0000922void ObjCMigrateASTConsumer::AnnotateImplicitBridging(ASTContext &Ctx) {
Fariborz Jahanian926fafb2013-08-22 18:35:27 +0000923 if (CFFunctionIBCandidates.empty())
924 return;
Fariborz Jahanian301b5212013-08-20 22:42:13 +0000925 if (!Ctx.Idents.get("CF_IMPLICIT_BRIDGING_ENABLED").hasMacroDefinition()) {
926 CFFunctionIBCandidates.clear();
Fariborz Jahanianb8343522013-08-20 23:35:26 +0000927 FileId = 0;
Fariborz Jahanian301b5212013-08-20 22:42:13 +0000928 return;
929 }
930 // Insert CF_IMPLICIT_BRIDGING_ENABLE/CF_IMPLICIT_BRIDGING_DISABLED
Fariborz Jahanian926fafb2013-08-22 18:35:27 +0000931 const Decl *FirstFD = CFFunctionIBCandidates[0];
932 const Decl *LastFD =
933 CFFunctionIBCandidates[CFFunctionIBCandidates.size()-1];
Fariborz Jahanian301b5212013-08-20 22:42:13 +0000934 const char *PragmaString = "\nCF_IMPLICIT_BRIDGING_ENABLED\n\n";
935 edit::Commit commit(*Editor);
936 commit.insertBefore(FirstFD->getLocStart(), PragmaString);
937 PragmaString = "\n\nCF_IMPLICIT_BRIDGING_DISABLED\n";
938 SourceLocation EndLoc = LastFD->getLocEnd();
939 // get location just past end of function location.
940 EndLoc = PP.getLocForEndOfToken(EndLoc);
Fariborz Jahanian926fafb2013-08-22 18:35:27 +0000941 if (isa<FunctionDecl>(LastFD)) {
942 // For Methods, EndLoc points to the ending semcolon. So,
943 // not of these extra work is needed.
944 Token Tok;
945 // get locaiton of token that comes after end of function.
946 bool Failed = PP.getRawToken(EndLoc, Tok, /*IgnoreWhiteSpace=*/true);
947 if (!Failed)
948 EndLoc = Tok.getLocation();
949 }
Fariborz Jahanian301b5212013-08-20 22:42:13 +0000950 commit.insertAfterToken(EndLoc, PragmaString);
951 Editor->commit(commit);
Fariborz Jahanianb8343522013-08-20 23:35:26 +0000952 FileId = 0;
Fariborz Jahanian301b5212013-08-20 22:42:13 +0000953 CFFunctionIBCandidates.clear();
954}
955
Fariborz Jahanian4f64dd22013-08-22 21:40:15 +0000956void ObjCMigrateASTConsumer::migrateCFAnnotation(ASTContext &Ctx, const Decl *Decl) {
Fariborz Jahanian75226d52013-09-17 21:56:04 +0000957 if (Decl->isDeprecated())
958 return;
959
Fariborz Jahanian4f64dd22013-08-22 21:40:15 +0000960 if (Decl->hasAttr<CFAuditedTransferAttr>()) {
Fariborz Jahanianc6dfd3f2013-08-19 22:00:50 +0000961 assert(CFFunctionIBCandidates.empty() &&
Fariborz Jahanian4f64dd22013-08-22 21:40:15 +0000962 "Cannot have audited functions/methods inside user "
Fariborz Jahanianc6dfd3f2013-08-19 22:00:50 +0000963 "provided CF_IMPLICIT_BRIDGING_ENABLE");
964 return;
965 }
966
Fariborz Jahanian2ec4d7b2013-08-16 23:35:05 +0000967 // Finction must be annotated first.
Fariborz Jahanian89f6d102013-09-04 00:10:06 +0000968 if (const FunctionDecl *FuncDecl = dyn_cast<FunctionDecl>(Decl)) {
969 CF_BRIDGING_KIND AuditKind = migrateAddFunctionAnnotation(Ctx, FuncDecl);
970 if (AuditKind == CF_BRIDGING_ENABLE) {
Fariborz Jahanian63ffce22013-08-27 22:42:30 +0000971 CFFunctionIBCandidates.push_back(Decl);
972 if (!FileId)
973 FileId = PP.getSourceManager().getFileID(Decl->getLocation()).getHashValue();
974 }
Fariborz Jahanian89f6d102013-09-04 00:10:06 +0000975 else if (AuditKind == CF_BRIDGING_MAY_INCLUDE) {
976 if (!CFFunctionIBCandidates.empty()) {
977 CFFunctionIBCandidates.push_back(Decl);
978 if (!FileId)
979 FileId = PP.getSourceManager().getFileID(Decl->getLocation()).getHashValue();
980 }
981 }
982 else
983 AnnotateImplicitBridging(Ctx);
Fariborz Jahanian63ffce22013-08-27 22:42:30 +0000984 }
Fariborz Jahanian89f6d102013-09-04 00:10:06 +0000985 else {
986 migrateAddMethodAnnotation(Ctx, cast<ObjCMethodDecl>(Decl));
Fariborz Jahanian301b5212013-08-20 22:42:13 +0000987 AnnotateImplicitBridging(Ctx);
Fariborz Jahanian89f6d102013-09-04 00:10:06 +0000988 }
Fariborz Jahanian2ec4d7b2013-08-16 23:35:05 +0000989}
990
Fariborz Jahanian63ffce22013-08-27 22:42:30 +0000991void ObjCMigrateASTConsumer::AddCFAnnotations(ASTContext &Ctx,
992 const CallEffects &CE,
Fariborz Jahanian7ca1d302013-08-27 23:56:54 +0000993 const FunctionDecl *FuncDecl,
994 bool ResultAnnotated) {
Fariborz Jahanian63ffce22013-08-27 22:42:30 +0000995 // Annotate function.
Fariborz Jahanian7ca1d302013-08-27 23:56:54 +0000996 if (!ResultAnnotated) {
Fariborz Jahanian9ef4a262013-08-19 19:13:34 +0000997 RetEffect Ret = CE.getReturnValue();
998 const char *AnnotationString = 0;
Fariborz Jahanian1a269272013-09-04 22:49:19 +0000999 if (Ret.getObjKind() == RetEffect::CF) {
1000 if (Ret.isOwned() &&
1001 Ctx.Idents.get("CF_RETURNS_RETAINED").hasMacroDefinition())
Fariborz Jahanian9ef4a262013-08-19 19:13:34 +00001002 AnnotationString = " CF_RETURNS_RETAINED";
Fariborz Jahanian1a269272013-09-04 22:49:19 +00001003 else if (Ret.notOwned() &&
1004 Ctx.Idents.get("CF_RETURNS_NOT_RETAINED").hasMacroDefinition())
Fariborz Jahanian9ef4a262013-08-19 19:13:34 +00001005 AnnotationString = " CF_RETURNS_NOT_RETAINED";
1006 }
Fariborz Jahanian1a269272013-09-04 22:49:19 +00001007 else if (Ret.getObjKind() == RetEffect::ObjC) {
1008 if (Ret.isOwned() &&
1009 Ctx.Idents.get("NS_RETURNS_RETAINED").hasMacroDefinition())
1010 AnnotationString = " NS_RETURNS_RETAINED";
Fariborz Jahanian1a269272013-09-04 22:49:19 +00001011 }
1012
Fariborz Jahanian9ef4a262013-08-19 19:13:34 +00001013 if (AnnotationString) {
1014 edit::Commit commit(*Editor);
1015 commit.insertAfterToken(FuncDecl->getLocEnd(), AnnotationString);
1016 Editor->commit(commit);
1017 }
Fariborz Jahanian84ac1de2013-08-15 21:44:38 +00001018 }
Fariborz Jahanian9ef4a262013-08-19 19:13:34 +00001019 llvm::ArrayRef<ArgEffect> AEArgs = CE.getArgs();
1020 unsigned i = 0;
1021 for (FunctionDecl::param_const_iterator pi = FuncDecl->param_begin(),
1022 pe = FuncDecl->param_end(); pi != pe; ++pi, ++i) {
Fariborz Jahanianb918d7a2013-08-21 19:37:47 +00001023 const ParmVarDecl *pd = *pi;
Fariborz Jahanian9ef4a262013-08-19 19:13:34 +00001024 ArgEffect AE = AEArgs[i];
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001025 if (AE == DecRef && !pd->getAttr<CFConsumedAttr>() &&
1026 Ctx.Idents.get("CF_CONSUMED").hasMacroDefinition()) {
1027 edit::Commit commit(*Editor);
1028 commit.insertBefore(pd->getLocation(), "CF_CONSUMED ");
1029 Editor->commit(commit);
Fariborz Jahanian94279392013-08-20 18:54:39 +00001030 }
Fariborz Jahanian1a269272013-09-04 22:49:19 +00001031 else if (AE == DecRefMsg && !pd->getAttr<NSConsumedAttr>() &&
1032 Ctx.Idents.get("NS_CONSUMED").hasMacroDefinition()) {
1033 edit::Commit commit(*Editor);
1034 commit.insertBefore(pd->getLocation(), "NS_CONSUMED ");
1035 Editor->commit(commit);
1036 }
Fariborz Jahanian84ac1de2013-08-15 21:44:38 +00001037 }
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001038}
1039
1040
1041ObjCMigrateASTConsumer::CF_BRIDGING_KIND
1042 ObjCMigrateASTConsumer::migrateAddFunctionAnnotation(
1043 ASTContext &Ctx,
1044 const FunctionDecl *FuncDecl) {
1045 if (FuncDecl->hasBody())
1046 return CF_BRIDGING_NONE;
1047
1048 CallEffects CE = CallEffects::getEffect(FuncDecl);
1049 bool FuncIsReturnAnnotated = (FuncDecl->getAttr<CFReturnsRetainedAttr>() ||
Fariborz Jahanian1a269272013-09-04 22:49:19 +00001050 FuncDecl->getAttr<CFReturnsNotRetainedAttr>() ||
1051 FuncDecl->getAttr<NSReturnsRetainedAttr>() ||
Fariborz Jahanianc24879e2013-09-05 23:04:33 +00001052 FuncDecl->getAttr<NSReturnsNotRetainedAttr>() ||
1053 FuncDecl->getAttr<NSReturnsAutoreleasedAttr>());
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001054
1055 // Trivial case of when funciton is annotated and has no argument.
1056 if (FuncIsReturnAnnotated && FuncDecl->getNumParams() == 0)
1057 return CF_BRIDGING_NONE;
1058
1059 bool ReturnCFAudited = false;
1060 if (!FuncIsReturnAnnotated) {
1061 RetEffect Ret = CE.getReturnValue();
1062 if (Ret.getObjKind() == RetEffect::CF &&
Fariborz Jahanian89f6d102013-09-04 00:10:06 +00001063 (Ret.isOwned() || Ret.notOwned()))
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001064 ReturnCFAudited = true;
1065 else if (!AuditedType(FuncDecl->getResultType()))
1066 return CF_BRIDGING_NONE;
1067 }
1068
1069 // At this point result type is audited for potential inclusion.
1070 // Now, how about argument types.
1071 llvm::ArrayRef<ArgEffect> AEArgs = CE.getArgs();
1072 unsigned i = 0;
1073 bool ArgCFAudited = false;
1074 for (FunctionDecl::param_const_iterator pi = FuncDecl->param_begin(),
1075 pe = FuncDecl->param_end(); pi != pe; ++pi, ++i) {
1076 const ParmVarDecl *pd = *pi;
1077 ArgEffect AE = AEArgs[i];
1078 if (AE == DecRef /*CFConsumed annotated*/ || AE == IncRef) {
1079 if (AE == DecRef && !pd->getAttr<CFConsumedAttr>())
1080 ArgCFAudited = true;
1081 else if (AE == IncRef)
1082 ArgCFAudited = true;
1083 }
1084 else {
1085 QualType AT = pd->getType();
1086 if (!AuditedType(AT)) {
Fariborz Jahanian7ca1d302013-08-27 23:56:54 +00001087 AddCFAnnotations(Ctx, CE, FuncDecl, FuncIsReturnAnnotated);
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001088 return CF_BRIDGING_NONE;
1089 }
1090 }
1091 }
1092 if (ReturnCFAudited || ArgCFAudited)
1093 return CF_BRIDGING_ENABLE;
1094
1095 return CF_BRIDGING_MAY_INCLUDE;
Fariborz Jahaniandfe6ed92013-08-12 23:17:13 +00001096}
1097
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001098void ObjCMigrateASTConsumer::migrateARCSafeAnnotation(ASTContext &Ctx,
1099 ObjCContainerDecl *CDecl) {
Fariborz Jahanian75226d52013-09-17 21:56:04 +00001100 if (!isa<ObjCInterfaceDecl>(CDecl) || CDecl->isDeprecated())
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001101 return;
1102
1103 // migrate methods which can have instancetype as their result type.
1104 for (ObjCContainerDecl::method_iterator M = CDecl->meth_begin(),
1105 MEnd = CDecl->meth_end();
1106 M != MEnd; ++M) {
1107 ObjCMethodDecl *Method = (*M);
Fariborz Jahanian4f64dd22013-08-22 21:40:15 +00001108 migrateCFAnnotation(Ctx, Method);
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001109 }
1110}
1111
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001112void ObjCMigrateASTConsumer::AddCFAnnotations(ASTContext &Ctx,
1113 const CallEffects &CE,
Fariborz Jahanian7ca1d302013-08-27 23:56:54 +00001114 const ObjCMethodDecl *MethodDecl,
1115 bool ResultAnnotated) {
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001116 // Annotate function.
Fariborz Jahanian7ca1d302013-08-27 23:56:54 +00001117 if (!ResultAnnotated) {
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001118 RetEffect Ret = CE.getReturnValue();
1119 const char *AnnotationString = 0;
Fariborz Jahanian1a269272013-09-04 22:49:19 +00001120 if (Ret.getObjKind() == RetEffect::CF) {
1121 if (Ret.isOwned() &&
1122 Ctx.Idents.get("CF_RETURNS_RETAINED").hasMacroDefinition())
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001123 AnnotationString = " CF_RETURNS_RETAINED";
Fariborz Jahanian1a269272013-09-04 22:49:19 +00001124 else if (Ret.notOwned() &&
1125 Ctx.Idents.get("CF_RETURNS_NOT_RETAINED").hasMacroDefinition())
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001126 AnnotationString = " CF_RETURNS_NOT_RETAINED";
1127 }
Fariborz Jahanian1a269272013-09-04 22:49:19 +00001128 else if (Ret.getObjKind() == RetEffect::ObjC) {
Fariborz Jahanianc24879e2013-09-05 23:04:33 +00001129 ObjCMethodFamily OMF = MethodDecl->getMethodFamily();
1130 switch (OMF) {
1131 case clang::OMF_alloc:
1132 case clang::OMF_new:
1133 case clang::OMF_copy:
1134 case clang::OMF_init:
1135 case clang::OMF_mutableCopy:
1136 break;
1137
1138 default:
1139 if (Ret.isOwned() &&
1140 Ctx.Idents.get("NS_RETURNS_RETAINED").hasMacroDefinition())
1141 AnnotationString = " NS_RETURNS_RETAINED";
Fariborz Jahanianc24879e2013-09-05 23:04:33 +00001142 break;
1143 }
Fariborz Jahanian1a269272013-09-04 22:49:19 +00001144 }
1145
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001146 if (AnnotationString) {
1147 edit::Commit commit(*Editor);
1148 commit.insertBefore(MethodDecl->getLocEnd(), AnnotationString);
1149 Editor->commit(commit);
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001150 }
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001151 }
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001152 llvm::ArrayRef<ArgEffect> AEArgs = CE.getArgs();
1153 unsigned i = 0;
1154 for (ObjCMethodDecl::param_const_iterator pi = MethodDecl->param_begin(),
1155 pe = MethodDecl->param_end(); pi != pe; ++pi, ++i) {
1156 const ParmVarDecl *pd = *pi;
1157 ArgEffect AE = AEArgs[i];
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001158 if (AE == DecRef && !pd->getAttr<CFConsumedAttr>() &&
1159 Ctx.Idents.get("CF_CONSUMED").hasMacroDefinition()) {
1160 edit::Commit commit(*Editor);
1161 commit.insertBefore(pd->getLocation(), "CF_CONSUMED ");
1162 Editor->commit(commit);
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001163 }
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001164 }
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001165}
1166
Fariborz Jahanian89f6d102013-09-04 00:10:06 +00001167void ObjCMigrateASTConsumer::migrateAddMethodAnnotation(
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001168 ASTContext &Ctx,
1169 const ObjCMethodDecl *MethodDecl) {
Fariborz Jahanian1a269272013-09-04 22:49:19 +00001170 if (MethodDecl->hasBody() || MethodDecl->isImplicit())
Fariborz Jahanian89f6d102013-09-04 00:10:06 +00001171 return;
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001172
1173 CallEffects CE = CallEffects::getEffect(MethodDecl);
1174 bool MethodIsReturnAnnotated = (MethodDecl->getAttr<CFReturnsRetainedAttr>() ||
Fariborz Jahanian1a269272013-09-04 22:49:19 +00001175 MethodDecl->getAttr<CFReturnsNotRetainedAttr>() ||
1176 MethodDecl->getAttr<NSReturnsRetainedAttr>() ||
Fariborz Jahanianc24879e2013-09-05 23:04:33 +00001177 MethodDecl->getAttr<NSReturnsNotRetainedAttr>() ||
1178 MethodDecl->getAttr<NSReturnsAutoreleasedAttr>());
1179
1180 if (CE.getReceiver() == DecRefMsg &&
1181 !MethodDecl->getAttr<NSConsumesSelfAttr>() &&
1182 MethodDecl->getMethodFamily() != OMF_init &&
1183 MethodDecl->getMethodFamily() != OMF_release &&
1184 Ctx.Idents.get("NS_CONSUMES_SELF").hasMacroDefinition()) {
1185 edit::Commit commit(*Editor);
1186 commit.insertBefore(MethodDecl->getLocEnd(), " NS_CONSUMES_SELF");
1187 Editor->commit(commit);
1188 }
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001189
1190 // Trivial case of when funciton is annotated and has no argument.
1191 if (MethodIsReturnAnnotated &&
1192 (MethodDecl->param_begin() == MethodDecl->param_end()))
Fariborz Jahanian89f6d102013-09-04 00:10:06 +00001193 return;
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001194
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001195 if (!MethodIsReturnAnnotated) {
1196 RetEffect Ret = CE.getReturnValue();
Fariborz Jahanian1a269272013-09-04 22:49:19 +00001197 if ((Ret.getObjKind() == RetEffect::CF ||
1198 Ret.getObjKind() == RetEffect::ObjC) &&
1199 (Ret.isOwned() || Ret.notOwned())) {
Fariborz Jahanian8b102302013-09-04 16:43:57 +00001200 AddCFAnnotations(Ctx, CE, MethodDecl, false);
1201 return;
1202 }
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001203 else if (!AuditedType(MethodDecl->getResultType()))
Fariborz Jahanian89f6d102013-09-04 00:10:06 +00001204 return;
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001205 }
1206
1207 // At this point result type is either annotated or audited.
1208 // Now, how about argument types.
1209 llvm::ArrayRef<ArgEffect> AEArgs = CE.getArgs();
1210 unsigned i = 0;
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001211 for (ObjCMethodDecl::param_const_iterator pi = MethodDecl->param_begin(),
1212 pe = MethodDecl->param_end(); pi != pe; ++pi, ++i) {
1213 const ParmVarDecl *pd = *pi;
1214 ArgEffect AE = AEArgs[i];
Fariborz Jahanian8b102302013-09-04 16:43:57 +00001215 if ((AE == DecRef && !pd->getAttr<CFConsumedAttr>()) || AE == IncRef ||
1216 !AuditedType(pd->getType())) {
1217 AddCFAnnotations(Ctx, CE, MethodDecl, MethodIsReturnAnnotated);
1218 return;
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001219 }
1220 }
Fariborz Jahanian89f6d102013-09-04 00:10:06 +00001221 return;
Fariborz Jahaniandfe6ed92013-08-12 23:17:13 +00001222}
1223
Ted Kremenekf7639e12012-03-06 20:06:33 +00001224namespace {
1225
1226class RewritesReceiver : public edit::EditsReceiver {
1227 Rewriter &Rewrite;
1228
1229public:
1230 RewritesReceiver(Rewriter &Rewrite) : Rewrite(Rewrite) { }
1231
1232 virtual void insert(SourceLocation loc, StringRef text) {
1233 Rewrite.InsertText(loc, text);
1234 }
1235 virtual void replace(CharSourceRange range, StringRef text) {
1236 Rewrite.ReplaceText(range.getBegin(), Rewrite.getRangeSize(range), text);
1237 }
1238};
1239
1240}
1241
1242void ObjCMigrateASTConsumer::HandleTranslationUnit(ASTContext &Ctx) {
Fariborz Jahaniana7437f02013-07-03 23:05:00 +00001243
1244 TranslationUnitDecl *TU = Ctx.getTranslationUnitDecl();
Fariborz Jahanian301b5212013-08-20 22:42:13 +00001245 if (MigrateProperty) {
Fariborz Jahaniand83ef842013-07-09 16:59:14 +00001246 for (DeclContext::decl_iterator D = TU->decls_begin(), DEnd = TU->decls_end();
1247 D != DEnd; ++D) {
Fariborz Jahanianb8343522013-08-20 23:35:26 +00001248 if (unsigned FID =
1249 PP.getSourceManager().getFileID((*D)->getLocation()).getHashValue())
Fariborz Jahanian75226d52013-09-17 21:56:04 +00001250 if (FileId && FileId != FID)
Fariborz Jahanianb8343522013-08-20 23:35:26 +00001251 AnnotateImplicitBridging(Ctx);
Fariborz Jahanianb8343522013-08-20 23:35:26 +00001252
Fariborz Jahaniand83ef842013-07-09 16:59:14 +00001253 if (ObjCInterfaceDecl *CDecl = dyn_cast<ObjCInterfaceDecl>(*D))
1254 migrateObjCInterfaceDecl(Ctx, CDecl);
Fariborz Jahanian92f72422013-09-17 19:00:30 +00001255 if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(*D))
1256 migrateObjCInterfaceDecl(Ctx, CatDecl);
Fariborz Jahanian1be01532013-07-12 22:32:19 +00001257 else if (ObjCProtocolDecl *PDecl = dyn_cast<ObjCProtocolDecl>(*D))
1258 ObjCProtocolDecls.insert(PDecl);
1259 else if (const ObjCImplementationDecl *ImpDecl =
1260 dyn_cast<ObjCImplementationDecl>(*D))
1261 migrateProtocolConformance(Ctx, ImpDecl);
Fariborz Jahanian92463272013-07-18 20:11:45 +00001262 else if (const EnumDecl *ED = dyn_cast<EnumDecl>(*D)) {
1263 DeclContext::decl_iterator N = D;
1264 ++N;
Fariborz Jahanian008ef722013-07-19 17:44:32 +00001265 if (N != DEnd)
1266 if (const TypedefDecl *TD = dyn_cast<TypedefDecl>(*N))
1267 migrateNSEnumDecl(Ctx, ED, TD);
Fariborz Jahanian92463272013-07-18 20:11:45 +00001268 }
Fariborz Jahanianc13c1b02013-08-13 18:01:42 +00001269 else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(*D))
Fariborz Jahanian4f64dd22013-08-22 21:40:15 +00001270 migrateCFAnnotation(Ctx, FD);
Fariborz Jahanianc13c1b02013-08-13 18:01:42 +00001271
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001272 if (ObjCContainerDecl *CDecl = dyn_cast<ObjCContainerDecl>(*D)) {
1273 // migrate methods which can have instancetype as their result type.
Fariborz Jahaniand0fbf6c2013-08-30 23:52:08 +00001274 migrateMethods(Ctx, CDecl);
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001275 // annotate methods with CF annotations.
1276 migrateARCSafeAnnotation(Ctx, CDecl);
1277 }
Fariborz Jahaniand83ef842013-07-09 16:59:14 +00001278 }
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001279 AnnotateImplicitBridging(Ctx);
Fariborz Jahanian301b5212013-08-20 22:42:13 +00001280 }
Fariborz Jahaniana7437f02013-07-03 23:05:00 +00001281
David Blaikiebbafb8a2012-03-11 07:00:24 +00001282 Rewriter rewriter(Ctx.getSourceManager(), Ctx.getLangOpts());
Ted Kremenekf7639e12012-03-06 20:06:33 +00001283 RewritesReceiver Rec(rewriter);
1284 Editor->applyRewrites(Rec);
1285
1286 for (Rewriter::buffer_iterator
1287 I = rewriter.buffer_begin(), E = rewriter.buffer_end(); I != E; ++I) {
1288 FileID FID = I->first;
1289 RewriteBuffer &buf = I->second;
1290 const FileEntry *file = Ctx.getSourceManager().getFileEntryForID(FID);
1291 assert(file);
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001292 SmallString<512> newText;
Ted Kremenekf7639e12012-03-06 20:06:33 +00001293 llvm::raw_svector_ostream vecOS(newText);
1294 buf.write(vecOS);
1295 vecOS.flush();
1296 llvm::MemoryBuffer *memBuf = llvm::MemoryBuffer::getMemBufferCopy(
1297 StringRef(newText.data(), newText.size()), file->getName());
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001298 SmallString<64> filePath(file->getName());
Ted Kremenekf7639e12012-03-06 20:06:33 +00001299 FileMgr.FixupRelativePath(filePath);
1300 Remapper.remap(filePath.str(), memBuf);
1301 }
1302
1303 if (IsOutputFile) {
1304 Remapper.flushToFile(MigrateDir, Ctx.getDiagnostics());
1305 } else {
1306 Remapper.flushToDisk(MigrateDir, Ctx.getDiagnostics());
1307 }
1308}
1309
1310bool MigrateSourceAction::BeginInvocation(CompilerInstance &CI) {
Argyrios Kyrtzidisb4822602012-05-24 16:48:23 +00001311 CI.getDiagnostics().setIgnoreAllWarnings(true);
Ted Kremenekf7639e12012-03-06 20:06:33 +00001312 return true;
1313}
1314
1315ASTConsumer *MigrateSourceAction::CreateASTConsumer(CompilerInstance &CI,
1316 StringRef InFile) {
Argyrios Kyrtzidisf3d587e2012-12-04 07:27:05 +00001317 PPConditionalDirectiveRecord *
1318 PPRec = new PPConditionalDirectiveRecord(CI.getSourceManager());
1319 CI.getPreprocessor().addPPCallbacks(PPRec);
Ted Kremenekf7639e12012-03-06 20:06:33 +00001320 return new ObjCMigrateASTConsumer(CI.getFrontendOpts().OutputFile,
1321 /*MigrateLiterals=*/true,
1322 /*MigrateSubscripting=*/true,
Fariborz Jahaniand83ef842013-07-09 16:59:14 +00001323 /*MigrateProperty*/true,
Fariborz Jahanian55d6e6c2013-08-28 23:22:46 +00001324 /*MigrateReadonlyProperty*/true,
Ted Kremenekf7639e12012-03-06 20:06:33 +00001325 Remapper,
1326 CI.getFileManager(),
Argyrios Kyrtzidisf3d587e2012-12-04 07:27:05 +00001327 PPRec,
Fariborz Jahaniana7437f02013-07-03 23:05:00 +00001328 CI.getPreprocessor(),
Ted Kremenekf7639e12012-03-06 20:06:33 +00001329 /*isOutputFile=*/true);
1330}