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/ARCMT.h"
12 #include "clang/ARCMigrate/ARCMTActions.h"
13 #include "clang/AST/ASTConsumer.h"
14 #include "clang/AST/ASTContext.h"
15 #include "clang/AST/Attr.h"
16 #include "clang/AST/NSAPI.h"
17 #include "clang/AST/ParentMap.h"
18 #include "clang/AST/RecursiveASTVisitor.h"
19 #include "clang/Analysis/DomainSpecific/CocoaConventions.h"
20 #include "clang/Basic/FileManager.h"
21 #include "clang/Edit/Commit.h"
22 #include "clang/Edit/EditedSource.h"
23 #include "clang/Edit/EditsReceiver.h"
24 #include "clang/Edit/Rewriters.h"
25 #include "clang/Frontend/CompilerInstance.h"
26 #include "clang/Frontend/MultiplexConsumer.h"
27 #include "clang/Lex/PPConditionalDirectiveRecord.h"
28 #include "clang/Lex/Preprocessor.h"
29 #include "clang/Rewrite/Core/Rewriter.h"
30 #include "clang/StaticAnalyzer/Checkers/ObjCRetainCount.h"
31 #include "llvm/ADT/SmallString.h"
32 #include "llvm/Support/Path.h"
33 #include "llvm/Support/SourceMgr.h"
34 #include "llvm/Support/YAMLParser.h"
35 
36 using namespace clang;
37 using namespace arcmt;
38 using namespace ento::objc_retain;
39 
40 namespace {
41 
42 class ObjCMigrateASTConsumer : public ASTConsumer {
43   enum CF_BRIDGING_KIND {
44     CF_BRIDGING_NONE,
45     CF_BRIDGING_ENABLE,
46     CF_BRIDGING_MAY_INCLUDE
47   };
48 
49   void migrateDecl(Decl *D);
50   void migrateObjCInterfaceDecl(ASTContext &Ctx, ObjCContainerDecl *D);
51   void migrateProtocolConformance(ASTContext &Ctx,
52                                   const ObjCImplementationDecl *ImpDecl);
53   void CacheObjCNSIntegerTypedefed(const TypedefDecl *TypedefDcl);
54   bool migrateNSEnumDecl(ASTContext &Ctx, const EnumDecl *EnumDcl,
55                      const TypedefDecl *TypedefDcl);
56   void migrateAllMethodInstaceType(ASTContext &Ctx, ObjCContainerDecl *CDecl);
57   void migrateMethodInstanceType(ASTContext &Ctx, ObjCContainerDecl *CDecl,
58                                  ObjCMethodDecl *OM);
59   bool migrateProperty(ASTContext &Ctx, ObjCContainerDecl *D, ObjCMethodDecl *OM);
60   void migrateNsReturnsInnerPointer(ASTContext &Ctx, ObjCMethodDecl *OM);
61   void migratePropertyNsReturnsInnerPointer(ASTContext &Ctx, ObjCPropertyDecl *P);
62   void migrateFactoryMethod(ASTContext &Ctx, ObjCContainerDecl *CDecl,
63                             ObjCMethodDecl *OM,
64                             ObjCInstanceTypeFamily OIT_Family = OIT_None);
65 
66   void migrateCFAnnotation(ASTContext &Ctx, const Decl *Decl);
67   void AddCFAnnotations(ASTContext &Ctx, const CallEffects &CE,
68                         const FunctionDecl *FuncDecl, bool ResultAnnotated);
69   void AddCFAnnotations(ASTContext &Ctx, const CallEffects &CE,
70                         const ObjCMethodDecl *MethodDecl, bool ResultAnnotated);
71 
72   void AnnotateImplicitBridging(ASTContext &Ctx);
73 
74   CF_BRIDGING_KIND migrateAddFunctionAnnotation(ASTContext &Ctx,
75                                                 const FunctionDecl *FuncDecl);
76 
77   void migrateARCSafeAnnotation(ASTContext &Ctx, ObjCContainerDecl *CDecl);
78 
79   void migrateAddMethodAnnotation(ASTContext &Ctx,
80                                   const ObjCMethodDecl *MethodDecl);
81 
82   void inferDesignatedInitializers(ASTContext &Ctx,
83                                    const ObjCImplementationDecl *ImplD);
84 
85 public:
86   std::string MigrateDir;
87   unsigned ASTMigrateActions;
88   FileID FileId;
89   const TypedefDecl *NSIntegerTypedefed;
90   const TypedefDecl *NSUIntegerTypedefed;
91   std::unique_ptr<NSAPI> NSAPIObj;
92   std::unique_ptr<edit::EditedSource> Editor;
93   FileRemapper &Remapper;
94   FileManager &FileMgr;
95   const PPConditionalDirectiveRecord *PPRec;
96   Preprocessor &PP;
97   bool IsOutputFile;
98   llvm::SmallPtrSet<ObjCProtocolDecl *, 32> ObjCProtocolDecls;
99   llvm::SmallVector<const Decl *, 8> CFFunctionIBCandidates;
100   llvm::StringMap<char> WhiteListFilenames;
101 
102   ObjCMigrateASTConsumer(StringRef migrateDir,
103                          unsigned astMigrateActions,
104                          FileRemapper &remapper,
105                          FileManager &fileMgr,
106                          const PPConditionalDirectiveRecord *PPRec,
107                          Preprocessor &PP,
108                          bool isOutputFile,
109                          ArrayRef<std::string> WhiteList)
110   : MigrateDir(migrateDir),
111     ASTMigrateActions(astMigrateActions),
112     NSIntegerTypedefed(0), NSUIntegerTypedefed(0),
113     Remapper(remapper), FileMgr(fileMgr), PPRec(PPRec), PP(PP),
114     IsOutputFile(isOutputFile) {
115 
116     for (ArrayRef<std::string>::iterator
117            I = WhiteList.begin(), E = WhiteList.end(); I != E; ++I) {
118       WhiteListFilenames.GetOrCreateValue(*I);
119     }
120   }
121 
122 protected:
123   void Initialize(ASTContext &Context) override {
124     NSAPIObj.reset(new NSAPI(Context));
125     Editor.reset(new edit::EditedSource(Context.getSourceManager(),
126                                         Context.getLangOpts(),
127                                         PPRec, false));
128   }
129 
130   bool HandleTopLevelDecl(DeclGroupRef DG) override {
131     for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I)
132       migrateDecl(*I);
133     return true;
134   }
135   void HandleInterestingDecl(DeclGroupRef DG) override {
136     // Ignore decls from the PCH.
137   }
138   void HandleTopLevelDeclInObjCContainer(DeclGroupRef DG) override {
139     ObjCMigrateASTConsumer::HandleTopLevelDecl(DG);
140   }
141 
142   void HandleTranslationUnit(ASTContext &Ctx) override;
143 
144   bool canModifyFile(StringRef Path) {
145     if (WhiteListFilenames.empty())
146       return true;
147     return WhiteListFilenames.find(llvm::sys::path::filename(Path))
148         != WhiteListFilenames.end();
149   }
150   bool canModifyFile(const FileEntry *FE) {
151     if (!FE)
152       return false;
153     return canModifyFile(FE->getName());
154   }
155   bool canModifyFile(FileID FID) {
156     if (FID.isInvalid())
157       return false;
158     return canModifyFile(PP.getSourceManager().getFileEntryForID(FID));
159   }
160 
161   bool canModify(const Decl *D) {
162     if (!D)
163       return false;
164     if (const ObjCCategoryImplDecl *CatImpl = dyn_cast<ObjCCategoryImplDecl>(D))
165       return canModify(CatImpl->getCategoryDecl());
166     if (const ObjCImplementationDecl *Impl = dyn_cast<ObjCImplementationDecl>(D))
167       return canModify(Impl->getClassInterface());
168     if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
169       return canModify(cast<Decl>(MD->getDeclContext()));
170 
171     FileID FID = PP.getSourceManager().getFileID(D->getLocation());
172     return canModifyFile(FID);
173   }
174 };
175 
176 }
177 
178 ObjCMigrateAction::ObjCMigrateAction(FrontendAction *WrappedAction,
179                                      StringRef migrateDir,
180                                      unsigned migrateAction)
181   : WrapperFrontendAction(WrappedAction), MigrateDir(migrateDir),
182     ObjCMigAction(migrateAction),
183     CompInst(0) {
184   if (MigrateDir.empty())
185     MigrateDir = "."; // user current directory if none is given.
186 }
187 
188 ASTConsumer *ObjCMigrateAction::CreateASTConsumer(CompilerInstance &CI,
189                                                   StringRef InFile) {
190   PPConditionalDirectiveRecord *
191     PPRec = new PPConditionalDirectiveRecord(CompInst->getSourceManager());
192   CompInst->getPreprocessor().addPPCallbacks(PPRec);
193   ASTConsumer *
194     WrappedConsumer = WrapperFrontendAction::CreateASTConsumer(CI, InFile);
195   ASTConsumer *MTConsumer = new ObjCMigrateASTConsumer(MigrateDir,
196                                                        ObjCMigAction,
197                                                        Remapper,
198                                                     CompInst->getFileManager(),
199                                                        PPRec,
200                                                        CompInst->getPreprocessor(),
201                                                        false,
202                                                        ArrayRef<std::string>());
203   ASTConsumer *Consumers[] = { MTConsumer, WrappedConsumer };
204   return new MultiplexConsumer(Consumers);
205 }
206 
207 bool ObjCMigrateAction::BeginInvocation(CompilerInstance &CI) {
208   Remapper.initFromDisk(MigrateDir, CI.getDiagnostics(),
209                         /*ignoreIfFilesChanges=*/true);
210   CompInst = &CI;
211   CI.getDiagnostics().setIgnoreAllWarnings(true);
212   return true;
213 }
214 
215 namespace {
216 class ObjCMigrator : public RecursiveASTVisitor<ObjCMigrator> {
217   ObjCMigrateASTConsumer &Consumer;
218   ParentMap &PMap;
219 
220 public:
221   ObjCMigrator(ObjCMigrateASTConsumer &consumer, ParentMap &PMap)
222     : Consumer(consumer), PMap(PMap) { }
223 
224   bool shouldVisitTemplateInstantiations() const { return false; }
225   bool shouldWalkTypesOfTypeLocs() const { return false; }
226 
227   bool VisitObjCMessageExpr(ObjCMessageExpr *E) {
228     if (Consumer.ASTMigrateActions & FrontendOptions::ObjCMT_Literals) {
229       edit::Commit commit(*Consumer.Editor);
230       edit::rewriteToObjCLiteralSyntax(E, *Consumer.NSAPIObj, commit, &PMap);
231       Consumer.Editor->commit(commit);
232     }
233 
234     if (Consumer.ASTMigrateActions & FrontendOptions::ObjCMT_Subscripting) {
235       edit::Commit commit(*Consumer.Editor);
236       edit::rewriteToObjCSubscriptSyntax(E, *Consumer.NSAPIObj, commit);
237       Consumer.Editor->commit(commit);
238     }
239 
240     return true;
241   }
242 
243   bool TraverseObjCMessageExpr(ObjCMessageExpr *E) {
244     // Do depth first; we want to rewrite the subexpressions first so that if
245     // we have to move expressions we will move them already rewritten.
246     for (Stmt::child_range range = E->children(); range; ++range)
247       if (!TraverseStmt(*range))
248         return false;
249 
250     return WalkUpFromObjCMessageExpr(E);
251   }
252 };
253 
254 class BodyMigrator : public RecursiveASTVisitor<BodyMigrator> {
255   ObjCMigrateASTConsumer &Consumer;
256   std::unique_ptr<ParentMap> PMap;
257 
258 public:
259   BodyMigrator(ObjCMigrateASTConsumer &consumer) : Consumer(consumer) { }
260 
261   bool shouldVisitTemplateInstantiations() const { return false; }
262   bool shouldWalkTypesOfTypeLocs() const { return false; }
263 
264   bool TraverseStmt(Stmt *S) {
265     PMap.reset(new ParentMap(S));
266     ObjCMigrator(Consumer, *PMap).TraverseStmt(S);
267     return true;
268   }
269 };
270 }
271 
272 void ObjCMigrateASTConsumer::migrateDecl(Decl *D) {
273   if (!D)
274     return;
275   if (isa<ObjCMethodDecl>(D))
276     return; // Wait for the ObjC container declaration.
277 
278   BodyMigrator(*this).TraverseDecl(D);
279 }
280 
281 static void append_attr(std::string &PropertyString, const char *attr,
282                         bool &LParenAdded) {
283   if (!LParenAdded) {
284     PropertyString += "(";
285     LParenAdded = true;
286   }
287   else
288     PropertyString += ", ";
289   PropertyString += attr;
290 }
291 
292 static
293 void MigrateBlockOrFunctionPointerTypeVariable(std::string & PropertyString,
294                                                const std::string& TypeString,
295                                                const char *name) {
296   const char *argPtr = TypeString.c_str();
297   int paren = 0;
298   while (*argPtr) {
299     switch (*argPtr) {
300       case '(':
301         PropertyString += *argPtr;
302         paren++;
303         break;
304       case ')':
305         PropertyString += *argPtr;
306         paren--;
307         break;
308       case '^':
309       case '*':
310         PropertyString += (*argPtr);
311         if (paren == 1) {
312           PropertyString += name;
313           name = "";
314         }
315         break;
316       default:
317         PropertyString += *argPtr;
318         break;
319     }
320     argPtr++;
321   }
322 }
323 
324 static const char *PropertyMemoryAttribute(ASTContext &Context, QualType ArgType) {
325   Qualifiers::ObjCLifetime propertyLifetime = ArgType.getObjCLifetime();
326   bool RetainableObject = ArgType->isObjCRetainableType();
327   if (RetainableObject &&
328       (propertyLifetime == Qualifiers::OCL_Strong
329        || propertyLifetime == Qualifiers::OCL_None)) {
330     if (const ObjCObjectPointerType *ObjPtrTy =
331         ArgType->getAs<ObjCObjectPointerType>()) {
332       ObjCInterfaceDecl *IDecl = ObjPtrTy->getObjectType()->getInterface();
333       if (IDecl &&
334           IDecl->lookupNestedProtocol(&Context.Idents.get("NSCopying")))
335         return "copy";
336       else
337         return "strong";
338     }
339     else if (ArgType->isBlockPointerType())
340       return "copy";
341   } else if (propertyLifetime == Qualifiers::OCL_Weak)
342     // TODO. More precise determination of 'weak' attribute requires
343     // looking into setter's implementation for backing weak ivar.
344     return "weak";
345   else if (RetainableObject)
346     return ArgType->isBlockPointerType() ? "copy" : "strong";
347   return 0;
348 }
349 
350 static void rewriteToObjCProperty(const ObjCMethodDecl *Getter,
351                                   const ObjCMethodDecl *Setter,
352                                   const NSAPI &NS, edit::Commit &commit,
353                                   unsigned LengthOfPrefix,
354                                   bool Atomic, bool UseNsIosOnlyMacro,
355                                   bool AvailabilityArgsMatch) {
356   ASTContext &Context = NS.getASTContext();
357   bool LParenAdded = false;
358   std::string PropertyString = "@property ";
359   if (UseNsIosOnlyMacro && Context.Idents.get("NS_NONATOMIC_IOSONLY").hasMacroDefinition()) {
360     PropertyString += "(NS_NONATOMIC_IOSONLY";
361     LParenAdded = true;
362   } else if (!Atomic) {
363     PropertyString += "(nonatomic";
364     LParenAdded = true;
365   }
366 
367   std::string PropertyNameString = Getter->getNameAsString();
368   StringRef PropertyName(PropertyNameString);
369   if (LengthOfPrefix > 0) {
370     if (!LParenAdded) {
371       PropertyString += "(getter=";
372       LParenAdded = true;
373     }
374     else
375       PropertyString += ", getter=";
376     PropertyString += PropertyNameString;
377   }
378   // Property with no setter may be suggested as a 'readonly' property.
379   if (!Setter)
380     append_attr(PropertyString, "readonly", LParenAdded);
381 
382 
383   // Short circuit 'delegate' properties that contain the name "delegate" or
384   // "dataSource", or have exact name "target" to have 'assign' attribute.
385   if (PropertyName.equals("target") ||
386       (PropertyName.find("delegate") != StringRef::npos) ||
387       (PropertyName.find("dataSource") != StringRef::npos)) {
388     QualType QT = Getter->getReturnType();
389     if (!QT->isRealType())
390       append_attr(PropertyString, "assign", LParenAdded);
391   } else if (!Setter) {
392     QualType ResType = Context.getCanonicalType(Getter->getReturnType());
393     if (const char *MemoryManagementAttr = PropertyMemoryAttribute(Context, ResType))
394       append_attr(PropertyString, MemoryManagementAttr, LParenAdded);
395   } else {
396     const ParmVarDecl *argDecl = *Setter->param_begin();
397     QualType ArgType = Context.getCanonicalType(argDecl->getType());
398     if (const char *MemoryManagementAttr = PropertyMemoryAttribute(Context, ArgType))
399       append_attr(PropertyString, MemoryManagementAttr, LParenAdded);
400   }
401   if (LParenAdded)
402     PropertyString += ')';
403   QualType RT = Getter->getReturnType();
404   if (!isa<TypedefType>(RT)) {
405     // strip off any ARC lifetime qualifier.
406     QualType CanResultTy = Context.getCanonicalType(RT);
407     if (CanResultTy.getQualifiers().hasObjCLifetime()) {
408       Qualifiers Qs = CanResultTy.getQualifiers();
409       Qs.removeObjCLifetime();
410       RT = Context.getQualifiedType(CanResultTy.getUnqualifiedType(), Qs);
411     }
412   }
413   PropertyString += " ";
414   PrintingPolicy SubPolicy(Context.getPrintingPolicy());
415   SubPolicy.SuppressStrongLifetime = true;
416   SubPolicy.SuppressLifetimeQualifiers = true;
417   std::string TypeString = RT.getAsString(SubPolicy);
418   if (LengthOfPrefix > 0) {
419     // property name must strip off "is" and lower case the first character
420     // after that; e.g. isContinuous will become continuous.
421     StringRef PropertyNameStringRef(PropertyNameString);
422     PropertyNameStringRef = PropertyNameStringRef.drop_front(LengthOfPrefix);
423     PropertyNameString = PropertyNameStringRef;
424     bool NoLowering = (isUppercase(PropertyNameString[0]) &&
425                        PropertyNameString.size() > 1 &&
426                        isUppercase(PropertyNameString[1]));
427     if (!NoLowering)
428       PropertyNameString[0] = toLowercase(PropertyNameString[0]);
429   }
430   if (RT->isBlockPointerType() || RT->isFunctionPointerType())
431     MigrateBlockOrFunctionPointerTypeVariable(PropertyString,
432                                               TypeString,
433                                               PropertyNameString.c_str());
434   else {
435     char LastChar = TypeString[TypeString.size()-1];
436     PropertyString += TypeString;
437     if (LastChar != '*')
438       PropertyString += ' ';
439     PropertyString += PropertyNameString;
440   }
441   SourceLocation StartGetterSelectorLoc = Getter->getSelectorStartLoc();
442   Selector GetterSelector = Getter->getSelector();
443 
444   SourceLocation EndGetterSelectorLoc =
445     StartGetterSelectorLoc.getLocWithOffset(GetterSelector.getNameForSlot(0).size());
446   commit.replace(CharSourceRange::getCharRange(Getter->getLocStart(),
447                                                EndGetterSelectorLoc),
448                  PropertyString);
449   if (Setter && AvailabilityArgsMatch) {
450     SourceLocation EndLoc = Setter->getDeclaratorEndLoc();
451     // Get location past ';'
452     EndLoc = EndLoc.getLocWithOffset(1);
453     SourceLocation BeginOfSetterDclLoc = Setter->getLocStart();
454     // FIXME. This assumes that setter decl; is immediately preceded by eoln.
455     // It is trying to remove the setter method decl. line entirely.
456     BeginOfSetterDclLoc = BeginOfSetterDclLoc.getLocWithOffset(-1);
457     commit.remove(SourceRange(BeginOfSetterDclLoc, EndLoc));
458   }
459 }
460 
461 static bool IsCategoryNameWithDeprecatedSuffix(ObjCContainerDecl *D) {
462   if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(D)) {
463     StringRef Name = CatDecl->getName();
464     return Name.endswith("Deprecated");
465   }
466   return false;
467 }
468 
469 void ObjCMigrateASTConsumer::migrateObjCInterfaceDecl(ASTContext &Ctx,
470                                                       ObjCContainerDecl *D) {
471   if (D->isDeprecated() || IsCategoryNameWithDeprecatedSuffix(D))
472     return;
473 
474   for (auto *Method : D->methods()) {
475     if (Method->isDeprecated())
476       continue;
477     bool PropertyInferred = migrateProperty(Ctx, D, Method);
478     // If a property is inferred, do not attempt to attach NS_RETURNS_INNER_POINTER to
479     // the getter method as it ends up on the property itself which we don't want
480     // to do unless -objcmt-returns-innerpointer-property  option is on.
481     if (!PropertyInferred ||
482         (ASTMigrateActions & FrontendOptions::ObjCMT_ReturnsInnerPointerProperty))
483       if (ASTMigrateActions & FrontendOptions::ObjCMT_Annotation)
484         migrateNsReturnsInnerPointer(Ctx, Method);
485   }
486   if (!(ASTMigrateActions & FrontendOptions::ObjCMT_ReturnsInnerPointerProperty))
487     return;
488 
489   for (auto *Prop : D->properties()) {
490     if ((ASTMigrateActions & FrontendOptions::ObjCMT_Annotation) &&
491         !Prop->isDeprecated())
492       migratePropertyNsReturnsInnerPointer(Ctx, Prop);
493   }
494 }
495 
496 static bool
497 ClassImplementsAllMethodsAndProperties(ASTContext &Ctx,
498                                       const ObjCImplementationDecl *ImpDecl,
499                                        const ObjCInterfaceDecl *IDecl,
500                                       ObjCProtocolDecl *Protocol) {
501   // In auto-synthesis, protocol properties are not synthesized. So,
502   // a conforming protocol must have its required properties declared
503   // in class interface.
504   bool HasAtleastOneRequiredProperty = false;
505   if (const ObjCProtocolDecl *PDecl = Protocol->getDefinition())
506     for (const auto *Property : PDecl->properties()) {
507       if (Property->getPropertyImplementation() == ObjCPropertyDecl::Optional)
508         continue;
509       HasAtleastOneRequiredProperty = true;
510       DeclContext::lookup_const_result R = IDecl->lookup(Property->getDeclName());
511       if (R.size() == 0) {
512         // Relax the rule and look into class's implementation for a synthesize
513         // or dynamic declaration. Class is implementing a property coming from
514         // another protocol. This still makes the target protocol as conforming.
515         if (!ImpDecl->FindPropertyImplDecl(
516                                   Property->getDeclName().getAsIdentifierInfo()))
517           return false;
518       }
519       else if (ObjCPropertyDecl *ClassProperty = dyn_cast<ObjCPropertyDecl>(R[0])) {
520           if ((ClassProperty->getPropertyAttributes()
521               != Property->getPropertyAttributes()) ||
522               !Ctx.hasSameType(ClassProperty->getType(), Property->getType()))
523             return false;
524       }
525       else
526         return false;
527     }
528 
529   // At this point, all required properties in this protocol conform to those
530   // declared in the class.
531   // Check that class implements the required methods of the protocol too.
532   bool HasAtleastOneRequiredMethod = false;
533   if (const ObjCProtocolDecl *PDecl = Protocol->getDefinition()) {
534     if (PDecl->meth_begin() == PDecl->meth_end())
535       return HasAtleastOneRequiredProperty;
536     for (const auto *MD : PDecl->methods()) {
537       if (MD->isImplicit())
538         continue;
539       if (MD->getImplementationControl() == ObjCMethodDecl::Optional)
540         continue;
541       DeclContext::lookup_const_result R = ImpDecl->lookup(MD->getDeclName());
542       if (R.size() == 0)
543         return false;
544       bool match = false;
545       HasAtleastOneRequiredMethod = true;
546       for (unsigned I = 0, N = R.size(); I != N; ++I)
547         if (ObjCMethodDecl *ImpMD = dyn_cast<ObjCMethodDecl>(R[0]))
548           if (Ctx.ObjCMethodsAreEqual(MD, ImpMD)) {
549             match = true;
550             break;
551           }
552       if (!match)
553         return false;
554     }
555   }
556   if (HasAtleastOneRequiredProperty || HasAtleastOneRequiredMethod)
557     return true;
558   return false;
559 }
560 
561 static bool rewriteToObjCInterfaceDecl(const ObjCInterfaceDecl *IDecl,
562                     llvm::SmallVectorImpl<ObjCProtocolDecl*> &ConformingProtocols,
563                     const NSAPI &NS, edit::Commit &commit) {
564   const ObjCList<ObjCProtocolDecl> &Protocols = IDecl->getReferencedProtocols();
565   std::string ClassString;
566   SourceLocation EndLoc =
567   IDecl->getSuperClass() ? IDecl->getSuperClassLoc() : IDecl->getLocation();
568 
569   if (Protocols.empty()) {
570     ClassString = '<';
571     for (unsigned i = 0, e = ConformingProtocols.size(); i != e; i++) {
572       ClassString += ConformingProtocols[i]->getNameAsString();
573       if (i != (e-1))
574         ClassString += ", ";
575     }
576     ClassString += "> ";
577   }
578   else {
579     ClassString = ", ";
580     for (unsigned i = 0, e = ConformingProtocols.size(); i != e; i++) {
581       ClassString += ConformingProtocols[i]->getNameAsString();
582       if (i != (e-1))
583         ClassString += ", ";
584     }
585     ObjCInterfaceDecl::protocol_loc_iterator PL = IDecl->protocol_loc_end() - 1;
586     EndLoc = *PL;
587   }
588 
589   commit.insertAfterToken(EndLoc, ClassString);
590   return true;
591 }
592 
593 static bool rewriteToNSEnumDecl(const EnumDecl *EnumDcl,
594                                 const TypedefDecl *TypedefDcl,
595                                 const NSAPI &NS, edit::Commit &commit,
596                                 bool IsNSIntegerType,
597                                 bool NSOptions) {
598   std::string ClassString;
599   if (NSOptions)
600     ClassString = "typedef NS_OPTIONS(NSUInteger, ";
601   else
602     ClassString =
603       IsNSIntegerType ? "typedef NS_ENUM(NSInteger, "
604                       : "typedef NS_ENUM(NSUInteger, ";
605 
606   ClassString += TypedefDcl->getIdentifier()->getName();
607   ClassString += ')';
608   SourceRange R(EnumDcl->getLocStart(), EnumDcl->getLocStart());
609   commit.replace(R, ClassString);
610   SourceLocation EndOfEnumDclLoc = EnumDcl->getLocEnd();
611   EndOfEnumDclLoc = trans::findSemiAfterLocation(EndOfEnumDclLoc,
612                                                  NS.getASTContext(), /*IsDecl*/true);
613   if (!EndOfEnumDclLoc.isInvalid()) {
614     SourceRange EnumDclRange(EnumDcl->getLocStart(), EndOfEnumDclLoc);
615     commit.insertFromRange(TypedefDcl->getLocStart(), EnumDclRange);
616   }
617   else
618     return false;
619 
620   SourceLocation EndTypedefDclLoc = TypedefDcl->getLocEnd();
621   EndTypedefDclLoc = trans::findSemiAfterLocation(EndTypedefDclLoc,
622                                                  NS.getASTContext(), /*IsDecl*/true);
623   if (!EndTypedefDclLoc.isInvalid()) {
624     SourceRange TDRange(TypedefDcl->getLocStart(), EndTypedefDclLoc);
625     commit.remove(TDRange);
626   }
627   else
628     return false;
629 
630   EndOfEnumDclLoc = trans::findLocationAfterSemi(EnumDcl->getLocEnd(), NS.getASTContext(),
631                                                  /*IsDecl*/true);
632   if (!EndOfEnumDclLoc.isInvalid()) {
633     SourceLocation BeginOfEnumDclLoc = EnumDcl->getLocStart();
634     // FIXME. This assumes that enum decl; is immediately preceded by eoln.
635     // It is trying to remove the enum decl. lines entirely.
636     BeginOfEnumDclLoc = BeginOfEnumDclLoc.getLocWithOffset(-1);
637     commit.remove(SourceRange(BeginOfEnumDclLoc, EndOfEnumDclLoc));
638     return true;
639   }
640   return false;
641 }
642 
643 static void rewriteToNSMacroDecl(const EnumDecl *EnumDcl,
644                                 const TypedefDecl *TypedefDcl,
645                                 const NSAPI &NS, edit::Commit &commit,
646                                  bool IsNSIntegerType) {
647   std::string ClassString =
648     IsNSIntegerType ? "NS_ENUM(NSInteger, " : "NS_OPTIONS(NSUInteger, ";
649   ClassString += TypedefDcl->getIdentifier()->getName();
650   ClassString += ')';
651   SourceRange R(EnumDcl->getLocStart(), EnumDcl->getLocStart());
652   commit.replace(R, ClassString);
653   SourceLocation TypedefLoc = TypedefDcl->getLocEnd();
654   commit.remove(SourceRange(TypedefLoc, TypedefLoc));
655 }
656 
657 static bool UseNSOptionsMacro(Preprocessor &PP, ASTContext &Ctx,
658                               const EnumDecl *EnumDcl) {
659   bool PowerOfTwo = true;
660   bool AllHexdecimalEnumerator = true;
661   uint64_t MaxPowerOfTwoVal = 0;
662   for (auto Enumerator : EnumDcl->enumerators()) {
663     const Expr *InitExpr = Enumerator->getInitExpr();
664     if (!InitExpr) {
665       PowerOfTwo = false;
666       AllHexdecimalEnumerator = false;
667       continue;
668     }
669     InitExpr = InitExpr->IgnoreParenCasts();
670     if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr))
671       if (BO->isShiftOp() || BO->isBitwiseOp())
672         return true;
673 
674     uint64_t EnumVal = Enumerator->getInitVal().getZExtValue();
675     if (PowerOfTwo && EnumVal) {
676       if (!llvm::isPowerOf2_64(EnumVal))
677         PowerOfTwo = false;
678       else if (EnumVal > MaxPowerOfTwoVal)
679         MaxPowerOfTwoVal = EnumVal;
680     }
681     if (AllHexdecimalEnumerator && EnumVal) {
682       bool FoundHexdecimalEnumerator = false;
683       SourceLocation EndLoc = Enumerator->getLocEnd();
684       Token Tok;
685       if (!PP.getRawToken(EndLoc, Tok, /*IgnoreWhiteSpace=*/true))
686         if (Tok.isLiteral() && Tok.getLength() > 2) {
687           if (const char *StringLit = Tok.getLiteralData())
688             FoundHexdecimalEnumerator =
689               (StringLit[0] == '0' && (toLowercase(StringLit[1]) == 'x'));
690         }
691       if (!FoundHexdecimalEnumerator)
692         AllHexdecimalEnumerator = false;
693     }
694   }
695   return AllHexdecimalEnumerator || (PowerOfTwo && (MaxPowerOfTwoVal > 2));
696 }
697 
698 void ObjCMigrateASTConsumer::migrateProtocolConformance(ASTContext &Ctx,
699                                             const ObjCImplementationDecl *ImpDecl) {
700   const ObjCInterfaceDecl *IDecl = ImpDecl->getClassInterface();
701   if (!IDecl || ObjCProtocolDecls.empty() || IDecl->isDeprecated())
702     return;
703   // Find all implicit conforming protocols for this class
704   // and make them explicit.
705   llvm::SmallPtrSet<ObjCProtocolDecl *, 8> ExplicitProtocols;
706   Ctx.CollectInheritedProtocols(IDecl, ExplicitProtocols);
707   llvm::SmallVector<ObjCProtocolDecl *, 8> PotentialImplicitProtocols;
708 
709   for (llvm::SmallPtrSet<ObjCProtocolDecl*, 32>::iterator I =
710        ObjCProtocolDecls.begin(),
711        E = ObjCProtocolDecls.end(); I != E; ++I)
712     if (!ExplicitProtocols.count(*I))
713       PotentialImplicitProtocols.push_back(*I);
714 
715   if (PotentialImplicitProtocols.empty())
716     return;
717 
718   // go through list of non-optional methods and properties in each protocol
719   // in the PotentialImplicitProtocols list. If class implements every one of the
720   // methods and properties, then this class conforms to this protocol.
721   llvm::SmallVector<ObjCProtocolDecl*, 8> ConformingProtocols;
722   for (unsigned i = 0, e = PotentialImplicitProtocols.size(); i != e; i++)
723     if (ClassImplementsAllMethodsAndProperties(Ctx, ImpDecl, IDecl,
724                                               PotentialImplicitProtocols[i]))
725       ConformingProtocols.push_back(PotentialImplicitProtocols[i]);
726 
727   if (ConformingProtocols.empty())
728     return;
729 
730   // Further reduce number of conforming protocols. If protocol P1 is in the list
731   // protocol P2 (P2<P1>), No need to include P1.
732   llvm::SmallVector<ObjCProtocolDecl*, 8> MinimalConformingProtocols;
733   for (unsigned i = 0, e = ConformingProtocols.size(); i != e; i++) {
734     bool DropIt = false;
735     ObjCProtocolDecl *TargetPDecl = ConformingProtocols[i];
736     for (unsigned i1 = 0, e1 = ConformingProtocols.size(); i1 != e1; i1++) {
737       ObjCProtocolDecl *PDecl = ConformingProtocols[i1];
738       if (PDecl == TargetPDecl)
739         continue;
740       if (PDecl->lookupProtocolNamed(
741             TargetPDecl->getDeclName().getAsIdentifierInfo())) {
742         DropIt = true;
743         break;
744       }
745     }
746     if (!DropIt)
747       MinimalConformingProtocols.push_back(TargetPDecl);
748   }
749   if (MinimalConformingProtocols.empty())
750     return;
751   edit::Commit commit(*Editor);
752   rewriteToObjCInterfaceDecl(IDecl, MinimalConformingProtocols,
753                              *NSAPIObj, commit);
754   Editor->commit(commit);
755 }
756 
757 void ObjCMigrateASTConsumer::CacheObjCNSIntegerTypedefed(
758                                           const TypedefDecl *TypedefDcl) {
759 
760   QualType qt = TypedefDcl->getTypeSourceInfo()->getType();
761   if (NSAPIObj->isObjCNSIntegerType(qt))
762     NSIntegerTypedefed = TypedefDcl;
763   else if (NSAPIObj->isObjCNSUIntegerType(qt))
764     NSUIntegerTypedefed = TypedefDcl;
765 }
766 
767 bool ObjCMigrateASTConsumer::migrateNSEnumDecl(ASTContext &Ctx,
768                                            const EnumDecl *EnumDcl,
769                                            const TypedefDecl *TypedefDcl) {
770   if (!EnumDcl->isCompleteDefinition() || EnumDcl->getIdentifier() ||
771       EnumDcl->isDeprecated())
772     return false;
773   if (!TypedefDcl) {
774     if (NSIntegerTypedefed) {
775       TypedefDcl = NSIntegerTypedefed;
776       NSIntegerTypedefed = 0;
777     }
778     else if (NSUIntegerTypedefed) {
779       TypedefDcl = NSUIntegerTypedefed;
780       NSUIntegerTypedefed = 0;
781     }
782     else
783       return false;
784     FileID FileIdOfTypedefDcl =
785       PP.getSourceManager().getFileID(TypedefDcl->getLocation());
786     FileID FileIdOfEnumDcl =
787       PP.getSourceManager().getFileID(EnumDcl->getLocation());
788     if (FileIdOfTypedefDcl != FileIdOfEnumDcl)
789       return false;
790   }
791   if (TypedefDcl->isDeprecated())
792     return false;
793 
794   QualType qt = TypedefDcl->getTypeSourceInfo()->getType();
795   bool IsNSIntegerType = NSAPIObj->isObjCNSIntegerType(qt);
796   bool IsNSUIntegerType = !IsNSIntegerType && NSAPIObj->isObjCNSUIntegerType(qt);
797 
798   if (!IsNSIntegerType && !IsNSUIntegerType) {
799     // Also check for typedef enum {...} TD;
800     if (const EnumType *EnumTy = qt->getAs<EnumType>()) {
801       if (EnumTy->getDecl() == EnumDcl) {
802         bool NSOptions = UseNSOptionsMacro(PP, Ctx, EnumDcl);
803         if (NSOptions) {
804           if (!Ctx.Idents.get("NS_OPTIONS").hasMacroDefinition())
805             return false;
806         }
807         else if (!Ctx.Idents.get("NS_ENUM").hasMacroDefinition())
808           return false;
809         edit::Commit commit(*Editor);
810         rewriteToNSMacroDecl(EnumDcl, TypedefDcl, *NSAPIObj, commit, !NSOptions);
811         Editor->commit(commit);
812         return true;
813       }
814     }
815     return false;
816   }
817 
818   // We may still use NS_OPTIONS based on what we find in the enumertor list.
819   bool NSOptions = UseNSOptionsMacro(PP, Ctx, EnumDcl);
820   // NS_ENUM must be available.
821   if (IsNSIntegerType && !Ctx.Idents.get("NS_ENUM").hasMacroDefinition())
822     return false;
823   // NS_OPTIONS must be available.
824   if (IsNSUIntegerType && !Ctx.Idents.get("NS_OPTIONS").hasMacroDefinition())
825     return false;
826   edit::Commit commit(*Editor);
827   bool Res = rewriteToNSEnumDecl(EnumDcl, TypedefDcl, *NSAPIObj,
828                                  commit, IsNSIntegerType, NSOptions);
829   Editor->commit(commit);
830   return Res;
831 }
832 
833 static void ReplaceWithInstancetype(const ObjCMigrateASTConsumer &ASTC,
834                                     ObjCMethodDecl *OM) {
835   SourceRange R;
836   std::string ClassString;
837   if (TypeSourceInfo *TSInfo = OM->getReturnTypeSourceInfo()) {
838     TypeLoc TL = TSInfo->getTypeLoc();
839     R = SourceRange(TL.getBeginLoc(), TL.getEndLoc());
840     ClassString = "instancetype";
841   }
842   else {
843     R = SourceRange(OM->getLocStart(), OM->getLocStart());
844     ClassString = OM->isInstanceMethod() ? '-' : '+';
845     ClassString += " (instancetype)";
846   }
847   edit::Commit commit(*ASTC.Editor);
848   commit.replace(R, ClassString);
849   ASTC.Editor->commit(commit);
850 }
851 
852 static void ReplaceWithClasstype(const ObjCMigrateASTConsumer &ASTC,
853                                     ObjCMethodDecl *OM) {
854   ObjCInterfaceDecl *IDecl = OM->getClassInterface();
855   SourceRange R;
856   std::string ClassString;
857   if (TypeSourceInfo *TSInfo = OM->getReturnTypeSourceInfo()) {
858     TypeLoc TL = TSInfo->getTypeLoc();
859     R = SourceRange(TL.getBeginLoc(), TL.getEndLoc()); {
860       ClassString  = IDecl->getName();
861       ClassString += "*";
862     }
863   }
864   else {
865     R = SourceRange(OM->getLocStart(), OM->getLocStart());
866     ClassString = "+ (";
867     ClassString += IDecl->getName(); ClassString += "*)";
868   }
869   edit::Commit commit(*ASTC.Editor);
870   commit.replace(R, ClassString);
871   ASTC.Editor->commit(commit);
872 }
873 
874 void ObjCMigrateASTConsumer::migrateMethodInstanceType(ASTContext &Ctx,
875                                                        ObjCContainerDecl *CDecl,
876                                                        ObjCMethodDecl *OM) {
877   ObjCInstanceTypeFamily OIT_Family =
878     Selector::getInstTypeMethodFamily(OM->getSelector());
879 
880   std::string ClassName;
881   switch (OIT_Family) {
882     case OIT_None:
883       migrateFactoryMethod(Ctx, CDecl, OM);
884       return;
885     case OIT_Array:
886       ClassName = "NSArray";
887       break;
888     case OIT_Dictionary:
889       ClassName = "NSDictionary";
890       break;
891     case OIT_Singleton:
892       migrateFactoryMethod(Ctx, CDecl, OM, OIT_Singleton);
893       return;
894     case OIT_Init:
895       if (OM->getReturnType()->isObjCIdType())
896         ReplaceWithInstancetype(*this, OM);
897       return;
898     case OIT_ReturnsSelf:
899       migrateFactoryMethod(Ctx, CDecl, OM, OIT_ReturnsSelf);
900       return;
901   }
902   if (!OM->getReturnType()->isObjCIdType())
903     return;
904 
905   ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(CDecl);
906   if (!IDecl) {
907     if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(CDecl))
908       IDecl = CatDecl->getClassInterface();
909     else if (ObjCImplDecl *ImpDecl = dyn_cast<ObjCImplDecl>(CDecl))
910       IDecl = ImpDecl->getClassInterface();
911   }
912   if (!IDecl ||
913       !IDecl->lookupInheritedClass(&Ctx.Idents.get(ClassName))) {
914     migrateFactoryMethod(Ctx, CDecl, OM);
915     return;
916   }
917   ReplaceWithInstancetype(*this, OM);
918 }
919 
920 static bool TypeIsInnerPointer(QualType T) {
921   if (!T->isAnyPointerType())
922     return false;
923   if (T->isObjCObjectPointerType() || T->isObjCBuiltinType() ||
924       T->isBlockPointerType() || T->isFunctionPointerType() ||
925       ento::coreFoundation::isCFObjectRef(T))
926     return false;
927   // Also, typedef-of-pointer-to-incomplete-struct is something that we assume
928   // is not an innter pointer type.
929   QualType OrigT = T;
930   while (const TypedefType *TD = dyn_cast<TypedefType>(T.getTypePtr()))
931     T = TD->getDecl()->getUnderlyingType();
932   if (OrigT == T || !T->isPointerType())
933     return true;
934   const PointerType* PT = T->getAs<PointerType>();
935   QualType UPointeeT = PT->getPointeeType().getUnqualifiedType();
936   if (UPointeeT->isRecordType()) {
937     const RecordType *RecordTy = UPointeeT->getAs<RecordType>();
938     if (!RecordTy->getDecl()->isCompleteDefinition())
939       return false;
940   }
941   return true;
942 }
943 
944 /// \brief Check whether the two versions match.
945 static bool versionsMatch(const VersionTuple &X, const VersionTuple &Y) {
946   return (X == Y);
947 }
948 
949 /// AvailabilityAttrsMatch - This routine checks that if comparing two
950 /// availability attributes, all their components match. It returns
951 /// true, if not dealing with availability or when all components of
952 /// availability attributes match. This routine is only called when
953 /// the attributes are of the same kind.
954 static bool AvailabilityAttrsMatch(Attr *At1, Attr *At2) {
955   const AvailabilityAttr *AA1 = dyn_cast<AvailabilityAttr>(At1);
956   if (!AA1)
957     return true;
958   const AvailabilityAttr *AA2 = dyn_cast<AvailabilityAttr>(At2);
959 
960   VersionTuple Introduced1 = AA1->getIntroduced();
961   VersionTuple Deprecated1 = AA1->getDeprecated();
962   VersionTuple Obsoleted1 = AA1->getObsoleted();
963   bool IsUnavailable1 = AA1->getUnavailable();
964   VersionTuple Introduced2 = AA2->getIntroduced();
965   VersionTuple Deprecated2 = AA2->getDeprecated();
966   VersionTuple Obsoleted2 = AA2->getObsoleted();
967   bool IsUnavailable2 = AA2->getUnavailable();
968   return (versionsMatch(Introduced1, Introduced2) &&
969           versionsMatch(Deprecated1, Deprecated2) &&
970           versionsMatch(Obsoleted1, Obsoleted2) &&
971           IsUnavailable1 == IsUnavailable2);
972 
973 }
974 
975 static bool MatchTwoAttributeLists(const AttrVec &Attrs1, const AttrVec &Attrs2,
976                                    bool &AvailabilityArgsMatch) {
977   // This list is very small, so this need not be optimized.
978   for (unsigned i = 0, e = Attrs1.size(); i != e; i++) {
979     bool match = false;
980     for (unsigned j = 0, f = Attrs2.size(); j != f; j++) {
981       // Matching attribute kind only. Except for Availabilty attributes,
982       // we are not getting into details of the attributes. For all practical purposes
983       // this is sufficient.
984       if (Attrs1[i]->getKind() == Attrs2[j]->getKind()) {
985         if (AvailabilityArgsMatch)
986           AvailabilityArgsMatch = AvailabilityAttrsMatch(Attrs1[i], Attrs2[j]);
987         match = true;
988         break;
989       }
990     }
991     if (!match)
992       return false;
993   }
994   return true;
995 }
996 
997 /// AttributesMatch - This routine checks list of attributes for two
998 /// decls. It returns false, if there is a mismatch in kind of
999 /// attributes seen in the decls. It returns true if the two decls
1000 /// have list of same kind of attributes. Furthermore, when there
1001 /// are availability attributes in the two decls, it sets the
1002 /// AvailabilityArgsMatch to false if availability attributes have
1003 /// different versions, etc.
1004 static bool AttributesMatch(const Decl *Decl1, const Decl *Decl2,
1005                             bool &AvailabilityArgsMatch) {
1006   if (!Decl1->hasAttrs() || !Decl2->hasAttrs()) {
1007     AvailabilityArgsMatch = (Decl1->hasAttrs() == Decl2->hasAttrs());
1008     return true;
1009   }
1010   AvailabilityArgsMatch = true;
1011   const AttrVec &Attrs1 = Decl1->getAttrs();
1012   const AttrVec &Attrs2 = Decl2->getAttrs();
1013   bool match = MatchTwoAttributeLists(Attrs1, Attrs2, AvailabilityArgsMatch);
1014   if (match && (Attrs2.size() > Attrs1.size()))
1015     return MatchTwoAttributeLists(Attrs2, Attrs1, AvailabilityArgsMatch);
1016   return match;
1017 }
1018 
1019 static bool IsValidIdentifier(ASTContext &Ctx,
1020                               const char *Name) {
1021   if (!isIdentifierHead(Name[0]))
1022     return false;
1023   std::string NameString = Name;
1024   NameString[0] = toLowercase(NameString[0]);
1025   IdentifierInfo *II = &Ctx.Idents.get(NameString);
1026   return II->getTokenID() ==  tok::identifier;
1027 }
1028 
1029 bool ObjCMigrateASTConsumer::migrateProperty(ASTContext &Ctx,
1030                              ObjCContainerDecl *D,
1031                              ObjCMethodDecl *Method) {
1032   if (Method->isPropertyAccessor() || !Method->isInstanceMethod() ||
1033       Method->param_size() != 0)
1034     return false;
1035   // Is this method candidate to be a getter?
1036   QualType GRT = Method->getReturnType();
1037   if (GRT->isVoidType())
1038     return false;
1039 
1040   Selector GetterSelector = Method->getSelector();
1041   ObjCInstanceTypeFamily OIT_Family =
1042     Selector::getInstTypeMethodFamily(GetterSelector);
1043 
1044   if (OIT_Family != OIT_None)
1045     return false;
1046 
1047   IdentifierInfo *getterName = GetterSelector.getIdentifierInfoForSlot(0);
1048   Selector SetterSelector =
1049   SelectorTable::constructSetterSelector(PP.getIdentifierTable(),
1050                                          PP.getSelectorTable(),
1051                                          getterName);
1052   ObjCMethodDecl *SetterMethod = D->getInstanceMethod(SetterSelector);
1053   unsigned LengthOfPrefix = 0;
1054   if (!SetterMethod) {
1055     // try a different naming convention for getter: isXxxxx
1056     StringRef getterNameString = getterName->getName();
1057     bool IsPrefix = getterNameString.startswith("is");
1058     // Note that we don't want to change an isXXX method of retainable object
1059     // type to property (readonly or otherwise).
1060     if (IsPrefix && GRT->isObjCRetainableType())
1061       return false;
1062     if (IsPrefix || getterNameString.startswith("get")) {
1063       LengthOfPrefix = (IsPrefix ? 2 : 3);
1064       const char *CGetterName = getterNameString.data() + LengthOfPrefix;
1065       // Make sure that first character after "is" or "get" prefix can
1066       // start an identifier.
1067       if (!IsValidIdentifier(Ctx, CGetterName))
1068         return false;
1069       if (CGetterName[0] && isUppercase(CGetterName[0])) {
1070         getterName = &Ctx.Idents.get(CGetterName);
1071         SetterSelector =
1072         SelectorTable::constructSetterSelector(PP.getIdentifierTable(),
1073                                                PP.getSelectorTable(),
1074                                                getterName);
1075         SetterMethod = D->getInstanceMethod(SetterSelector);
1076       }
1077     }
1078   }
1079 
1080   if (SetterMethod) {
1081     if ((ASTMigrateActions & FrontendOptions::ObjCMT_ReadwriteProperty) == 0)
1082       return false;
1083     bool AvailabilityArgsMatch;
1084     if (SetterMethod->isDeprecated() ||
1085         !AttributesMatch(Method, SetterMethod, AvailabilityArgsMatch))
1086       return false;
1087 
1088     // Is this a valid setter, matching the target getter?
1089     QualType SRT = SetterMethod->getReturnType();
1090     if (!SRT->isVoidType())
1091       return false;
1092     const ParmVarDecl *argDecl = *SetterMethod->param_begin();
1093     QualType ArgType = argDecl->getType();
1094     if (!Ctx.hasSameUnqualifiedType(ArgType, GRT))
1095       return false;
1096     edit::Commit commit(*Editor);
1097     rewriteToObjCProperty(Method, SetterMethod, *NSAPIObj, commit,
1098                           LengthOfPrefix,
1099                           (ASTMigrateActions &
1100                            FrontendOptions::ObjCMT_AtomicProperty) != 0,
1101                           (ASTMigrateActions &
1102                            FrontendOptions::ObjCMT_NsAtomicIOSOnlyProperty) != 0,
1103                           AvailabilityArgsMatch);
1104     Editor->commit(commit);
1105     return true;
1106   }
1107   else if (ASTMigrateActions & FrontendOptions::ObjCMT_ReadonlyProperty) {
1108     // Try a non-void method with no argument (and no setter or property of same name
1109     // as a 'readonly' property.
1110     edit::Commit commit(*Editor);
1111     rewriteToObjCProperty(Method, 0 /*SetterMethod*/, *NSAPIObj, commit,
1112                           LengthOfPrefix,
1113                           (ASTMigrateActions &
1114                            FrontendOptions::ObjCMT_AtomicProperty) != 0,
1115                           (ASTMigrateActions &
1116                            FrontendOptions::ObjCMT_NsAtomicIOSOnlyProperty) != 0,
1117                           /*AvailabilityArgsMatch*/false);
1118     Editor->commit(commit);
1119     return true;
1120   }
1121   return false;
1122 }
1123 
1124 void ObjCMigrateASTConsumer::migrateNsReturnsInnerPointer(ASTContext &Ctx,
1125                                                           ObjCMethodDecl *OM) {
1126   if (OM->isImplicit() ||
1127       !OM->isInstanceMethod() ||
1128       OM->hasAttr<ObjCReturnsInnerPointerAttr>())
1129     return;
1130 
1131   QualType RT = OM->getReturnType();
1132   if (!TypeIsInnerPointer(RT) ||
1133       !Ctx.Idents.get("NS_RETURNS_INNER_POINTER").hasMacroDefinition())
1134     return;
1135 
1136   edit::Commit commit(*Editor);
1137   commit.insertBefore(OM->getLocEnd(), " NS_RETURNS_INNER_POINTER");
1138   Editor->commit(commit);
1139 }
1140 
1141 void ObjCMigrateASTConsumer::migratePropertyNsReturnsInnerPointer(ASTContext &Ctx,
1142                                                                   ObjCPropertyDecl *P) {
1143   QualType T = P->getType();
1144 
1145   if (!TypeIsInnerPointer(T) ||
1146       !Ctx.Idents.get("NS_RETURNS_INNER_POINTER").hasMacroDefinition())
1147     return;
1148   edit::Commit commit(*Editor);
1149   commit.insertBefore(P->getLocEnd(), " NS_RETURNS_INNER_POINTER ");
1150   Editor->commit(commit);
1151 }
1152 
1153 void ObjCMigrateASTConsumer::migrateAllMethodInstaceType(ASTContext &Ctx,
1154                                                  ObjCContainerDecl *CDecl) {
1155   if (CDecl->isDeprecated() || IsCategoryNameWithDeprecatedSuffix(CDecl))
1156     return;
1157 
1158   // migrate methods which can have instancetype as their result type.
1159   for (auto *Method : CDecl->methods()) {
1160     if (Method->isDeprecated())
1161       continue;
1162     migrateMethodInstanceType(Ctx, CDecl, Method);
1163   }
1164 }
1165 
1166 void ObjCMigrateASTConsumer::migrateFactoryMethod(ASTContext &Ctx,
1167                                                   ObjCContainerDecl *CDecl,
1168                                                   ObjCMethodDecl *OM,
1169                                                   ObjCInstanceTypeFamily OIT_Family) {
1170   if (OM->isInstanceMethod() ||
1171       OM->getReturnType() == Ctx.getObjCInstanceType() ||
1172       !OM->getReturnType()->isObjCIdType())
1173     return;
1174 
1175   // Candidate factory methods are + (id) NaMeXXX : ... which belong to a class
1176   // NSYYYNamE with matching names be at least 3 characters long.
1177   ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(CDecl);
1178   if (!IDecl) {
1179     if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(CDecl))
1180       IDecl = CatDecl->getClassInterface();
1181     else if (ObjCImplDecl *ImpDecl = dyn_cast<ObjCImplDecl>(CDecl))
1182       IDecl = ImpDecl->getClassInterface();
1183   }
1184   if (!IDecl)
1185     return;
1186 
1187   std::string StringClassName = IDecl->getName();
1188   StringRef LoweredClassName(StringClassName);
1189   std::string StringLoweredClassName = LoweredClassName.lower();
1190   LoweredClassName = StringLoweredClassName;
1191 
1192   IdentifierInfo *MethodIdName = OM->getSelector().getIdentifierInfoForSlot(0);
1193   // Handle method with no name at its first selector slot; e.g. + (id):(int)x.
1194   if (!MethodIdName)
1195     return;
1196 
1197   std::string MethodName = MethodIdName->getName();
1198   if (OIT_Family == OIT_Singleton || OIT_Family == OIT_ReturnsSelf) {
1199     StringRef STRefMethodName(MethodName);
1200     size_t len = 0;
1201     if (STRefMethodName.startswith("standard"))
1202       len = strlen("standard");
1203     else if (STRefMethodName.startswith("shared"))
1204       len = strlen("shared");
1205     else if (STRefMethodName.startswith("default"))
1206       len = strlen("default");
1207     else
1208       return;
1209     MethodName = STRefMethodName.substr(len);
1210   }
1211   std::string MethodNameSubStr = MethodName.substr(0, 3);
1212   StringRef MethodNamePrefix(MethodNameSubStr);
1213   std::string StringLoweredMethodNamePrefix = MethodNamePrefix.lower();
1214   MethodNamePrefix = StringLoweredMethodNamePrefix;
1215   size_t Ix = LoweredClassName.rfind(MethodNamePrefix);
1216   if (Ix == StringRef::npos)
1217     return;
1218   std::string ClassNamePostfix = LoweredClassName.substr(Ix);
1219   StringRef LoweredMethodName(MethodName);
1220   std::string StringLoweredMethodName = LoweredMethodName.lower();
1221   LoweredMethodName = StringLoweredMethodName;
1222   if (!LoweredMethodName.startswith(ClassNamePostfix))
1223     return;
1224   if (OIT_Family == OIT_ReturnsSelf)
1225     ReplaceWithClasstype(*this, OM);
1226   else
1227     ReplaceWithInstancetype(*this, OM);
1228 }
1229 
1230 static bool IsVoidStarType(QualType Ty) {
1231   if (!Ty->isPointerType())
1232     return false;
1233 
1234   while (const TypedefType *TD = dyn_cast<TypedefType>(Ty.getTypePtr()))
1235     Ty = TD->getDecl()->getUnderlyingType();
1236 
1237   // Is the type void*?
1238   const PointerType* PT = Ty->getAs<PointerType>();
1239   if (PT->getPointeeType().getUnqualifiedType()->isVoidType())
1240     return true;
1241   return IsVoidStarType(PT->getPointeeType());
1242 }
1243 
1244 /// AuditedType - This routine audits the type AT and returns false if it is one of known
1245 /// CF object types or of the "void *" variety. It returns true if we don't care about the type
1246 /// such as a non-pointer or pointers which have no ownership issues (such as "int *").
1247 static bool AuditedType (QualType AT) {
1248   if (!AT->isAnyPointerType() && !AT->isBlockPointerType())
1249     return true;
1250   // FIXME. There isn't much we can say about CF pointer type; or is there?
1251   if (ento::coreFoundation::isCFObjectRef(AT) ||
1252       IsVoidStarType(AT) ||
1253       // If an ObjC object is type, assuming that it is not a CF function and
1254       // that it is an un-audited function.
1255       AT->isObjCObjectPointerType() || AT->isObjCBuiltinType())
1256     return false;
1257   // All other pointers are assumed audited as harmless.
1258   return true;
1259 }
1260 
1261 void ObjCMigrateASTConsumer::AnnotateImplicitBridging(ASTContext &Ctx) {
1262   if (CFFunctionIBCandidates.empty())
1263     return;
1264   if (!Ctx.Idents.get("CF_IMPLICIT_BRIDGING_ENABLED").hasMacroDefinition()) {
1265     CFFunctionIBCandidates.clear();
1266     FileId = FileID();
1267     return;
1268   }
1269   // Insert CF_IMPLICIT_BRIDGING_ENABLE/CF_IMPLICIT_BRIDGING_DISABLED
1270   const Decl *FirstFD = CFFunctionIBCandidates[0];
1271   const Decl *LastFD  =
1272     CFFunctionIBCandidates[CFFunctionIBCandidates.size()-1];
1273   const char *PragmaString = "\nCF_IMPLICIT_BRIDGING_ENABLED\n\n";
1274   edit::Commit commit(*Editor);
1275   commit.insertBefore(FirstFD->getLocStart(), PragmaString);
1276   PragmaString = "\n\nCF_IMPLICIT_BRIDGING_DISABLED\n";
1277   SourceLocation EndLoc = LastFD->getLocEnd();
1278   // get location just past end of function location.
1279   EndLoc = PP.getLocForEndOfToken(EndLoc);
1280   if (isa<FunctionDecl>(LastFD)) {
1281     // For Methods, EndLoc points to the ending semcolon. So,
1282     // not of these extra work is needed.
1283     Token Tok;
1284     // get locaiton of token that comes after end of function.
1285     bool Failed = PP.getRawToken(EndLoc, Tok, /*IgnoreWhiteSpace=*/true);
1286     if (!Failed)
1287       EndLoc = Tok.getLocation();
1288   }
1289   commit.insertAfterToken(EndLoc, PragmaString);
1290   Editor->commit(commit);
1291   FileId = FileID();
1292   CFFunctionIBCandidates.clear();
1293 }
1294 
1295 void ObjCMigrateASTConsumer::migrateCFAnnotation(ASTContext &Ctx, const Decl *Decl) {
1296   if (Decl->isDeprecated())
1297     return;
1298 
1299   if (Decl->hasAttr<CFAuditedTransferAttr>()) {
1300     assert(CFFunctionIBCandidates.empty() &&
1301            "Cannot have audited functions/methods inside user "
1302            "provided CF_IMPLICIT_BRIDGING_ENABLE");
1303     return;
1304   }
1305 
1306   // Finction must be annotated first.
1307   if (const FunctionDecl *FuncDecl = dyn_cast<FunctionDecl>(Decl)) {
1308     CF_BRIDGING_KIND AuditKind = migrateAddFunctionAnnotation(Ctx, FuncDecl);
1309     if (AuditKind == CF_BRIDGING_ENABLE) {
1310       CFFunctionIBCandidates.push_back(Decl);
1311       if (FileId.isInvalid())
1312         FileId = PP.getSourceManager().getFileID(Decl->getLocation());
1313     }
1314     else if (AuditKind == CF_BRIDGING_MAY_INCLUDE) {
1315       if (!CFFunctionIBCandidates.empty()) {
1316         CFFunctionIBCandidates.push_back(Decl);
1317         if (FileId.isInvalid())
1318           FileId = PP.getSourceManager().getFileID(Decl->getLocation());
1319       }
1320     }
1321     else
1322       AnnotateImplicitBridging(Ctx);
1323   }
1324   else {
1325     migrateAddMethodAnnotation(Ctx, cast<ObjCMethodDecl>(Decl));
1326     AnnotateImplicitBridging(Ctx);
1327   }
1328 }
1329 
1330 void ObjCMigrateASTConsumer::AddCFAnnotations(ASTContext &Ctx,
1331                                               const CallEffects &CE,
1332                                               const FunctionDecl *FuncDecl,
1333                                               bool ResultAnnotated) {
1334   // Annotate function.
1335   if (!ResultAnnotated) {
1336     RetEffect Ret = CE.getReturnValue();
1337     const char *AnnotationString = 0;
1338     if (Ret.getObjKind() == RetEffect::CF) {
1339       if (Ret.isOwned() &&
1340           Ctx.Idents.get("CF_RETURNS_RETAINED").hasMacroDefinition())
1341         AnnotationString = " CF_RETURNS_RETAINED";
1342       else if (Ret.notOwned() &&
1343                Ctx.Idents.get("CF_RETURNS_NOT_RETAINED").hasMacroDefinition())
1344         AnnotationString = " CF_RETURNS_NOT_RETAINED";
1345     }
1346     else if (Ret.getObjKind() == RetEffect::ObjC) {
1347       if (Ret.isOwned() &&
1348           Ctx.Idents.get("NS_RETURNS_RETAINED").hasMacroDefinition())
1349         AnnotationString = " NS_RETURNS_RETAINED";
1350     }
1351 
1352     if (AnnotationString) {
1353       edit::Commit commit(*Editor);
1354       commit.insertAfterToken(FuncDecl->getLocEnd(), AnnotationString);
1355       Editor->commit(commit);
1356     }
1357   }
1358   llvm::ArrayRef<ArgEffect> AEArgs = CE.getArgs();
1359   unsigned i = 0;
1360   for (FunctionDecl::param_const_iterator pi = FuncDecl->param_begin(),
1361        pe = FuncDecl->param_end(); pi != pe; ++pi, ++i) {
1362     const ParmVarDecl *pd = *pi;
1363     ArgEffect AE = AEArgs[i];
1364     if (AE == DecRef && !pd->hasAttr<CFConsumedAttr>() &&
1365         Ctx.Idents.get("CF_CONSUMED").hasMacroDefinition()) {
1366       edit::Commit commit(*Editor);
1367       commit.insertBefore(pd->getLocation(), "CF_CONSUMED ");
1368       Editor->commit(commit);
1369     }
1370     else if (AE == DecRefMsg && !pd->hasAttr<NSConsumedAttr>() &&
1371              Ctx.Idents.get("NS_CONSUMED").hasMacroDefinition()) {
1372       edit::Commit commit(*Editor);
1373       commit.insertBefore(pd->getLocation(), "NS_CONSUMED ");
1374       Editor->commit(commit);
1375     }
1376   }
1377 }
1378 
1379 
1380 ObjCMigrateASTConsumer::CF_BRIDGING_KIND
1381   ObjCMigrateASTConsumer::migrateAddFunctionAnnotation(
1382                                                   ASTContext &Ctx,
1383                                                   const FunctionDecl *FuncDecl) {
1384   if (FuncDecl->hasBody())
1385     return CF_BRIDGING_NONE;
1386 
1387   CallEffects CE  = CallEffects::getEffect(FuncDecl);
1388   bool FuncIsReturnAnnotated = (FuncDecl->hasAttr<CFReturnsRetainedAttr>() ||
1389                                 FuncDecl->hasAttr<CFReturnsNotRetainedAttr>() ||
1390                                 FuncDecl->hasAttr<NSReturnsRetainedAttr>() ||
1391                                 FuncDecl->hasAttr<NSReturnsNotRetainedAttr>() ||
1392                                 FuncDecl->hasAttr<NSReturnsAutoreleasedAttr>());
1393 
1394   // Trivial case of when funciton is annotated and has no argument.
1395   if (FuncIsReturnAnnotated && FuncDecl->getNumParams() == 0)
1396     return CF_BRIDGING_NONE;
1397 
1398   bool ReturnCFAudited = false;
1399   if (!FuncIsReturnAnnotated) {
1400     RetEffect Ret = CE.getReturnValue();
1401     if (Ret.getObjKind() == RetEffect::CF &&
1402         (Ret.isOwned() || Ret.notOwned()))
1403       ReturnCFAudited = true;
1404     else if (!AuditedType(FuncDecl->getReturnType()))
1405       return CF_BRIDGING_NONE;
1406   }
1407 
1408   // At this point result type is audited for potential inclusion.
1409   // Now, how about argument types.
1410   llvm::ArrayRef<ArgEffect> AEArgs = CE.getArgs();
1411   unsigned i = 0;
1412   bool ArgCFAudited = false;
1413   for (FunctionDecl::param_const_iterator pi = FuncDecl->param_begin(),
1414        pe = FuncDecl->param_end(); pi != pe; ++pi, ++i) {
1415     const ParmVarDecl *pd = *pi;
1416     ArgEffect AE = AEArgs[i];
1417     if (AE == DecRef /*CFConsumed annotated*/ || AE == IncRef) {
1418       if (AE == DecRef && !pd->hasAttr<CFConsumedAttr>())
1419         ArgCFAudited = true;
1420       else if (AE == IncRef)
1421         ArgCFAudited = true;
1422     }
1423     else {
1424       QualType AT = pd->getType();
1425       if (!AuditedType(AT)) {
1426         AddCFAnnotations(Ctx, CE, FuncDecl, FuncIsReturnAnnotated);
1427         return CF_BRIDGING_NONE;
1428       }
1429     }
1430   }
1431   if (ReturnCFAudited || ArgCFAudited)
1432     return CF_BRIDGING_ENABLE;
1433 
1434   return CF_BRIDGING_MAY_INCLUDE;
1435 }
1436 
1437 void ObjCMigrateASTConsumer::migrateARCSafeAnnotation(ASTContext &Ctx,
1438                                                  ObjCContainerDecl *CDecl) {
1439   if (!isa<ObjCInterfaceDecl>(CDecl) || CDecl->isDeprecated())
1440     return;
1441 
1442   // migrate methods which can have instancetype as their result type.
1443   for (const auto *Method : CDecl->methods())
1444     migrateCFAnnotation(Ctx, Method);
1445 }
1446 
1447 void ObjCMigrateASTConsumer::AddCFAnnotations(ASTContext &Ctx,
1448                                               const CallEffects &CE,
1449                                               const ObjCMethodDecl *MethodDecl,
1450                                               bool ResultAnnotated) {
1451   // Annotate function.
1452   if (!ResultAnnotated) {
1453     RetEffect Ret = CE.getReturnValue();
1454     const char *AnnotationString = 0;
1455     if (Ret.getObjKind() == RetEffect::CF) {
1456       if (Ret.isOwned() &&
1457           Ctx.Idents.get("CF_RETURNS_RETAINED").hasMacroDefinition())
1458         AnnotationString = " CF_RETURNS_RETAINED";
1459       else if (Ret.notOwned() &&
1460                Ctx.Idents.get("CF_RETURNS_NOT_RETAINED").hasMacroDefinition())
1461         AnnotationString = " CF_RETURNS_NOT_RETAINED";
1462     }
1463     else if (Ret.getObjKind() == RetEffect::ObjC) {
1464       ObjCMethodFamily OMF = MethodDecl->getMethodFamily();
1465       switch (OMF) {
1466         case clang::OMF_alloc:
1467         case clang::OMF_new:
1468         case clang::OMF_copy:
1469         case clang::OMF_init:
1470         case clang::OMF_mutableCopy:
1471           break;
1472 
1473         default:
1474           if (Ret.isOwned() &&
1475               Ctx.Idents.get("NS_RETURNS_RETAINED").hasMacroDefinition())
1476             AnnotationString = " NS_RETURNS_RETAINED";
1477           break;
1478       }
1479     }
1480 
1481     if (AnnotationString) {
1482       edit::Commit commit(*Editor);
1483       commit.insertBefore(MethodDecl->getLocEnd(), AnnotationString);
1484       Editor->commit(commit);
1485     }
1486   }
1487   llvm::ArrayRef<ArgEffect> AEArgs = CE.getArgs();
1488   unsigned i = 0;
1489   for (ObjCMethodDecl::param_const_iterator pi = MethodDecl->param_begin(),
1490        pe = MethodDecl->param_end(); pi != pe; ++pi, ++i) {
1491     const ParmVarDecl *pd = *pi;
1492     ArgEffect AE = AEArgs[i];
1493     if (AE == DecRef && !pd->hasAttr<CFConsumedAttr>() &&
1494         Ctx.Idents.get("CF_CONSUMED").hasMacroDefinition()) {
1495       edit::Commit commit(*Editor);
1496       commit.insertBefore(pd->getLocation(), "CF_CONSUMED ");
1497       Editor->commit(commit);
1498     }
1499   }
1500 }
1501 
1502 void ObjCMigrateASTConsumer::migrateAddMethodAnnotation(
1503                                             ASTContext &Ctx,
1504                                             const ObjCMethodDecl *MethodDecl) {
1505   if (MethodDecl->hasBody() || MethodDecl->isImplicit())
1506     return;
1507 
1508   CallEffects CE  = CallEffects::getEffect(MethodDecl);
1509   bool MethodIsReturnAnnotated = (MethodDecl->hasAttr<CFReturnsRetainedAttr>() ||
1510                                   MethodDecl->hasAttr<CFReturnsNotRetainedAttr>() ||
1511                                   MethodDecl->hasAttr<NSReturnsRetainedAttr>() ||
1512                                   MethodDecl->hasAttr<NSReturnsNotRetainedAttr>() ||
1513                                   MethodDecl->hasAttr<NSReturnsAutoreleasedAttr>());
1514 
1515   if (CE.getReceiver() ==  DecRefMsg &&
1516       !MethodDecl->hasAttr<NSConsumesSelfAttr>() &&
1517       MethodDecl->getMethodFamily() != OMF_init &&
1518       MethodDecl->getMethodFamily() != OMF_release &&
1519       Ctx.Idents.get("NS_CONSUMES_SELF").hasMacroDefinition()) {
1520     edit::Commit commit(*Editor);
1521     commit.insertBefore(MethodDecl->getLocEnd(), " NS_CONSUMES_SELF");
1522     Editor->commit(commit);
1523   }
1524 
1525   // Trivial case of when funciton is annotated and has no argument.
1526   if (MethodIsReturnAnnotated &&
1527       (MethodDecl->param_begin() == MethodDecl->param_end()))
1528     return;
1529 
1530   if (!MethodIsReturnAnnotated) {
1531     RetEffect Ret = CE.getReturnValue();
1532     if ((Ret.getObjKind() == RetEffect::CF ||
1533          Ret.getObjKind() == RetEffect::ObjC) &&
1534         (Ret.isOwned() || Ret.notOwned())) {
1535       AddCFAnnotations(Ctx, CE, MethodDecl, false);
1536       return;
1537     } else if (!AuditedType(MethodDecl->getReturnType()))
1538       return;
1539   }
1540 
1541   // At this point result type is either annotated or audited.
1542   // Now, how about argument types.
1543   llvm::ArrayRef<ArgEffect> AEArgs = CE.getArgs();
1544   unsigned i = 0;
1545   for (ObjCMethodDecl::param_const_iterator pi = MethodDecl->param_begin(),
1546        pe = MethodDecl->param_end(); pi != pe; ++pi, ++i) {
1547     const ParmVarDecl *pd = *pi;
1548     ArgEffect AE = AEArgs[i];
1549     if ((AE == DecRef && !pd->hasAttr<CFConsumedAttr>()) || AE == IncRef ||
1550         !AuditedType(pd->getType())) {
1551       AddCFAnnotations(Ctx, CE, MethodDecl, MethodIsReturnAnnotated);
1552       return;
1553     }
1554   }
1555   return;
1556 }
1557 
1558 namespace {
1559 class SuperInitChecker : public RecursiveASTVisitor<SuperInitChecker> {
1560 public:
1561   bool shouldVisitTemplateInstantiations() const { return false; }
1562   bool shouldWalkTypesOfTypeLocs() const { return false; }
1563 
1564   bool VisitObjCMessageExpr(ObjCMessageExpr *E) {
1565     if (E->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
1566       if (E->getMethodFamily() == OMF_init)
1567         return false;
1568     }
1569     return true;
1570   }
1571 };
1572 } // anonymous namespace
1573 
1574 static bool hasSuperInitCall(const ObjCMethodDecl *MD) {
1575   return !SuperInitChecker().TraverseStmt(MD->getBody());
1576 }
1577 
1578 void ObjCMigrateASTConsumer::inferDesignatedInitializers(
1579     ASTContext &Ctx,
1580     const ObjCImplementationDecl *ImplD) {
1581 
1582   const ObjCInterfaceDecl *IFace = ImplD->getClassInterface();
1583   if (!IFace || IFace->hasDesignatedInitializers())
1584     return;
1585   if (!Ctx.Idents.get("NS_DESIGNATED_INITIALIZER").hasMacroDefinition())
1586     return;
1587 
1588   for (const auto *MD : ImplD->instance_methods()) {
1589     if (MD->isDeprecated() ||
1590         MD->getMethodFamily() != OMF_init ||
1591         MD->isDesignatedInitializerForTheInterface())
1592       continue;
1593     const ObjCMethodDecl *IFaceM = IFace->getMethod(MD->getSelector(),
1594                                                     /*isInstance=*/true);
1595     if (!IFaceM)
1596       continue;
1597     if (hasSuperInitCall(MD)) {
1598       edit::Commit commit(*Editor);
1599       commit.insert(IFaceM->getLocEnd(), " NS_DESIGNATED_INITIALIZER");
1600       Editor->commit(commit);
1601     }
1602   }
1603 }
1604 
1605 namespace {
1606 
1607 class RewritesReceiver : public edit::EditsReceiver {
1608   Rewriter &Rewrite;
1609 
1610 public:
1611   RewritesReceiver(Rewriter &Rewrite) : Rewrite(Rewrite) { }
1612 
1613   void insert(SourceLocation loc, StringRef text) override {
1614     Rewrite.InsertText(loc, text);
1615   }
1616   void replace(CharSourceRange range, StringRef text) override {
1617     Rewrite.ReplaceText(range.getBegin(), Rewrite.getRangeSize(range), text);
1618   }
1619 };
1620 
1621 class JSONEditWriter : public edit::EditsReceiver {
1622   SourceManager &SourceMgr;
1623   llvm::raw_ostream &OS;
1624 
1625 public:
1626   JSONEditWriter(SourceManager &SM, llvm::raw_ostream &OS)
1627     : SourceMgr(SM), OS(OS) {
1628     OS << "[\n";
1629   }
1630   ~JSONEditWriter() {
1631     OS << "]\n";
1632   }
1633 
1634 private:
1635   struct EntryWriter {
1636     SourceManager &SourceMgr;
1637     llvm::raw_ostream &OS;
1638 
1639     EntryWriter(SourceManager &SM, llvm::raw_ostream &OS)
1640       : SourceMgr(SM), OS(OS) {
1641       OS << " {\n";
1642     }
1643     ~EntryWriter() {
1644       OS << " },\n";
1645     }
1646 
1647     void writeLoc(SourceLocation Loc) {
1648       FileID FID;
1649       unsigned Offset;
1650       std::tie(FID, Offset) = SourceMgr.getDecomposedLoc(Loc);
1651       assert(!FID.isInvalid());
1652       SmallString<200> Path =
1653           StringRef(SourceMgr.getFileEntryForID(FID)->getName());
1654       llvm::sys::fs::make_absolute(Path);
1655       OS << "  \"file\": \"";
1656       OS.write_escaped(Path.str()) << "\",\n";
1657       OS << "  \"offset\": " << Offset << ",\n";
1658     }
1659 
1660     void writeRemove(CharSourceRange Range) {
1661       assert(Range.isCharRange());
1662       std::pair<FileID, unsigned> Begin =
1663           SourceMgr.getDecomposedLoc(Range.getBegin());
1664       std::pair<FileID, unsigned> End =
1665           SourceMgr.getDecomposedLoc(Range.getEnd());
1666       assert(Begin.first == End.first);
1667       assert(Begin.second <= End.second);
1668       unsigned Length = End.second - Begin.second;
1669 
1670       OS << "  \"remove\": " << Length << ",\n";
1671     }
1672 
1673     void writeText(StringRef Text) {
1674       OS << "  \"text\": \"";
1675       OS.write_escaped(Text) << "\",\n";
1676     }
1677   };
1678 
1679   void insert(SourceLocation Loc, StringRef Text) override {
1680     EntryWriter Writer(SourceMgr, OS);
1681     Writer.writeLoc(Loc);
1682     Writer.writeText(Text);
1683   }
1684 
1685   void replace(CharSourceRange Range, StringRef Text) override {
1686     EntryWriter Writer(SourceMgr, OS);
1687     Writer.writeLoc(Range.getBegin());
1688     Writer.writeRemove(Range);
1689     Writer.writeText(Text);
1690   }
1691 
1692   void remove(CharSourceRange Range) override {
1693     EntryWriter Writer(SourceMgr, OS);
1694     Writer.writeLoc(Range.getBegin());
1695     Writer.writeRemove(Range);
1696   }
1697 };
1698 
1699 }
1700 
1701 static bool
1702 IsReallyASystemHeader(ASTContext &Ctx, const FileEntry *file, FileID FID) {
1703   bool Invalid = false;
1704   const SrcMgr::SLocEntry &SEntry =
1705   Ctx.getSourceManager().getSLocEntry(FID, &Invalid);
1706   if (!Invalid && SEntry.isFile()) {
1707     const SrcMgr::FileInfo &FI = SEntry.getFile();
1708     if (!FI.hasLineDirectives()) {
1709       if (FI.getFileCharacteristic() == SrcMgr::C_ExternCSystem)
1710         return true;
1711       if (FI.getFileCharacteristic() == SrcMgr::C_System) {
1712         // This file is in a system header directory. Continue committing
1713         // change only if it's a user-specified system directory because user
1714         // put a .system_framework file in the framework directory.
1715         StringRef Directory(file->getDir()->getName());
1716         size_t Ix = Directory.rfind(".framework");
1717         if (Ix == StringRef::npos)
1718           return true;
1719         std::string PatchToSystemFramework = Directory.slice(0, Ix+sizeof(".framework"));
1720         PatchToSystemFramework += ".system_framework";
1721         if (!llvm::sys::fs::exists(PatchToSystemFramework.data()))
1722           return true;
1723       }
1724     }
1725   }
1726   return false;
1727 }
1728 
1729 void ObjCMigrateASTConsumer::HandleTranslationUnit(ASTContext &Ctx) {
1730 
1731   TranslationUnitDecl *TU = Ctx.getTranslationUnitDecl();
1732   if (ASTMigrateActions & FrontendOptions::ObjCMT_MigrateDecls) {
1733     for (DeclContext::decl_iterator D = TU->decls_begin(), DEnd = TU->decls_end();
1734          D != DEnd; ++D) {
1735       FileID FID = PP.getSourceManager().getFileID((*D)->getLocation());
1736       if (!FID.isInvalid())
1737         if (!FileId.isInvalid() && FileId != FID) {
1738           if (ASTMigrateActions & FrontendOptions::ObjCMT_Annotation)
1739             AnnotateImplicitBridging(Ctx);
1740         }
1741 
1742       if (ObjCInterfaceDecl *CDecl = dyn_cast<ObjCInterfaceDecl>(*D))
1743         if (canModify(CDecl))
1744           migrateObjCInterfaceDecl(Ctx, CDecl);
1745       if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(*D)) {
1746         if (canModify(CatDecl))
1747           migrateObjCInterfaceDecl(Ctx, CatDecl);
1748       }
1749       else if (ObjCProtocolDecl *PDecl = dyn_cast<ObjCProtocolDecl>(*D))
1750         ObjCProtocolDecls.insert(PDecl->getCanonicalDecl());
1751       else if (const ObjCImplementationDecl *ImpDecl =
1752                dyn_cast<ObjCImplementationDecl>(*D)) {
1753         if ((ASTMigrateActions & FrontendOptions::ObjCMT_ProtocolConformance) &&
1754             canModify(ImpDecl))
1755           migrateProtocolConformance(Ctx, ImpDecl);
1756       }
1757       else if (const EnumDecl *ED = dyn_cast<EnumDecl>(*D)) {
1758         if (!(ASTMigrateActions & FrontendOptions::ObjCMT_NsMacros))
1759           continue;
1760         if (!canModify(ED))
1761           continue;
1762         DeclContext::decl_iterator N = D;
1763         if (++N != DEnd) {
1764           const TypedefDecl *TD = dyn_cast<TypedefDecl>(*N);
1765           if (migrateNSEnumDecl(Ctx, ED, TD) && TD)
1766             D++;
1767         }
1768         else
1769           migrateNSEnumDecl(Ctx, ED, /*TypedefDecl */0);
1770       }
1771       else if (const TypedefDecl *TD = dyn_cast<TypedefDecl>(*D)) {
1772         if (!(ASTMigrateActions & FrontendOptions::ObjCMT_NsMacros))
1773           continue;
1774         if (!canModify(TD))
1775           continue;
1776         DeclContext::decl_iterator N = D;
1777         if (++N == DEnd)
1778           continue;
1779         if (const EnumDecl *ED = dyn_cast<EnumDecl>(*N)) {
1780           if (++N != DEnd)
1781             if (const TypedefDecl *TDF = dyn_cast<TypedefDecl>(*N)) {
1782               // prefer typedef-follows-enum to enum-follows-typedef pattern.
1783               if (migrateNSEnumDecl(Ctx, ED, TDF)) {
1784                 ++D; ++D;
1785                 CacheObjCNSIntegerTypedefed(TD);
1786                 continue;
1787               }
1788             }
1789           if (migrateNSEnumDecl(Ctx, ED, TD)) {
1790             ++D;
1791             continue;
1792           }
1793         }
1794         CacheObjCNSIntegerTypedefed(TD);
1795       }
1796       else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(*D)) {
1797         if ((ASTMigrateActions & FrontendOptions::ObjCMT_Annotation) &&
1798             canModify(FD))
1799           migrateCFAnnotation(Ctx, FD);
1800       }
1801 
1802       if (ObjCContainerDecl *CDecl = dyn_cast<ObjCContainerDecl>(*D)) {
1803         bool CanModify = canModify(CDecl);
1804         // migrate methods which can have instancetype as their result type.
1805         if ((ASTMigrateActions & FrontendOptions::ObjCMT_Instancetype) &&
1806             CanModify)
1807           migrateAllMethodInstaceType(Ctx, CDecl);
1808         // annotate methods with CF annotations.
1809         if ((ASTMigrateActions & FrontendOptions::ObjCMT_Annotation) &&
1810             CanModify)
1811           migrateARCSafeAnnotation(Ctx, CDecl);
1812       }
1813 
1814       if (const ObjCImplementationDecl *
1815             ImplD = dyn_cast<ObjCImplementationDecl>(*D)) {
1816         if ((ASTMigrateActions & FrontendOptions::ObjCMT_DesignatedInitializer) &&
1817             canModify(ImplD))
1818           inferDesignatedInitializers(Ctx, ImplD);
1819       }
1820     }
1821     if (ASTMigrateActions & FrontendOptions::ObjCMT_Annotation)
1822       AnnotateImplicitBridging(Ctx);
1823   }
1824 
1825  if (IsOutputFile) {
1826    std::string Error;
1827    llvm::raw_fd_ostream OS(MigrateDir.c_str(), Error, llvm::sys::fs::F_None);
1828     if (!Error.empty()) {
1829       DiagnosticsEngine &Diags = Ctx.getDiagnostics();
1830       Diags.Report(Diags.getCustomDiagID(DiagnosticsEngine::Error, "%0"))
1831           << Error;
1832       return;
1833     }
1834 
1835    JSONEditWriter Writer(Ctx.getSourceManager(), OS);
1836    Editor->applyRewrites(Writer);
1837    return;
1838  }
1839 
1840   Rewriter rewriter(Ctx.getSourceManager(), Ctx.getLangOpts());
1841   RewritesReceiver Rec(rewriter);
1842   Editor->applyRewrites(Rec);
1843 
1844   for (Rewriter::buffer_iterator
1845         I = rewriter.buffer_begin(), E = rewriter.buffer_end(); I != E; ++I) {
1846     FileID FID = I->first;
1847     RewriteBuffer &buf = I->second;
1848     const FileEntry *file = Ctx.getSourceManager().getFileEntryForID(FID);
1849     assert(file);
1850     if (IsReallyASystemHeader(Ctx, file, FID))
1851       continue;
1852     SmallString<512> newText;
1853     llvm::raw_svector_ostream vecOS(newText);
1854     buf.write(vecOS);
1855     vecOS.flush();
1856     llvm::MemoryBuffer *memBuf = llvm::MemoryBuffer::getMemBufferCopy(
1857                    StringRef(newText.data(), newText.size()), file->getName());
1858     SmallString<64> filePath(file->getName());
1859     FileMgr.FixupRelativePath(filePath);
1860     Remapper.remap(filePath.str(), memBuf);
1861   }
1862 
1863   if (IsOutputFile) {
1864     Remapper.flushToFile(MigrateDir, Ctx.getDiagnostics());
1865   } else {
1866     Remapper.flushToDisk(MigrateDir, Ctx.getDiagnostics());
1867   }
1868 }
1869 
1870 bool MigrateSourceAction::BeginInvocation(CompilerInstance &CI) {
1871   CI.getDiagnostics().setIgnoreAllWarnings(true);
1872   return true;
1873 }
1874 
1875 static std::vector<std::string> getWhiteListFilenames(StringRef DirPath) {
1876   using namespace llvm::sys::fs;
1877   using namespace llvm::sys::path;
1878 
1879   std::vector<std::string> Filenames;
1880   if (DirPath.empty() || !is_directory(DirPath))
1881     return Filenames;
1882 
1883   llvm::error_code EC;
1884   directory_iterator DI = directory_iterator(DirPath, EC);
1885   directory_iterator DE;
1886   for (; !EC && DI != DE; DI = DI.increment(EC)) {
1887     if (is_regular_file(DI->path()))
1888       Filenames.push_back(filename(DI->path()));
1889   }
1890 
1891   return Filenames;
1892 }
1893 
1894 ASTConsumer *MigrateSourceAction::CreateASTConsumer(CompilerInstance &CI,
1895                                                   StringRef InFile) {
1896   PPConditionalDirectiveRecord *
1897     PPRec = new PPConditionalDirectiveRecord(CI.getSourceManager());
1898   unsigned ObjCMTAction = CI.getFrontendOpts().ObjCMTAction;
1899   unsigned ObjCMTOpts = ObjCMTAction;
1900   // These are companion flags, they do not enable transformations.
1901   ObjCMTOpts &= ~(FrontendOptions::ObjCMT_AtomicProperty |
1902                   FrontendOptions::ObjCMT_NsAtomicIOSOnlyProperty);
1903   if (ObjCMTOpts == FrontendOptions::ObjCMT_None) {
1904     // If no specific option was given, enable literals+subscripting transforms
1905     // by default.
1906     ObjCMTAction |= FrontendOptions::ObjCMT_Literals |
1907                     FrontendOptions::ObjCMT_Subscripting;
1908   }
1909   CI.getPreprocessor().addPPCallbacks(PPRec);
1910   std::vector<std::string> WhiteList =
1911     getWhiteListFilenames(CI.getFrontendOpts().ObjCMTWhiteListPath);
1912   return new ObjCMigrateASTConsumer(CI.getFrontendOpts().OutputFile,
1913                                     ObjCMTAction,
1914                                     Remapper,
1915                                     CI.getFileManager(),
1916                                     PPRec,
1917                                     CI.getPreprocessor(),
1918                                     /*isOutputFile=*/true,
1919                                     WhiteList);
1920 }
1921 
1922 namespace {
1923 struct EditEntry {
1924   const FileEntry *File;
1925   unsigned Offset;
1926   unsigned RemoveLen;
1927   std::string Text;
1928 
1929   EditEntry() : File(), Offset(), RemoveLen() {}
1930 };
1931 }
1932 
1933 namespace llvm {
1934 template<> struct DenseMapInfo<EditEntry> {
1935   static inline EditEntry getEmptyKey() {
1936     EditEntry Entry;
1937     Entry.Offset = unsigned(-1);
1938     return Entry;
1939   }
1940   static inline EditEntry getTombstoneKey() {
1941     EditEntry Entry;
1942     Entry.Offset = unsigned(-2);
1943     return Entry;
1944   }
1945   static unsigned getHashValue(const EditEntry& Val) {
1946     llvm::FoldingSetNodeID ID;
1947     ID.AddPointer(Val.File);
1948     ID.AddInteger(Val.Offset);
1949     ID.AddInteger(Val.RemoveLen);
1950     ID.AddString(Val.Text);
1951     return ID.ComputeHash();
1952   }
1953   static bool isEqual(const EditEntry &LHS, const EditEntry &RHS) {
1954     return LHS.File == RHS.File &&
1955         LHS.Offset == RHS.Offset &&
1956         LHS.RemoveLen == RHS.RemoveLen &&
1957         LHS.Text == RHS.Text;
1958   }
1959 };
1960 }
1961 
1962 namespace {
1963 class RemapFileParser {
1964   FileManager &FileMgr;
1965 
1966 public:
1967   RemapFileParser(FileManager &FileMgr) : FileMgr(FileMgr) { }
1968 
1969   bool parse(StringRef File, SmallVectorImpl<EditEntry> &Entries) {
1970     using namespace llvm::yaml;
1971 
1972     std::unique_ptr<llvm::MemoryBuffer> FileBuf;
1973     if (llvm::MemoryBuffer::getFile(File, FileBuf))
1974       return true;
1975 
1976     llvm::SourceMgr SM;
1977     Stream YAMLStream(FileBuf.release(), SM);
1978     document_iterator I = YAMLStream.begin();
1979     if (I == YAMLStream.end())
1980       return true;
1981     Node *Root = I->getRoot();
1982     if (!Root)
1983       return true;
1984 
1985     SequenceNode *SeqNode = dyn_cast<SequenceNode>(Root);
1986     if (!SeqNode)
1987       return true;
1988 
1989     for (SequenceNode::iterator
1990            AI = SeqNode->begin(), AE = SeqNode->end(); AI != AE; ++AI) {
1991       MappingNode *MapNode = dyn_cast<MappingNode>(&*AI);
1992       if (!MapNode)
1993         continue;
1994       parseEdit(MapNode, Entries);
1995     }
1996 
1997     return false;
1998   }
1999 
2000 private:
2001   void parseEdit(llvm::yaml::MappingNode *Node,
2002                  SmallVectorImpl<EditEntry> &Entries) {
2003     using namespace llvm::yaml;
2004     EditEntry Entry;
2005     bool Ignore = false;
2006 
2007     for (MappingNode::iterator
2008            KVI = Node->begin(), KVE = Node->end(); KVI != KVE; ++KVI) {
2009       ScalarNode *KeyString = dyn_cast<ScalarNode>((*KVI).getKey());
2010       if (!KeyString)
2011         continue;
2012       SmallString<10> KeyStorage;
2013       StringRef Key = KeyString->getValue(KeyStorage);
2014 
2015       ScalarNode *ValueString = dyn_cast<ScalarNode>((*KVI).getValue());
2016       if (!ValueString)
2017         continue;
2018       SmallString<64> ValueStorage;
2019       StringRef Val = ValueString->getValue(ValueStorage);
2020 
2021       if (Key == "file") {
2022         const FileEntry *FE = FileMgr.getFile(Val);
2023         if (!FE)
2024           Ignore = true;
2025         Entry.File = FE;
2026       } else if (Key == "offset") {
2027         if (Val.getAsInteger(10, Entry.Offset))
2028           Ignore = true;
2029       } else if (Key == "remove") {
2030         if (Val.getAsInteger(10, Entry.RemoveLen))
2031           Ignore = true;
2032       } else if (Key == "text") {
2033         Entry.Text = Val;
2034       }
2035     }
2036 
2037     if (!Ignore)
2038       Entries.push_back(Entry);
2039   }
2040 };
2041 }
2042 
2043 static bool reportDiag(const Twine &Err, DiagnosticsEngine &Diag) {
2044   Diag.Report(Diag.getCustomDiagID(DiagnosticsEngine::Error, "%0"))
2045       << Err.str();
2046   return true;
2047 }
2048 
2049 static std::string applyEditsToTemp(const FileEntry *FE,
2050                                     ArrayRef<EditEntry> Edits,
2051                                     FileManager &FileMgr,
2052                                     DiagnosticsEngine &Diag) {
2053   using namespace llvm::sys;
2054 
2055   SourceManager SM(Diag, FileMgr);
2056   FileID FID = SM.createFileID(FE, SourceLocation(), SrcMgr::C_User);
2057   LangOptions LangOpts;
2058   edit::EditedSource Editor(SM, LangOpts);
2059   for (ArrayRef<EditEntry>::iterator
2060         I = Edits.begin(), E = Edits.end(); I != E; ++I) {
2061     const EditEntry &Entry = *I;
2062     assert(Entry.File == FE);
2063     SourceLocation Loc =
2064         SM.getLocForStartOfFile(FID).getLocWithOffset(Entry.Offset);
2065     CharSourceRange Range;
2066     if (Entry.RemoveLen != 0) {
2067       Range = CharSourceRange::getCharRange(Loc,
2068                                          Loc.getLocWithOffset(Entry.RemoveLen));
2069     }
2070 
2071     edit::Commit commit(Editor);
2072     if (Range.isInvalid()) {
2073       commit.insert(Loc, Entry.Text);
2074     } else if (Entry.Text.empty()) {
2075       commit.remove(Range);
2076     } else {
2077       commit.replace(Range, Entry.Text);
2078     }
2079     Editor.commit(commit);
2080   }
2081 
2082   Rewriter rewriter(SM, LangOpts);
2083   RewritesReceiver Rec(rewriter);
2084   Editor.applyRewrites(Rec);
2085 
2086   const RewriteBuffer *Buf = rewriter.getRewriteBufferFor(FID);
2087   SmallString<512> NewText;
2088   llvm::raw_svector_ostream OS(NewText);
2089   Buf->write(OS);
2090   OS.flush();
2091 
2092   SmallString<64> TempPath;
2093   int FD;
2094   if (fs::createTemporaryFile(path::filename(FE->getName()),
2095                               path::extension(FE->getName()), FD,
2096                               TempPath)) {
2097     reportDiag("Could not create file: " + TempPath.str(), Diag);
2098     return std::string();
2099   }
2100 
2101   llvm::raw_fd_ostream TmpOut(FD, /*shouldClose=*/true);
2102   TmpOut.write(NewText.data(), NewText.size());
2103   TmpOut.close();
2104 
2105   return TempPath.str();
2106 }
2107 
2108 bool arcmt::getFileRemappingsFromFileList(
2109                         std::vector<std::pair<std::string,std::string> > &remap,
2110                         ArrayRef<StringRef> remapFiles,
2111                         DiagnosticConsumer *DiagClient) {
2112   bool hasErrorOccurred = false;
2113 
2114   FileSystemOptions FSOpts;
2115   FileManager FileMgr(FSOpts);
2116   RemapFileParser Parser(FileMgr);
2117 
2118   IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
2119   IntrusiveRefCntPtr<DiagnosticsEngine> Diags(
2120       new DiagnosticsEngine(DiagID, new DiagnosticOptions,
2121                             DiagClient, /*ShouldOwnClient=*/false));
2122 
2123   typedef llvm::DenseMap<const FileEntry *, std::vector<EditEntry> >
2124       FileEditEntriesTy;
2125   FileEditEntriesTy FileEditEntries;
2126 
2127   llvm::DenseSet<EditEntry> EntriesSet;
2128 
2129   for (ArrayRef<StringRef>::iterator
2130          I = remapFiles.begin(), E = remapFiles.end(); I != E; ++I) {
2131     SmallVector<EditEntry, 16> Entries;
2132     if (Parser.parse(*I, Entries))
2133       continue;
2134 
2135     for (SmallVectorImpl<EditEntry>::iterator
2136            EI = Entries.begin(), EE = Entries.end(); EI != EE; ++EI) {
2137       EditEntry &Entry = *EI;
2138       if (!Entry.File)
2139         continue;
2140       std::pair<llvm::DenseSet<EditEntry>::iterator, bool>
2141         Insert = EntriesSet.insert(Entry);
2142       if (!Insert.second)
2143         continue;
2144 
2145       FileEditEntries[Entry.File].push_back(Entry);
2146     }
2147   }
2148 
2149   for (FileEditEntriesTy::iterator
2150          I = FileEditEntries.begin(), E = FileEditEntries.end(); I != E; ++I) {
2151     std::string TempFile = applyEditsToTemp(I->first, I->second,
2152                                             FileMgr, *Diags);
2153     if (TempFile.empty()) {
2154       hasErrorOccurred = true;
2155       continue;
2156     }
2157 
2158     remap.push_back(std::make_pair(I->first->getName(), TempFile));
2159   }
2160 
2161   return hasErrorOccurred;
2162 }
2163