blob: 4fa4b1e6606bfba096b02a6f877beb7b3ea099e7 [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 Jahaniana7437f02013-07-03 23:05:00 +000046 void migrateObjCInterfaceDecl(ASTContext &Ctx, ObjCInterfaceDecl *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 Jahanian71221352013-07-23 22:42:28 +000051 void migrateInstanceType(ASTContext &Ctx, ObjCContainerDecl *CDecl);
Fariborz Jahanian670ef262013-07-23 23:34:42 +000052 void migrateMethodInstanceType(ASTContext &Ctx, ObjCContainerDecl *CDecl,
53 ObjCMethodDecl *OM);
Fariborz Jahanianc4291852013-08-02 18:00:53 +000054 void migrateFactoryMethod(ASTContext &Ctx, ObjCContainerDecl *CDecl,
Fariborz Jahanian9275c682013-08-02 20:54:18 +000055 ObjCMethodDecl *OM,
56 ObjCInstanceTypeFamily OIT_Family = OIT_None);
Fariborz Jahaniandfe6ed92013-08-12 23:17:13 +000057
Fariborz Jahanian4f64dd22013-08-22 21:40:15 +000058 void migrateCFAnnotation(ASTContext &Ctx, const Decl *Decl);
Fariborz Jahanian63ffce22013-08-27 22:42:30 +000059 void AddCFAnnotations(ASTContext &Ctx, const CallEffects &CE,
60 const FunctionDecl *FuncDecl);
61 void AddCFAnnotations(ASTContext &Ctx, const CallEffects &CE,
62 const ObjCMethodDecl *MethodDecl);
Fariborz Jahanian2ec4d7b2013-08-16 23:35:05 +000063
Fariborz Jahanian301b5212013-08-20 22:42:13 +000064 void AnnotateImplicitBridging(ASTContext &Ctx);
65
Fariborz Jahanian63ffce22013-08-27 22:42:30 +000066 CF_BRIDGING_KIND migrateAddFunctionAnnotation(ASTContext &Ctx,
67 const FunctionDecl *FuncDecl);
Fariborz Jahaniandfe6ed92013-08-12 23:17:13 +000068
Fariborz Jahanian926fafb2013-08-22 18:35:27 +000069 void migrateARCSafeAnnotation(ASTContext &Ctx, ObjCContainerDecl *CDecl);
70
Fariborz Jahanian63ffce22013-08-27 22:42:30 +000071 CF_BRIDGING_KIND migrateAddMethodAnnotation(ASTContext &Ctx,
72 const ObjCMethodDecl *MethodDecl);
Ted Kremenekf7639e12012-03-06 20:06:33 +000073public:
74 std::string MigrateDir;
75 bool MigrateLiterals;
76 bool MigrateSubscripting;
Fariborz Jahaniand83ef842013-07-09 16:59:14 +000077 bool MigrateProperty;
Fariborz Jahanianb8343522013-08-20 23:35:26 +000078 unsigned FileId;
Dmitri Gribenkof8579502013-01-12 19:30:44 +000079 OwningPtr<NSAPI> NSAPIObj;
80 OwningPtr<edit::EditedSource> Editor;
Ted Kremenekf7639e12012-03-06 20:06:33 +000081 FileRemapper &Remapper;
82 FileManager &FileMgr;
Argyrios Kyrtzidisf3d587e2012-12-04 07:27:05 +000083 const PPConditionalDirectiveRecord *PPRec;
Fariborz Jahaniana7437f02013-07-03 23:05:00 +000084 Preprocessor &PP;
Ted Kremenekf7639e12012-03-06 20:06:33 +000085 bool IsOutputFile;
Fariborz Jahanian1be01532013-07-12 22:32:19 +000086 llvm::SmallPtrSet<ObjCProtocolDecl *, 32> ObjCProtocolDecls;
Fariborz Jahanian926fafb2013-08-22 18:35:27 +000087 llvm::SmallVector<const Decl *, 8> CFFunctionIBCandidates;
Fariborz Jahanian1be01532013-07-12 22:32:19 +000088
Ted Kremenekf7639e12012-03-06 20:06:33 +000089 ObjCMigrateASTConsumer(StringRef migrateDir,
90 bool migrateLiterals,
91 bool migrateSubscripting,
Fariborz Jahaniand83ef842013-07-09 16:59:14 +000092 bool migrateProperty,
Ted Kremenekf7639e12012-03-06 20:06:33 +000093 FileRemapper &remapper,
94 FileManager &fileMgr,
Argyrios Kyrtzidisf3d587e2012-12-04 07:27:05 +000095 const PPConditionalDirectiveRecord *PPRec,
Fariborz Jahaniana7437f02013-07-03 23:05:00 +000096 Preprocessor &PP,
Ted Kremenekf7639e12012-03-06 20:06:33 +000097 bool isOutputFile = false)
98 : MigrateDir(migrateDir),
99 MigrateLiterals(migrateLiterals),
100 MigrateSubscripting(migrateSubscripting),
Fariborz Jahanianb8343522013-08-20 23:35:26 +0000101 MigrateProperty(migrateProperty), FileId(0),
Fariborz Jahaniana7437f02013-07-03 23:05:00 +0000102 Remapper(remapper), FileMgr(fileMgr), PPRec(PPRec), PP(PP),
Ted Kremenekf7639e12012-03-06 20:06:33 +0000103 IsOutputFile(isOutputFile) { }
104
105protected:
106 virtual void Initialize(ASTContext &Context) {
107 NSAPIObj.reset(new NSAPI(Context));
108 Editor.reset(new edit::EditedSource(Context.getSourceManager(),
David Blaikiebbafb8a2012-03-11 07:00:24 +0000109 Context.getLangOpts(),
Ted Kremenekf7639e12012-03-06 20:06:33 +0000110 PPRec));
111 }
112
113 virtual bool HandleTopLevelDecl(DeclGroupRef DG) {
114 for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I)
115 migrateDecl(*I);
116 return true;
117 }
118 virtual void HandleInterestingDecl(DeclGroupRef DG) {
119 // Ignore decls from the PCH.
120 }
121 virtual void HandleTopLevelDeclInObjCContainer(DeclGroupRef DG) {
122 ObjCMigrateASTConsumer::HandleTopLevelDecl(DG);
123 }
124
125 virtual void HandleTranslationUnit(ASTContext &Ctx);
126};
127
128}
129
130ObjCMigrateAction::ObjCMigrateAction(FrontendAction *WrappedAction,
131 StringRef migrateDir,
132 bool migrateLiterals,
Fariborz Jahaniand83ef842013-07-09 16:59:14 +0000133 bool migrateSubscripting,
134 bool migrateProperty)
Ted Kremenekf7639e12012-03-06 20:06:33 +0000135 : WrapperFrontendAction(WrappedAction), MigrateDir(migrateDir),
136 MigrateLiterals(migrateLiterals), MigrateSubscripting(migrateSubscripting),
Fariborz Jahaniand83ef842013-07-09 16:59:14 +0000137 MigrateProperty(migrateProperty),
Ted Kremenekf7639e12012-03-06 20:06:33 +0000138 CompInst(0) {
139 if (MigrateDir.empty())
140 MigrateDir = "."; // user current directory if none is given.
141}
142
143ASTConsumer *ObjCMigrateAction::CreateASTConsumer(CompilerInstance &CI,
144 StringRef InFile) {
Argyrios Kyrtzidisf3d587e2012-12-04 07:27:05 +0000145 PPConditionalDirectiveRecord *
146 PPRec = new PPConditionalDirectiveRecord(CompInst->getSourceManager());
147 CompInst->getPreprocessor().addPPCallbacks(PPRec);
Ted Kremenekf7639e12012-03-06 20:06:33 +0000148 ASTConsumer *
149 WrappedConsumer = WrapperFrontendAction::CreateASTConsumer(CI, InFile);
150 ASTConsumer *MTConsumer = new ObjCMigrateASTConsumer(MigrateDir,
151 MigrateLiterals,
152 MigrateSubscripting,
Fariborz Jahaniand83ef842013-07-09 16:59:14 +0000153 MigrateProperty,
Ted Kremenekf7639e12012-03-06 20:06:33 +0000154 Remapper,
155 CompInst->getFileManager(),
Fariborz Jahaniana7437f02013-07-03 23:05:00 +0000156 PPRec,
157 CompInst->getPreprocessor());
Ted Kremenekf7639e12012-03-06 20:06:33 +0000158 ASTConsumer *Consumers[] = { MTConsumer, WrappedConsumer };
159 return new MultiplexConsumer(Consumers);
160}
161
162bool ObjCMigrateAction::BeginInvocation(CompilerInstance &CI) {
163 Remapper.initFromDisk(MigrateDir, CI.getDiagnostics(),
164 /*ignoreIfFilesChanges=*/true);
165 CompInst = &CI;
166 CI.getDiagnostics().setIgnoreAllWarnings(true);
Ted Kremenekf7639e12012-03-06 20:06:33 +0000167 return true;
168}
169
170namespace {
171class ObjCMigrator : public RecursiveASTVisitor<ObjCMigrator> {
172 ObjCMigrateASTConsumer &Consumer;
Argyrios Kyrtzidis6b4f3412013-01-16 23:54:48 +0000173 ParentMap &PMap;
Ted Kremenekf7639e12012-03-06 20:06:33 +0000174
175public:
Argyrios Kyrtzidis6b4f3412013-01-16 23:54:48 +0000176 ObjCMigrator(ObjCMigrateASTConsumer &consumer, ParentMap &PMap)
177 : Consumer(consumer), PMap(PMap) { }
Ted Kremenekf7639e12012-03-06 20:06:33 +0000178
179 bool shouldVisitTemplateInstantiations() const { return false; }
180 bool shouldWalkTypesOfTypeLocs() const { return false; }
181
182 bool VisitObjCMessageExpr(ObjCMessageExpr *E) {
183 if (Consumer.MigrateLiterals) {
184 edit::Commit commit(*Consumer.Editor);
Argyrios Kyrtzidis6b4f3412013-01-16 23:54:48 +0000185 edit::rewriteToObjCLiteralSyntax(E, *Consumer.NSAPIObj, commit, &PMap);
Ted Kremenekf7639e12012-03-06 20:06:33 +0000186 Consumer.Editor->commit(commit);
187 }
188
189 if (Consumer.MigrateSubscripting) {
190 edit::Commit commit(*Consumer.Editor);
191 edit::rewriteToObjCSubscriptSyntax(E, *Consumer.NSAPIObj, commit);
192 Consumer.Editor->commit(commit);
193 }
194
195 return true;
196 }
197
198 bool TraverseObjCMessageExpr(ObjCMessageExpr *E) {
199 // Do depth first; we want to rewrite the subexpressions first so that if
200 // we have to move expressions we will move them already rewritten.
201 for (Stmt::child_range range = E->children(); range; ++range)
202 if (!TraverseStmt(*range))
203 return false;
204
205 return WalkUpFromObjCMessageExpr(E);
206 }
207};
Argyrios Kyrtzidis6b4f3412013-01-16 23:54:48 +0000208
209class BodyMigrator : public RecursiveASTVisitor<BodyMigrator> {
210 ObjCMigrateASTConsumer &Consumer;
211 OwningPtr<ParentMap> PMap;
212
213public:
214 BodyMigrator(ObjCMigrateASTConsumer &consumer) : Consumer(consumer) { }
215
216 bool shouldVisitTemplateInstantiations() const { return false; }
217 bool shouldWalkTypesOfTypeLocs() const { return false; }
218
219 bool TraverseStmt(Stmt *S) {
220 PMap.reset(new ParentMap(S));
221 ObjCMigrator(Consumer, *PMap).TraverseStmt(S);
222 return true;
223 }
224};
Ted Kremenekf7639e12012-03-06 20:06:33 +0000225}
226
227void ObjCMigrateASTConsumer::migrateDecl(Decl *D) {
228 if (!D)
229 return;
230 if (isa<ObjCMethodDecl>(D))
231 return; // Wait for the ObjC container declaration.
232
Argyrios Kyrtzidis6b4f3412013-01-16 23:54:48 +0000233 BodyMigrator(*this).TraverseDecl(D);
Ted Kremenekf7639e12012-03-06 20:06:33 +0000234}
235
Fariborz Jahanian447b15e2013-08-21 18:49:03 +0000236static void append_attr(std::string &PropertyString, const char *attr) {
237 PropertyString += ", ";
Fariborz Jahaniancf2ff9b2013-08-08 20:51:58 +0000238 PropertyString += attr;
Fariborz Jahaniancf2ff9b2013-08-08 20:51:58 +0000239}
240
Fariborz Jahanian85e988b2013-07-18 22:17:33 +0000241static bool rewriteToObjCProperty(const ObjCMethodDecl *Getter,
242 const ObjCMethodDecl *Setter,
Fariborz Jahaniancf2ff9b2013-08-08 20:51:58 +0000243 const NSAPI &NS, edit::Commit &commit,
244 bool GetterHasIsPrefix) {
Fariborz Jahanian85e988b2013-07-18 22:17:33 +0000245 ASTContext &Context = NS.getASTContext();
Fariborz Jahanian447b15e2013-08-21 18:49:03 +0000246 std::string PropertyString = "@property(nonatomic";
Fariborz Jahaniancf387c62013-08-06 18:06:23 +0000247 std::string PropertyNameString = Getter->getNameAsString();
248 StringRef PropertyName(PropertyNameString);
Fariborz Jahaniancf2ff9b2013-08-08 20:51:58 +0000249 if (GetterHasIsPrefix) {
Fariborz Jahanian447b15e2013-08-21 18:49:03 +0000250 PropertyString += ", getter=";
Fariborz Jahaniancf2ff9b2013-08-08 20:51:58 +0000251 PropertyString += PropertyNameString;
252 }
Fariborz Jahaniancf387c62013-08-06 18:06:23 +0000253 // Short circuit properties that contain the name "delegate" or "dataSource",
254 // or have exact name "target" to have unsafe_unretained attribute.
255 if (PropertyName.equals("target") ||
256 (PropertyName.find("delegate") != StringRef::npos) ||
257 (PropertyName.find("dataSource") != StringRef::npos))
Fariborz Jahanian447b15e2013-08-21 18:49:03 +0000258 append_attr(PropertyString, "unsafe_unretained");
Fariborz Jahaniancf387c62013-08-06 18:06:23 +0000259 else {
260 const ParmVarDecl *argDecl = *Setter->param_begin();
261 QualType ArgType = Context.getCanonicalType(argDecl->getType());
262 Qualifiers::ObjCLifetime propertyLifetime = ArgType.getObjCLifetime();
263 bool RetainableObject = ArgType->isObjCRetainableType();
264 if (RetainableObject && propertyLifetime == Qualifiers::OCL_Strong) {
265 if (const ObjCObjectPointerType *ObjPtrTy =
266 ArgType->getAs<ObjCObjectPointerType>()) {
267 ObjCInterfaceDecl *IDecl = ObjPtrTy->getObjectType()->getInterface();
268 if (IDecl &&
269 IDecl->lookupNestedProtocol(&Context.Idents.get("NSCopying")))
Fariborz Jahanian447b15e2013-08-21 18:49:03 +0000270 append_attr(PropertyString, "copy");
Fariborz Jahaniancf387c62013-08-06 18:06:23 +0000271 else
Fariborz Jahanian447b15e2013-08-21 18:49:03 +0000272 append_attr(PropertyString, "retain");
273 }
Fariborz Jahaniancf387c62013-08-06 18:06:23 +0000274 } else if (propertyLifetime == Qualifiers::OCL_Weak)
275 // TODO. More precise determination of 'weak' attribute requires
276 // looking into setter's implementation for backing weak ivar.
Fariborz Jahanian447b15e2013-08-21 18:49:03 +0000277 append_attr(PropertyString, "weak");
Fariborz Jahaniancf387c62013-08-06 18:06:23 +0000278 else if (RetainableObject)
Fariborz Jahanian447b15e2013-08-21 18:49:03 +0000279 append_attr(PropertyString, "retain");
Fariborz Jahaniancf387c62013-08-06 18:06:23 +0000280 }
Fariborz Jahanian447b15e2013-08-21 18:49:03 +0000281 PropertyString += ')';
Fariborz Jahanian85e988b2013-07-18 22:17:33 +0000282
Fariborz Jahaniancf2ff9b2013-08-08 20:51:58 +0000283 QualType RT = Getter->getResultType();
284 if (!isa<TypedefType>(RT)) {
285 // strip off any ARC lifetime qualifier.
286 QualType CanResultTy = Context.getCanonicalType(RT);
287 if (CanResultTy.getQualifiers().hasObjCLifetime()) {
288 Qualifiers Qs = CanResultTy.getQualifiers();
289 Qs.removeObjCLifetime();
290 RT = Context.getQualifiedType(CanResultTy.getUnqualifiedType(), Qs);
291 }
Fariborz Jahanian85e988b2013-07-18 22:17:33 +0000292 }
293 PropertyString += " ";
Fariborz Jahaniancf2ff9b2013-08-08 20:51:58 +0000294 PropertyString += RT.getAsString(Context.getPrintingPolicy());
Fariborz Jahanian85e988b2013-07-18 22:17:33 +0000295 PropertyString += " ";
Fariborz Jahaniancf2ff9b2013-08-08 20:51:58 +0000296 if (GetterHasIsPrefix) {
297 // property name must strip off "is" and lower case the first character
298 // after that; e.g. isContinuous will become continuous.
299 StringRef PropertyNameStringRef(PropertyNameString);
300 PropertyNameStringRef = PropertyNameStringRef.drop_front(2);
301 PropertyNameString = PropertyNameStringRef;
302 std::string NewPropertyNameString = PropertyNameString;
Fariborz Jahaniandb8bf832013-08-08 21:51:06 +0000303 NewPropertyNameString[0] = toLowercase(NewPropertyNameString[0]);
Fariborz Jahaniancf2ff9b2013-08-08 20:51:58 +0000304 PropertyString += NewPropertyNameString;
305 }
306 else
307 PropertyString += PropertyNameString;
Fariborz Jahanian85e988b2013-07-18 22:17:33 +0000308 commit.replace(CharSourceRange::getCharRange(Getter->getLocStart(),
309 Getter->getDeclaratorEndLoc()),
310 PropertyString);
311 SourceLocation EndLoc = Setter->getDeclaratorEndLoc();
312 // Get location past ';'
313 EndLoc = EndLoc.getLocWithOffset(1);
314 commit.remove(CharSourceRange::getCharRange(Setter->getLocStart(), EndLoc));
315 return true;
316}
317
Fariborz Jahaniana7437f02013-07-03 23:05:00 +0000318void ObjCMigrateASTConsumer::migrateObjCInterfaceDecl(ASTContext &Ctx,
319 ObjCInterfaceDecl *D) {
320 for (ObjCContainerDecl::method_iterator M = D->meth_begin(), MEnd = D->meth_end();
321 M != MEnd; ++M) {
322 ObjCMethodDecl *Method = (*M);
Fariborz Jahaniande661002013-07-03 23:44:11 +0000323 if (Method->isPropertyAccessor() || Method->param_size() != 0)
Fariborz Jahaniana7437f02013-07-03 23:05:00 +0000324 continue;
325 // Is this method candidate to be a getter?
Fariborz Jahaniande661002013-07-03 23:44:11 +0000326 QualType GRT = Method->getResultType();
327 if (GRT->isVoidType())
328 continue;
Fariborz Jahanian7ac20e12013-07-08 22:49:25 +0000329 // FIXME. Don't know what todo with attributes, skip for now.
330 if (Method->hasAttrs())
331 continue;
332
Fariborz Jahaniande661002013-07-03 23:44:11 +0000333 Selector GetterSelector = Method->getSelector();
334 IdentifierInfo *getterName = GetterSelector.getIdentifierInfoForSlot(0);
335 Selector SetterSelector =
336 SelectorTable::constructSetterSelector(PP.getIdentifierTable(),
337 PP.getSelectorTable(),
338 getterName);
Fariborz Jahaniancf2ff9b2013-08-08 20:51:58 +0000339 ObjCMethodDecl *SetterMethod = D->lookupMethod(SetterSelector, true);
340 bool GetterHasIsPrefix = false;
341 if (!SetterMethod) {
342 // try a different naming convention for getter: isXxxxx
343 StringRef getterNameString = getterName->getName();
Fariborz Jahanian261fdb72013-08-08 21:20:01 +0000344 if (getterNameString.startswith("is") && !GRT->isObjCRetainableType()) {
Fariborz Jahaniancf2ff9b2013-08-08 20:51:58 +0000345 GetterHasIsPrefix = true;
346 const char *CGetterName = getterNameString.data() + 2;
Fariborz Jahanian261fdb72013-08-08 21:20:01 +0000347 if (CGetterName[0] && isUppercase(CGetterName[0])) {
Fariborz Jahaniancf2ff9b2013-08-08 20:51:58 +0000348 getterName = &Ctx.Idents.get(CGetterName);
349 SetterSelector =
350 SelectorTable::constructSetterSelector(PP.getIdentifierTable(),
351 PP.getSelectorTable(),
352 getterName);
353 SetterMethod = D->lookupMethod(SetterSelector, true);
354 }
355 }
356 }
357 if (SetterMethod) {
Fariborz Jahaniande661002013-07-03 23:44:11 +0000358 // Is this a valid setter, matching the target getter?
359 QualType SRT = SetterMethod->getResultType();
360 if (!SRT->isVoidType())
Fariborz Jahaniana7437f02013-07-03 23:05:00 +0000361 continue;
Fariborz Jahaniande661002013-07-03 23:44:11 +0000362 const ParmVarDecl *argDecl = *SetterMethod->param_begin();
Fariborz Jahanian43bbaac2013-07-04 00:24:32 +0000363 QualType ArgType = argDecl->getType();
Fariborz Jahanian7ac20e12013-07-08 22:49:25 +0000364 if (!Ctx.hasSameUnqualifiedType(ArgType, GRT) ||
365 SetterMethod->hasAttrs())
Fariborz Jahanian43bbaac2013-07-04 00:24:32 +0000366 continue;
Fariborz Jahanian266926d2013-07-05 20:46:03 +0000367 edit::Commit commit(*Editor);
Fariborz Jahaniancf2ff9b2013-08-08 20:51:58 +0000368 rewriteToObjCProperty(Method, SetterMethod, *NSAPIObj, commit,
369 GetterHasIsPrefix);
Fariborz Jahanian266926d2013-07-05 20:46:03 +0000370 Editor->commit(commit);
Fariborz Jahaniana7437f02013-07-03 23:05:00 +0000371 }
Fariborz Jahaniana7437f02013-07-03 23:05:00 +0000372 }
373}
374
Fariborz Jahanian9eabf452013-07-13 00:04:20 +0000375static bool
Fariborz Jahanian9a3512b2013-07-13 17:16:41 +0000376ClassImplementsAllMethodsAndProperties(ASTContext &Ctx,
Fariborz Jahanian9eabf452013-07-13 00:04:20 +0000377 const ObjCImplementationDecl *ImpDecl,
Fariborz Jahaniand36150d2013-07-15 21:22:08 +0000378 const ObjCInterfaceDecl *IDecl,
Fariborz Jahanian9eabf452013-07-13 00:04:20 +0000379 ObjCProtocolDecl *Protocol) {
Fariborz Jahaniand36150d2013-07-15 21:22:08 +0000380 // In auto-synthesis, protocol properties are not synthesized. So,
381 // a conforming protocol must have its required properties declared
382 // in class interface.
Fariborz Jahanian9e543af2013-07-22 23:50:04 +0000383 bool HasAtleastOneRequiredProperty = false;
Fariborz Jahaniand36150d2013-07-15 21:22:08 +0000384 if (const ObjCProtocolDecl *PDecl = Protocol->getDefinition())
385 for (ObjCProtocolDecl::prop_iterator P = PDecl->prop_begin(),
386 E = PDecl->prop_end(); P != E; ++P) {
387 ObjCPropertyDecl *Property = *P;
388 if (Property->getPropertyImplementation() == ObjCPropertyDecl::Optional)
389 continue;
Fariborz Jahanian9e543af2013-07-22 23:50:04 +0000390 HasAtleastOneRequiredProperty = true;
Fariborz Jahaniand36150d2013-07-15 21:22:08 +0000391 DeclContext::lookup_const_result R = IDecl->lookup(Property->getDeclName());
Fariborz Jahanian2bc3dda2013-07-16 21:59:42 +0000392 if (R.size() == 0) {
393 // Relax the rule and look into class's implementation for a synthesize
394 // or dynamic declaration. Class is implementing a property coming from
395 // another protocol. This still makes the target protocol as conforming.
396 if (!ImpDecl->FindPropertyImplDecl(
397 Property->getDeclName().getAsIdentifierInfo()))
398 return false;
Fariborz Jahaniand36150d2013-07-15 21:22:08 +0000399 }
Fariborz Jahanian2bc3dda2013-07-16 21:59:42 +0000400 else if (ObjCPropertyDecl *ClassProperty = dyn_cast<ObjCPropertyDecl>(R[0])) {
401 if ((ClassProperty->getPropertyAttributes()
402 != Property->getPropertyAttributes()) ||
403 !Ctx.hasSameType(ClassProperty->getType(), Property->getType()))
404 return false;
405 }
406 else
407 return false;
Fariborz Jahaniand36150d2013-07-15 21:22:08 +0000408 }
Fariborz Jahanian9e543af2013-07-22 23:50:04 +0000409
Fariborz Jahaniand36150d2013-07-15 21:22:08 +0000410 // At this point, all required properties in this protocol conform to those
411 // declared in the class.
412 // Check that class implements the required methods of the protocol too.
Fariborz Jahanian9e543af2013-07-22 23:50:04 +0000413 bool HasAtleastOneRequiredMethod = false;
Fariborz Jahanian5bd5aff2013-07-16 00:20:21 +0000414 if (const ObjCProtocolDecl *PDecl = Protocol->getDefinition()) {
415 if (PDecl->meth_begin() == PDecl->meth_end())
Fariborz Jahanian9e543af2013-07-22 23:50:04 +0000416 return HasAtleastOneRequiredProperty;
Fariborz Jahaniand36150d2013-07-15 21:22:08 +0000417 for (ObjCContainerDecl::method_iterator M = PDecl->meth_begin(),
418 MEnd = PDecl->meth_end(); M != MEnd; ++M) {
419 ObjCMethodDecl *MD = (*M);
Fariborz Jahanian5bd5aff2013-07-16 00:20:21 +0000420 if (MD->isImplicit())
421 continue;
Fariborz Jahaniand36150d2013-07-15 21:22:08 +0000422 if (MD->getImplementationControl() == ObjCMethodDecl::Optional)
423 continue;
Fariborz Jahaniand36150d2013-07-15 21:22:08 +0000424 DeclContext::lookup_const_result R = ImpDecl->lookup(MD->getDeclName());
Fariborz Jahanian5bd5aff2013-07-16 00:20:21 +0000425 if (R.size() == 0)
426 return false;
Fariborz Jahanian9e543af2013-07-22 23:50:04 +0000427 bool match = false;
428 HasAtleastOneRequiredMethod = true;
Fariborz Jahaniand36150d2013-07-15 21:22:08 +0000429 for (unsigned I = 0, N = R.size(); I != N; ++I)
430 if (ObjCMethodDecl *ImpMD = dyn_cast<ObjCMethodDecl>(R[0]))
431 if (Ctx.ObjCMethodsAreEqual(MD, ImpMD)) {
432 match = true;
433 break;
434 }
435 if (!match)
436 return false;
437 }
Fariborz Jahanian5bd5aff2013-07-16 00:20:21 +0000438 }
Fariborz Jahanian9e543af2013-07-22 23:50:04 +0000439 if (HasAtleastOneRequiredProperty || HasAtleastOneRequiredMethod)
440 return true;
441 return false;
Fariborz Jahanian9eabf452013-07-13 00:04:20 +0000442}
443
Fariborz Jahanian85e988b2013-07-18 22:17:33 +0000444static bool rewriteToObjCInterfaceDecl(const ObjCInterfaceDecl *IDecl,
445 llvm::SmallVectorImpl<ObjCProtocolDecl*> &ConformingProtocols,
446 const NSAPI &NS, edit::Commit &commit) {
447 const ObjCList<ObjCProtocolDecl> &Protocols = IDecl->getReferencedProtocols();
448 std::string ClassString;
449 SourceLocation EndLoc =
450 IDecl->getSuperClass() ? IDecl->getSuperClassLoc() : IDecl->getLocation();
451
452 if (Protocols.empty()) {
453 ClassString = '<';
454 for (unsigned i = 0, e = ConformingProtocols.size(); i != e; i++) {
455 ClassString += ConformingProtocols[i]->getNameAsString();
456 if (i != (e-1))
457 ClassString += ", ";
458 }
459 ClassString += "> ";
460 }
461 else {
462 ClassString = ", ";
463 for (unsigned i = 0, e = ConformingProtocols.size(); i != e; i++) {
464 ClassString += ConformingProtocols[i]->getNameAsString();
465 if (i != (e-1))
466 ClassString += ", ";
467 }
468 ObjCInterfaceDecl::protocol_loc_iterator PL = IDecl->protocol_loc_end() - 1;
469 EndLoc = *PL;
470 }
471
472 commit.insertAfterToken(EndLoc, ClassString);
473 return true;
474}
475
476static bool rewriteToNSEnumDecl(const EnumDecl *EnumDcl,
477 const TypedefDecl *TypedefDcl,
Fariborz Jahanianb0057bb2013-07-19 01:05:49 +0000478 const NSAPI &NS, edit::Commit &commit,
479 bool IsNSIntegerType) {
Fariborz Jahanianc1c44f62013-07-19 20:18:36 +0000480 std::string ClassString =
Fariborz Jahanianb0057bb2013-07-19 01:05:49 +0000481 IsNSIntegerType ? "typedef NS_ENUM(NSInteger, " : "typedef NS_OPTIONS(NSUInteger, ";
Fariborz Jahanian85e988b2013-07-18 22:17:33 +0000482 ClassString += TypedefDcl->getIdentifier()->getName();
483 ClassString += ')';
484 SourceRange R(EnumDcl->getLocStart(), EnumDcl->getLocStart());
485 commit.replace(R, ClassString);
486 SourceLocation EndOfTypedefLoc = TypedefDcl->getLocEnd();
487 EndOfTypedefLoc = trans::findLocationAfterSemi(EndOfTypedefLoc, NS.getASTContext());
488 if (!EndOfTypedefLoc.isInvalid()) {
489 commit.remove(SourceRange(TypedefDcl->getLocStart(), EndOfTypedefLoc));
490 return true;
491 }
492 return false;
493}
494
Fariborz Jahaniand0f6f792013-07-22 18:53:45 +0000495static bool rewriteToNSMacroDecl(const EnumDecl *EnumDcl,
Fariborz Jahanianc1c44f62013-07-19 20:18:36 +0000496 const TypedefDecl *TypedefDcl,
Fariborz Jahaniand0f6f792013-07-22 18:53:45 +0000497 const NSAPI &NS, edit::Commit &commit,
498 bool IsNSIntegerType) {
499 std::string ClassString =
500 IsNSIntegerType ? "NS_ENUM(NSInteger, " : "NS_OPTIONS(NSUInteger, ";
Fariborz Jahanianc1c44f62013-07-19 20:18:36 +0000501 ClassString += TypedefDcl->getIdentifier()->getName();
502 ClassString += ')';
503 SourceRange R(EnumDcl->getLocStart(), EnumDcl->getLocStart());
504 commit.replace(R, ClassString);
505 SourceLocation TypedefLoc = TypedefDcl->getLocEnd();
506 commit.remove(SourceRange(TypedefLoc, TypedefLoc));
507 return true;
508}
509
Fariborz Jahaniand0f6f792013-07-22 18:53:45 +0000510static bool UseNSOptionsMacro(ASTContext &Ctx,
511 const EnumDecl *EnumDcl) {
512 bool PowerOfTwo = true;
Fariborz Jahanianbe7bc112013-08-15 18:46:37 +0000513 uint64_t MaxPowerOfTwoVal = 0;
Fariborz Jahaniand0f6f792013-07-22 18:53:45 +0000514 for (EnumDecl::enumerator_iterator EI = EnumDcl->enumerator_begin(),
515 EE = EnumDcl->enumerator_end(); EI != EE; ++EI) {
516 EnumConstantDecl *Enumerator = (*EI);
517 const Expr *InitExpr = Enumerator->getInitExpr();
518 if (!InitExpr) {
519 PowerOfTwo = false;
520 continue;
521 }
522 InitExpr = InitExpr->IgnoreImpCasts();
523 if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr))
524 if (BO->isShiftOp() || BO->isBitwiseOp())
525 return true;
526
527 uint64_t EnumVal = Enumerator->getInitVal().getZExtValue();
Fariborz Jahanianbe7bc112013-08-15 18:46:37 +0000528 if (PowerOfTwo && EnumVal) {
529 if (!llvm::isPowerOf2_64(EnumVal))
530 PowerOfTwo = false;
531 else if (EnumVal > MaxPowerOfTwoVal)
532 MaxPowerOfTwoVal = EnumVal;
533 }
Fariborz Jahaniand0f6f792013-07-22 18:53:45 +0000534 }
Fariborz Jahanian0b48e7c2013-08-15 18:58:00 +0000535 return PowerOfTwo && (MaxPowerOfTwoVal > 2);
Fariborz Jahaniand0f6f792013-07-22 18:53:45 +0000536}
537
Fariborz Jahanian008ef722013-07-19 17:44:32 +0000538void ObjCMigrateASTConsumer::migrateProtocolConformance(ASTContext &Ctx,
Fariborz Jahanian1be01532013-07-12 22:32:19 +0000539 const ObjCImplementationDecl *ImpDecl) {
540 const ObjCInterfaceDecl *IDecl = ImpDecl->getClassInterface();
541 if (!IDecl || ObjCProtocolDecls.empty())
542 return;
543 // Find all implicit conforming protocols for this class
544 // and make them explicit.
545 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> ExplicitProtocols;
546 Ctx.CollectInheritedProtocols(IDecl, ExplicitProtocols);
Fariborz Jahanian9eabf452013-07-13 00:04:20 +0000547 llvm::SmallVector<ObjCProtocolDecl *, 8> PotentialImplicitProtocols;
Fariborz Jahanian1be01532013-07-12 22:32:19 +0000548
Fariborz Jahanian9eabf452013-07-13 00:04:20 +0000549 for (llvm::SmallPtrSet<ObjCProtocolDecl*, 32>::iterator I =
Fariborz Jahanian1be01532013-07-12 22:32:19 +0000550 ObjCProtocolDecls.begin(),
551 E = ObjCProtocolDecls.end(); I != E; ++I)
552 if (!ExplicitProtocols.count(*I))
Fariborz Jahanian9eabf452013-07-13 00:04:20 +0000553 PotentialImplicitProtocols.push_back(*I);
Fariborz Jahanian1be01532013-07-12 22:32:19 +0000554
555 if (PotentialImplicitProtocols.empty())
556 return;
Fariborz Jahanian9eabf452013-07-13 00:04:20 +0000557
558 // go through list of non-optional methods and properties in each protocol
559 // in the PotentialImplicitProtocols list. If class implements every one of the
560 // methods and properties, then this class conforms to this protocol.
561 llvm::SmallVector<ObjCProtocolDecl*, 8> ConformingProtocols;
562 for (unsigned i = 0, e = PotentialImplicitProtocols.size(); i != e; i++)
Fariborz Jahaniand36150d2013-07-15 21:22:08 +0000563 if (ClassImplementsAllMethodsAndProperties(Ctx, ImpDecl, IDecl,
Fariborz Jahanian9eabf452013-07-13 00:04:20 +0000564 PotentialImplicitProtocols[i]))
565 ConformingProtocols.push_back(PotentialImplicitProtocols[i]);
Fariborz Jahanian5bd5aff2013-07-16 00:20:21 +0000566
567 if (ConformingProtocols.empty())
568 return;
Fariborz Jahaniancb7b8de2013-07-17 00:02:22 +0000569
570 // Further reduce number of conforming protocols. If protocol P1 is in the list
571 // protocol P2 (P2<P1>), No need to include P1.
572 llvm::SmallVector<ObjCProtocolDecl*, 8> MinimalConformingProtocols;
573 for (unsigned i = 0, e = ConformingProtocols.size(); i != e; i++) {
574 bool DropIt = false;
575 ObjCProtocolDecl *TargetPDecl = ConformingProtocols[i];
576 for (unsigned i1 = 0, e1 = ConformingProtocols.size(); i1 != e1; i1++) {
577 ObjCProtocolDecl *PDecl = ConformingProtocols[i1];
578 if (PDecl == TargetPDecl)
579 continue;
580 if (PDecl->lookupProtocolNamed(
581 TargetPDecl->getDeclName().getAsIdentifierInfo())) {
582 DropIt = true;
583 break;
584 }
585 }
586 if (!DropIt)
587 MinimalConformingProtocols.push_back(TargetPDecl);
588 }
Fariborz Jahanian5bd5aff2013-07-16 00:20:21 +0000589 edit::Commit commit(*Editor);
Fariborz Jahanian85e988b2013-07-18 22:17:33 +0000590 rewriteToObjCInterfaceDecl(IDecl, MinimalConformingProtocols,
591 *NSAPIObj, commit);
Fariborz Jahanian5bd5aff2013-07-16 00:20:21 +0000592 Editor->commit(commit);
Fariborz Jahanian1be01532013-07-12 22:32:19 +0000593}
594
Fariborz Jahanian92463272013-07-18 20:11:45 +0000595void ObjCMigrateASTConsumer::migrateNSEnumDecl(ASTContext &Ctx,
596 const EnumDecl *EnumDcl,
597 const TypedefDecl *TypedefDcl) {
598 if (!EnumDcl->isCompleteDefinition() || EnumDcl->getIdentifier() ||
599 !TypedefDcl->getIdentifier())
600 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 Jahaniand0f6f792013-07-22 18:53:45 +0000610 bool NSOptions = UseNSOptionsMacro(Ctx, EnumDcl);
611 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 }
624 if (IsNSIntegerType && UseNSOptionsMacro(Ctx, EnumDcl)) {
625 // We may still use NS_OPTIONS based on what we find in the enumertor list.
626 IsNSIntegerType = false;
627 IsNSUIntegerType = true;
Fariborz Jahanianc1c44f62013-07-19 20:18:36 +0000628 }
Fariborz Jahanian92463272013-07-18 20:11:45 +0000629
630 // NS_ENUM must be available.
Fariborz Jahanianb0057bb2013-07-19 01:05:49 +0000631 if (IsNSIntegerType && !Ctx.Idents.get("NS_ENUM").hasMacroDefinition())
632 return;
633 // NS_OPTIONS must be available.
634 if (IsNSUIntegerType && !Ctx.Idents.get("NS_OPTIONS").hasMacroDefinition())
Fariborz Jahanian92463272013-07-18 20:11:45 +0000635 return;
636 edit::Commit commit(*Editor);
Fariborz Jahanianb0057bb2013-07-19 01:05:49 +0000637 rewriteToNSEnumDecl(EnumDcl, TypedefDcl, *NSAPIObj, commit, IsNSIntegerType);
Fariborz Jahanian92463272013-07-18 20:11:45 +0000638 Editor->commit(commit);
639}
640
Fariborz Jahanianc4291852013-08-02 18:00:53 +0000641static void ReplaceWithInstancetype(const ObjCMigrateASTConsumer &ASTC,
642 ObjCMethodDecl *OM) {
643 SourceRange R;
644 std::string ClassString;
645 if (TypeSourceInfo *TSInfo = OM->getResultTypeSourceInfo()) {
646 TypeLoc TL = TSInfo->getTypeLoc();
647 R = SourceRange(TL.getBeginLoc(), TL.getEndLoc());
648 ClassString = "instancetype";
649 }
650 else {
651 R = SourceRange(OM->getLocStart(), OM->getLocStart());
652 ClassString = OM->isInstanceMethod() ? '-' : '+';
653 ClassString += " (instancetype)";
654 }
655 edit::Commit commit(*ASTC.Editor);
656 commit.replace(R, ClassString);
657 ASTC.Editor->commit(commit);
658}
659
Fariborz Jahanian670ef262013-07-23 23:34:42 +0000660void ObjCMigrateASTConsumer::migrateMethodInstanceType(ASTContext &Ctx,
661 ObjCContainerDecl *CDecl,
662 ObjCMethodDecl *OM) {
Fariborz Jahanian71221352013-07-23 22:42:28 +0000663 ObjCInstanceTypeFamily OIT_Family =
664 Selector::getInstTypeMethodFamily(OM->getSelector());
Fariborz Jahanian9275c682013-08-02 20:54:18 +0000665
Fariborz Jahanian267bae32013-07-24 19:18:37 +0000666 std::string ClassName;
Fariborz Jahanian631925f2013-07-23 23:55:55 +0000667 switch (OIT_Family) {
Fariborz Jahanian9275c682013-08-02 20:54:18 +0000668 case OIT_None:
669 migrateFactoryMethod(Ctx, CDecl, OM);
670 return;
Fariborz Jahanian631925f2013-07-23 23:55:55 +0000671 case OIT_Array:
Fariborz Jahanian267bae32013-07-24 19:18:37 +0000672 ClassName = "NSArray";
Fariborz Jahanian631925f2013-07-23 23:55:55 +0000673 break;
674 case OIT_Dictionary:
Fariborz Jahanian267bae32013-07-24 19:18:37 +0000675 ClassName = "NSDictionary";
676 break;
677 case OIT_MemManage:
678 ClassName = "NSObject";
Fariborz Jahanian631925f2013-07-23 23:55:55 +0000679 break;
Fariborz Jahanian9275c682013-08-02 20:54:18 +0000680 case OIT_Singleton:
681 migrateFactoryMethod(Ctx, CDecl, OM, OIT_Singleton);
Fariborz Jahanian631925f2013-07-23 23:55:55 +0000682 return;
683 }
Fariborz Jahanian71221352013-07-23 22:42:28 +0000684 if (!OM->getResultType()->isObjCIdType())
685 return;
686
687 ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(CDecl);
688 if (!IDecl) {
689 if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(CDecl))
690 IDecl = CatDecl->getClassInterface();
691 else if (ObjCImplDecl *ImpDecl = dyn_cast<ObjCImplDecl>(CDecl))
692 IDecl = ImpDecl->getClassInterface();
693 }
Fariborz Jahanian267bae32013-07-24 19:18:37 +0000694 if (!IDecl ||
Fariborz Jahanianc4291852013-08-02 18:00:53 +0000695 !IDecl->lookupInheritedClass(&Ctx.Idents.get(ClassName))) {
696 migrateFactoryMethod(Ctx, CDecl, OM);
Fariborz Jahanian71221352013-07-23 22:42:28 +0000697 return;
Fariborz Jahanian280954a2013-07-24 18:31:42 +0000698 }
Fariborz Jahanianc4291852013-08-02 18:00:53 +0000699 ReplaceWithInstancetype(*this, OM);
Fariborz Jahanian71221352013-07-23 22:42:28 +0000700}
701
702void ObjCMigrateASTConsumer::migrateInstanceType(ASTContext &Ctx,
703 ObjCContainerDecl *CDecl) {
704 // migrate methods which can have instancetype as their result type.
705 for (ObjCContainerDecl::method_iterator M = CDecl->meth_begin(),
706 MEnd = CDecl->meth_end();
707 M != MEnd; ++M) {
708 ObjCMethodDecl *Method = (*M);
709 migrateMethodInstanceType(Ctx, CDecl, Method);
710 }
711}
712
Fariborz Jahanianc4291852013-08-02 18:00:53 +0000713void ObjCMigrateASTConsumer::migrateFactoryMethod(ASTContext &Ctx,
714 ObjCContainerDecl *CDecl,
Fariborz Jahanian9275c682013-08-02 20:54:18 +0000715 ObjCMethodDecl *OM,
716 ObjCInstanceTypeFamily OIT_Family) {
Fariborz Jahanian3bfc35e2013-08-02 22:34:18 +0000717 if (OM->isInstanceMethod() ||
718 OM->getResultType() == Ctx.getObjCInstanceType() ||
719 !OM->getResultType()->isObjCIdType())
Fariborz Jahanianc4291852013-08-02 18:00:53 +0000720 return;
721
722 // Candidate factory methods are + (id) NaMeXXX : ... which belong to a class
723 // NSYYYNamE with matching names be at least 3 characters long.
724 ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(CDecl);
725 if (!IDecl) {
726 if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(CDecl))
727 IDecl = CatDecl->getClassInterface();
728 else if (ObjCImplDecl *ImpDecl = dyn_cast<ObjCImplDecl>(CDecl))
729 IDecl = ImpDecl->getClassInterface();
730 }
731 if (!IDecl)
732 return;
733
734 std::string StringClassName = IDecl->getName();
735 StringRef LoweredClassName(StringClassName);
736 std::string StringLoweredClassName = LoweredClassName.lower();
737 LoweredClassName = StringLoweredClassName;
738
739 IdentifierInfo *MethodIdName = OM->getSelector().getIdentifierInfoForSlot(0);
Fariborz Jahanianc13c1b02013-08-13 18:01:42 +0000740 // Handle method with no name at its first selector slot; e.g. + (id):(int)x.
741 if (!MethodIdName)
742 return;
743
Fariborz Jahanianc4291852013-08-02 18:00:53 +0000744 std::string MethodName = MethodIdName->getName();
Fariborz Jahanian9275c682013-08-02 20:54:18 +0000745 if (OIT_Family == OIT_Singleton) {
746 StringRef STRefMethodName(MethodName);
747 size_t len = 0;
748 if (STRefMethodName.startswith("standard"))
749 len = strlen("standard");
750 else if (STRefMethodName.startswith("shared"))
751 len = strlen("shared");
752 else if (STRefMethodName.startswith("default"))
753 len = strlen("default");
754 else
755 return;
756 MethodName = STRefMethodName.substr(len);
757 }
Fariborz Jahanianc4291852013-08-02 18:00:53 +0000758 std::string MethodNameSubStr = MethodName.substr(0, 3);
759 StringRef MethodNamePrefix(MethodNameSubStr);
760 std::string StringLoweredMethodNamePrefix = MethodNamePrefix.lower();
761 MethodNamePrefix = StringLoweredMethodNamePrefix;
762 size_t Ix = LoweredClassName.rfind(MethodNamePrefix);
763 if (Ix == StringRef::npos)
764 return;
765 std::string ClassNamePostfix = LoweredClassName.substr(Ix);
766 StringRef LoweredMethodName(MethodName);
767 std::string StringLoweredMethodName = LoweredMethodName.lower();
768 LoweredMethodName = StringLoweredMethodName;
769 if (!LoweredMethodName.startswith(ClassNamePostfix))
770 return;
771 ReplaceWithInstancetype(*this, OM);
772}
773
Fariborz Jahanian2ec4d7b2013-08-16 23:35:05 +0000774static bool IsVoidStarType(QualType Ty) {
775 if (!Ty->isPointerType())
776 return false;
777
778 while (const TypedefType *TD = dyn_cast<TypedefType>(Ty.getTypePtr()))
779 Ty = TD->getDecl()->getUnderlyingType();
780
781 // Is the type void*?
782 const PointerType* PT = Ty->getAs<PointerType>();
783 if (PT->getPointeeType().getUnqualifiedType()->isVoidType())
784 return true;
785 return IsVoidStarType(PT->getPointeeType());
786}
787
Fariborz Jahanian94279392013-08-20 18:54:39 +0000788/// AuditedType - This routine audits the type AT and returns false if it is one of known
789/// CF object types or of the "void *" variety. It returns true if we don't care about the type
790/// such as a non-pointer or pointers which have no ownership issues (such as "int *").
Fariborz Jahanian63ffce22013-08-27 22:42:30 +0000791static bool AuditedType (QualType AT) {
792 if (!AT->isAnyPointerType() && !AT->isBlockPointerType())
Fariborz Jahanian9ef4a262013-08-19 19:13:34 +0000793 return true;
Fariborz Jahanian9ef4a262013-08-19 19:13:34 +0000794 // FIXME. There isn't much we can say about CF pointer type; or is there?
Fariborz Jahanian94279392013-08-20 18:54:39 +0000795 if (ento::coreFoundation::isCFObjectRef(AT) ||
796 IsVoidStarType(AT) ||
797 // If an ObjC object is type, assuming that it is not a CF function and
798 // that it is an un-audited function.
Fariborz Jahanian2e9c19c2013-08-22 22:27:36 +0000799 AT->isObjCObjectPointerType() || AT->isObjCBuiltinType())
Fariborz Jahanian9ef4a262013-08-19 19:13:34 +0000800 return false;
Fariborz Jahanian94279392013-08-20 18:54:39 +0000801 // All other pointers are assumed audited as harmless.
Fariborz Jahanian9ef4a262013-08-19 19:13:34 +0000802 return true;
Fariborz Jahanian2ec4d7b2013-08-16 23:35:05 +0000803}
804
Fariborz Jahanian301b5212013-08-20 22:42:13 +0000805void ObjCMigrateASTConsumer::AnnotateImplicitBridging(ASTContext &Ctx) {
Fariborz Jahanian926fafb2013-08-22 18:35:27 +0000806 if (CFFunctionIBCandidates.empty())
807 return;
Fariborz Jahanian301b5212013-08-20 22:42:13 +0000808 if (!Ctx.Idents.get("CF_IMPLICIT_BRIDGING_ENABLED").hasMacroDefinition()) {
809 CFFunctionIBCandidates.clear();
Fariborz Jahanianb8343522013-08-20 23:35:26 +0000810 FileId = 0;
Fariborz Jahanian301b5212013-08-20 22:42:13 +0000811 return;
812 }
813 // Insert CF_IMPLICIT_BRIDGING_ENABLE/CF_IMPLICIT_BRIDGING_DISABLED
Fariborz Jahanian926fafb2013-08-22 18:35:27 +0000814 const Decl *FirstFD = CFFunctionIBCandidates[0];
815 const Decl *LastFD =
816 CFFunctionIBCandidates[CFFunctionIBCandidates.size()-1];
Fariborz Jahanian301b5212013-08-20 22:42:13 +0000817 const char *PragmaString = "\nCF_IMPLICIT_BRIDGING_ENABLED\n\n";
818 edit::Commit commit(*Editor);
819 commit.insertBefore(FirstFD->getLocStart(), PragmaString);
820 PragmaString = "\n\nCF_IMPLICIT_BRIDGING_DISABLED\n";
821 SourceLocation EndLoc = LastFD->getLocEnd();
822 // get location just past end of function location.
823 EndLoc = PP.getLocForEndOfToken(EndLoc);
Fariborz Jahanian926fafb2013-08-22 18:35:27 +0000824 if (isa<FunctionDecl>(LastFD)) {
825 // For Methods, EndLoc points to the ending semcolon. So,
826 // not of these extra work is needed.
827 Token Tok;
828 // get locaiton of token that comes after end of function.
829 bool Failed = PP.getRawToken(EndLoc, Tok, /*IgnoreWhiteSpace=*/true);
830 if (!Failed)
831 EndLoc = Tok.getLocation();
832 }
Fariborz Jahanian301b5212013-08-20 22:42:13 +0000833 commit.insertAfterToken(EndLoc, PragmaString);
834 Editor->commit(commit);
Fariborz Jahanianb8343522013-08-20 23:35:26 +0000835 FileId = 0;
Fariborz Jahanian301b5212013-08-20 22:42:13 +0000836 CFFunctionIBCandidates.clear();
837}
838
Fariborz Jahanian4f64dd22013-08-22 21:40:15 +0000839void ObjCMigrateASTConsumer::migrateCFAnnotation(ASTContext &Ctx, const Decl *Decl) {
840 if (Decl->hasAttr<CFAuditedTransferAttr>()) {
Fariborz Jahanianc6dfd3f2013-08-19 22:00:50 +0000841 assert(CFFunctionIBCandidates.empty() &&
Fariborz Jahanian4f64dd22013-08-22 21:40:15 +0000842 "Cannot have audited functions/methods inside user "
Fariborz Jahanianc6dfd3f2013-08-19 22:00:50 +0000843 "provided CF_IMPLICIT_BRIDGING_ENABLE");
844 return;
845 }
846
Fariborz Jahanian2ec4d7b2013-08-16 23:35:05 +0000847 // Finction must be annotated first.
Fariborz Jahanian63ffce22013-08-27 22:42:30 +0000848 CF_BRIDGING_KIND AuditKind;
Fariborz Jahanian4f64dd22013-08-22 21:40:15 +0000849 if (const FunctionDecl *FuncDecl = dyn_cast<FunctionDecl>(Decl))
Fariborz Jahanian63ffce22013-08-27 22:42:30 +0000850 AuditKind = migrateAddFunctionAnnotation(Ctx, FuncDecl);
Fariborz Jahanian4f64dd22013-08-22 21:40:15 +0000851 else
Fariborz Jahanian63ffce22013-08-27 22:42:30 +0000852 AuditKind = migrateAddMethodAnnotation(Ctx, cast<ObjCMethodDecl>(Decl));
853 if (AuditKind == CF_BRIDGING_ENABLE) {
Fariborz Jahanian4f64dd22013-08-22 21:40:15 +0000854 CFFunctionIBCandidates.push_back(Decl);
Fariborz Jahanianb8343522013-08-20 23:35:26 +0000855 if (!FileId)
Fariborz Jahanian4f64dd22013-08-22 21:40:15 +0000856 FileId = PP.getSourceManager().getFileID(Decl->getLocation()).getHashValue();
Fariborz Jahanianb8343522013-08-20 23:35:26 +0000857 }
Fariborz Jahanian63ffce22013-08-27 22:42:30 +0000858 else if (AuditKind == CF_BRIDGING_MAY_INCLUDE) {
859 if (!CFFunctionIBCandidates.empty()) {
860 CFFunctionIBCandidates.push_back(Decl);
861 if (!FileId)
862 FileId = PP.getSourceManager().getFileID(Decl->getLocation()).getHashValue();
863 }
864 }
Fariborz Jahanian926fafb2013-08-22 18:35:27 +0000865 else
Fariborz Jahanian301b5212013-08-20 22:42:13 +0000866 AnnotateImplicitBridging(Ctx);
Fariborz Jahanian2ec4d7b2013-08-16 23:35:05 +0000867}
868
Fariborz Jahanian63ffce22013-08-27 22:42:30 +0000869void ObjCMigrateASTConsumer::AddCFAnnotations(ASTContext &Ctx,
870 const CallEffects &CE,
871 const FunctionDecl *FuncDecl) {
872 // Annotate function.
873 if (!FuncDecl->getAttr<CFReturnsRetainedAttr>() &&
874 !FuncDecl->getAttr<CFReturnsNotRetainedAttr>()) {
Fariborz Jahanian9ef4a262013-08-19 19:13:34 +0000875 RetEffect Ret = CE.getReturnValue();
876 const char *AnnotationString = 0;
877 if (Ret.getObjKind() == RetEffect::CF && Ret.isOwned()) {
878 if (Ctx.Idents.get("CF_RETURNS_RETAINED").hasMacroDefinition())
879 AnnotationString = " CF_RETURNS_RETAINED";
880 }
881 else if (Ret.getObjKind() == RetEffect::CF && !Ret.isOwned()) {
882 if (Ctx.Idents.get("CF_RETURNS_NOT_RETAINED").hasMacroDefinition())
883 AnnotationString = " CF_RETURNS_NOT_RETAINED";
884 }
885 if (AnnotationString) {
886 edit::Commit commit(*Editor);
887 commit.insertAfterToken(FuncDecl->getLocEnd(), AnnotationString);
888 Editor->commit(commit);
889 }
Fariborz Jahanian84ac1de2013-08-15 21:44:38 +0000890 }
Fariborz Jahanian9ef4a262013-08-19 19:13:34 +0000891 llvm::ArrayRef<ArgEffect> AEArgs = CE.getArgs();
892 unsigned i = 0;
893 for (FunctionDecl::param_const_iterator pi = FuncDecl->param_begin(),
894 pe = FuncDecl->param_end(); pi != pe; ++pi, ++i) {
Fariborz Jahanianb918d7a2013-08-21 19:37:47 +0000895 const ParmVarDecl *pd = *pi;
Fariborz Jahanian9ef4a262013-08-19 19:13:34 +0000896 ArgEffect AE = AEArgs[i];
Fariborz Jahanian63ffce22013-08-27 22:42:30 +0000897 if (AE == DecRef && !pd->getAttr<CFConsumedAttr>() &&
898 Ctx.Idents.get("CF_CONSUMED").hasMacroDefinition()) {
899 edit::Commit commit(*Editor);
900 commit.insertBefore(pd->getLocation(), "CF_CONSUMED ");
901 Editor->commit(commit);
Fariborz Jahanian94279392013-08-20 18:54:39 +0000902 }
Fariborz Jahanian84ac1de2013-08-15 21:44:38 +0000903 }
Fariborz Jahanian63ffce22013-08-27 22:42:30 +0000904}
905
906
907ObjCMigrateASTConsumer::CF_BRIDGING_KIND
908 ObjCMigrateASTConsumer::migrateAddFunctionAnnotation(
909 ASTContext &Ctx,
910 const FunctionDecl *FuncDecl) {
911 if (FuncDecl->hasBody())
912 return CF_BRIDGING_NONE;
913
914 CallEffects CE = CallEffects::getEffect(FuncDecl);
915 bool FuncIsReturnAnnotated = (FuncDecl->getAttr<CFReturnsRetainedAttr>() ||
916 FuncDecl->getAttr<CFReturnsNotRetainedAttr>());
917
918 // Trivial case of when funciton is annotated and has no argument.
919 if (FuncIsReturnAnnotated && FuncDecl->getNumParams() == 0)
920 return CF_BRIDGING_NONE;
921
922 bool ReturnCFAudited = false;
923 if (!FuncIsReturnAnnotated) {
924 RetEffect Ret = CE.getReturnValue();
925 if (Ret.getObjKind() == RetEffect::CF &&
926 (Ret.isOwned() || !Ret.isOwned()))
927 ReturnCFAudited = true;
928 else if (!AuditedType(FuncDecl->getResultType()))
929 return CF_BRIDGING_NONE;
930 }
931
932 // At this point result type is audited for potential inclusion.
933 // Now, how about argument types.
934 llvm::ArrayRef<ArgEffect> AEArgs = CE.getArgs();
935 unsigned i = 0;
936 bool ArgCFAudited = false;
937 for (FunctionDecl::param_const_iterator pi = FuncDecl->param_begin(),
938 pe = FuncDecl->param_end(); pi != pe; ++pi, ++i) {
939 const ParmVarDecl *pd = *pi;
940 ArgEffect AE = AEArgs[i];
941 if (AE == DecRef /*CFConsumed annotated*/ || AE == IncRef) {
942 if (AE == DecRef && !pd->getAttr<CFConsumedAttr>())
943 ArgCFAudited = true;
944 else if (AE == IncRef)
945 ArgCFAudited = true;
946 }
947 else {
948 QualType AT = pd->getType();
949 if (!AuditedType(AT)) {
950 AddCFAnnotations(Ctx, CE, FuncDecl);
951 return CF_BRIDGING_NONE;
952 }
953 }
954 }
955 if (ReturnCFAudited || ArgCFAudited)
956 return CF_BRIDGING_ENABLE;
957
958 return CF_BRIDGING_MAY_INCLUDE;
Fariborz Jahaniandfe6ed92013-08-12 23:17:13 +0000959}
960
Fariborz Jahanian926fafb2013-08-22 18:35:27 +0000961void ObjCMigrateASTConsumer::migrateARCSafeAnnotation(ASTContext &Ctx,
962 ObjCContainerDecl *CDecl) {
963 if (!isa<ObjCInterfaceDecl>(CDecl))
964 return;
965
966 // migrate methods which can have instancetype as their result type.
967 for (ObjCContainerDecl::method_iterator M = CDecl->meth_begin(),
968 MEnd = CDecl->meth_end();
969 M != MEnd; ++M) {
970 ObjCMethodDecl *Method = (*M);
Fariborz Jahanian4f64dd22013-08-22 21:40:15 +0000971 migrateCFAnnotation(Ctx, Method);
Fariborz Jahanian926fafb2013-08-22 18:35:27 +0000972 }
973}
974
Fariborz Jahanian63ffce22013-08-27 22:42:30 +0000975void ObjCMigrateASTConsumer::AddCFAnnotations(ASTContext &Ctx,
976 const CallEffects &CE,
977 const ObjCMethodDecl *MethodDecl) {
978 // Annotate function.
979 if (!MethodDecl->getAttr<CFReturnsRetainedAttr>() &&
980 !MethodDecl->getAttr<CFReturnsNotRetainedAttr>()) {
Fariborz Jahanian926fafb2013-08-22 18:35:27 +0000981 RetEffect Ret = CE.getReturnValue();
982 const char *AnnotationString = 0;
983 if (Ret.getObjKind() == RetEffect::CF && Ret.isOwned()) {
984 if (Ctx.Idents.get("CF_RETURNS_RETAINED").hasMacroDefinition())
985 AnnotationString = " CF_RETURNS_RETAINED";
986 }
987 else if (Ret.getObjKind() == RetEffect::CF && !Ret.isOwned()) {
988 if (Ctx.Idents.get("CF_RETURNS_NOT_RETAINED").hasMacroDefinition())
989 AnnotationString = " CF_RETURNS_NOT_RETAINED";
990 }
991 if (AnnotationString) {
992 edit::Commit commit(*Editor);
993 commit.insertBefore(MethodDecl->getLocEnd(), AnnotationString);
994 Editor->commit(commit);
Fariborz Jahanian926fafb2013-08-22 18:35:27 +0000995 }
Fariborz Jahanian926fafb2013-08-22 18:35:27 +0000996 }
Fariborz Jahanian926fafb2013-08-22 18:35:27 +0000997 llvm::ArrayRef<ArgEffect> AEArgs = CE.getArgs();
998 unsigned i = 0;
999 for (ObjCMethodDecl::param_const_iterator pi = MethodDecl->param_begin(),
1000 pe = MethodDecl->param_end(); pi != pe; ++pi, ++i) {
1001 const ParmVarDecl *pd = *pi;
1002 ArgEffect AE = AEArgs[i];
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001003 if (AE == DecRef && !pd->getAttr<CFConsumedAttr>() &&
1004 Ctx.Idents.get("CF_CONSUMED").hasMacroDefinition()) {
1005 edit::Commit commit(*Editor);
1006 commit.insertBefore(pd->getLocation(), "CF_CONSUMED ");
1007 Editor->commit(commit);
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001008 }
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001009 }
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001010}
1011
1012ObjCMigrateASTConsumer::CF_BRIDGING_KIND
1013 ObjCMigrateASTConsumer::migrateAddMethodAnnotation(
1014 ASTContext &Ctx,
1015 const ObjCMethodDecl *MethodDecl) {
1016 if (MethodDecl->hasBody())
1017 return CF_BRIDGING_NONE;
1018
1019 CallEffects CE = CallEffects::getEffect(MethodDecl);
1020 bool MethodIsReturnAnnotated = (MethodDecl->getAttr<CFReturnsRetainedAttr>() ||
1021 MethodDecl->getAttr<CFReturnsNotRetainedAttr>());
1022
1023 // Trivial case of when funciton is annotated and has no argument.
1024 if (MethodIsReturnAnnotated &&
1025 (MethodDecl->param_begin() == MethodDecl->param_end()))
1026 return CF_BRIDGING_NONE;
1027
1028 bool ReturnCFAudited = false;
1029 if (!MethodIsReturnAnnotated) {
1030 RetEffect Ret = CE.getReturnValue();
1031 if (Ret.getObjKind() == RetEffect::CF && (Ret.isOwned() || !Ret.isOwned()))
1032 ReturnCFAudited = true;
1033 else if (!AuditedType(MethodDecl->getResultType()))
1034 return CF_BRIDGING_NONE;
1035 }
1036
1037 // At this point result type is either annotated or audited.
1038 // Now, how about argument types.
1039 llvm::ArrayRef<ArgEffect> AEArgs = CE.getArgs();
1040 unsigned i = 0;
1041 bool ArgCFAudited = false;
1042 for (ObjCMethodDecl::param_const_iterator pi = MethodDecl->param_begin(),
1043 pe = MethodDecl->param_end(); pi != pe; ++pi, ++i) {
1044 const ParmVarDecl *pd = *pi;
1045 ArgEffect AE = AEArgs[i];
1046 if (AE == DecRef /*CFConsumed annotated*/ || AE == IncRef) {
1047 if (AE == DecRef && !pd->getAttr<CFConsumedAttr>())
1048 ArgCFAudited = true;
1049 else if (AE == IncRef)
1050 ArgCFAudited = true;
1051 }
1052 else {
1053 QualType AT = pd->getType();
1054 if (!AuditedType(AT)) {
1055 AddCFAnnotations(Ctx, CE, MethodDecl);
1056 return CF_BRIDGING_NONE;
1057 }
1058 }
1059 }
1060 if (ReturnCFAudited || ArgCFAudited)
1061 return CF_BRIDGING_ENABLE;
1062
1063 return CF_BRIDGING_MAY_INCLUDE;
Fariborz Jahaniandfe6ed92013-08-12 23:17:13 +00001064}
1065
Ted Kremenekf7639e12012-03-06 20:06:33 +00001066namespace {
1067
1068class RewritesReceiver : public edit::EditsReceiver {
1069 Rewriter &Rewrite;
1070
1071public:
1072 RewritesReceiver(Rewriter &Rewrite) : Rewrite(Rewrite) { }
1073
1074 virtual void insert(SourceLocation loc, StringRef text) {
1075 Rewrite.InsertText(loc, text);
1076 }
1077 virtual void replace(CharSourceRange range, StringRef text) {
1078 Rewrite.ReplaceText(range.getBegin(), Rewrite.getRangeSize(range), text);
1079 }
1080};
1081
1082}
1083
1084void ObjCMigrateASTConsumer::HandleTranslationUnit(ASTContext &Ctx) {
Fariborz Jahaniana7437f02013-07-03 23:05:00 +00001085
1086 TranslationUnitDecl *TU = Ctx.getTranslationUnitDecl();
Fariborz Jahanian301b5212013-08-20 22:42:13 +00001087 if (MigrateProperty) {
Fariborz Jahaniand83ef842013-07-09 16:59:14 +00001088 for (DeclContext::decl_iterator D = TU->decls_begin(), DEnd = TU->decls_end();
1089 D != DEnd; ++D) {
Fariborz Jahanianb8343522013-08-20 23:35:26 +00001090 if (unsigned FID =
1091 PP.getSourceManager().getFileID((*D)->getLocation()).getHashValue())
1092 if (FileId && FileId != FID) {
1093 assert(!CFFunctionIBCandidates.empty());
1094 AnnotateImplicitBridging(Ctx);
1095 }
1096
Fariborz Jahaniand83ef842013-07-09 16:59:14 +00001097 if (ObjCInterfaceDecl *CDecl = dyn_cast<ObjCInterfaceDecl>(*D))
1098 migrateObjCInterfaceDecl(Ctx, CDecl);
Fariborz Jahanian1be01532013-07-12 22:32:19 +00001099 else if (ObjCProtocolDecl *PDecl = dyn_cast<ObjCProtocolDecl>(*D))
1100 ObjCProtocolDecls.insert(PDecl);
1101 else if (const ObjCImplementationDecl *ImpDecl =
1102 dyn_cast<ObjCImplementationDecl>(*D))
1103 migrateProtocolConformance(Ctx, ImpDecl);
Fariborz Jahanian92463272013-07-18 20:11:45 +00001104 else if (const EnumDecl *ED = dyn_cast<EnumDecl>(*D)) {
1105 DeclContext::decl_iterator N = D;
1106 ++N;
Fariborz Jahanian008ef722013-07-19 17:44:32 +00001107 if (N != DEnd)
1108 if (const TypedefDecl *TD = dyn_cast<TypedefDecl>(*N))
1109 migrateNSEnumDecl(Ctx, ED, TD);
Fariborz Jahanian92463272013-07-18 20:11:45 +00001110 }
Fariborz Jahanianc13c1b02013-08-13 18:01:42 +00001111 else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(*D))
Fariborz Jahanian4f64dd22013-08-22 21:40:15 +00001112 migrateCFAnnotation(Ctx, FD);
Fariborz Jahanianc13c1b02013-08-13 18:01:42 +00001113
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001114 if (ObjCContainerDecl *CDecl = dyn_cast<ObjCContainerDecl>(*D)) {
1115 // migrate methods which can have instancetype as their result type.
Fariborz Jahanian71221352013-07-23 22:42:28 +00001116 migrateInstanceType(Ctx, CDecl);
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001117 // annotate methods with CF annotations.
1118 migrateARCSafeAnnotation(Ctx, CDecl);
1119 }
Fariborz Jahaniand83ef842013-07-09 16:59:14 +00001120 }
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001121 AnnotateImplicitBridging(Ctx);
Fariborz Jahanian301b5212013-08-20 22:42:13 +00001122 }
Fariborz Jahaniana7437f02013-07-03 23:05:00 +00001123
David Blaikiebbafb8a2012-03-11 07:00:24 +00001124 Rewriter rewriter(Ctx.getSourceManager(), Ctx.getLangOpts());
Ted Kremenekf7639e12012-03-06 20:06:33 +00001125 RewritesReceiver Rec(rewriter);
1126 Editor->applyRewrites(Rec);
1127
1128 for (Rewriter::buffer_iterator
1129 I = rewriter.buffer_begin(), E = rewriter.buffer_end(); I != E; ++I) {
1130 FileID FID = I->first;
1131 RewriteBuffer &buf = I->second;
1132 const FileEntry *file = Ctx.getSourceManager().getFileEntryForID(FID);
1133 assert(file);
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001134 SmallString<512> newText;
Ted Kremenekf7639e12012-03-06 20:06:33 +00001135 llvm::raw_svector_ostream vecOS(newText);
1136 buf.write(vecOS);
1137 vecOS.flush();
1138 llvm::MemoryBuffer *memBuf = llvm::MemoryBuffer::getMemBufferCopy(
1139 StringRef(newText.data(), newText.size()), file->getName());
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001140 SmallString<64> filePath(file->getName());
Ted Kremenekf7639e12012-03-06 20:06:33 +00001141 FileMgr.FixupRelativePath(filePath);
1142 Remapper.remap(filePath.str(), memBuf);
1143 }
1144
1145 if (IsOutputFile) {
1146 Remapper.flushToFile(MigrateDir, Ctx.getDiagnostics());
1147 } else {
1148 Remapper.flushToDisk(MigrateDir, Ctx.getDiagnostics());
1149 }
1150}
1151
1152bool MigrateSourceAction::BeginInvocation(CompilerInstance &CI) {
Argyrios Kyrtzidisb4822602012-05-24 16:48:23 +00001153 CI.getDiagnostics().setIgnoreAllWarnings(true);
Ted Kremenekf7639e12012-03-06 20:06:33 +00001154 return true;
1155}
1156
1157ASTConsumer *MigrateSourceAction::CreateASTConsumer(CompilerInstance &CI,
1158 StringRef InFile) {
Argyrios Kyrtzidisf3d587e2012-12-04 07:27:05 +00001159 PPConditionalDirectiveRecord *
1160 PPRec = new PPConditionalDirectiveRecord(CI.getSourceManager());
1161 CI.getPreprocessor().addPPCallbacks(PPRec);
Ted Kremenekf7639e12012-03-06 20:06:33 +00001162 return new ObjCMigrateASTConsumer(CI.getFrontendOpts().OutputFile,
1163 /*MigrateLiterals=*/true,
1164 /*MigrateSubscripting=*/true,
Fariborz Jahaniand83ef842013-07-09 16:59:14 +00001165 /*MigrateProperty*/true,
Ted Kremenekf7639e12012-03-06 20:06:33 +00001166 Remapper,
1167 CI.getFileManager(),
Argyrios Kyrtzidisf3d587e2012-12-04 07:27:05 +00001168 PPRec,
Fariborz Jahaniana7437f02013-07-03 23:05:00 +00001169 CI.getPreprocessor(),
Ted Kremenekf7639e12012-03-06 20:06:33 +00001170 /*isOutputFile=*/true);
1171}