1 //===--- 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 
10 #include "Transforms.h"
11 #include "clang/ARCMigrate/ARCMTActions.h"
12 #include "clang/AST/ASTConsumer.h"
13 #include "clang/AST/ASTContext.h"
14 #include "clang/AST/NSAPI.h"
15 #include "clang/AST/ParentMap.h"
16 #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"
22 #include "clang/Frontend/CompilerInstance.h"
23 #include "clang/Frontend/MultiplexConsumer.h"
24 #include "clang/Lex/PPConditionalDirectiveRecord.h"
25 #include "clang/Lex/Preprocessor.h"
26 #include "clang/Rewrite/Core/Rewriter.h"
27 #include "clang/Analysis/DomainSpecific/CocoaConventions.h"
28 #include "clang/StaticAnalyzer/Checkers/ObjCRetainCount.h"
29 #include "clang/AST/Attr.h"
30 #include "llvm/ADT/SmallString.h"
31 
32 using namespace clang;
33 using namespace arcmt;
34 using namespace ento::objc_retain;
35 
36 namespace {
37 
38 class ObjCMigrateASTConsumer : public ASTConsumer {
39   enum CF_BRIDGING_KIND {
40     CF_BRIDGING_NONE,
41     CF_BRIDGING_ENABLE,
42     CF_BRIDGING_MAY_INCLUDE
43   };
44 
45   void migrateDecl(Decl *D);
46   void migrateObjCInterfaceDecl(ASTContext &Ctx, ObjCContainerDecl *D);
47   void migrateProtocolConformance(ASTContext &Ctx,
48                                   const ObjCImplementationDecl *ImpDecl);
49   void migrateNSEnumDecl(ASTContext &Ctx, const EnumDecl *EnumDcl,
50                      const TypedefDecl *TypedefDcl);
51   void migrateMethods(ASTContext &Ctx, ObjCContainerDecl *CDecl);
52   void migrateMethodInstanceType(ASTContext &Ctx, ObjCContainerDecl *CDecl,
53                                  ObjCMethodDecl *OM);
54   bool migrateProperty(ASTContext &Ctx, ObjCContainerDecl *D, ObjCMethodDecl *OM);
55   void migrateNsReturnsInnerPointer(ASTContext &Ctx, ObjCMethodDecl *OM);
56   void migratePropertyNsReturnsInnerPointer(ASTContext &Ctx, ObjCPropertyDecl *P);
57   void migrateFactoryMethod(ASTContext &Ctx, ObjCContainerDecl *CDecl,
58                             ObjCMethodDecl *OM,
59                             ObjCInstanceTypeFamily OIT_Family = OIT_None);
60 
61   void migrateCFAnnotation(ASTContext &Ctx, const Decl *Decl);
62   void AddCFAnnotations(ASTContext &Ctx, const CallEffects &CE,
63                         const FunctionDecl *FuncDecl, bool ResultAnnotated);
64   void AddCFAnnotations(ASTContext &Ctx, const CallEffects &CE,
65                         const ObjCMethodDecl *MethodDecl, bool ResultAnnotated);
66 
67   void AnnotateImplicitBridging(ASTContext &Ctx);
68 
69   CF_BRIDGING_KIND migrateAddFunctionAnnotation(ASTContext &Ctx,
70                                                 const FunctionDecl *FuncDecl);
71 
72   void migrateARCSafeAnnotation(ASTContext &Ctx, ObjCContainerDecl *CDecl);
73 
74   void migrateAddMethodAnnotation(ASTContext &Ctx,
75                                   const ObjCMethodDecl *MethodDecl);
76 public:
77   std::string MigrateDir;
78   bool MigrateLiterals;
79   bool MigrateSubscripting;
80   bool MigrateProperty;
81   bool MigrateReadonlyProperty;
82   unsigned  FileId;
83   OwningPtr<NSAPI> NSAPIObj;
84   OwningPtr<edit::EditedSource> Editor;
85   FileRemapper &Remapper;
86   FileManager &FileMgr;
87   const PPConditionalDirectiveRecord *PPRec;
88   Preprocessor &PP;
89   bool IsOutputFile;
90   llvm::SmallPtrSet<ObjCProtocolDecl *, 32> ObjCProtocolDecls;
91   llvm::SmallVector<const Decl *, 8> CFFunctionIBCandidates;
92 
93   ObjCMigrateASTConsumer(StringRef migrateDir,
94                          bool migrateLiterals,
95                          bool migrateSubscripting,
96                          bool migrateProperty,
97                          bool migrateReadonlyProperty,
98                          FileRemapper &remapper,
99                          FileManager &fileMgr,
100                          const PPConditionalDirectiveRecord *PPRec,
101                          Preprocessor &PP,
102                          bool isOutputFile = false)
103   : MigrateDir(migrateDir),
104     MigrateLiterals(migrateLiterals),
105     MigrateSubscripting(migrateSubscripting),
106     MigrateProperty(migrateProperty),
107     MigrateReadonlyProperty(migrateReadonlyProperty),
108     FileId(0), Remapper(remapper), FileMgr(fileMgr), PPRec(PPRec), PP(PP),
109     IsOutputFile(isOutputFile) { }
110 
111 protected:
112   virtual void Initialize(ASTContext &Context) {
113     NSAPIObj.reset(new NSAPI(Context));
114     Editor.reset(new edit::EditedSource(Context.getSourceManager(),
115                                         Context.getLangOpts(),
116                                         PPRec));
117   }
118 
119   virtual bool HandleTopLevelDecl(DeclGroupRef DG) {
120     for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I)
121       migrateDecl(*I);
122     return true;
123   }
124   virtual void HandleInterestingDecl(DeclGroupRef DG) {
125     // Ignore decls from the PCH.
126   }
127   virtual void HandleTopLevelDeclInObjCContainer(DeclGroupRef DG) {
128     ObjCMigrateASTConsumer::HandleTopLevelDecl(DG);
129   }
130 
131   virtual void HandleTranslationUnit(ASTContext &Ctx);
132 };
133 
134 }
135 
136 ObjCMigrateAction::ObjCMigrateAction(FrontendAction *WrappedAction,
137                              StringRef migrateDir,
138                              bool migrateLiterals,
139                              bool migrateSubscripting,
140                              bool migrateProperty,
141                              bool migrateReadonlyProperty)
142   : WrapperFrontendAction(WrappedAction), MigrateDir(migrateDir),
143     MigrateLiterals(migrateLiterals), MigrateSubscripting(migrateSubscripting),
144     MigrateProperty(migrateProperty),
145     MigrateReadonlyProperty(migrateReadonlyProperty),
146     CompInst(0) {
147   if (MigrateDir.empty())
148     MigrateDir = "."; // user current directory if none is given.
149 }
150 
151 ASTConsumer *ObjCMigrateAction::CreateASTConsumer(CompilerInstance &CI,
152                                                   StringRef InFile) {
153   PPConditionalDirectiveRecord *
154     PPRec = new PPConditionalDirectiveRecord(CompInst->getSourceManager());
155   CompInst->getPreprocessor().addPPCallbacks(PPRec);
156   ASTConsumer *
157     WrappedConsumer = WrapperFrontendAction::CreateASTConsumer(CI, InFile);
158   ASTConsumer *MTConsumer = new ObjCMigrateASTConsumer(MigrateDir,
159                                                        MigrateLiterals,
160                                                        MigrateSubscripting,
161                                                        MigrateProperty,
162                                                        MigrateReadonlyProperty,
163                                                        Remapper,
164                                                     CompInst->getFileManager(),
165                                                        PPRec,
166                                                        CompInst->getPreprocessor());
167   ASTConsumer *Consumers[] = { MTConsumer, WrappedConsumer };
168   return new MultiplexConsumer(Consumers);
169 }
170 
171 bool ObjCMigrateAction::BeginInvocation(CompilerInstance &CI) {
172   Remapper.initFromDisk(MigrateDir, CI.getDiagnostics(),
173                         /*ignoreIfFilesChanges=*/true);
174   CompInst = &CI;
175   CI.getDiagnostics().setIgnoreAllWarnings(true);
176   return true;
177 }
178 
179 namespace {
180 class ObjCMigrator : public RecursiveASTVisitor<ObjCMigrator> {
181   ObjCMigrateASTConsumer &Consumer;
182   ParentMap &PMap;
183 
184 public:
185   ObjCMigrator(ObjCMigrateASTConsumer &consumer, ParentMap &PMap)
186     : Consumer(consumer), PMap(PMap) { }
187 
188   bool shouldVisitTemplateInstantiations() const { return false; }
189   bool shouldWalkTypesOfTypeLocs() const { return false; }
190 
191   bool VisitObjCMessageExpr(ObjCMessageExpr *E) {
192     if (Consumer.MigrateLiterals) {
193       edit::Commit commit(*Consumer.Editor);
194       edit::rewriteToObjCLiteralSyntax(E, *Consumer.NSAPIObj, commit, &PMap);
195       Consumer.Editor->commit(commit);
196     }
197 
198     if (Consumer.MigrateSubscripting) {
199       edit::Commit commit(*Consumer.Editor);
200       edit::rewriteToObjCSubscriptSyntax(E, *Consumer.NSAPIObj, commit);
201       Consumer.Editor->commit(commit);
202     }
203 
204     return true;
205   }
206 
207   bool TraverseObjCMessageExpr(ObjCMessageExpr *E) {
208     // Do depth first; we want to rewrite the subexpressions first so that if
209     // we have to move expressions we will move them already rewritten.
210     for (Stmt::child_range range = E->children(); range; ++range)
211       if (!TraverseStmt(*range))
212         return false;
213 
214     return WalkUpFromObjCMessageExpr(E);
215   }
216 };
217 
218 class BodyMigrator : public RecursiveASTVisitor<BodyMigrator> {
219   ObjCMigrateASTConsumer &Consumer;
220   OwningPtr<ParentMap> PMap;
221 
222 public:
223   BodyMigrator(ObjCMigrateASTConsumer &consumer) : Consumer(consumer) { }
224 
225   bool shouldVisitTemplateInstantiations() const { return false; }
226   bool shouldWalkTypesOfTypeLocs() const { return false; }
227 
228   bool TraverseStmt(Stmt *S) {
229     PMap.reset(new ParentMap(S));
230     ObjCMigrator(Consumer, *PMap).TraverseStmt(S);
231     return true;
232   }
233 };
234 }
235 
236 void ObjCMigrateASTConsumer::migrateDecl(Decl *D) {
237   if (!D)
238     return;
239   if (isa<ObjCMethodDecl>(D))
240     return; // Wait for the ObjC container declaration.
241 
242   BodyMigrator(*this).TraverseDecl(D);
243 }
244 
245 static void append_attr(std::string &PropertyString, const char *attr) {
246   PropertyString += ", ";
247   PropertyString += attr;
248 }
249 
250 static bool rewriteToObjCProperty(const ObjCMethodDecl *Getter,
251                                   const ObjCMethodDecl *Setter,
252                                   const NSAPI &NS, edit::Commit &commit,
253                                   unsigned LengthOfPrefix) {
254   ASTContext &Context = NS.getASTContext();
255   std::string PropertyString = "@property (nonatomic";
256   std::string PropertyNameString = Getter->getNameAsString();
257   StringRef PropertyName(PropertyNameString);
258   if (LengthOfPrefix > 0) {
259     PropertyString += ", getter=";
260     PropertyString += PropertyNameString;
261   }
262   // Property with no setter may be suggested as a 'readonly' property.
263   if (!Setter)
264     append_attr(PropertyString, "readonly");
265 
266   // Short circuit properties that contain the name "delegate" or "dataSource",
267   // or have exact name "target" to have unsafe_unretained attribute.
268   if (PropertyName.equals("target") ||
269       (PropertyName.find("delegate") != StringRef::npos) ||
270       (PropertyName.find("dataSource") != StringRef::npos))
271     append_attr(PropertyString, "unsafe_unretained");
272   else if (Setter) {
273     const ParmVarDecl *argDecl = *Setter->param_begin();
274     QualType ArgType = Context.getCanonicalType(argDecl->getType());
275     Qualifiers::ObjCLifetime propertyLifetime = ArgType.getObjCLifetime();
276     bool RetainableObject = ArgType->isObjCRetainableType();
277     if (RetainableObject && propertyLifetime == Qualifiers::OCL_Strong) {
278       if (const ObjCObjectPointerType *ObjPtrTy =
279           ArgType->getAs<ObjCObjectPointerType>()) {
280         ObjCInterfaceDecl *IDecl = ObjPtrTy->getObjectType()->getInterface();
281         if (IDecl &&
282             IDecl->lookupNestedProtocol(&Context.Idents.get("NSCopying")))
283           append_attr(PropertyString, "copy");
284         else
285           append_attr(PropertyString, "retain");
286       }
287     } else if (propertyLifetime == Qualifiers::OCL_Weak)
288       // TODO. More precise determination of 'weak' attribute requires
289       // looking into setter's implementation for backing weak ivar.
290       append_attr(PropertyString, "weak");
291     else if (RetainableObject)
292       append_attr(PropertyString, "retain");
293   }
294   PropertyString += ')';
295 
296   QualType RT = Getter->getResultType();
297   if (!isa<TypedefType>(RT)) {
298     // strip off any ARC lifetime qualifier.
299     QualType CanResultTy = Context.getCanonicalType(RT);
300     if (CanResultTy.getQualifiers().hasObjCLifetime()) {
301       Qualifiers Qs = CanResultTy.getQualifiers();
302       Qs.removeObjCLifetime();
303       RT = Context.getQualifiedType(CanResultTy.getUnqualifiedType(), Qs);
304     }
305   }
306   PropertyString += " ";
307   PropertyString += RT.getAsString(Context.getPrintingPolicy());
308   char LastChar = PropertyString[PropertyString.size()-1];
309   if (LastChar != '*')
310     PropertyString += " ";
311   if (LengthOfPrefix > 0) {
312     // property name must strip off "is" and lower case the first character
313     // after that; e.g. isContinuous will become continuous.
314     StringRef PropertyNameStringRef(PropertyNameString);
315     PropertyNameStringRef = PropertyNameStringRef.drop_front(LengthOfPrefix);
316     PropertyNameString = PropertyNameStringRef;
317     std::string NewPropertyNameString = PropertyNameString;
318     bool NoLowering = (isUppercase(NewPropertyNameString[0]) &&
319                        NewPropertyNameString.size() > 1 &&
320                        isUppercase(NewPropertyNameString[1]));
321     if (!NoLowering)
322       NewPropertyNameString[0] = toLowercase(NewPropertyNameString[0]);
323     PropertyString += NewPropertyNameString;
324   }
325   else
326     PropertyString += PropertyNameString;
327   SourceLocation StartGetterSelectorLoc = Getter->getSelectorStartLoc();
328   Selector GetterSelector = Getter->getSelector();
329 
330   SourceLocation EndGetterSelectorLoc =
331     StartGetterSelectorLoc.getLocWithOffset(GetterSelector.getNameForSlot(0).size());
332   commit.replace(CharSourceRange::getCharRange(Getter->getLocStart(),
333                                                EndGetterSelectorLoc),
334                  PropertyString);
335   if (Setter) {
336     SourceLocation EndLoc = Setter->getDeclaratorEndLoc();
337     // Get location past ';'
338     EndLoc = EndLoc.getLocWithOffset(1);
339     commit.remove(CharSourceRange::getCharRange(Setter->getLocStart(), EndLoc));
340   }
341   return true;
342 }
343 
344 void ObjCMigrateASTConsumer::migrateObjCInterfaceDecl(ASTContext &Ctx,
345                                                       ObjCContainerDecl *D) {
346   if (D->isDeprecated())
347     return;
348 
349   for (ObjCContainerDecl::method_iterator M = D->meth_begin(), MEnd = D->meth_end();
350        M != MEnd; ++M) {
351     ObjCMethodDecl *Method = (*M);
352     if (Method->isDeprecated())
353       continue;
354     migrateProperty(Ctx, D, Method);
355     migrateNsReturnsInnerPointer(Ctx, Method);
356   }
357   for (ObjCContainerDecl::prop_iterator P = D->prop_begin(),
358        E = D->prop_end(); P != E; ++P) {
359     ObjCPropertyDecl *Prop = *P;
360     if (!P->isDeprecated())
361       migratePropertyNsReturnsInnerPointer(Ctx, Prop);
362   }
363 }
364 
365 static bool
366 ClassImplementsAllMethodsAndProperties(ASTContext &Ctx,
367                                       const ObjCImplementationDecl *ImpDecl,
368                                        const ObjCInterfaceDecl *IDecl,
369                                       ObjCProtocolDecl *Protocol) {
370   // In auto-synthesis, protocol properties are not synthesized. So,
371   // a conforming protocol must have its required properties declared
372   // in class interface.
373   bool HasAtleastOneRequiredProperty = false;
374   if (const ObjCProtocolDecl *PDecl = Protocol->getDefinition())
375     for (ObjCProtocolDecl::prop_iterator P = PDecl->prop_begin(),
376          E = PDecl->prop_end(); P != E; ++P) {
377       ObjCPropertyDecl *Property = *P;
378       if (Property->getPropertyImplementation() == ObjCPropertyDecl::Optional)
379         continue;
380       HasAtleastOneRequiredProperty = true;
381       DeclContext::lookup_const_result R = IDecl->lookup(Property->getDeclName());
382       if (R.size() == 0) {
383         // Relax the rule and look into class's implementation for a synthesize
384         // or dynamic declaration. Class is implementing a property coming from
385         // another protocol. This still makes the target protocol as conforming.
386         if (!ImpDecl->FindPropertyImplDecl(
387                                   Property->getDeclName().getAsIdentifierInfo()))
388           return false;
389       }
390       else if (ObjCPropertyDecl *ClassProperty = dyn_cast<ObjCPropertyDecl>(R[0])) {
391           if ((ClassProperty->getPropertyAttributes()
392               != Property->getPropertyAttributes()) ||
393               !Ctx.hasSameType(ClassProperty->getType(), Property->getType()))
394             return false;
395       }
396       else
397         return false;
398     }
399 
400   // At this point, all required properties in this protocol conform to those
401   // declared in the class.
402   // Check that class implements the required methods of the protocol too.
403   bool HasAtleastOneRequiredMethod = false;
404   if (const ObjCProtocolDecl *PDecl = Protocol->getDefinition()) {
405     if (PDecl->meth_begin() == PDecl->meth_end())
406       return HasAtleastOneRequiredProperty;
407     for (ObjCContainerDecl::method_iterator M = PDecl->meth_begin(),
408          MEnd = PDecl->meth_end(); M != MEnd; ++M) {
409       ObjCMethodDecl *MD = (*M);
410       if (MD->isImplicit())
411         continue;
412       if (MD->getImplementationControl() == ObjCMethodDecl::Optional)
413         continue;
414       DeclContext::lookup_const_result R = ImpDecl->lookup(MD->getDeclName());
415       if (R.size() == 0)
416         return false;
417       bool match = false;
418       HasAtleastOneRequiredMethod = true;
419       for (unsigned I = 0, N = R.size(); I != N; ++I)
420         if (ObjCMethodDecl *ImpMD = dyn_cast<ObjCMethodDecl>(R[0]))
421           if (Ctx.ObjCMethodsAreEqual(MD, ImpMD)) {
422             match = true;
423             break;
424           }
425       if (!match)
426         return false;
427     }
428   }
429   if (HasAtleastOneRequiredProperty || HasAtleastOneRequiredMethod)
430     return true;
431   return false;
432 }
433 
434 static bool rewriteToObjCInterfaceDecl(const ObjCInterfaceDecl *IDecl,
435                     llvm::SmallVectorImpl<ObjCProtocolDecl*> &ConformingProtocols,
436                     const NSAPI &NS, edit::Commit &commit) {
437   const ObjCList<ObjCProtocolDecl> &Protocols = IDecl->getReferencedProtocols();
438   std::string ClassString;
439   SourceLocation EndLoc =
440   IDecl->getSuperClass() ? IDecl->getSuperClassLoc() : IDecl->getLocation();
441 
442   if (Protocols.empty()) {
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     ClassString += "> ";
450   }
451   else {
452     ClassString = ", ";
453     for (unsigned i = 0, e = ConformingProtocols.size(); i != e; i++) {
454       ClassString += ConformingProtocols[i]->getNameAsString();
455       if (i != (e-1))
456         ClassString += ", ";
457     }
458     ObjCInterfaceDecl::protocol_loc_iterator PL = IDecl->protocol_loc_end() - 1;
459     EndLoc = *PL;
460   }
461 
462   commit.insertAfterToken(EndLoc, ClassString);
463   return true;
464 }
465 
466 static bool rewriteToNSEnumDecl(const EnumDecl *EnumDcl,
467                                 const TypedefDecl *TypedefDcl,
468                                 const NSAPI &NS, edit::Commit &commit,
469                                 bool IsNSIntegerType,
470                                 bool NSOptions) {
471   std::string ClassString;
472   if (NSOptions)
473     ClassString = "typedef NS_OPTIONS(NSUInteger, ";
474   else
475     ClassString =
476       IsNSIntegerType ? "typedef NS_ENUM(NSInteger, "
477                       : "typedef NS_ENUM(NSUInteger, ";
478 
479   ClassString += TypedefDcl->getIdentifier()->getName();
480   ClassString += ')';
481   SourceRange R(EnumDcl->getLocStart(), EnumDcl->getLocStart());
482   commit.replace(R, ClassString);
483   SourceLocation EndOfTypedefLoc = TypedefDcl->getLocEnd();
484   EndOfTypedefLoc = trans::findLocationAfterSemi(EndOfTypedefLoc, NS.getASTContext());
485   if (!EndOfTypedefLoc.isInvalid()) {
486     commit.remove(SourceRange(TypedefDcl->getLocStart(), EndOfTypedefLoc));
487     return true;
488   }
489   return false;
490 }
491 
492 static bool rewriteToNSMacroDecl(const EnumDecl *EnumDcl,
493                                 const TypedefDecl *TypedefDcl,
494                                 const NSAPI &NS, edit::Commit &commit,
495                                  bool IsNSIntegerType) {
496   std::string ClassString =
497     IsNSIntegerType ? "NS_ENUM(NSInteger, " : "NS_OPTIONS(NSUInteger, ";
498   ClassString += TypedefDcl->getIdentifier()->getName();
499   ClassString += ')';
500   SourceRange R(EnumDcl->getLocStart(), EnumDcl->getLocStart());
501   commit.replace(R, ClassString);
502   SourceLocation TypedefLoc = TypedefDcl->getLocEnd();
503   commit.remove(SourceRange(TypedefLoc, TypedefLoc));
504   return true;
505 }
506 
507 static bool UseNSOptionsMacro(Preprocessor &PP, ASTContext &Ctx,
508                               const EnumDecl *EnumDcl) {
509   bool PowerOfTwo = true;
510   bool AllHexdecimalEnumerator = true;
511   uint64_t MaxPowerOfTwoVal = 0;
512   for (EnumDecl::enumerator_iterator EI = EnumDcl->enumerator_begin(),
513        EE = EnumDcl->enumerator_end(); EI != EE; ++EI) {
514     EnumConstantDecl *Enumerator = (*EI);
515     const Expr *InitExpr = Enumerator->getInitExpr();
516     if (!InitExpr) {
517       PowerOfTwo = false;
518       AllHexdecimalEnumerator = false;
519       continue;
520     }
521     InitExpr = InitExpr->IgnoreParenCasts();
522     if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr))
523       if (BO->isShiftOp() || BO->isBitwiseOp())
524         return true;
525 
526     uint64_t EnumVal = Enumerator->getInitVal().getZExtValue();
527     if (PowerOfTwo && EnumVal) {
528       if (!llvm::isPowerOf2_64(EnumVal))
529         PowerOfTwo = false;
530       else if (EnumVal > MaxPowerOfTwoVal)
531         MaxPowerOfTwoVal = EnumVal;
532     }
533     if (AllHexdecimalEnumerator && EnumVal) {
534       bool FoundHexdecimalEnumerator = false;
535       SourceLocation EndLoc = Enumerator->getLocEnd();
536       Token Tok;
537       if (!PP.getRawToken(EndLoc, Tok, /*IgnoreWhiteSpace=*/true))
538         if (Tok.isLiteral() && Tok.getLength() > 2) {
539           if (const char *StringLit = Tok.getLiteralData())
540             FoundHexdecimalEnumerator =
541               (StringLit[0] == '0' && (toLowercase(StringLit[1]) == 'x'));
542         }
543       if (!FoundHexdecimalEnumerator)
544         AllHexdecimalEnumerator = false;
545     }
546   }
547   return AllHexdecimalEnumerator || (PowerOfTwo && (MaxPowerOfTwoVal > 2));
548 }
549 
550 void ObjCMigrateASTConsumer::migrateProtocolConformance(ASTContext &Ctx,
551                                             const ObjCImplementationDecl *ImpDecl) {
552   const ObjCInterfaceDecl *IDecl = ImpDecl->getClassInterface();
553   if (!IDecl || ObjCProtocolDecls.empty() || IDecl->isDeprecated())
554     return;
555   // Find all implicit conforming protocols for this class
556   // and make them explicit.
557   llvm::SmallPtrSet<ObjCProtocolDecl *, 8> ExplicitProtocols;
558   Ctx.CollectInheritedProtocols(IDecl, ExplicitProtocols);
559   llvm::SmallVector<ObjCProtocolDecl *, 8> PotentialImplicitProtocols;
560 
561   for (llvm::SmallPtrSet<ObjCProtocolDecl*, 32>::iterator I =
562        ObjCProtocolDecls.begin(),
563        E = ObjCProtocolDecls.end(); I != E; ++I)
564     if (!ExplicitProtocols.count(*I))
565       PotentialImplicitProtocols.push_back(*I);
566 
567   if (PotentialImplicitProtocols.empty())
568     return;
569 
570   // go through list of non-optional methods and properties in each protocol
571   // in the PotentialImplicitProtocols list. If class implements every one of the
572   // methods and properties, then this class conforms to this protocol.
573   llvm::SmallVector<ObjCProtocolDecl*, 8> ConformingProtocols;
574   for (unsigned i = 0, e = PotentialImplicitProtocols.size(); i != e; i++)
575     if (ClassImplementsAllMethodsAndProperties(Ctx, ImpDecl, IDecl,
576                                               PotentialImplicitProtocols[i]))
577       ConformingProtocols.push_back(PotentialImplicitProtocols[i]);
578 
579   if (ConformingProtocols.empty())
580     return;
581 
582   // Further reduce number of conforming protocols. If protocol P1 is in the list
583   // protocol P2 (P2<P1>), No need to include P1.
584   llvm::SmallVector<ObjCProtocolDecl*, 8> MinimalConformingProtocols;
585   for (unsigned i = 0, e = ConformingProtocols.size(); i != e; i++) {
586     bool DropIt = false;
587     ObjCProtocolDecl *TargetPDecl = ConformingProtocols[i];
588     for (unsigned i1 = 0, e1 = ConformingProtocols.size(); i1 != e1; i1++) {
589       ObjCProtocolDecl *PDecl = ConformingProtocols[i1];
590       if (PDecl == TargetPDecl)
591         continue;
592       if (PDecl->lookupProtocolNamed(
593             TargetPDecl->getDeclName().getAsIdentifierInfo())) {
594         DropIt = true;
595         break;
596       }
597     }
598     if (!DropIt)
599       MinimalConformingProtocols.push_back(TargetPDecl);
600   }
601   edit::Commit commit(*Editor);
602   rewriteToObjCInterfaceDecl(IDecl, MinimalConformingProtocols,
603                              *NSAPIObj, commit);
604   Editor->commit(commit);
605 }
606 
607 void ObjCMigrateASTConsumer::migrateNSEnumDecl(ASTContext &Ctx,
608                                            const EnumDecl *EnumDcl,
609                                            const TypedefDecl *TypedefDcl) {
610   if (!EnumDcl->isCompleteDefinition() || EnumDcl->getIdentifier() ||
611       !TypedefDcl->getIdentifier() ||
612       EnumDcl->isDeprecated() || TypedefDcl->isDeprecated())
613     return;
614 
615   QualType qt = TypedefDcl->getTypeSourceInfo()->getType();
616   bool IsNSIntegerType = NSAPIObj->isObjCNSIntegerType(qt);
617   bool IsNSUIntegerType = !IsNSIntegerType && NSAPIObj->isObjCNSUIntegerType(qt);
618 
619   if (!IsNSIntegerType && !IsNSUIntegerType) {
620     // Also check for typedef enum {...} TD;
621     if (const EnumType *EnumTy = qt->getAs<EnumType>()) {
622       if (EnumTy->getDecl() == EnumDcl) {
623         bool NSOptions = UseNSOptionsMacro(PP, Ctx, EnumDcl);
624         if (NSOptions) {
625           if (!Ctx.Idents.get("NS_OPTIONS").hasMacroDefinition())
626             return;
627         }
628         else if (!Ctx.Idents.get("NS_ENUM").hasMacroDefinition())
629           return;
630         edit::Commit commit(*Editor);
631         rewriteToNSMacroDecl(EnumDcl, TypedefDcl, *NSAPIObj, commit, !NSOptions);
632         Editor->commit(commit);
633       }
634     }
635     return;
636   }
637 
638   // We may still use NS_OPTIONS based on what we find in the enumertor list.
639   bool NSOptions = UseNSOptionsMacro(PP, Ctx, EnumDcl);
640   // NS_ENUM must be available.
641   if (IsNSIntegerType && !Ctx.Idents.get("NS_ENUM").hasMacroDefinition())
642     return;
643   // NS_OPTIONS must be available.
644   if (IsNSUIntegerType && !Ctx.Idents.get("NS_OPTIONS").hasMacroDefinition())
645     return;
646   edit::Commit commit(*Editor);
647   rewriteToNSEnumDecl(EnumDcl, TypedefDcl, *NSAPIObj, commit, IsNSIntegerType, NSOptions);
648   Editor->commit(commit);
649 }
650 
651 static void ReplaceWithInstancetype(const ObjCMigrateASTConsumer &ASTC,
652                                     ObjCMethodDecl *OM) {
653   SourceRange R;
654   std::string ClassString;
655   if (TypeSourceInfo *TSInfo =  OM->getResultTypeSourceInfo()) {
656     TypeLoc TL = TSInfo->getTypeLoc();
657     R = SourceRange(TL.getBeginLoc(), TL.getEndLoc());
658     ClassString = "instancetype";
659   }
660   else {
661     R = SourceRange(OM->getLocStart(), OM->getLocStart());
662     ClassString = OM->isInstanceMethod() ? '-' : '+';
663     ClassString += " (instancetype)";
664   }
665   edit::Commit commit(*ASTC.Editor);
666   commit.replace(R, ClassString);
667   ASTC.Editor->commit(commit);
668 }
669 
670 void ObjCMigrateASTConsumer::migrateMethodInstanceType(ASTContext &Ctx,
671                                                        ObjCContainerDecl *CDecl,
672                                                        ObjCMethodDecl *OM) {
673   ObjCInstanceTypeFamily OIT_Family =
674     Selector::getInstTypeMethodFamily(OM->getSelector());
675 
676   std::string ClassName;
677   switch (OIT_Family) {
678     case OIT_None:
679       migrateFactoryMethod(Ctx, CDecl, OM);
680       return;
681     case OIT_Array:
682       ClassName = "NSArray";
683       break;
684     case OIT_Dictionary:
685       ClassName = "NSDictionary";
686       break;
687     case OIT_Singleton:
688       migrateFactoryMethod(Ctx, CDecl, OM, OIT_Singleton);
689       return;
690     case OIT_Init:
691       if (OM->getResultType()->isObjCIdType())
692         ReplaceWithInstancetype(*this, OM);
693       return;
694   }
695   if (!OM->getResultType()->isObjCIdType())
696     return;
697 
698   ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(CDecl);
699   if (!IDecl) {
700     if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(CDecl))
701       IDecl = CatDecl->getClassInterface();
702     else if (ObjCImplDecl *ImpDecl = dyn_cast<ObjCImplDecl>(CDecl))
703       IDecl = ImpDecl->getClassInterface();
704   }
705   if (!IDecl ||
706       !IDecl->lookupInheritedClass(&Ctx.Idents.get(ClassName))) {
707     migrateFactoryMethod(Ctx, CDecl, OM);
708     return;
709   }
710   ReplaceWithInstancetype(*this, OM);
711 }
712 
713 static bool TypeIsInnerPointer(QualType T) {
714   if (!T->isAnyPointerType())
715     return false;
716   if (T->isObjCObjectPointerType() || T->isObjCBuiltinType() ||
717       T->isBlockPointerType() || ento::coreFoundation::isCFObjectRef(T))
718     return false;
719   // Also, typedef-of-pointer-to-incomplete-struct is something that we assume
720   // is not an innter pointer type.
721   QualType OrigT = T;
722   while (const TypedefType *TD = dyn_cast<TypedefType>(T.getTypePtr()))
723     T = TD->getDecl()->getUnderlyingType();
724   if (OrigT == T || !T->isPointerType())
725     return true;
726   const PointerType* PT = T->getAs<PointerType>();
727   QualType UPointeeT = PT->getPointeeType().getUnqualifiedType();
728   if (UPointeeT->isRecordType()) {
729     const RecordType *RecordTy = UPointeeT->getAs<RecordType>();
730     if (!RecordTy->getDecl()->isCompleteDefinition())
731       return false;
732   }
733   return true;
734 }
735 
736 static bool AttributesMatch(const Decl *Decl1, const Decl *Decl2) {
737   if (Decl1->hasAttrs() != Decl2->hasAttrs())
738     return false;
739 
740   if (!Decl1->hasAttrs())
741     return true;
742 
743   const AttrVec &Attrs1 = Decl1->getAttrs();
744   const AttrVec &Attrs2 = Decl2->getAttrs();
745   // This list is very small, so this need not be optimized.
746   for (unsigned i = 0, e = Attrs1.size(); i != e; i++) {
747     bool match = false;
748     for (unsigned j = 0, f = Attrs2.size(); j != f; j++) {
749       // Matching attribute kind only. We are not getting into
750       // details of the attributes. For all practical purposes
751       // this is sufficient.
752       if (Attrs1[i]->getKind() == Attrs2[j]->getKind()) {
753         match = true;
754         break;
755       }
756     }
757     if (!match)
758       return false;
759   }
760   return true;
761 }
762 
763 bool ObjCMigrateASTConsumer::migrateProperty(ASTContext &Ctx,
764                              ObjCContainerDecl *D,
765                              ObjCMethodDecl *Method) {
766   if (Method->isPropertyAccessor() || !Method->isInstanceMethod() ||
767       Method->param_size() != 0)
768     return false;
769   // Is this method candidate to be a getter?
770   QualType GRT = Method->getResultType();
771   if (GRT->isVoidType())
772     return false;
773 
774   Selector GetterSelector = Method->getSelector();
775   ObjCInstanceTypeFamily OIT_Family =
776     Selector::getInstTypeMethodFamily(GetterSelector);
777 
778   if (OIT_Family != OIT_None)
779     return false;
780 
781   IdentifierInfo *getterName = GetterSelector.getIdentifierInfoForSlot(0);
782   Selector SetterSelector =
783   SelectorTable::constructSetterSelector(PP.getIdentifierTable(),
784                                          PP.getSelectorTable(),
785                                          getterName);
786   ObjCMethodDecl *SetterMethod = D->getInstanceMethod(SetterSelector);
787   unsigned LengthOfPrefix = 0;
788   if (!SetterMethod) {
789     // try a different naming convention for getter: isXxxxx
790     StringRef getterNameString = getterName->getName();
791     bool IsPrefix = getterNameString.startswith("is");
792     // Note that we don't want to change an isXXX method of retainable object
793     // type to property (readonly or otherwise).
794     if (IsPrefix && GRT->isObjCRetainableType())
795       return false;
796     if (IsPrefix || getterNameString.startswith("get")) {
797       LengthOfPrefix = (IsPrefix ? 2 : 3);
798       const char *CGetterName = getterNameString.data() + LengthOfPrefix;
799       // Make sure that first character after "is" or "get" prefix can
800       // start an identifier.
801       if (!isIdentifierHead(CGetterName[0]))
802         return false;
803       if (CGetterName[0] && isUppercase(CGetterName[0])) {
804         getterName = &Ctx.Idents.get(CGetterName);
805         SetterSelector =
806         SelectorTable::constructSetterSelector(PP.getIdentifierTable(),
807                                                PP.getSelectorTable(),
808                                                getterName);
809         SetterMethod = D->getInstanceMethod(SetterSelector);
810       }
811     }
812   }
813 
814   if (SetterMethod) {
815     if (SetterMethod->isDeprecated() ||
816         !AttributesMatch(Method, SetterMethod))
817       return false;
818 
819     // Is this a valid setter, matching the target getter?
820     QualType SRT = SetterMethod->getResultType();
821     if (!SRT->isVoidType())
822       return false;
823     const ParmVarDecl *argDecl = *SetterMethod->param_begin();
824     QualType ArgType = argDecl->getType();
825     if (!Ctx.hasSameUnqualifiedType(ArgType, GRT))
826       return false;
827     edit::Commit commit(*Editor);
828     rewriteToObjCProperty(Method, SetterMethod, *NSAPIObj, commit,
829                           LengthOfPrefix);
830     Editor->commit(commit);
831     return true;
832   }
833   else if (MigrateReadonlyProperty) {
834     // Try a non-void method with no argument (and no setter or property of same name
835     // as a 'readonly' property.
836     edit::Commit commit(*Editor);
837     rewriteToObjCProperty(Method, 0 /*SetterMethod*/, *NSAPIObj, commit,
838                           LengthOfPrefix);
839     Editor->commit(commit);
840     return true;
841   }
842   return false;
843 }
844 
845 void ObjCMigrateASTConsumer::migrateNsReturnsInnerPointer(ASTContext &Ctx,
846                                                           ObjCMethodDecl *OM) {
847   if (OM->isImplicit() ||
848       OM->hasAttr<ObjCReturnsInnerPointerAttr>())
849     return;
850 
851   QualType RT = OM->getResultType();
852   if (!TypeIsInnerPointer(RT) ||
853       !Ctx.Idents.get("NS_RETURNS_INNER_POINTER").hasMacroDefinition())
854     return;
855 
856   edit::Commit commit(*Editor);
857   commit.insertBefore(OM->getLocEnd(), " NS_RETURNS_INNER_POINTER");
858   Editor->commit(commit);
859 }
860 
861 void ObjCMigrateASTConsumer::migratePropertyNsReturnsInnerPointer(ASTContext &Ctx,
862                                                                   ObjCPropertyDecl *P) {
863   QualType T = P->getType();
864 
865   if (!TypeIsInnerPointer(T) ||
866       !Ctx.Idents.get("NS_RETURNS_INNER_POINTER").hasMacroDefinition())
867     return;
868   edit::Commit commit(*Editor);
869   commit.insertBefore(P->getLocEnd(), " NS_RETURNS_INNER_POINTER ");
870   Editor->commit(commit);
871 }
872 
873 void ObjCMigrateASTConsumer::migrateMethods(ASTContext &Ctx,
874                                                  ObjCContainerDecl *CDecl) {
875   if (CDecl->isDeprecated())
876     return;
877 
878   // migrate methods which can have instancetype as their result type.
879   for (ObjCContainerDecl::method_iterator M = CDecl->meth_begin(),
880        MEnd = CDecl->meth_end();
881        M != MEnd; ++M) {
882     ObjCMethodDecl *Method = (*M);
883     if (Method->isDeprecated())
884       continue;
885     migrateMethodInstanceType(Ctx, CDecl, Method);
886   }
887 }
888 
889 void ObjCMigrateASTConsumer::migrateFactoryMethod(ASTContext &Ctx,
890                                                   ObjCContainerDecl *CDecl,
891                                                   ObjCMethodDecl *OM,
892                                                   ObjCInstanceTypeFamily OIT_Family) {
893   if (OM->isInstanceMethod() ||
894       OM->getResultType() == Ctx.getObjCInstanceType() ||
895       !OM->getResultType()->isObjCIdType())
896     return;
897 
898   // Candidate factory methods are + (id) NaMeXXX : ... which belong to a class
899   // NSYYYNamE with matching names be at least 3 characters long.
900   ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(CDecl);
901   if (!IDecl) {
902     if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(CDecl))
903       IDecl = CatDecl->getClassInterface();
904     else if (ObjCImplDecl *ImpDecl = dyn_cast<ObjCImplDecl>(CDecl))
905       IDecl = ImpDecl->getClassInterface();
906   }
907   if (!IDecl)
908     return;
909 
910   std::string StringClassName = IDecl->getName();
911   StringRef LoweredClassName(StringClassName);
912   std::string StringLoweredClassName = LoweredClassName.lower();
913   LoweredClassName = StringLoweredClassName;
914 
915   IdentifierInfo *MethodIdName = OM->getSelector().getIdentifierInfoForSlot(0);
916   // Handle method with no name at its first selector slot; e.g. + (id):(int)x.
917   if (!MethodIdName)
918     return;
919 
920   std::string MethodName = MethodIdName->getName();
921   if (OIT_Family == OIT_Singleton) {
922     StringRef STRefMethodName(MethodName);
923     size_t len = 0;
924     if (STRefMethodName.startswith("standard"))
925       len = strlen("standard");
926     else if (STRefMethodName.startswith("shared"))
927       len = strlen("shared");
928     else if (STRefMethodName.startswith("default"))
929       len = strlen("default");
930     else
931       return;
932     MethodName = STRefMethodName.substr(len);
933   }
934   std::string MethodNameSubStr = MethodName.substr(0, 3);
935   StringRef MethodNamePrefix(MethodNameSubStr);
936   std::string StringLoweredMethodNamePrefix = MethodNamePrefix.lower();
937   MethodNamePrefix = StringLoweredMethodNamePrefix;
938   size_t Ix = LoweredClassName.rfind(MethodNamePrefix);
939   if (Ix == StringRef::npos)
940     return;
941   std::string ClassNamePostfix = LoweredClassName.substr(Ix);
942   StringRef LoweredMethodName(MethodName);
943   std::string StringLoweredMethodName = LoweredMethodName.lower();
944   LoweredMethodName = StringLoweredMethodName;
945   if (!LoweredMethodName.startswith(ClassNamePostfix))
946     return;
947   ReplaceWithInstancetype(*this, OM);
948 }
949 
950 static bool IsVoidStarType(QualType Ty) {
951   if (!Ty->isPointerType())
952     return false;
953 
954   while (const TypedefType *TD = dyn_cast<TypedefType>(Ty.getTypePtr()))
955     Ty = TD->getDecl()->getUnderlyingType();
956 
957   // Is the type void*?
958   const PointerType* PT = Ty->getAs<PointerType>();
959   if (PT->getPointeeType().getUnqualifiedType()->isVoidType())
960     return true;
961   return IsVoidStarType(PT->getPointeeType());
962 }
963 
964 /// AuditedType - This routine audits the type AT and returns false if it is one of known
965 /// CF object types or of the "void *" variety. It returns true if we don't care about the type
966 /// such as a non-pointer or pointers which have no ownership issues (such as "int *").
967 static bool AuditedType (QualType AT) {
968   if (!AT->isAnyPointerType() && !AT->isBlockPointerType())
969     return true;
970   // FIXME. There isn't much we can say about CF pointer type; or is there?
971   if (ento::coreFoundation::isCFObjectRef(AT) ||
972       IsVoidStarType(AT) ||
973       // If an ObjC object is type, assuming that it is not a CF function and
974       // that it is an un-audited function.
975       AT->isObjCObjectPointerType() || AT->isObjCBuiltinType())
976     return false;
977   // All other pointers are assumed audited as harmless.
978   return true;
979 }
980 
981 void ObjCMigrateASTConsumer::AnnotateImplicitBridging(ASTContext &Ctx) {
982   if (CFFunctionIBCandidates.empty())
983     return;
984   if (!Ctx.Idents.get("CF_IMPLICIT_BRIDGING_ENABLED").hasMacroDefinition()) {
985     CFFunctionIBCandidates.clear();
986     FileId = 0;
987     return;
988   }
989   // Insert CF_IMPLICIT_BRIDGING_ENABLE/CF_IMPLICIT_BRIDGING_DISABLED
990   const Decl *FirstFD = CFFunctionIBCandidates[0];
991   const Decl *LastFD  =
992     CFFunctionIBCandidates[CFFunctionIBCandidates.size()-1];
993   const char *PragmaString = "\nCF_IMPLICIT_BRIDGING_ENABLED\n\n";
994   edit::Commit commit(*Editor);
995   commit.insertBefore(FirstFD->getLocStart(), PragmaString);
996   PragmaString = "\n\nCF_IMPLICIT_BRIDGING_DISABLED\n";
997   SourceLocation EndLoc = LastFD->getLocEnd();
998   // get location just past end of function location.
999   EndLoc = PP.getLocForEndOfToken(EndLoc);
1000   if (isa<FunctionDecl>(LastFD)) {
1001     // For Methods, EndLoc points to the ending semcolon. So,
1002     // not of these extra work is needed.
1003     Token Tok;
1004     // get locaiton of token that comes after end of function.
1005     bool Failed = PP.getRawToken(EndLoc, Tok, /*IgnoreWhiteSpace=*/true);
1006     if (!Failed)
1007       EndLoc = Tok.getLocation();
1008   }
1009   commit.insertAfterToken(EndLoc, PragmaString);
1010   Editor->commit(commit);
1011   FileId = 0;
1012   CFFunctionIBCandidates.clear();
1013 }
1014 
1015 void ObjCMigrateASTConsumer::migrateCFAnnotation(ASTContext &Ctx, const Decl *Decl) {
1016   if (Decl->isDeprecated())
1017     return;
1018 
1019   if (Decl->hasAttr<CFAuditedTransferAttr>()) {
1020     assert(CFFunctionIBCandidates.empty() &&
1021            "Cannot have audited functions/methods inside user "
1022            "provided CF_IMPLICIT_BRIDGING_ENABLE");
1023     return;
1024   }
1025 
1026   // Finction must be annotated first.
1027   if (const FunctionDecl *FuncDecl = dyn_cast<FunctionDecl>(Decl)) {
1028     CF_BRIDGING_KIND AuditKind = migrateAddFunctionAnnotation(Ctx, FuncDecl);
1029     if (AuditKind == CF_BRIDGING_ENABLE) {
1030       CFFunctionIBCandidates.push_back(Decl);
1031       if (!FileId)
1032         FileId = PP.getSourceManager().getFileID(Decl->getLocation()).getHashValue();
1033     }
1034     else if (AuditKind == CF_BRIDGING_MAY_INCLUDE) {
1035       if (!CFFunctionIBCandidates.empty()) {
1036         CFFunctionIBCandidates.push_back(Decl);
1037         if (!FileId)
1038           FileId = PP.getSourceManager().getFileID(Decl->getLocation()).getHashValue();
1039       }
1040     }
1041     else
1042       AnnotateImplicitBridging(Ctx);
1043   }
1044   else {
1045     migrateAddMethodAnnotation(Ctx, cast<ObjCMethodDecl>(Decl));
1046     AnnotateImplicitBridging(Ctx);
1047   }
1048 }
1049 
1050 void ObjCMigrateASTConsumer::AddCFAnnotations(ASTContext &Ctx,
1051                                               const CallEffects &CE,
1052                                               const FunctionDecl *FuncDecl,
1053                                               bool ResultAnnotated) {
1054   // Annotate function.
1055   if (!ResultAnnotated) {
1056     RetEffect Ret = CE.getReturnValue();
1057     const char *AnnotationString = 0;
1058     if (Ret.getObjKind() == RetEffect::CF) {
1059       if (Ret.isOwned() &&
1060           Ctx.Idents.get("CF_RETURNS_RETAINED").hasMacroDefinition())
1061         AnnotationString = " CF_RETURNS_RETAINED";
1062       else if (Ret.notOwned() &&
1063                Ctx.Idents.get("CF_RETURNS_NOT_RETAINED").hasMacroDefinition())
1064         AnnotationString = " CF_RETURNS_NOT_RETAINED";
1065     }
1066     else if (Ret.getObjKind() == RetEffect::ObjC) {
1067       if (Ret.isOwned() &&
1068           Ctx.Idents.get("NS_RETURNS_RETAINED").hasMacroDefinition())
1069         AnnotationString = " NS_RETURNS_RETAINED";
1070     }
1071 
1072     if (AnnotationString) {
1073       edit::Commit commit(*Editor);
1074       commit.insertAfterToken(FuncDecl->getLocEnd(), AnnotationString);
1075       Editor->commit(commit);
1076     }
1077   }
1078   llvm::ArrayRef<ArgEffect> AEArgs = CE.getArgs();
1079   unsigned i = 0;
1080   for (FunctionDecl::param_const_iterator pi = FuncDecl->param_begin(),
1081        pe = FuncDecl->param_end(); pi != pe; ++pi, ++i) {
1082     const ParmVarDecl *pd = *pi;
1083     ArgEffect AE = AEArgs[i];
1084     if (AE == DecRef && !pd->getAttr<CFConsumedAttr>() &&
1085         Ctx.Idents.get("CF_CONSUMED").hasMacroDefinition()) {
1086       edit::Commit commit(*Editor);
1087       commit.insertBefore(pd->getLocation(), "CF_CONSUMED ");
1088       Editor->commit(commit);
1089     }
1090     else if (AE == DecRefMsg && !pd->getAttr<NSConsumedAttr>() &&
1091              Ctx.Idents.get("NS_CONSUMED").hasMacroDefinition()) {
1092       edit::Commit commit(*Editor);
1093       commit.insertBefore(pd->getLocation(), "NS_CONSUMED ");
1094       Editor->commit(commit);
1095     }
1096   }
1097 }
1098 
1099 
1100 ObjCMigrateASTConsumer::CF_BRIDGING_KIND
1101   ObjCMigrateASTConsumer::migrateAddFunctionAnnotation(
1102                                                   ASTContext &Ctx,
1103                                                   const FunctionDecl *FuncDecl) {
1104   if (FuncDecl->hasBody())
1105     return CF_BRIDGING_NONE;
1106 
1107   CallEffects CE  = CallEffects::getEffect(FuncDecl);
1108   bool FuncIsReturnAnnotated = (FuncDecl->getAttr<CFReturnsRetainedAttr>() ||
1109                                 FuncDecl->getAttr<CFReturnsNotRetainedAttr>() ||
1110                                 FuncDecl->getAttr<NSReturnsRetainedAttr>() ||
1111                                 FuncDecl->getAttr<NSReturnsNotRetainedAttr>() ||
1112                                 FuncDecl->getAttr<NSReturnsAutoreleasedAttr>());
1113 
1114   // Trivial case of when funciton is annotated and has no argument.
1115   if (FuncIsReturnAnnotated && FuncDecl->getNumParams() == 0)
1116     return CF_BRIDGING_NONE;
1117 
1118   bool ReturnCFAudited = false;
1119   if (!FuncIsReturnAnnotated) {
1120     RetEffect Ret = CE.getReturnValue();
1121     if (Ret.getObjKind() == RetEffect::CF &&
1122         (Ret.isOwned() || Ret.notOwned()))
1123       ReturnCFAudited = true;
1124     else if (!AuditedType(FuncDecl->getResultType()))
1125       return CF_BRIDGING_NONE;
1126   }
1127 
1128   // At this point result type is audited for potential inclusion.
1129   // Now, how about argument types.
1130   llvm::ArrayRef<ArgEffect> AEArgs = CE.getArgs();
1131   unsigned i = 0;
1132   bool ArgCFAudited = false;
1133   for (FunctionDecl::param_const_iterator pi = FuncDecl->param_begin(),
1134        pe = FuncDecl->param_end(); pi != pe; ++pi, ++i) {
1135     const ParmVarDecl *pd = *pi;
1136     ArgEffect AE = AEArgs[i];
1137     if (AE == DecRef /*CFConsumed annotated*/ || AE == IncRef) {
1138       if (AE == DecRef && !pd->getAttr<CFConsumedAttr>())
1139         ArgCFAudited = true;
1140       else if (AE == IncRef)
1141         ArgCFAudited = true;
1142     }
1143     else {
1144       QualType AT = pd->getType();
1145       if (!AuditedType(AT)) {
1146         AddCFAnnotations(Ctx, CE, FuncDecl, FuncIsReturnAnnotated);
1147         return CF_BRIDGING_NONE;
1148       }
1149     }
1150   }
1151   if (ReturnCFAudited || ArgCFAudited)
1152     return CF_BRIDGING_ENABLE;
1153 
1154   return CF_BRIDGING_MAY_INCLUDE;
1155 }
1156 
1157 void ObjCMigrateASTConsumer::migrateARCSafeAnnotation(ASTContext &Ctx,
1158                                                  ObjCContainerDecl *CDecl) {
1159   if (!isa<ObjCInterfaceDecl>(CDecl) || CDecl->isDeprecated())
1160     return;
1161 
1162   // migrate methods which can have instancetype as their result type.
1163   for (ObjCContainerDecl::method_iterator M = CDecl->meth_begin(),
1164        MEnd = CDecl->meth_end();
1165        M != MEnd; ++M) {
1166     ObjCMethodDecl *Method = (*M);
1167     migrateCFAnnotation(Ctx, Method);
1168   }
1169 }
1170 
1171 void ObjCMigrateASTConsumer::AddCFAnnotations(ASTContext &Ctx,
1172                                               const CallEffects &CE,
1173                                               const ObjCMethodDecl *MethodDecl,
1174                                               bool ResultAnnotated) {
1175   // Annotate function.
1176   if (!ResultAnnotated) {
1177     RetEffect Ret = CE.getReturnValue();
1178     const char *AnnotationString = 0;
1179     if (Ret.getObjKind() == RetEffect::CF) {
1180       if (Ret.isOwned() &&
1181           Ctx.Idents.get("CF_RETURNS_RETAINED").hasMacroDefinition())
1182         AnnotationString = " CF_RETURNS_RETAINED";
1183       else if (Ret.notOwned() &&
1184                Ctx.Idents.get("CF_RETURNS_NOT_RETAINED").hasMacroDefinition())
1185         AnnotationString = " CF_RETURNS_NOT_RETAINED";
1186     }
1187     else if (Ret.getObjKind() == RetEffect::ObjC) {
1188       ObjCMethodFamily OMF = MethodDecl->getMethodFamily();
1189       switch (OMF) {
1190         case clang::OMF_alloc:
1191         case clang::OMF_new:
1192         case clang::OMF_copy:
1193         case clang::OMF_init:
1194         case clang::OMF_mutableCopy:
1195           break;
1196 
1197         default:
1198           if (Ret.isOwned() &&
1199               Ctx.Idents.get("NS_RETURNS_RETAINED").hasMacroDefinition())
1200             AnnotationString = " NS_RETURNS_RETAINED";
1201           break;
1202       }
1203     }
1204 
1205     if (AnnotationString) {
1206       edit::Commit commit(*Editor);
1207       commit.insertBefore(MethodDecl->getLocEnd(), AnnotationString);
1208       Editor->commit(commit);
1209     }
1210   }
1211   llvm::ArrayRef<ArgEffect> AEArgs = CE.getArgs();
1212   unsigned i = 0;
1213   for (ObjCMethodDecl::param_const_iterator pi = MethodDecl->param_begin(),
1214        pe = MethodDecl->param_end(); pi != pe; ++pi, ++i) {
1215     const ParmVarDecl *pd = *pi;
1216     ArgEffect AE = AEArgs[i];
1217     if (AE == DecRef && !pd->getAttr<CFConsumedAttr>() &&
1218         Ctx.Idents.get("CF_CONSUMED").hasMacroDefinition()) {
1219       edit::Commit commit(*Editor);
1220       commit.insertBefore(pd->getLocation(), "CF_CONSUMED ");
1221       Editor->commit(commit);
1222     }
1223   }
1224 }
1225 
1226 void ObjCMigrateASTConsumer::migrateAddMethodAnnotation(
1227                                             ASTContext &Ctx,
1228                                             const ObjCMethodDecl *MethodDecl) {
1229   if (MethodDecl->hasBody() || MethodDecl->isImplicit())
1230     return;
1231 
1232   CallEffects CE  = CallEffects::getEffect(MethodDecl);
1233   bool MethodIsReturnAnnotated = (MethodDecl->getAttr<CFReturnsRetainedAttr>() ||
1234                                   MethodDecl->getAttr<CFReturnsNotRetainedAttr>() ||
1235                                   MethodDecl->getAttr<NSReturnsRetainedAttr>() ||
1236                                   MethodDecl->getAttr<NSReturnsNotRetainedAttr>() ||
1237                                   MethodDecl->getAttr<NSReturnsAutoreleasedAttr>());
1238 
1239   if (CE.getReceiver() ==  DecRefMsg &&
1240       !MethodDecl->getAttr<NSConsumesSelfAttr>() &&
1241       MethodDecl->getMethodFamily() != OMF_init &&
1242       MethodDecl->getMethodFamily() != OMF_release &&
1243       Ctx.Idents.get("NS_CONSUMES_SELF").hasMacroDefinition()) {
1244     edit::Commit commit(*Editor);
1245     commit.insertBefore(MethodDecl->getLocEnd(), " NS_CONSUMES_SELF");
1246     Editor->commit(commit);
1247   }
1248 
1249   // Trivial case of when funciton is annotated and has no argument.
1250   if (MethodIsReturnAnnotated &&
1251       (MethodDecl->param_begin() == MethodDecl->param_end()))
1252     return;
1253 
1254   if (!MethodIsReturnAnnotated) {
1255     RetEffect Ret = CE.getReturnValue();
1256     if ((Ret.getObjKind() == RetEffect::CF ||
1257          Ret.getObjKind() == RetEffect::ObjC) &&
1258         (Ret.isOwned() || Ret.notOwned())) {
1259       AddCFAnnotations(Ctx, CE, MethodDecl, false);
1260       return;
1261     }
1262     else if (!AuditedType(MethodDecl->getResultType()))
1263       return;
1264   }
1265 
1266   // At this point result type is either annotated or audited.
1267   // Now, how about argument types.
1268   llvm::ArrayRef<ArgEffect> AEArgs = CE.getArgs();
1269   unsigned i = 0;
1270   for (ObjCMethodDecl::param_const_iterator pi = MethodDecl->param_begin(),
1271        pe = MethodDecl->param_end(); pi != pe; ++pi, ++i) {
1272     const ParmVarDecl *pd = *pi;
1273     ArgEffect AE = AEArgs[i];
1274     if ((AE == DecRef && !pd->getAttr<CFConsumedAttr>()) || AE == IncRef ||
1275         !AuditedType(pd->getType())) {
1276       AddCFAnnotations(Ctx, CE, MethodDecl, MethodIsReturnAnnotated);
1277       return;
1278     }
1279   }
1280   return;
1281 }
1282 
1283 namespace {
1284 
1285 class RewritesReceiver : public edit::EditsReceiver {
1286   Rewriter &Rewrite;
1287 
1288 public:
1289   RewritesReceiver(Rewriter &Rewrite) : Rewrite(Rewrite) { }
1290 
1291   virtual void insert(SourceLocation loc, StringRef text) {
1292     Rewrite.InsertText(loc, text);
1293   }
1294   virtual void replace(CharSourceRange range, StringRef text) {
1295     Rewrite.ReplaceText(range.getBegin(), Rewrite.getRangeSize(range), text);
1296   }
1297 };
1298 
1299 }
1300 
1301 void ObjCMigrateASTConsumer::HandleTranslationUnit(ASTContext &Ctx) {
1302 
1303   TranslationUnitDecl *TU = Ctx.getTranslationUnitDecl();
1304   if (MigrateProperty) {
1305     for (DeclContext::decl_iterator D = TU->decls_begin(), DEnd = TU->decls_end();
1306          D != DEnd; ++D) {
1307       if (unsigned FID =
1308             PP.getSourceManager().getFileID((*D)->getLocation()).getHashValue())
1309         if (FileId && FileId != FID)
1310           AnnotateImplicitBridging(Ctx);
1311 
1312       if (ObjCInterfaceDecl *CDecl = dyn_cast<ObjCInterfaceDecl>(*D))
1313         migrateObjCInterfaceDecl(Ctx, CDecl);
1314       if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(*D))
1315         migrateObjCInterfaceDecl(Ctx, CatDecl);
1316       else if (ObjCProtocolDecl *PDecl = dyn_cast<ObjCProtocolDecl>(*D))
1317         ObjCProtocolDecls.insert(PDecl);
1318       else if (const ObjCImplementationDecl *ImpDecl =
1319                dyn_cast<ObjCImplementationDecl>(*D))
1320         migrateProtocolConformance(Ctx, ImpDecl);
1321       else if (const EnumDecl *ED = dyn_cast<EnumDecl>(*D)) {
1322         DeclContext::decl_iterator N = D;
1323         ++N;
1324         if (N != DEnd)
1325           if (const TypedefDecl *TD = dyn_cast<TypedefDecl>(*N))
1326             migrateNSEnumDecl(Ctx, ED, TD);
1327       }
1328       else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(*D))
1329         migrateCFAnnotation(Ctx, FD);
1330 
1331       if (ObjCContainerDecl *CDecl = dyn_cast<ObjCContainerDecl>(*D)) {
1332         // migrate methods which can have instancetype as their result type.
1333         migrateMethods(Ctx, CDecl);
1334         // annotate methods with CF annotations.
1335         migrateARCSafeAnnotation(Ctx, CDecl);
1336       }
1337     }
1338     AnnotateImplicitBridging(Ctx);
1339   }
1340 
1341   Rewriter rewriter(Ctx.getSourceManager(), Ctx.getLangOpts());
1342   RewritesReceiver Rec(rewriter);
1343   Editor->applyRewrites(Rec);
1344 
1345   for (Rewriter::buffer_iterator
1346         I = rewriter.buffer_begin(), E = rewriter.buffer_end(); I != E; ++I) {
1347     FileID FID = I->first;
1348     RewriteBuffer &buf = I->second;
1349     const FileEntry *file = Ctx.getSourceManager().getFileEntryForID(FID);
1350     assert(file);
1351     SmallString<512> newText;
1352     llvm::raw_svector_ostream vecOS(newText);
1353     buf.write(vecOS);
1354     vecOS.flush();
1355     llvm::MemoryBuffer *memBuf = llvm::MemoryBuffer::getMemBufferCopy(
1356                    StringRef(newText.data(), newText.size()), file->getName());
1357     SmallString<64> filePath(file->getName());
1358     FileMgr.FixupRelativePath(filePath);
1359     Remapper.remap(filePath.str(), memBuf);
1360   }
1361 
1362   if (IsOutputFile) {
1363     Remapper.flushToFile(MigrateDir, Ctx.getDiagnostics());
1364   } else {
1365     Remapper.flushToDisk(MigrateDir, Ctx.getDiagnostics());
1366   }
1367 }
1368 
1369 bool MigrateSourceAction::BeginInvocation(CompilerInstance &CI) {
1370   CI.getDiagnostics().setIgnoreAllWarnings(true);
1371   return true;
1372 }
1373 
1374 ASTConsumer *MigrateSourceAction::CreateASTConsumer(CompilerInstance &CI,
1375                                                   StringRef InFile) {
1376   PPConditionalDirectiveRecord *
1377     PPRec = new PPConditionalDirectiveRecord(CI.getSourceManager());
1378   CI.getPreprocessor().addPPCallbacks(PPRec);
1379   return new ObjCMigrateASTConsumer(CI.getFrontendOpts().OutputFile,
1380                                     /*MigrateLiterals=*/true,
1381                                     /*MigrateSubscripting=*/true,
1382                                     /*MigrateProperty*/true,
1383                                     /*MigrateReadonlyProperty*/true,
1384                                     Remapper,
1385                                     CI.getFileManager(),
1386                                     PPRec,
1387                                     CI.getPreprocessor(),
1388                                     /*isOutputFile=*/true);
1389 }
1390