106f32e7eSjoerg //===--- ObjCMT.cpp - ObjC Migrate Tool -----------------------------------===//
206f32e7eSjoerg //
306f32e7eSjoerg // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
406f32e7eSjoerg // See https://llvm.org/LICENSE.txt for license information.
506f32e7eSjoerg // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
606f32e7eSjoerg //
706f32e7eSjoerg //===----------------------------------------------------------------------===//
806f32e7eSjoerg 
906f32e7eSjoerg #include "Transforms.h"
1006f32e7eSjoerg #include "clang/Analysis/RetainSummaryManager.h"
1106f32e7eSjoerg #include "clang/ARCMigrate/ARCMT.h"
1206f32e7eSjoerg #include "clang/ARCMigrate/ARCMTActions.h"
1306f32e7eSjoerg #include "clang/AST/ASTConsumer.h"
1406f32e7eSjoerg #include "clang/AST/ASTContext.h"
1506f32e7eSjoerg #include "clang/AST/Attr.h"
1606f32e7eSjoerg #include "clang/AST/NSAPI.h"
1706f32e7eSjoerg #include "clang/AST/ParentMap.h"
1806f32e7eSjoerg #include "clang/AST/RecursiveASTVisitor.h"
1906f32e7eSjoerg #include "clang/Analysis/DomainSpecific/CocoaConventions.h"
2006f32e7eSjoerg #include "clang/Basic/FileManager.h"
2106f32e7eSjoerg #include "clang/Edit/Commit.h"
2206f32e7eSjoerg #include "clang/Edit/EditedSource.h"
2306f32e7eSjoerg #include "clang/Edit/EditsReceiver.h"
2406f32e7eSjoerg #include "clang/Edit/Rewriters.h"
2506f32e7eSjoerg #include "clang/Frontend/CompilerInstance.h"
2606f32e7eSjoerg #include "clang/Frontend/MultiplexConsumer.h"
2706f32e7eSjoerg #include "clang/Lex/PPConditionalDirectiveRecord.h"
2806f32e7eSjoerg #include "clang/Lex/Preprocessor.h"
2906f32e7eSjoerg #include "clang/Rewrite/Core/Rewriter.h"
3006f32e7eSjoerg #include "llvm/ADT/SmallString.h"
3106f32e7eSjoerg #include "llvm/ADT/StringSet.h"
3206f32e7eSjoerg #include "llvm/Support/Path.h"
3306f32e7eSjoerg #include "llvm/Support/SourceMgr.h"
3406f32e7eSjoerg #include "llvm/Support/YAMLParser.h"
3506f32e7eSjoerg 
3606f32e7eSjoerg using namespace clang;
3706f32e7eSjoerg using namespace arcmt;
3806f32e7eSjoerg using namespace ento;
3906f32e7eSjoerg 
4006f32e7eSjoerg namespace {
4106f32e7eSjoerg 
4206f32e7eSjoerg class ObjCMigrateASTConsumer : public ASTConsumer {
4306f32e7eSjoerg   enum CF_BRIDGING_KIND {
4406f32e7eSjoerg     CF_BRIDGING_NONE,
4506f32e7eSjoerg     CF_BRIDGING_ENABLE,
4606f32e7eSjoerg     CF_BRIDGING_MAY_INCLUDE
4706f32e7eSjoerg   };
4806f32e7eSjoerg 
4906f32e7eSjoerg   void migrateDecl(Decl *D);
5006f32e7eSjoerg   void migrateObjCContainerDecl(ASTContext &Ctx, ObjCContainerDecl *D);
5106f32e7eSjoerg   void migrateProtocolConformance(ASTContext &Ctx,
5206f32e7eSjoerg                                   const ObjCImplementationDecl *ImpDecl);
5306f32e7eSjoerg   void CacheObjCNSIntegerTypedefed(const TypedefDecl *TypedefDcl);
5406f32e7eSjoerg   bool migrateNSEnumDecl(ASTContext &Ctx, const EnumDecl *EnumDcl,
5506f32e7eSjoerg                      const TypedefDecl *TypedefDcl);
5606f32e7eSjoerg   void migrateAllMethodInstaceType(ASTContext &Ctx, ObjCContainerDecl *CDecl);
5706f32e7eSjoerg   void migrateMethodInstanceType(ASTContext &Ctx, ObjCContainerDecl *CDecl,
5806f32e7eSjoerg                                  ObjCMethodDecl *OM);
5906f32e7eSjoerg   bool migrateProperty(ASTContext &Ctx, ObjCContainerDecl *D, ObjCMethodDecl *OM);
6006f32e7eSjoerg   void migrateNsReturnsInnerPointer(ASTContext &Ctx, ObjCMethodDecl *OM);
6106f32e7eSjoerg   void migratePropertyNsReturnsInnerPointer(ASTContext &Ctx, ObjCPropertyDecl *P);
6206f32e7eSjoerg   void migrateFactoryMethod(ASTContext &Ctx, ObjCContainerDecl *CDecl,
6306f32e7eSjoerg                             ObjCMethodDecl *OM,
6406f32e7eSjoerg                             ObjCInstanceTypeFamily OIT_Family = OIT_None);
6506f32e7eSjoerg 
6606f32e7eSjoerg   void migrateCFAnnotation(ASTContext &Ctx, const Decl *Decl);
6706f32e7eSjoerg   void AddCFAnnotations(ASTContext &Ctx,
6806f32e7eSjoerg                         const RetainSummary *RS,
6906f32e7eSjoerg                         const FunctionDecl *FuncDecl, bool ResultAnnotated);
7006f32e7eSjoerg   void AddCFAnnotations(ASTContext &Ctx,
7106f32e7eSjoerg                         const RetainSummary *RS,
7206f32e7eSjoerg                         const ObjCMethodDecl *MethodDecl, bool ResultAnnotated);
7306f32e7eSjoerg 
7406f32e7eSjoerg   void AnnotateImplicitBridging(ASTContext &Ctx);
7506f32e7eSjoerg 
7606f32e7eSjoerg   CF_BRIDGING_KIND migrateAddFunctionAnnotation(ASTContext &Ctx,
7706f32e7eSjoerg                                                 const FunctionDecl *FuncDecl);
7806f32e7eSjoerg 
7906f32e7eSjoerg   void migrateARCSafeAnnotation(ASTContext &Ctx, ObjCContainerDecl *CDecl);
8006f32e7eSjoerg 
8106f32e7eSjoerg   void migrateAddMethodAnnotation(ASTContext &Ctx,
8206f32e7eSjoerg                                   const ObjCMethodDecl *MethodDecl);
8306f32e7eSjoerg 
8406f32e7eSjoerg   void inferDesignatedInitializers(ASTContext &Ctx,
8506f32e7eSjoerg                                    const ObjCImplementationDecl *ImplD);
8606f32e7eSjoerg 
8706f32e7eSjoerg   bool InsertFoundation(ASTContext &Ctx, SourceLocation Loc);
8806f32e7eSjoerg 
8906f32e7eSjoerg   std::unique_ptr<RetainSummaryManager> Summaries;
9006f32e7eSjoerg 
9106f32e7eSjoerg public:
9206f32e7eSjoerg   std::string MigrateDir;
9306f32e7eSjoerg   unsigned ASTMigrateActions;
9406f32e7eSjoerg   FileID FileId;
9506f32e7eSjoerg   const TypedefDecl *NSIntegerTypedefed;
9606f32e7eSjoerg   const TypedefDecl *NSUIntegerTypedefed;
9706f32e7eSjoerg   std::unique_ptr<NSAPI> NSAPIObj;
9806f32e7eSjoerg   std::unique_ptr<edit::EditedSource> Editor;
9906f32e7eSjoerg   FileRemapper &Remapper;
10006f32e7eSjoerg   FileManager &FileMgr;
10106f32e7eSjoerg   const PPConditionalDirectiveRecord *PPRec;
10206f32e7eSjoerg   Preprocessor &PP;
10306f32e7eSjoerg   bool IsOutputFile;
10406f32e7eSjoerg   bool FoundationIncluded;
10506f32e7eSjoerg   llvm::SmallPtrSet<ObjCProtocolDecl *, 32> ObjCProtocolDecls;
10606f32e7eSjoerg   llvm::SmallVector<const Decl *, 8> CFFunctionIBCandidates;
10706f32e7eSjoerg   llvm::StringSet<> WhiteListFilenames;
10806f32e7eSjoerg 
getSummaryManager(ASTContext & Ctx)10906f32e7eSjoerg   RetainSummaryManager &getSummaryManager(ASTContext &Ctx) {
11006f32e7eSjoerg     if (!Summaries)
11106f32e7eSjoerg       Summaries.reset(new RetainSummaryManager(Ctx,
11206f32e7eSjoerg                                                /*TrackNSCFObjects=*/true,
11306f32e7eSjoerg                                                /*trackOSObjects=*/false));
11406f32e7eSjoerg     return *Summaries;
11506f32e7eSjoerg   }
11606f32e7eSjoerg 
ObjCMigrateASTConsumer(StringRef migrateDir,unsigned astMigrateActions,FileRemapper & remapper,FileManager & fileMgr,const PPConditionalDirectiveRecord * PPRec,Preprocessor & PP,bool isOutputFile,ArrayRef<std::string> WhiteList)117*13fbcb42Sjoerg   ObjCMigrateASTConsumer(StringRef migrateDir, unsigned astMigrateActions,
118*13fbcb42Sjoerg                          FileRemapper &remapper, FileManager &fileMgr,
11906f32e7eSjoerg                          const PPConditionalDirectiveRecord *PPRec,
120*13fbcb42Sjoerg                          Preprocessor &PP, bool isOutputFile,
12106f32e7eSjoerg                          ArrayRef<std::string> WhiteList)
122*13fbcb42Sjoerg       : MigrateDir(migrateDir), ASTMigrateActions(astMigrateActions),
12306f32e7eSjoerg         NSIntegerTypedefed(nullptr), NSUIntegerTypedefed(nullptr),
12406f32e7eSjoerg         Remapper(remapper), FileMgr(fileMgr), PPRec(PPRec), PP(PP),
125*13fbcb42Sjoerg         IsOutputFile(isOutputFile), FoundationIncluded(false) {
12606f32e7eSjoerg     // FIXME: StringSet should have insert(iter, iter) to use here.
12706f32e7eSjoerg     for (const std::string &Val : WhiteList)
12806f32e7eSjoerg       WhiteListFilenames.insert(Val);
12906f32e7eSjoerg   }
13006f32e7eSjoerg 
13106f32e7eSjoerg protected:
Initialize(ASTContext & Context)13206f32e7eSjoerg   void Initialize(ASTContext &Context) override {
13306f32e7eSjoerg     NSAPIObj.reset(new NSAPI(Context));
13406f32e7eSjoerg     Editor.reset(new edit::EditedSource(Context.getSourceManager(),
13506f32e7eSjoerg                                         Context.getLangOpts(),
13606f32e7eSjoerg                                         PPRec));
13706f32e7eSjoerg   }
13806f32e7eSjoerg 
HandleTopLevelDecl(DeclGroupRef DG)13906f32e7eSjoerg   bool HandleTopLevelDecl(DeclGroupRef DG) override {
14006f32e7eSjoerg     for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I)
14106f32e7eSjoerg       migrateDecl(*I);
14206f32e7eSjoerg     return true;
14306f32e7eSjoerg   }
HandleInterestingDecl(DeclGroupRef DG)14406f32e7eSjoerg   void HandleInterestingDecl(DeclGroupRef DG) override {
14506f32e7eSjoerg     // Ignore decls from the PCH.
14606f32e7eSjoerg   }
HandleTopLevelDeclInObjCContainer(DeclGroupRef DG)14706f32e7eSjoerg   void HandleTopLevelDeclInObjCContainer(DeclGroupRef DG) override {
14806f32e7eSjoerg     ObjCMigrateASTConsumer::HandleTopLevelDecl(DG);
14906f32e7eSjoerg   }
15006f32e7eSjoerg 
15106f32e7eSjoerg   void HandleTranslationUnit(ASTContext &Ctx) override;
15206f32e7eSjoerg 
canModifyFile(StringRef Path)15306f32e7eSjoerg   bool canModifyFile(StringRef Path) {
15406f32e7eSjoerg     if (WhiteListFilenames.empty())
15506f32e7eSjoerg       return true;
15606f32e7eSjoerg     return WhiteListFilenames.find(llvm::sys::path::filename(Path))
15706f32e7eSjoerg         != WhiteListFilenames.end();
15806f32e7eSjoerg   }
canModifyFile(Optional<FileEntryRef> FE)159*13fbcb42Sjoerg   bool canModifyFile(Optional<FileEntryRef> FE) {
16006f32e7eSjoerg     if (!FE)
16106f32e7eSjoerg       return false;
16206f32e7eSjoerg     return canModifyFile(FE->getName());
16306f32e7eSjoerg   }
canModifyFile(FileID FID)16406f32e7eSjoerg   bool canModifyFile(FileID FID) {
16506f32e7eSjoerg     if (FID.isInvalid())
16606f32e7eSjoerg       return false;
167*13fbcb42Sjoerg     return canModifyFile(PP.getSourceManager().getFileEntryRefForID(FID));
16806f32e7eSjoerg   }
16906f32e7eSjoerg 
canModify(const Decl * D)17006f32e7eSjoerg   bool canModify(const Decl *D) {
17106f32e7eSjoerg     if (!D)
17206f32e7eSjoerg       return false;
17306f32e7eSjoerg     if (const ObjCCategoryImplDecl *CatImpl = dyn_cast<ObjCCategoryImplDecl>(D))
17406f32e7eSjoerg       return canModify(CatImpl->getCategoryDecl());
17506f32e7eSjoerg     if (const ObjCImplementationDecl *Impl = dyn_cast<ObjCImplementationDecl>(D))
17606f32e7eSjoerg       return canModify(Impl->getClassInterface());
17706f32e7eSjoerg     if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
17806f32e7eSjoerg       return canModify(cast<Decl>(MD->getDeclContext()));
17906f32e7eSjoerg 
18006f32e7eSjoerg     FileID FID = PP.getSourceManager().getFileID(D->getLocation());
18106f32e7eSjoerg     return canModifyFile(FID);
18206f32e7eSjoerg   }
18306f32e7eSjoerg };
18406f32e7eSjoerg 
18506f32e7eSjoerg } // end anonymous namespace
18606f32e7eSjoerg 
ObjCMigrateAction(std::unique_ptr<FrontendAction> WrappedAction,StringRef migrateDir,unsigned migrateAction)18706f32e7eSjoerg ObjCMigrateAction::ObjCMigrateAction(
188*13fbcb42Sjoerg     std::unique_ptr<FrontendAction> WrappedAction, StringRef migrateDir,
18906f32e7eSjoerg     unsigned migrateAction)
19006f32e7eSjoerg     : WrapperFrontendAction(std::move(WrappedAction)), MigrateDir(migrateDir),
191*13fbcb42Sjoerg       ObjCMigAction(migrateAction), CompInst(nullptr) {
19206f32e7eSjoerg   if (MigrateDir.empty())
19306f32e7eSjoerg     MigrateDir = "."; // user current directory if none is given.
19406f32e7eSjoerg }
19506f32e7eSjoerg 
19606f32e7eSjoerg std::unique_ptr<ASTConsumer>
CreateASTConsumer(CompilerInstance & CI,StringRef InFile)19706f32e7eSjoerg ObjCMigrateAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
19806f32e7eSjoerg   PPConditionalDirectiveRecord *
19906f32e7eSjoerg     PPRec = new PPConditionalDirectiveRecord(CompInst->getSourceManager());
20006f32e7eSjoerg   CI.getPreprocessor().addPPCallbacks(std::unique_ptr<PPCallbacks>(PPRec));
20106f32e7eSjoerg   std::vector<std::unique_ptr<ASTConsumer>> Consumers;
20206f32e7eSjoerg   Consumers.push_back(WrapperFrontendAction::CreateASTConsumer(CI, InFile));
20306f32e7eSjoerg   Consumers.push_back(std::make_unique<ObjCMigrateASTConsumer>(
20406f32e7eSjoerg       MigrateDir, ObjCMigAction, Remapper, CompInst->getFileManager(), PPRec,
20506f32e7eSjoerg       CompInst->getPreprocessor(), false, None));
20606f32e7eSjoerg   return std::make_unique<MultiplexConsumer>(std::move(Consumers));
20706f32e7eSjoerg }
20806f32e7eSjoerg 
BeginInvocation(CompilerInstance & CI)20906f32e7eSjoerg bool ObjCMigrateAction::BeginInvocation(CompilerInstance &CI) {
21006f32e7eSjoerg   Remapper.initFromDisk(MigrateDir, CI.getDiagnostics(),
21106f32e7eSjoerg                         /*ignoreIfFilesChanged=*/true);
21206f32e7eSjoerg   CompInst = &CI;
21306f32e7eSjoerg   CI.getDiagnostics().setIgnoreAllWarnings(true);
21406f32e7eSjoerg   return true;
21506f32e7eSjoerg }
21606f32e7eSjoerg 
21706f32e7eSjoerg namespace {
21806f32e7eSjoerg   // FIXME. This duplicates one in RewriteObjCFoundationAPI.cpp
subscriptOperatorNeedsParens(const Expr * FullExpr)21906f32e7eSjoerg   bool subscriptOperatorNeedsParens(const Expr *FullExpr) {
22006f32e7eSjoerg     const Expr* Expr = FullExpr->IgnoreImpCasts();
22106f32e7eSjoerg     return !(isa<ArraySubscriptExpr>(Expr) || isa<CallExpr>(Expr) ||
22206f32e7eSjoerg              isa<DeclRefExpr>(Expr) || isa<CXXNamedCastExpr>(Expr) ||
22306f32e7eSjoerg              isa<CXXConstructExpr>(Expr) || isa<CXXThisExpr>(Expr) ||
22406f32e7eSjoerg              isa<CXXTypeidExpr>(Expr) ||
22506f32e7eSjoerg              isa<CXXUnresolvedConstructExpr>(Expr) ||
22606f32e7eSjoerg              isa<ObjCMessageExpr>(Expr) || isa<ObjCPropertyRefExpr>(Expr) ||
22706f32e7eSjoerg              isa<ObjCProtocolExpr>(Expr) || isa<MemberExpr>(Expr) ||
22806f32e7eSjoerg              isa<ObjCIvarRefExpr>(Expr) || isa<ParenExpr>(FullExpr) ||
22906f32e7eSjoerg              isa<ParenListExpr>(Expr) || isa<SizeOfPackExpr>(Expr));
23006f32e7eSjoerg   }
23106f32e7eSjoerg 
23206f32e7eSjoerg   /// - Rewrite message expression for Objective-C setter and getters into
23306f32e7eSjoerg   /// property-dot syntax.
rewriteToPropertyDotSyntax(const ObjCMessageExpr * Msg,Preprocessor & PP,const NSAPI & NS,edit::Commit & commit,const ParentMap * PMap)23406f32e7eSjoerg   bool rewriteToPropertyDotSyntax(const ObjCMessageExpr *Msg,
23506f32e7eSjoerg                                   Preprocessor &PP,
23606f32e7eSjoerg                                   const NSAPI &NS, edit::Commit &commit,
23706f32e7eSjoerg                                   const ParentMap *PMap) {
23806f32e7eSjoerg     if (!Msg || Msg->isImplicit() ||
23906f32e7eSjoerg         (Msg->getReceiverKind() != ObjCMessageExpr::Instance &&
24006f32e7eSjoerg          Msg->getReceiverKind() != ObjCMessageExpr::SuperInstance))
24106f32e7eSjoerg       return false;
24206f32e7eSjoerg     if (const Expr *Receiver = Msg->getInstanceReceiver())
24306f32e7eSjoerg       if (Receiver->getType()->isObjCBuiltinType())
24406f32e7eSjoerg         return false;
24506f32e7eSjoerg 
24606f32e7eSjoerg     const ObjCMethodDecl *Method = Msg->getMethodDecl();
24706f32e7eSjoerg     if (!Method)
24806f32e7eSjoerg       return false;
24906f32e7eSjoerg     if (!Method->isPropertyAccessor())
25006f32e7eSjoerg       return false;
25106f32e7eSjoerg 
25206f32e7eSjoerg     const ObjCPropertyDecl *Prop = Method->findPropertyDecl();
25306f32e7eSjoerg     if (!Prop)
25406f32e7eSjoerg       return false;
25506f32e7eSjoerg 
25606f32e7eSjoerg     SourceRange MsgRange = Msg->getSourceRange();
25706f32e7eSjoerg     bool ReceiverIsSuper =
25806f32e7eSjoerg       (Msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
25906f32e7eSjoerg     // for 'super' receiver is nullptr.
26006f32e7eSjoerg     const Expr *receiver = Msg->getInstanceReceiver();
26106f32e7eSjoerg     bool NeedsParen =
26206f32e7eSjoerg       ReceiverIsSuper ? false : subscriptOperatorNeedsParens(receiver);
26306f32e7eSjoerg     bool IsGetter = (Msg->getNumArgs() == 0);
26406f32e7eSjoerg     if (IsGetter) {
26506f32e7eSjoerg       // Find space location range between receiver expression and getter method.
26606f32e7eSjoerg       SourceLocation BegLoc =
26706f32e7eSjoerg           ReceiverIsSuper ? Msg->getSuperLoc() : receiver->getEndLoc();
26806f32e7eSjoerg       BegLoc = PP.getLocForEndOfToken(BegLoc);
26906f32e7eSjoerg       SourceLocation EndLoc = Msg->getSelectorLoc(0);
27006f32e7eSjoerg       SourceRange SpaceRange(BegLoc, EndLoc);
27106f32e7eSjoerg       std::string PropertyDotString;
27206f32e7eSjoerg       // rewrite getter method expression into: receiver.property or
27306f32e7eSjoerg       // (receiver).property
27406f32e7eSjoerg       if (NeedsParen) {
27506f32e7eSjoerg         commit.insertBefore(receiver->getBeginLoc(), "(");
27606f32e7eSjoerg         PropertyDotString = ").";
27706f32e7eSjoerg       }
27806f32e7eSjoerg       else
27906f32e7eSjoerg         PropertyDotString = ".";
28006f32e7eSjoerg       PropertyDotString += Prop->getName();
28106f32e7eSjoerg       commit.replace(SpaceRange, PropertyDotString);
28206f32e7eSjoerg 
28306f32e7eSjoerg       // remove '[' ']'
28406f32e7eSjoerg       commit.replace(SourceRange(MsgRange.getBegin(), MsgRange.getBegin()), "");
28506f32e7eSjoerg       commit.replace(SourceRange(MsgRange.getEnd(), MsgRange.getEnd()), "");
28606f32e7eSjoerg     } else {
28706f32e7eSjoerg       if (NeedsParen)
28806f32e7eSjoerg         commit.insertWrap("(", receiver->getSourceRange(), ")");
28906f32e7eSjoerg       std::string PropertyDotString = ".";
29006f32e7eSjoerg       PropertyDotString += Prop->getName();
29106f32e7eSjoerg       PropertyDotString += " =";
29206f32e7eSjoerg       const Expr*const* Args = Msg->getArgs();
29306f32e7eSjoerg       const Expr *RHS = Args[0];
29406f32e7eSjoerg       if (!RHS)
29506f32e7eSjoerg         return false;
29606f32e7eSjoerg       SourceLocation BegLoc =
29706f32e7eSjoerg           ReceiverIsSuper ? Msg->getSuperLoc() : receiver->getEndLoc();
29806f32e7eSjoerg       BegLoc = PP.getLocForEndOfToken(BegLoc);
29906f32e7eSjoerg       SourceLocation EndLoc = RHS->getBeginLoc();
30006f32e7eSjoerg       EndLoc = EndLoc.getLocWithOffset(-1);
30106f32e7eSjoerg       const char *colon = PP.getSourceManager().getCharacterData(EndLoc);
30206f32e7eSjoerg       // Add a space after '=' if there is no space between RHS and '='
30306f32e7eSjoerg       if (colon && colon[0] == ':')
30406f32e7eSjoerg         PropertyDotString += " ";
30506f32e7eSjoerg       SourceRange Range(BegLoc, EndLoc);
30606f32e7eSjoerg       commit.replace(Range, PropertyDotString);
30706f32e7eSjoerg       // remove '[' ']'
30806f32e7eSjoerg       commit.replace(SourceRange(MsgRange.getBegin(), MsgRange.getBegin()), "");
30906f32e7eSjoerg       commit.replace(SourceRange(MsgRange.getEnd(), MsgRange.getEnd()), "");
31006f32e7eSjoerg     }
31106f32e7eSjoerg     return true;
31206f32e7eSjoerg   }
31306f32e7eSjoerg 
31406f32e7eSjoerg class ObjCMigrator : public RecursiveASTVisitor<ObjCMigrator> {
31506f32e7eSjoerg   ObjCMigrateASTConsumer &Consumer;
31606f32e7eSjoerg   ParentMap &PMap;
31706f32e7eSjoerg 
31806f32e7eSjoerg public:
ObjCMigrator(ObjCMigrateASTConsumer & consumer,ParentMap & PMap)31906f32e7eSjoerg   ObjCMigrator(ObjCMigrateASTConsumer &consumer, ParentMap &PMap)
32006f32e7eSjoerg     : Consumer(consumer), PMap(PMap) { }
32106f32e7eSjoerg 
shouldVisitTemplateInstantiations() const32206f32e7eSjoerg   bool shouldVisitTemplateInstantiations() const { return false; }
shouldWalkTypesOfTypeLocs() const32306f32e7eSjoerg   bool shouldWalkTypesOfTypeLocs() const { return false; }
32406f32e7eSjoerg 
VisitObjCMessageExpr(ObjCMessageExpr * E)32506f32e7eSjoerg   bool VisitObjCMessageExpr(ObjCMessageExpr *E) {
32606f32e7eSjoerg     if (Consumer.ASTMigrateActions & FrontendOptions::ObjCMT_Literals) {
32706f32e7eSjoerg       edit::Commit commit(*Consumer.Editor);
32806f32e7eSjoerg       edit::rewriteToObjCLiteralSyntax(E, *Consumer.NSAPIObj, commit, &PMap);
32906f32e7eSjoerg       Consumer.Editor->commit(commit);
33006f32e7eSjoerg     }
33106f32e7eSjoerg 
33206f32e7eSjoerg     if (Consumer.ASTMigrateActions & FrontendOptions::ObjCMT_Subscripting) {
33306f32e7eSjoerg       edit::Commit commit(*Consumer.Editor);
33406f32e7eSjoerg       edit::rewriteToObjCSubscriptSyntax(E, *Consumer.NSAPIObj, commit);
33506f32e7eSjoerg       Consumer.Editor->commit(commit);
33606f32e7eSjoerg     }
33706f32e7eSjoerg 
33806f32e7eSjoerg     if (Consumer.ASTMigrateActions & FrontendOptions::ObjCMT_PropertyDotSyntax) {
33906f32e7eSjoerg       edit::Commit commit(*Consumer.Editor);
34006f32e7eSjoerg       rewriteToPropertyDotSyntax(E, Consumer.PP, *Consumer.NSAPIObj,
34106f32e7eSjoerg                                  commit, &PMap);
34206f32e7eSjoerg       Consumer.Editor->commit(commit);
34306f32e7eSjoerg     }
34406f32e7eSjoerg 
34506f32e7eSjoerg     return true;
34606f32e7eSjoerg   }
34706f32e7eSjoerg 
TraverseObjCMessageExpr(ObjCMessageExpr * E)34806f32e7eSjoerg   bool TraverseObjCMessageExpr(ObjCMessageExpr *E) {
34906f32e7eSjoerg     // Do depth first; we want to rewrite the subexpressions first so that if
35006f32e7eSjoerg     // we have to move expressions we will move them already rewritten.
35106f32e7eSjoerg     for (Stmt *SubStmt : E->children())
35206f32e7eSjoerg       if (!TraverseStmt(SubStmt))
35306f32e7eSjoerg         return false;
35406f32e7eSjoerg 
35506f32e7eSjoerg     return WalkUpFromObjCMessageExpr(E);
35606f32e7eSjoerg   }
35706f32e7eSjoerg };
35806f32e7eSjoerg 
35906f32e7eSjoerg class BodyMigrator : public RecursiveASTVisitor<BodyMigrator> {
36006f32e7eSjoerg   ObjCMigrateASTConsumer &Consumer;
36106f32e7eSjoerg   std::unique_ptr<ParentMap> PMap;
36206f32e7eSjoerg 
36306f32e7eSjoerg public:
BodyMigrator(ObjCMigrateASTConsumer & consumer)36406f32e7eSjoerg   BodyMigrator(ObjCMigrateASTConsumer &consumer) : Consumer(consumer) { }
36506f32e7eSjoerg 
shouldVisitTemplateInstantiations() const36606f32e7eSjoerg   bool shouldVisitTemplateInstantiations() const { return false; }
shouldWalkTypesOfTypeLocs() const36706f32e7eSjoerg   bool shouldWalkTypesOfTypeLocs() const { return false; }
36806f32e7eSjoerg 
TraverseStmt(Stmt * S)36906f32e7eSjoerg   bool TraverseStmt(Stmt *S) {
37006f32e7eSjoerg     PMap.reset(new ParentMap(S));
37106f32e7eSjoerg     ObjCMigrator(Consumer, *PMap).TraverseStmt(S);
37206f32e7eSjoerg     return true;
37306f32e7eSjoerg   }
37406f32e7eSjoerg };
37506f32e7eSjoerg } // end anonymous namespace
37606f32e7eSjoerg 
migrateDecl(Decl * D)37706f32e7eSjoerg void ObjCMigrateASTConsumer::migrateDecl(Decl *D) {
37806f32e7eSjoerg   if (!D)
37906f32e7eSjoerg     return;
38006f32e7eSjoerg   if (isa<ObjCMethodDecl>(D))
38106f32e7eSjoerg     return; // Wait for the ObjC container declaration.
38206f32e7eSjoerg 
38306f32e7eSjoerg   BodyMigrator(*this).TraverseDecl(D);
38406f32e7eSjoerg }
38506f32e7eSjoerg 
append_attr(std::string & PropertyString,const char * attr,bool & LParenAdded)38606f32e7eSjoerg static void append_attr(std::string &PropertyString, const char *attr,
38706f32e7eSjoerg                         bool &LParenAdded) {
38806f32e7eSjoerg   if (!LParenAdded) {
38906f32e7eSjoerg     PropertyString += "(";
39006f32e7eSjoerg     LParenAdded = true;
39106f32e7eSjoerg   }
39206f32e7eSjoerg   else
39306f32e7eSjoerg     PropertyString += ", ";
39406f32e7eSjoerg   PropertyString += attr;
39506f32e7eSjoerg }
39606f32e7eSjoerg 
39706f32e7eSjoerg static
MigrateBlockOrFunctionPointerTypeVariable(std::string & PropertyString,const std::string & TypeString,const char * name)39806f32e7eSjoerg void MigrateBlockOrFunctionPointerTypeVariable(std::string & PropertyString,
39906f32e7eSjoerg                                                const std::string& TypeString,
40006f32e7eSjoerg                                                const char *name) {
40106f32e7eSjoerg   const char *argPtr = TypeString.c_str();
40206f32e7eSjoerg   int paren = 0;
40306f32e7eSjoerg   while (*argPtr) {
40406f32e7eSjoerg     switch (*argPtr) {
40506f32e7eSjoerg       case '(':
40606f32e7eSjoerg         PropertyString += *argPtr;
40706f32e7eSjoerg         paren++;
40806f32e7eSjoerg         break;
40906f32e7eSjoerg       case ')':
41006f32e7eSjoerg         PropertyString += *argPtr;
41106f32e7eSjoerg         paren--;
41206f32e7eSjoerg         break;
41306f32e7eSjoerg       case '^':
41406f32e7eSjoerg       case '*':
41506f32e7eSjoerg         PropertyString += (*argPtr);
41606f32e7eSjoerg         if (paren == 1) {
41706f32e7eSjoerg           PropertyString += name;
41806f32e7eSjoerg           name = "";
41906f32e7eSjoerg         }
42006f32e7eSjoerg         break;
42106f32e7eSjoerg       default:
42206f32e7eSjoerg         PropertyString += *argPtr;
42306f32e7eSjoerg         break;
42406f32e7eSjoerg     }
42506f32e7eSjoerg     argPtr++;
42606f32e7eSjoerg   }
42706f32e7eSjoerg }
42806f32e7eSjoerg 
PropertyMemoryAttribute(ASTContext & Context,QualType ArgType)42906f32e7eSjoerg static const char *PropertyMemoryAttribute(ASTContext &Context, QualType ArgType) {
43006f32e7eSjoerg   Qualifiers::ObjCLifetime propertyLifetime = ArgType.getObjCLifetime();
43106f32e7eSjoerg   bool RetainableObject = ArgType->isObjCRetainableType();
43206f32e7eSjoerg   if (RetainableObject &&
43306f32e7eSjoerg       (propertyLifetime == Qualifiers::OCL_Strong
43406f32e7eSjoerg        || propertyLifetime == Qualifiers::OCL_None)) {
43506f32e7eSjoerg     if (const ObjCObjectPointerType *ObjPtrTy =
43606f32e7eSjoerg         ArgType->getAs<ObjCObjectPointerType>()) {
43706f32e7eSjoerg       ObjCInterfaceDecl *IDecl = ObjPtrTy->getObjectType()->getInterface();
43806f32e7eSjoerg       if (IDecl &&
43906f32e7eSjoerg           IDecl->lookupNestedProtocol(&Context.Idents.get("NSCopying")))
44006f32e7eSjoerg         return "copy";
44106f32e7eSjoerg       else
44206f32e7eSjoerg         return "strong";
44306f32e7eSjoerg     }
44406f32e7eSjoerg     else if (ArgType->isBlockPointerType())
44506f32e7eSjoerg       return "copy";
44606f32e7eSjoerg   } else if (propertyLifetime == Qualifiers::OCL_Weak)
44706f32e7eSjoerg     // TODO. More precise determination of 'weak' attribute requires
44806f32e7eSjoerg     // looking into setter's implementation for backing weak ivar.
44906f32e7eSjoerg     return "weak";
45006f32e7eSjoerg   else if (RetainableObject)
45106f32e7eSjoerg     return ArgType->isBlockPointerType() ? "copy" : "strong";
45206f32e7eSjoerg   return nullptr;
45306f32e7eSjoerg }
45406f32e7eSjoerg 
rewriteToObjCProperty(const ObjCMethodDecl * Getter,const ObjCMethodDecl * Setter,const NSAPI & NS,edit::Commit & commit,unsigned LengthOfPrefix,bool Atomic,bool UseNsIosOnlyMacro,bool AvailabilityArgsMatch)45506f32e7eSjoerg static void rewriteToObjCProperty(const ObjCMethodDecl *Getter,
45606f32e7eSjoerg                                   const ObjCMethodDecl *Setter,
45706f32e7eSjoerg                                   const NSAPI &NS, edit::Commit &commit,
45806f32e7eSjoerg                                   unsigned LengthOfPrefix,
45906f32e7eSjoerg                                   bool Atomic, bool UseNsIosOnlyMacro,
46006f32e7eSjoerg                                   bool AvailabilityArgsMatch) {
46106f32e7eSjoerg   ASTContext &Context = NS.getASTContext();
46206f32e7eSjoerg   bool LParenAdded = false;
46306f32e7eSjoerg   std::string PropertyString = "@property ";
46406f32e7eSjoerg   if (UseNsIosOnlyMacro && NS.isMacroDefined("NS_NONATOMIC_IOSONLY")) {
46506f32e7eSjoerg     PropertyString += "(NS_NONATOMIC_IOSONLY";
46606f32e7eSjoerg     LParenAdded = true;
46706f32e7eSjoerg   } else if (!Atomic) {
46806f32e7eSjoerg     PropertyString += "(nonatomic";
46906f32e7eSjoerg     LParenAdded = true;
47006f32e7eSjoerg   }
47106f32e7eSjoerg 
47206f32e7eSjoerg   std::string PropertyNameString = Getter->getNameAsString();
47306f32e7eSjoerg   StringRef PropertyName(PropertyNameString);
47406f32e7eSjoerg   if (LengthOfPrefix > 0) {
47506f32e7eSjoerg     if (!LParenAdded) {
47606f32e7eSjoerg       PropertyString += "(getter=";
47706f32e7eSjoerg       LParenAdded = true;
47806f32e7eSjoerg     }
47906f32e7eSjoerg     else
48006f32e7eSjoerg       PropertyString += ", getter=";
48106f32e7eSjoerg     PropertyString += PropertyNameString;
48206f32e7eSjoerg   }
48306f32e7eSjoerg   // Property with no setter may be suggested as a 'readonly' property.
48406f32e7eSjoerg   if (!Setter)
48506f32e7eSjoerg     append_attr(PropertyString, "readonly", LParenAdded);
48606f32e7eSjoerg 
48706f32e7eSjoerg 
48806f32e7eSjoerg   // Short circuit 'delegate' properties that contain the name "delegate" or
48906f32e7eSjoerg   // "dataSource", or have exact name "target" to have 'assign' attribute.
49006f32e7eSjoerg   if (PropertyName.equals("target") ||
49106f32e7eSjoerg       (PropertyName.find("delegate") != StringRef::npos) ||
49206f32e7eSjoerg       (PropertyName.find("dataSource") != StringRef::npos)) {
49306f32e7eSjoerg     QualType QT = Getter->getReturnType();
49406f32e7eSjoerg     if (!QT->isRealType())
49506f32e7eSjoerg       append_attr(PropertyString, "assign", LParenAdded);
49606f32e7eSjoerg   } else if (!Setter) {
49706f32e7eSjoerg     QualType ResType = Context.getCanonicalType(Getter->getReturnType());
49806f32e7eSjoerg     if (const char *MemoryManagementAttr = PropertyMemoryAttribute(Context, ResType))
49906f32e7eSjoerg       append_attr(PropertyString, MemoryManagementAttr, LParenAdded);
50006f32e7eSjoerg   } else {
50106f32e7eSjoerg     const ParmVarDecl *argDecl = *Setter->param_begin();
50206f32e7eSjoerg     QualType ArgType = Context.getCanonicalType(argDecl->getType());
50306f32e7eSjoerg     if (const char *MemoryManagementAttr = PropertyMemoryAttribute(Context, ArgType))
50406f32e7eSjoerg       append_attr(PropertyString, MemoryManagementAttr, LParenAdded);
50506f32e7eSjoerg   }
50606f32e7eSjoerg   if (LParenAdded)
50706f32e7eSjoerg     PropertyString += ')';
50806f32e7eSjoerg   QualType RT = Getter->getReturnType();
50906f32e7eSjoerg   if (!isa<TypedefType>(RT)) {
51006f32e7eSjoerg     // strip off any ARC lifetime qualifier.
51106f32e7eSjoerg     QualType CanResultTy = Context.getCanonicalType(RT);
51206f32e7eSjoerg     if (CanResultTy.getQualifiers().hasObjCLifetime()) {
51306f32e7eSjoerg       Qualifiers Qs = CanResultTy.getQualifiers();
51406f32e7eSjoerg       Qs.removeObjCLifetime();
51506f32e7eSjoerg       RT = Context.getQualifiedType(CanResultTy.getUnqualifiedType(), Qs);
51606f32e7eSjoerg     }
51706f32e7eSjoerg   }
51806f32e7eSjoerg   PropertyString += " ";
51906f32e7eSjoerg   PrintingPolicy SubPolicy(Context.getPrintingPolicy());
52006f32e7eSjoerg   SubPolicy.SuppressStrongLifetime = true;
52106f32e7eSjoerg   SubPolicy.SuppressLifetimeQualifiers = true;
52206f32e7eSjoerg   std::string TypeString = RT.getAsString(SubPolicy);
52306f32e7eSjoerg   if (LengthOfPrefix > 0) {
52406f32e7eSjoerg     // property name must strip off "is" and lower case the first character
52506f32e7eSjoerg     // after that; e.g. isContinuous will become continuous.
52606f32e7eSjoerg     StringRef PropertyNameStringRef(PropertyNameString);
52706f32e7eSjoerg     PropertyNameStringRef = PropertyNameStringRef.drop_front(LengthOfPrefix);
528*13fbcb42Sjoerg     PropertyNameString = std::string(PropertyNameStringRef);
52906f32e7eSjoerg     bool NoLowering = (isUppercase(PropertyNameString[0]) &&
53006f32e7eSjoerg                        PropertyNameString.size() > 1 &&
53106f32e7eSjoerg                        isUppercase(PropertyNameString[1]));
53206f32e7eSjoerg     if (!NoLowering)
53306f32e7eSjoerg       PropertyNameString[0] = toLowercase(PropertyNameString[0]);
53406f32e7eSjoerg   }
53506f32e7eSjoerg   if (RT->isBlockPointerType() || RT->isFunctionPointerType())
53606f32e7eSjoerg     MigrateBlockOrFunctionPointerTypeVariable(PropertyString,
53706f32e7eSjoerg                                               TypeString,
53806f32e7eSjoerg                                               PropertyNameString.c_str());
53906f32e7eSjoerg   else {
54006f32e7eSjoerg     char LastChar = TypeString[TypeString.size()-1];
54106f32e7eSjoerg     PropertyString += TypeString;
54206f32e7eSjoerg     if (LastChar != '*')
54306f32e7eSjoerg       PropertyString += ' ';
54406f32e7eSjoerg     PropertyString += PropertyNameString;
54506f32e7eSjoerg   }
54606f32e7eSjoerg   SourceLocation StartGetterSelectorLoc = Getter->getSelectorStartLoc();
54706f32e7eSjoerg   Selector GetterSelector = Getter->getSelector();
54806f32e7eSjoerg 
54906f32e7eSjoerg   SourceLocation EndGetterSelectorLoc =
55006f32e7eSjoerg     StartGetterSelectorLoc.getLocWithOffset(GetterSelector.getNameForSlot(0).size());
55106f32e7eSjoerg   commit.replace(CharSourceRange::getCharRange(Getter->getBeginLoc(),
55206f32e7eSjoerg                                                EndGetterSelectorLoc),
55306f32e7eSjoerg                  PropertyString);
55406f32e7eSjoerg   if (Setter && AvailabilityArgsMatch) {
55506f32e7eSjoerg     SourceLocation EndLoc = Setter->getDeclaratorEndLoc();
55606f32e7eSjoerg     // Get location past ';'
55706f32e7eSjoerg     EndLoc = EndLoc.getLocWithOffset(1);
55806f32e7eSjoerg     SourceLocation BeginOfSetterDclLoc = Setter->getBeginLoc();
55906f32e7eSjoerg     // FIXME. This assumes that setter decl; is immediately preceded by eoln.
56006f32e7eSjoerg     // It is trying to remove the setter method decl. line entirely.
56106f32e7eSjoerg     BeginOfSetterDclLoc = BeginOfSetterDclLoc.getLocWithOffset(-1);
56206f32e7eSjoerg     commit.remove(SourceRange(BeginOfSetterDclLoc, EndLoc));
56306f32e7eSjoerg   }
56406f32e7eSjoerg }
56506f32e7eSjoerg 
IsCategoryNameWithDeprecatedSuffix(ObjCContainerDecl * D)56606f32e7eSjoerg static bool IsCategoryNameWithDeprecatedSuffix(ObjCContainerDecl *D) {
56706f32e7eSjoerg   if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(D)) {
56806f32e7eSjoerg     StringRef Name = CatDecl->getName();
56906f32e7eSjoerg     return Name.endswith("Deprecated");
57006f32e7eSjoerg   }
57106f32e7eSjoerg   return false;
57206f32e7eSjoerg }
57306f32e7eSjoerg 
migrateObjCContainerDecl(ASTContext & Ctx,ObjCContainerDecl * D)57406f32e7eSjoerg void ObjCMigrateASTConsumer::migrateObjCContainerDecl(ASTContext &Ctx,
57506f32e7eSjoerg                                                       ObjCContainerDecl *D) {
57606f32e7eSjoerg   if (D->isDeprecated() || IsCategoryNameWithDeprecatedSuffix(D))
57706f32e7eSjoerg     return;
57806f32e7eSjoerg 
57906f32e7eSjoerg   for (auto *Method : D->methods()) {
58006f32e7eSjoerg     if (Method->isDeprecated())
58106f32e7eSjoerg       continue;
58206f32e7eSjoerg     bool PropertyInferred = migrateProperty(Ctx, D, Method);
58306f32e7eSjoerg     // If a property is inferred, do not attempt to attach NS_RETURNS_INNER_POINTER to
58406f32e7eSjoerg     // the getter method as it ends up on the property itself which we don't want
58506f32e7eSjoerg     // to do unless -objcmt-returns-innerpointer-property  option is on.
58606f32e7eSjoerg     if (!PropertyInferred ||
58706f32e7eSjoerg         (ASTMigrateActions & FrontendOptions::ObjCMT_ReturnsInnerPointerProperty))
58806f32e7eSjoerg       if (ASTMigrateActions & FrontendOptions::ObjCMT_Annotation)
58906f32e7eSjoerg         migrateNsReturnsInnerPointer(Ctx, Method);
59006f32e7eSjoerg   }
59106f32e7eSjoerg   if (!(ASTMigrateActions & FrontendOptions::ObjCMT_ReturnsInnerPointerProperty))
59206f32e7eSjoerg     return;
59306f32e7eSjoerg 
59406f32e7eSjoerg   for (auto *Prop : D->instance_properties()) {
59506f32e7eSjoerg     if ((ASTMigrateActions & FrontendOptions::ObjCMT_Annotation) &&
59606f32e7eSjoerg         !Prop->isDeprecated())
59706f32e7eSjoerg       migratePropertyNsReturnsInnerPointer(Ctx, Prop);
59806f32e7eSjoerg   }
59906f32e7eSjoerg }
60006f32e7eSjoerg 
60106f32e7eSjoerg static bool
ClassImplementsAllMethodsAndProperties(ASTContext & Ctx,const ObjCImplementationDecl * ImpDecl,const ObjCInterfaceDecl * IDecl,ObjCProtocolDecl * Protocol)60206f32e7eSjoerg ClassImplementsAllMethodsAndProperties(ASTContext &Ctx,
60306f32e7eSjoerg                                       const ObjCImplementationDecl *ImpDecl,
60406f32e7eSjoerg                                        const ObjCInterfaceDecl *IDecl,
60506f32e7eSjoerg                                       ObjCProtocolDecl *Protocol) {
60606f32e7eSjoerg   // In auto-synthesis, protocol properties are not synthesized. So,
60706f32e7eSjoerg   // a conforming protocol must have its required properties declared
60806f32e7eSjoerg   // in class interface.
60906f32e7eSjoerg   bool HasAtleastOneRequiredProperty = false;
61006f32e7eSjoerg   if (const ObjCProtocolDecl *PDecl = Protocol->getDefinition())
61106f32e7eSjoerg     for (const auto *Property : PDecl->instance_properties()) {
61206f32e7eSjoerg       if (Property->getPropertyImplementation() == ObjCPropertyDecl::Optional)
61306f32e7eSjoerg         continue;
61406f32e7eSjoerg       HasAtleastOneRequiredProperty = true;
61506f32e7eSjoerg       DeclContext::lookup_result R = IDecl->lookup(Property->getDeclName());
616*13fbcb42Sjoerg       if (R.empty()) {
61706f32e7eSjoerg         // Relax the rule and look into class's implementation for a synthesize
61806f32e7eSjoerg         // or dynamic declaration. Class is implementing a property coming from
61906f32e7eSjoerg         // another protocol. This still makes the target protocol as conforming.
62006f32e7eSjoerg         if (!ImpDecl->FindPropertyImplDecl(
62106f32e7eSjoerg                                   Property->getDeclName().getAsIdentifierInfo(),
62206f32e7eSjoerg                                   Property->getQueryKind()))
62306f32e7eSjoerg           return false;
624*13fbcb42Sjoerg       } else if (auto *ClassProperty = R.find_first<ObjCPropertyDecl>()) {
625*13fbcb42Sjoerg         if ((ClassProperty->getPropertyAttributes() !=
626*13fbcb42Sjoerg              Property->getPropertyAttributes()) ||
62706f32e7eSjoerg             !Ctx.hasSameType(ClassProperty->getType(), Property->getType()))
62806f32e7eSjoerg           return false;
629*13fbcb42Sjoerg       } else
63006f32e7eSjoerg         return false;
63106f32e7eSjoerg     }
63206f32e7eSjoerg 
63306f32e7eSjoerg   // At this point, all required properties in this protocol conform to those
63406f32e7eSjoerg   // declared in the class.
63506f32e7eSjoerg   // Check that class implements the required methods of the protocol too.
63606f32e7eSjoerg   bool HasAtleastOneRequiredMethod = false;
63706f32e7eSjoerg   if (const ObjCProtocolDecl *PDecl = Protocol->getDefinition()) {
63806f32e7eSjoerg     if (PDecl->meth_begin() == PDecl->meth_end())
63906f32e7eSjoerg       return HasAtleastOneRequiredProperty;
64006f32e7eSjoerg     for (const auto *MD : PDecl->methods()) {
64106f32e7eSjoerg       if (MD->isImplicit())
64206f32e7eSjoerg         continue;
64306f32e7eSjoerg       if (MD->getImplementationControl() == ObjCMethodDecl::Optional)
64406f32e7eSjoerg         continue;
64506f32e7eSjoerg       DeclContext::lookup_result R = ImpDecl->lookup(MD->getDeclName());
646*13fbcb42Sjoerg       if (R.empty())
64706f32e7eSjoerg         return false;
64806f32e7eSjoerg       bool match = false;
64906f32e7eSjoerg       HasAtleastOneRequiredMethod = true;
650*13fbcb42Sjoerg       for (NamedDecl *ND : R)
651*13fbcb42Sjoerg         if (ObjCMethodDecl *ImpMD = dyn_cast<ObjCMethodDecl>(ND))
65206f32e7eSjoerg           if (Ctx.ObjCMethodsAreEqual(MD, ImpMD)) {
65306f32e7eSjoerg             match = true;
65406f32e7eSjoerg             break;
65506f32e7eSjoerg           }
65606f32e7eSjoerg       if (!match)
65706f32e7eSjoerg         return false;
65806f32e7eSjoerg     }
65906f32e7eSjoerg   }
66006f32e7eSjoerg   return HasAtleastOneRequiredProperty || HasAtleastOneRequiredMethod;
66106f32e7eSjoerg }
66206f32e7eSjoerg 
rewriteToObjCInterfaceDecl(const ObjCInterfaceDecl * IDecl,llvm::SmallVectorImpl<ObjCProtocolDecl * > & ConformingProtocols,const NSAPI & NS,edit::Commit & commit)66306f32e7eSjoerg static bool rewriteToObjCInterfaceDecl(const ObjCInterfaceDecl *IDecl,
66406f32e7eSjoerg                     llvm::SmallVectorImpl<ObjCProtocolDecl*> &ConformingProtocols,
66506f32e7eSjoerg                     const NSAPI &NS, edit::Commit &commit) {
66606f32e7eSjoerg   const ObjCList<ObjCProtocolDecl> &Protocols = IDecl->getReferencedProtocols();
66706f32e7eSjoerg   std::string ClassString;
66806f32e7eSjoerg   SourceLocation EndLoc =
66906f32e7eSjoerg   IDecl->getSuperClass() ? IDecl->getSuperClassLoc() : IDecl->getLocation();
67006f32e7eSjoerg 
67106f32e7eSjoerg   if (Protocols.empty()) {
67206f32e7eSjoerg     ClassString = '<';
67306f32e7eSjoerg     for (unsigned i = 0, e = ConformingProtocols.size(); i != e; i++) {
67406f32e7eSjoerg       ClassString += ConformingProtocols[i]->getNameAsString();
67506f32e7eSjoerg       if (i != (e-1))
67606f32e7eSjoerg         ClassString += ", ";
67706f32e7eSjoerg     }
67806f32e7eSjoerg     ClassString += "> ";
67906f32e7eSjoerg   }
68006f32e7eSjoerg   else {
68106f32e7eSjoerg     ClassString = ", ";
68206f32e7eSjoerg     for (unsigned i = 0, e = ConformingProtocols.size(); i != e; i++) {
68306f32e7eSjoerg       ClassString += ConformingProtocols[i]->getNameAsString();
68406f32e7eSjoerg       if (i != (e-1))
68506f32e7eSjoerg         ClassString += ", ";
68606f32e7eSjoerg     }
68706f32e7eSjoerg     ObjCInterfaceDecl::protocol_loc_iterator PL = IDecl->protocol_loc_end() - 1;
68806f32e7eSjoerg     EndLoc = *PL;
68906f32e7eSjoerg   }
69006f32e7eSjoerg 
69106f32e7eSjoerg   commit.insertAfterToken(EndLoc, ClassString);
69206f32e7eSjoerg   return true;
69306f32e7eSjoerg }
69406f32e7eSjoerg 
GetUnsignedName(StringRef NSIntegerName)69506f32e7eSjoerg static StringRef GetUnsignedName(StringRef NSIntegerName) {
69606f32e7eSjoerg   StringRef UnsignedName = llvm::StringSwitch<StringRef>(NSIntegerName)
69706f32e7eSjoerg     .Case("int8_t", "uint8_t")
69806f32e7eSjoerg     .Case("int16_t", "uint16_t")
69906f32e7eSjoerg     .Case("int32_t", "uint32_t")
70006f32e7eSjoerg     .Case("NSInteger", "NSUInteger")
70106f32e7eSjoerg     .Case("int64_t", "uint64_t")
70206f32e7eSjoerg     .Default(NSIntegerName);
70306f32e7eSjoerg   return UnsignedName;
70406f32e7eSjoerg }
70506f32e7eSjoerg 
rewriteToNSEnumDecl(const EnumDecl * EnumDcl,const TypedefDecl * TypedefDcl,const NSAPI & NS,edit::Commit & commit,StringRef NSIntegerName,bool NSOptions)70606f32e7eSjoerg static bool rewriteToNSEnumDecl(const EnumDecl *EnumDcl,
70706f32e7eSjoerg                                 const TypedefDecl *TypedefDcl,
70806f32e7eSjoerg                                 const NSAPI &NS, edit::Commit &commit,
70906f32e7eSjoerg                                 StringRef NSIntegerName,
71006f32e7eSjoerg                                 bool NSOptions) {
71106f32e7eSjoerg   std::string ClassString;
71206f32e7eSjoerg   if (NSOptions) {
71306f32e7eSjoerg     ClassString = "typedef NS_OPTIONS(";
71406f32e7eSjoerg     ClassString += GetUnsignedName(NSIntegerName);
71506f32e7eSjoerg   }
71606f32e7eSjoerg   else {
71706f32e7eSjoerg     ClassString = "typedef NS_ENUM(";
71806f32e7eSjoerg     ClassString += NSIntegerName;
71906f32e7eSjoerg   }
72006f32e7eSjoerg   ClassString += ", ";
72106f32e7eSjoerg 
72206f32e7eSjoerg   ClassString += TypedefDcl->getIdentifier()->getName();
72306f32e7eSjoerg   ClassString += ')';
72406f32e7eSjoerg   SourceRange R(EnumDcl->getBeginLoc(), EnumDcl->getBeginLoc());
72506f32e7eSjoerg   commit.replace(R, ClassString);
72606f32e7eSjoerg   SourceLocation EndOfEnumDclLoc = EnumDcl->getEndLoc();
72706f32e7eSjoerg   EndOfEnumDclLoc = trans::findSemiAfterLocation(EndOfEnumDclLoc,
72806f32e7eSjoerg                                                  NS.getASTContext(), /*IsDecl*/true);
72906f32e7eSjoerg   if (EndOfEnumDclLoc.isValid()) {
73006f32e7eSjoerg     SourceRange EnumDclRange(EnumDcl->getBeginLoc(), EndOfEnumDclLoc);
73106f32e7eSjoerg     commit.insertFromRange(TypedefDcl->getBeginLoc(), EnumDclRange);
73206f32e7eSjoerg   }
73306f32e7eSjoerg   else
73406f32e7eSjoerg     return false;
73506f32e7eSjoerg 
73606f32e7eSjoerg   SourceLocation EndTypedefDclLoc = TypedefDcl->getEndLoc();
73706f32e7eSjoerg   EndTypedefDclLoc = trans::findSemiAfterLocation(EndTypedefDclLoc,
73806f32e7eSjoerg                                                  NS.getASTContext(), /*IsDecl*/true);
73906f32e7eSjoerg   if (EndTypedefDclLoc.isValid()) {
74006f32e7eSjoerg     SourceRange TDRange(TypedefDcl->getBeginLoc(), EndTypedefDclLoc);
74106f32e7eSjoerg     commit.remove(TDRange);
74206f32e7eSjoerg   }
74306f32e7eSjoerg   else
74406f32e7eSjoerg     return false;
74506f32e7eSjoerg 
74606f32e7eSjoerg   EndOfEnumDclLoc =
74706f32e7eSjoerg       trans::findLocationAfterSemi(EnumDcl->getEndLoc(), NS.getASTContext(),
74806f32e7eSjoerg                                    /*IsDecl*/ true);
74906f32e7eSjoerg   if (EndOfEnumDclLoc.isValid()) {
75006f32e7eSjoerg     SourceLocation BeginOfEnumDclLoc = EnumDcl->getBeginLoc();
75106f32e7eSjoerg     // FIXME. This assumes that enum decl; is immediately preceded by eoln.
75206f32e7eSjoerg     // It is trying to remove the enum decl. lines entirely.
75306f32e7eSjoerg     BeginOfEnumDclLoc = BeginOfEnumDclLoc.getLocWithOffset(-1);
75406f32e7eSjoerg     commit.remove(SourceRange(BeginOfEnumDclLoc, EndOfEnumDclLoc));
75506f32e7eSjoerg     return true;
75606f32e7eSjoerg   }
75706f32e7eSjoerg   return false;
75806f32e7eSjoerg }
75906f32e7eSjoerg 
rewriteToNSMacroDecl(ASTContext & Ctx,const EnumDecl * EnumDcl,const TypedefDecl * TypedefDcl,const NSAPI & NS,edit::Commit & commit,bool IsNSIntegerType)76006f32e7eSjoerg static void rewriteToNSMacroDecl(ASTContext &Ctx,
76106f32e7eSjoerg                                  const EnumDecl *EnumDcl,
76206f32e7eSjoerg                                 const TypedefDecl *TypedefDcl,
76306f32e7eSjoerg                                 const NSAPI &NS, edit::Commit &commit,
76406f32e7eSjoerg                                  bool IsNSIntegerType) {
76506f32e7eSjoerg   QualType DesignatedEnumType = EnumDcl->getIntegerType();
76606f32e7eSjoerg   assert(!DesignatedEnumType.isNull()
76706f32e7eSjoerg          && "rewriteToNSMacroDecl - underlying enum type is null");
76806f32e7eSjoerg 
76906f32e7eSjoerg   PrintingPolicy Policy(Ctx.getPrintingPolicy());
77006f32e7eSjoerg   std::string TypeString = DesignatedEnumType.getAsString(Policy);
77106f32e7eSjoerg   std::string ClassString = IsNSIntegerType ? "NS_ENUM(" : "NS_OPTIONS(";
77206f32e7eSjoerg   ClassString += TypeString;
77306f32e7eSjoerg   ClassString += ", ";
77406f32e7eSjoerg 
77506f32e7eSjoerg   ClassString += TypedefDcl->getIdentifier()->getName();
77606f32e7eSjoerg   ClassString += ") ";
77706f32e7eSjoerg   SourceLocation EndLoc = EnumDcl->getBraceRange().getBegin();
77806f32e7eSjoerg   if (EndLoc.isInvalid())
77906f32e7eSjoerg     return;
78006f32e7eSjoerg   CharSourceRange R =
78106f32e7eSjoerg       CharSourceRange::getCharRange(EnumDcl->getBeginLoc(), EndLoc);
78206f32e7eSjoerg   commit.replace(R, ClassString);
78306f32e7eSjoerg   // This is to remove spaces between '}' and typedef name.
78406f32e7eSjoerg   SourceLocation StartTypedefLoc = EnumDcl->getEndLoc();
78506f32e7eSjoerg   StartTypedefLoc = StartTypedefLoc.getLocWithOffset(+1);
78606f32e7eSjoerg   SourceLocation EndTypedefLoc = TypedefDcl->getEndLoc();
78706f32e7eSjoerg 
78806f32e7eSjoerg   commit.remove(SourceRange(StartTypedefLoc, EndTypedefLoc));
78906f32e7eSjoerg }
79006f32e7eSjoerg 
UseNSOptionsMacro(Preprocessor & PP,ASTContext & Ctx,const EnumDecl * EnumDcl)79106f32e7eSjoerg static bool UseNSOptionsMacro(Preprocessor &PP, ASTContext &Ctx,
79206f32e7eSjoerg                               const EnumDecl *EnumDcl) {
79306f32e7eSjoerg   bool PowerOfTwo = true;
79406f32e7eSjoerg   bool AllHexdecimalEnumerator = true;
79506f32e7eSjoerg   uint64_t MaxPowerOfTwoVal = 0;
79606f32e7eSjoerg   for (auto Enumerator : EnumDcl->enumerators()) {
79706f32e7eSjoerg     const Expr *InitExpr = Enumerator->getInitExpr();
79806f32e7eSjoerg     if (!InitExpr) {
79906f32e7eSjoerg       PowerOfTwo = false;
80006f32e7eSjoerg       AllHexdecimalEnumerator = false;
80106f32e7eSjoerg       continue;
80206f32e7eSjoerg     }
80306f32e7eSjoerg     InitExpr = InitExpr->IgnoreParenCasts();
80406f32e7eSjoerg     if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr))
80506f32e7eSjoerg       if (BO->isShiftOp() || BO->isBitwiseOp())
80606f32e7eSjoerg         return true;
80706f32e7eSjoerg 
80806f32e7eSjoerg     uint64_t EnumVal = Enumerator->getInitVal().getZExtValue();
80906f32e7eSjoerg     if (PowerOfTwo && EnumVal) {
81006f32e7eSjoerg       if (!llvm::isPowerOf2_64(EnumVal))
81106f32e7eSjoerg         PowerOfTwo = false;
81206f32e7eSjoerg       else if (EnumVal > MaxPowerOfTwoVal)
81306f32e7eSjoerg         MaxPowerOfTwoVal = EnumVal;
81406f32e7eSjoerg     }
81506f32e7eSjoerg     if (AllHexdecimalEnumerator && EnumVal) {
81606f32e7eSjoerg       bool FoundHexdecimalEnumerator = false;
81706f32e7eSjoerg       SourceLocation EndLoc = Enumerator->getEndLoc();
81806f32e7eSjoerg       Token Tok;
81906f32e7eSjoerg       if (!PP.getRawToken(EndLoc, Tok, /*IgnoreWhiteSpace=*/true))
82006f32e7eSjoerg         if (Tok.isLiteral() && Tok.getLength() > 2) {
82106f32e7eSjoerg           if (const char *StringLit = Tok.getLiteralData())
82206f32e7eSjoerg             FoundHexdecimalEnumerator =
82306f32e7eSjoerg               (StringLit[0] == '0' && (toLowercase(StringLit[1]) == 'x'));
82406f32e7eSjoerg         }
82506f32e7eSjoerg       if (!FoundHexdecimalEnumerator)
82606f32e7eSjoerg         AllHexdecimalEnumerator = false;
82706f32e7eSjoerg     }
82806f32e7eSjoerg   }
82906f32e7eSjoerg   return AllHexdecimalEnumerator || (PowerOfTwo && (MaxPowerOfTwoVal > 2));
83006f32e7eSjoerg }
83106f32e7eSjoerg 
migrateProtocolConformance(ASTContext & Ctx,const ObjCImplementationDecl * ImpDecl)83206f32e7eSjoerg void ObjCMigrateASTConsumer::migrateProtocolConformance(ASTContext &Ctx,
83306f32e7eSjoerg                                             const ObjCImplementationDecl *ImpDecl) {
83406f32e7eSjoerg   const ObjCInterfaceDecl *IDecl = ImpDecl->getClassInterface();
83506f32e7eSjoerg   if (!IDecl || ObjCProtocolDecls.empty() || IDecl->isDeprecated())
83606f32e7eSjoerg     return;
83706f32e7eSjoerg   // Find all implicit conforming protocols for this class
83806f32e7eSjoerg   // and make them explicit.
83906f32e7eSjoerg   llvm::SmallPtrSet<ObjCProtocolDecl *, 8> ExplicitProtocols;
84006f32e7eSjoerg   Ctx.CollectInheritedProtocols(IDecl, ExplicitProtocols);
84106f32e7eSjoerg   llvm::SmallVector<ObjCProtocolDecl *, 8> PotentialImplicitProtocols;
84206f32e7eSjoerg 
84306f32e7eSjoerg   for (ObjCProtocolDecl *ProtDecl : ObjCProtocolDecls)
84406f32e7eSjoerg     if (!ExplicitProtocols.count(ProtDecl))
84506f32e7eSjoerg       PotentialImplicitProtocols.push_back(ProtDecl);
84606f32e7eSjoerg 
84706f32e7eSjoerg   if (PotentialImplicitProtocols.empty())
84806f32e7eSjoerg     return;
84906f32e7eSjoerg 
85006f32e7eSjoerg   // go through list of non-optional methods and properties in each protocol
85106f32e7eSjoerg   // in the PotentialImplicitProtocols list. If class implements every one of the
85206f32e7eSjoerg   // methods and properties, then this class conforms to this protocol.
85306f32e7eSjoerg   llvm::SmallVector<ObjCProtocolDecl*, 8> ConformingProtocols;
85406f32e7eSjoerg   for (unsigned i = 0, e = PotentialImplicitProtocols.size(); i != e; i++)
85506f32e7eSjoerg     if (ClassImplementsAllMethodsAndProperties(Ctx, ImpDecl, IDecl,
85606f32e7eSjoerg                                               PotentialImplicitProtocols[i]))
85706f32e7eSjoerg       ConformingProtocols.push_back(PotentialImplicitProtocols[i]);
85806f32e7eSjoerg 
85906f32e7eSjoerg   if (ConformingProtocols.empty())
86006f32e7eSjoerg     return;
86106f32e7eSjoerg 
86206f32e7eSjoerg   // Further reduce number of conforming protocols. If protocol P1 is in the list
86306f32e7eSjoerg   // protocol P2 (P2<P1>), No need to include P1.
86406f32e7eSjoerg   llvm::SmallVector<ObjCProtocolDecl*, 8> MinimalConformingProtocols;
86506f32e7eSjoerg   for (unsigned i = 0, e = ConformingProtocols.size(); i != e; i++) {
86606f32e7eSjoerg     bool DropIt = false;
86706f32e7eSjoerg     ObjCProtocolDecl *TargetPDecl = ConformingProtocols[i];
86806f32e7eSjoerg     for (unsigned i1 = 0, e1 = ConformingProtocols.size(); i1 != e1; i1++) {
86906f32e7eSjoerg       ObjCProtocolDecl *PDecl = ConformingProtocols[i1];
87006f32e7eSjoerg       if (PDecl == TargetPDecl)
87106f32e7eSjoerg         continue;
87206f32e7eSjoerg       if (PDecl->lookupProtocolNamed(
87306f32e7eSjoerg             TargetPDecl->getDeclName().getAsIdentifierInfo())) {
87406f32e7eSjoerg         DropIt = true;
87506f32e7eSjoerg         break;
87606f32e7eSjoerg       }
87706f32e7eSjoerg     }
87806f32e7eSjoerg     if (!DropIt)
87906f32e7eSjoerg       MinimalConformingProtocols.push_back(TargetPDecl);
88006f32e7eSjoerg   }
88106f32e7eSjoerg   if (MinimalConformingProtocols.empty())
88206f32e7eSjoerg     return;
88306f32e7eSjoerg   edit::Commit commit(*Editor);
88406f32e7eSjoerg   rewriteToObjCInterfaceDecl(IDecl, MinimalConformingProtocols,
88506f32e7eSjoerg                              *NSAPIObj, commit);
88606f32e7eSjoerg   Editor->commit(commit);
88706f32e7eSjoerg }
88806f32e7eSjoerg 
CacheObjCNSIntegerTypedefed(const TypedefDecl * TypedefDcl)88906f32e7eSjoerg void ObjCMigrateASTConsumer::CacheObjCNSIntegerTypedefed(
89006f32e7eSjoerg                                           const TypedefDecl *TypedefDcl) {
89106f32e7eSjoerg 
89206f32e7eSjoerg   QualType qt = TypedefDcl->getTypeSourceInfo()->getType();
89306f32e7eSjoerg   if (NSAPIObj->isObjCNSIntegerType(qt))
89406f32e7eSjoerg     NSIntegerTypedefed = TypedefDcl;
89506f32e7eSjoerg   else if (NSAPIObj->isObjCNSUIntegerType(qt))
89606f32e7eSjoerg     NSUIntegerTypedefed = TypedefDcl;
89706f32e7eSjoerg }
89806f32e7eSjoerg 
migrateNSEnumDecl(ASTContext & Ctx,const EnumDecl * EnumDcl,const TypedefDecl * TypedefDcl)89906f32e7eSjoerg bool ObjCMigrateASTConsumer::migrateNSEnumDecl(ASTContext &Ctx,
90006f32e7eSjoerg                                            const EnumDecl *EnumDcl,
90106f32e7eSjoerg                                            const TypedefDecl *TypedefDcl) {
90206f32e7eSjoerg   if (!EnumDcl->isCompleteDefinition() || EnumDcl->getIdentifier() ||
90306f32e7eSjoerg       EnumDcl->isDeprecated())
90406f32e7eSjoerg     return false;
90506f32e7eSjoerg   if (!TypedefDcl) {
90606f32e7eSjoerg     if (NSIntegerTypedefed) {
90706f32e7eSjoerg       TypedefDcl = NSIntegerTypedefed;
90806f32e7eSjoerg       NSIntegerTypedefed = nullptr;
90906f32e7eSjoerg     }
91006f32e7eSjoerg     else if (NSUIntegerTypedefed) {
91106f32e7eSjoerg       TypedefDcl = NSUIntegerTypedefed;
91206f32e7eSjoerg       NSUIntegerTypedefed = nullptr;
91306f32e7eSjoerg     }
91406f32e7eSjoerg     else
91506f32e7eSjoerg       return false;
91606f32e7eSjoerg     FileID FileIdOfTypedefDcl =
91706f32e7eSjoerg       PP.getSourceManager().getFileID(TypedefDcl->getLocation());
91806f32e7eSjoerg     FileID FileIdOfEnumDcl =
91906f32e7eSjoerg       PP.getSourceManager().getFileID(EnumDcl->getLocation());
92006f32e7eSjoerg     if (FileIdOfTypedefDcl != FileIdOfEnumDcl)
92106f32e7eSjoerg       return false;
92206f32e7eSjoerg   }
92306f32e7eSjoerg   if (TypedefDcl->isDeprecated())
92406f32e7eSjoerg     return false;
92506f32e7eSjoerg 
92606f32e7eSjoerg   QualType qt = TypedefDcl->getTypeSourceInfo()->getType();
92706f32e7eSjoerg   StringRef NSIntegerName = NSAPIObj->GetNSIntegralKind(qt);
92806f32e7eSjoerg 
92906f32e7eSjoerg   if (NSIntegerName.empty()) {
93006f32e7eSjoerg     // Also check for typedef enum {...} TD;
93106f32e7eSjoerg     if (const EnumType *EnumTy = qt->getAs<EnumType>()) {
93206f32e7eSjoerg       if (EnumTy->getDecl() == EnumDcl) {
93306f32e7eSjoerg         bool NSOptions = UseNSOptionsMacro(PP, Ctx, EnumDcl);
93406f32e7eSjoerg         if (!InsertFoundation(Ctx, TypedefDcl->getBeginLoc()))
93506f32e7eSjoerg           return false;
93606f32e7eSjoerg         edit::Commit commit(*Editor);
93706f32e7eSjoerg         rewriteToNSMacroDecl(Ctx, EnumDcl, TypedefDcl, *NSAPIObj, commit, !NSOptions);
93806f32e7eSjoerg         Editor->commit(commit);
93906f32e7eSjoerg         return true;
94006f32e7eSjoerg       }
94106f32e7eSjoerg     }
94206f32e7eSjoerg     return false;
94306f32e7eSjoerg   }
94406f32e7eSjoerg 
94506f32e7eSjoerg   // We may still use NS_OPTIONS based on what we find in the enumertor list.
94606f32e7eSjoerg   bool NSOptions = UseNSOptionsMacro(PP, Ctx, EnumDcl);
94706f32e7eSjoerg   if (!InsertFoundation(Ctx, TypedefDcl->getBeginLoc()))
94806f32e7eSjoerg     return false;
94906f32e7eSjoerg   edit::Commit commit(*Editor);
95006f32e7eSjoerg   bool Res = rewriteToNSEnumDecl(EnumDcl, TypedefDcl, *NSAPIObj,
95106f32e7eSjoerg                                  commit, NSIntegerName, NSOptions);
95206f32e7eSjoerg   Editor->commit(commit);
95306f32e7eSjoerg   return Res;
95406f32e7eSjoerg }
95506f32e7eSjoerg 
ReplaceWithInstancetype(ASTContext & Ctx,const ObjCMigrateASTConsumer & ASTC,ObjCMethodDecl * OM)95606f32e7eSjoerg static void ReplaceWithInstancetype(ASTContext &Ctx,
95706f32e7eSjoerg                                     const ObjCMigrateASTConsumer &ASTC,
95806f32e7eSjoerg                                     ObjCMethodDecl *OM) {
95906f32e7eSjoerg   if (OM->getReturnType() == Ctx.getObjCInstanceType())
96006f32e7eSjoerg     return; // already has instancetype.
96106f32e7eSjoerg 
96206f32e7eSjoerg   SourceRange R;
96306f32e7eSjoerg   std::string ClassString;
96406f32e7eSjoerg   if (TypeSourceInfo *TSInfo = OM->getReturnTypeSourceInfo()) {
96506f32e7eSjoerg     TypeLoc TL = TSInfo->getTypeLoc();
96606f32e7eSjoerg     R = SourceRange(TL.getBeginLoc(), TL.getEndLoc());
96706f32e7eSjoerg     ClassString = "instancetype";
96806f32e7eSjoerg   }
96906f32e7eSjoerg   else {
97006f32e7eSjoerg     R = SourceRange(OM->getBeginLoc(), OM->getBeginLoc());
97106f32e7eSjoerg     ClassString = OM->isInstanceMethod() ? '-' : '+';
97206f32e7eSjoerg     ClassString += " (instancetype)";
97306f32e7eSjoerg   }
97406f32e7eSjoerg   edit::Commit commit(*ASTC.Editor);
97506f32e7eSjoerg   commit.replace(R, ClassString);
97606f32e7eSjoerg   ASTC.Editor->commit(commit);
97706f32e7eSjoerg }
97806f32e7eSjoerg 
ReplaceWithClasstype(const ObjCMigrateASTConsumer & ASTC,ObjCMethodDecl * OM)97906f32e7eSjoerg static void ReplaceWithClasstype(const ObjCMigrateASTConsumer &ASTC,
98006f32e7eSjoerg                                     ObjCMethodDecl *OM) {
98106f32e7eSjoerg   ObjCInterfaceDecl *IDecl = OM->getClassInterface();
98206f32e7eSjoerg   SourceRange R;
98306f32e7eSjoerg   std::string ClassString;
98406f32e7eSjoerg   if (TypeSourceInfo *TSInfo = OM->getReturnTypeSourceInfo()) {
98506f32e7eSjoerg     TypeLoc TL = TSInfo->getTypeLoc();
98606f32e7eSjoerg     R = SourceRange(TL.getBeginLoc(), TL.getEndLoc()); {
987*13fbcb42Sjoerg       ClassString = std::string(IDecl->getName());
98806f32e7eSjoerg       ClassString += "*";
98906f32e7eSjoerg     }
99006f32e7eSjoerg   }
99106f32e7eSjoerg   else {
99206f32e7eSjoerg     R = SourceRange(OM->getBeginLoc(), OM->getBeginLoc());
99306f32e7eSjoerg     ClassString = "+ (";
99406f32e7eSjoerg     ClassString += IDecl->getName(); ClassString += "*)";
99506f32e7eSjoerg   }
99606f32e7eSjoerg   edit::Commit commit(*ASTC.Editor);
99706f32e7eSjoerg   commit.replace(R, ClassString);
99806f32e7eSjoerg   ASTC.Editor->commit(commit);
99906f32e7eSjoerg }
100006f32e7eSjoerg 
migrateMethodInstanceType(ASTContext & Ctx,ObjCContainerDecl * CDecl,ObjCMethodDecl * OM)100106f32e7eSjoerg void ObjCMigrateASTConsumer::migrateMethodInstanceType(ASTContext &Ctx,
100206f32e7eSjoerg                                                        ObjCContainerDecl *CDecl,
100306f32e7eSjoerg                                                        ObjCMethodDecl *OM) {
100406f32e7eSjoerg   ObjCInstanceTypeFamily OIT_Family =
100506f32e7eSjoerg     Selector::getInstTypeMethodFamily(OM->getSelector());
100606f32e7eSjoerg 
100706f32e7eSjoerg   std::string ClassName;
100806f32e7eSjoerg   switch (OIT_Family) {
100906f32e7eSjoerg     case OIT_None:
101006f32e7eSjoerg       migrateFactoryMethod(Ctx, CDecl, OM);
101106f32e7eSjoerg       return;
101206f32e7eSjoerg     case OIT_Array:
101306f32e7eSjoerg       ClassName = "NSArray";
101406f32e7eSjoerg       break;
101506f32e7eSjoerg     case OIT_Dictionary:
101606f32e7eSjoerg       ClassName = "NSDictionary";
101706f32e7eSjoerg       break;
101806f32e7eSjoerg     case OIT_Singleton:
101906f32e7eSjoerg       migrateFactoryMethod(Ctx, CDecl, OM, OIT_Singleton);
102006f32e7eSjoerg       return;
102106f32e7eSjoerg     case OIT_Init:
102206f32e7eSjoerg       if (OM->getReturnType()->isObjCIdType())
102306f32e7eSjoerg         ReplaceWithInstancetype(Ctx, *this, OM);
102406f32e7eSjoerg       return;
102506f32e7eSjoerg     case OIT_ReturnsSelf:
102606f32e7eSjoerg       migrateFactoryMethod(Ctx, CDecl, OM, OIT_ReturnsSelf);
102706f32e7eSjoerg       return;
102806f32e7eSjoerg   }
102906f32e7eSjoerg   if (!OM->getReturnType()->isObjCIdType())
103006f32e7eSjoerg     return;
103106f32e7eSjoerg 
103206f32e7eSjoerg   ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(CDecl);
103306f32e7eSjoerg   if (!IDecl) {
103406f32e7eSjoerg     if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(CDecl))
103506f32e7eSjoerg       IDecl = CatDecl->getClassInterface();
103606f32e7eSjoerg     else if (ObjCImplDecl *ImpDecl = dyn_cast<ObjCImplDecl>(CDecl))
103706f32e7eSjoerg       IDecl = ImpDecl->getClassInterface();
103806f32e7eSjoerg   }
103906f32e7eSjoerg   if (!IDecl ||
104006f32e7eSjoerg       !IDecl->lookupInheritedClass(&Ctx.Idents.get(ClassName))) {
104106f32e7eSjoerg     migrateFactoryMethod(Ctx, CDecl, OM);
104206f32e7eSjoerg     return;
104306f32e7eSjoerg   }
104406f32e7eSjoerg   ReplaceWithInstancetype(Ctx, *this, OM);
104506f32e7eSjoerg }
104606f32e7eSjoerg 
TypeIsInnerPointer(QualType T)104706f32e7eSjoerg static bool TypeIsInnerPointer(QualType T) {
104806f32e7eSjoerg   if (!T->isAnyPointerType())
104906f32e7eSjoerg     return false;
105006f32e7eSjoerg   if (T->isObjCObjectPointerType() || T->isObjCBuiltinType() ||
105106f32e7eSjoerg       T->isBlockPointerType() || T->isFunctionPointerType() ||
105206f32e7eSjoerg       ento::coreFoundation::isCFObjectRef(T))
105306f32e7eSjoerg     return false;
105406f32e7eSjoerg   // Also, typedef-of-pointer-to-incomplete-struct is something that we assume
105506f32e7eSjoerg   // is not an innter pointer type.
105606f32e7eSjoerg   QualType OrigT = T;
105706f32e7eSjoerg   while (const TypedefType *TD = dyn_cast<TypedefType>(T.getTypePtr()))
105806f32e7eSjoerg     T = TD->getDecl()->getUnderlyingType();
105906f32e7eSjoerg   if (OrigT == T || !T->isPointerType())
106006f32e7eSjoerg     return true;
106106f32e7eSjoerg   const PointerType* PT = T->getAs<PointerType>();
106206f32e7eSjoerg   QualType UPointeeT = PT->getPointeeType().getUnqualifiedType();
106306f32e7eSjoerg   if (UPointeeT->isRecordType()) {
106406f32e7eSjoerg     const RecordType *RecordTy = UPointeeT->getAs<RecordType>();
106506f32e7eSjoerg     if (!RecordTy->getDecl()->isCompleteDefinition())
106606f32e7eSjoerg       return false;
106706f32e7eSjoerg   }
106806f32e7eSjoerg   return true;
106906f32e7eSjoerg }
107006f32e7eSjoerg 
107106f32e7eSjoerg /// Check whether the two versions match.
versionsMatch(const VersionTuple & X,const VersionTuple & Y)107206f32e7eSjoerg static bool versionsMatch(const VersionTuple &X, const VersionTuple &Y) {
107306f32e7eSjoerg   return (X == Y);
107406f32e7eSjoerg }
107506f32e7eSjoerg 
107606f32e7eSjoerg /// AvailabilityAttrsMatch - This routine checks that if comparing two
107706f32e7eSjoerg /// availability attributes, all their components match. It returns
107806f32e7eSjoerg /// true, if not dealing with availability or when all components of
107906f32e7eSjoerg /// availability attributes match. This routine is only called when
108006f32e7eSjoerg /// the attributes are of the same kind.
AvailabilityAttrsMatch(Attr * At1,Attr * At2)108106f32e7eSjoerg static bool AvailabilityAttrsMatch(Attr *At1, Attr *At2) {
108206f32e7eSjoerg   const AvailabilityAttr *AA1 = dyn_cast<AvailabilityAttr>(At1);
108306f32e7eSjoerg   if (!AA1)
108406f32e7eSjoerg     return true;
1085*13fbcb42Sjoerg   const AvailabilityAttr *AA2 = cast<AvailabilityAttr>(At2);
108606f32e7eSjoerg 
108706f32e7eSjoerg   VersionTuple Introduced1 = AA1->getIntroduced();
108806f32e7eSjoerg   VersionTuple Deprecated1 = AA1->getDeprecated();
108906f32e7eSjoerg   VersionTuple Obsoleted1 = AA1->getObsoleted();
109006f32e7eSjoerg   bool IsUnavailable1 = AA1->getUnavailable();
109106f32e7eSjoerg   VersionTuple Introduced2 = AA2->getIntroduced();
109206f32e7eSjoerg   VersionTuple Deprecated2 = AA2->getDeprecated();
109306f32e7eSjoerg   VersionTuple Obsoleted2 = AA2->getObsoleted();
109406f32e7eSjoerg   bool IsUnavailable2 = AA2->getUnavailable();
109506f32e7eSjoerg   return (versionsMatch(Introduced1, Introduced2) &&
109606f32e7eSjoerg           versionsMatch(Deprecated1, Deprecated2) &&
109706f32e7eSjoerg           versionsMatch(Obsoleted1, Obsoleted2) &&
109806f32e7eSjoerg           IsUnavailable1 == IsUnavailable2);
109906f32e7eSjoerg }
110006f32e7eSjoerg 
MatchTwoAttributeLists(const AttrVec & Attrs1,const AttrVec & Attrs2,bool & AvailabilityArgsMatch)110106f32e7eSjoerg static bool MatchTwoAttributeLists(const AttrVec &Attrs1, const AttrVec &Attrs2,
110206f32e7eSjoerg                                    bool &AvailabilityArgsMatch) {
110306f32e7eSjoerg   // This list is very small, so this need not be optimized.
110406f32e7eSjoerg   for (unsigned i = 0, e = Attrs1.size(); i != e; i++) {
110506f32e7eSjoerg     bool match = false;
110606f32e7eSjoerg     for (unsigned j = 0, f = Attrs2.size(); j != f; j++) {
110706f32e7eSjoerg       // Matching attribute kind only. Except for Availability attributes,
110806f32e7eSjoerg       // we are not getting into details of the attributes. For all practical purposes
110906f32e7eSjoerg       // this is sufficient.
111006f32e7eSjoerg       if (Attrs1[i]->getKind() == Attrs2[j]->getKind()) {
111106f32e7eSjoerg         if (AvailabilityArgsMatch)
111206f32e7eSjoerg           AvailabilityArgsMatch = AvailabilityAttrsMatch(Attrs1[i], Attrs2[j]);
111306f32e7eSjoerg         match = true;
111406f32e7eSjoerg         break;
111506f32e7eSjoerg       }
111606f32e7eSjoerg     }
111706f32e7eSjoerg     if (!match)
111806f32e7eSjoerg       return false;
111906f32e7eSjoerg   }
112006f32e7eSjoerg   return true;
112106f32e7eSjoerg }
112206f32e7eSjoerg 
112306f32e7eSjoerg /// AttributesMatch - This routine checks list of attributes for two
112406f32e7eSjoerg /// decls. It returns false, if there is a mismatch in kind of
112506f32e7eSjoerg /// attributes seen in the decls. It returns true if the two decls
112606f32e7eSjoerg /// have list of same kind of attributes. Furthermore, when there
112706f32e7eSjoerg /// are availability attributes in the two decls, it sets the
112806f32e7eSjoerg /// AvailabilityArgsMatch to false if availability attributes have
112906f32e7eSjoerg /// different versions, etc.
AttributesMatch(const Decl * Decl1,const Decl * Decl2,bool & AvailabilityArgsMatch)113006f32e7eSjoerg static bool AttributesMatch(const Decl *Decl1, const Decl *Decl2,
113106f32e7eSjoerg                             bool &AvailabilityArgsMatch) {
113206f32e7eSjoerg   if (!Decl1->hasAttrs() || !Decl2->hasAttrs()) {
113306f32e7eSjoerg     AvailabilityArgsMatch = (Decl1->hasAttrs() == Decl2->hasAttrs());
113406f32e7eSjoerg     return true;
113506f32e7eSjoerg   }
113606f32e7eSjoerg   AvailabilityArgsMatch = true;
113706f32e7eSjoerg   const AttrVec &Attrs1 = Decl1->getAttrs();
113806f32e7eSjoerg   const AttrVec &Attrs2 = Decl2->getAttrs();
113906f32e7eSjoerg   bool match = MatchTwoAttributeLists(Attrs1, Attrs2, AvailabilityArgsMatch);
114006f32e7eSjoerg   if (match && (Attrs2.size() > Attrs1.size()))
114106f32e7eSjoerg     return MatchTwoAttributeLists(Attrs2, Attrs1, AvailabilityArgsMatch);
114206f32e7eSjoerg   return match;
114306f32e7eSjoerg }
114406f32e7eSjoerg 
IsValidIdentifier(ASTContext & Ctx,const char * Name)114506f32e7eSjoerg static bool IsValidIdentifier(ASTContext &Ctx,
114606f32e7eSjoerg                               const char *Name) {
114706f32e7eSjoerg   if (!isIdentifierHead(Name[0]))
114806f32e7eSjoerg     return false;
114906f32e7eSjoerg   std::string NameString = Name;
115006f32e7eSjoerg   NameString[0] = toLowercase(NameString[0]);
115106f32e7eSjoerg   IdentifierInfo *II = &Ctx.Idents.get(NameString);
115206f32e7eSjoerg   return II->getTokenID() ==  tok::identifier;
115306f32e7eSjoerg }
115406f32e7eSjoerg 
migrateProperty(ASTContext & Ctx,ObjCContainerDecl * D,ObjCMethodDecl * Method)115506f32e7eSjoerg bool ObjCMigrateASTConsumer::migrateProperty(ASTContext &Ctx,
115606f32e7eSjoerg                              ObjCContainerDecl *D,
115706f32e7eSjoerg                              ObjCMethodDecl *Method) {
115806f32e7eSjoerg   if (Method->isPropertyAccessor() || !Method->isInstanceMethod() ||
115906f32e7eSjoerg       Method->param_size() != 0)
116006f32e7eSjoerg     return false;
116106f32e7eSjoerg   // Is this method candidate to be a getter?
116206f32e7eSjoerg   QualType GRT = Method->getReturnType();
116306f32e7eSjoerg   if (GRT->isVoidType())
116406f32e7eSjoerg     return false;
116506f32e7eSjoerg 
116606f32e7eSjoerg   Selector GetterSelector = Method->getSelector();
116706f32e7eSjoerg   ObjCInstanceTypeFamily OIT_Family =
116806f32e7eSjoerg     Selector::getInstTypeMethodFamily(GetterSelector);
116906f32e7eSjoerg 
117006f32e7eSjoerg   if (OIT_Family != OIT_None)
117106f32e7eSjoerg     return false;
117206f32e7eSjoerg 
117306f32e7eSjoerg   IdentifierInfo *getterName = GetterSelector.getIdentifierInfoForSlot(0);
117406f32e7eSjoerg   Selector SetterSelector =
117506f32e7eSjoerg   SelectorTable::constructSetterSelector(PP.getIdentifierTable(),
117606f32e7eSjoerg                                          PP.getSelectorTable(),
117706f32e7eSjoerg                                          getterName);
117806f32e7eSjoerg   ObjCMethodDecl *SetterMethod = D->getInstanceMethod(SetterSelector);
117906f32e7eSjoerg   unsigned LengthOfPrefix = 0;
118006f32e7eSjoerg   if (!SetterMethod) {
118106f32e7eSjoerg     // try a different naming convention for getter: isXxxxx
118206f32e7eSjoerg     StringRef getterNameString = getterName->getName();
118306f32e7eSjoerg     bool IsPrefix = getterNameString.startswith("is");
118406f32e7eSjoerg     // Note that we don't want to change an isXXX method of retainable object
118506f32e7eSjoerg     // type to property (readonly or otherwise).
118606f32e7eSjoerg     if (IsPrefix && GRT->isObjCRetainableType())
118706f32e7eSjoerg       return false;
118806f32e7eSjoerg     if (IsPrefix || getterNameString.startswith("get")) {
118906f32e7eSjoerg       LengthOfPrefix = (IsPrefix ? 2 : 3);
119006f32e7eSjoerg       const char *CGetterName = getterNameString.data() + LengthOfPrefix;
119106f32e7eSjoerg       // Make sure that first character after "is" or "get" prefix can
119206f32e7eSjoerg       // start an identifier.
119306f32e7eSjoerg       if (!IsValidIdentifier(Ctx, CGetterName))
119406f32e7eSjoerg         return false;
119506f32e7eSjoerg       if (CGetterName[0] && isUppercase(CGetterName[0])) {
119606f32e7eSjoerg         getterName = &Ctx.Idents.get(CGetterName);
119706f32e7eSjoerg         SetterSelector =
119806f32e7eSjoerg         SelectorTable::constructSetterSelector(PP.getIdentifierTable(),
119906f32e7eSjoerg                                                PP.getSelectorTable(),
120006f32e7eSjoerg                                                getterName);
120106f32e7eSjoerg         SetterMethod = D->getInstanceMethod(SetterSelector);
120206f32e7eSjoerg       }
120306f32e7eSjoerg     }
120406f32e7eSjoerg   }
120506f32e7eSjoerg 
120606f32e7eSjoerg   if (SetterMethod) {
120706f32e7eSjoerg     if ((ASTMigrateActions & FrontendOptions::ObjCMT_ReadwriteProperty) == 0)
120806f32e7eSjoerg       return false;
120906f32e7eSjoerg     bool AvailabilityArgsMatch;
121006f32e7eSjoerg     if (SetterMethod->isDeprecated() ||
121106f32e7eSjoerg         !AttributesMatch(Method, SetterMethod, AvailabilityArgsMatch))
121206f32e7eSjoerg       return false;
121306f32e7eSjoerg 
121406f32e7eSjoerg     // Is this a valid setter, matching the target getter?
121506f32e7eSjoerg     QualType SRT = SetterMethod->getReturnType();
121606f32e7eSjoerg     if (!SRT->isVoidType())
121706f32e7eSjoerg       return false;
121806f32e7eSjoerg     const ParmVarDecl *argDecl = *SetterMethod->param_begin();
121906f32e7eSjoerg     QualType ArgType = argDecl->getType();
122006f32e7eSjoerg     if (!Ctx.hasSameUnqualifiedType(ArgType, GRT))
122106f32e7eSjoerg       return false;
122206f32e7eSjoerg     edit::Commit commit(*Editor);
122306f32e7eSjoerg     rewriteToObjCProperty(Method, SetterMethod, *NSAPIObj, commit,
122406f32e7eSjoerg                           LengthOfPrefix,
122506f32e7eSjoerg                           (ASTMigrateActions &
122606f32e7eSjoerg                            FrontendOptions::ObjCMT_AtomicProperty) != 0,
122706f32e7eSjoerg                           (ASTMigrateActions &
122806f32e7eSjoerg                            FrontendOptions::ObjCMT_NsAtomicIOSOnlyProperty) != 0,
122906f32e7eSjoerg                           AvailabilityArgsMatch);
123006f32e7eSjoerg     Editor->commit(commit);
123106f32e7eSjoerg     return true;
123206f32e7eSjoerg   }
123306f32e7eSjoerg   else if (ASTMigrateActions & FrontendOptions::ObjCMT_ReadonlyProperty) {
123406f32e7eSjoerg     // Try a non-void method with no argument (and no setter or property of same name
123506f32e7eSjoerg     // as a 'readonly' property.
123606f32e7eSjoerg     edit::Commit commit(*Editor);
123706f32e7eSjoerg     rewriteToObjCProperty(Method, nullptr /*SetterMethod*/, *NSAPIObj, commit,
123806f32e7eSjoerg                           LengthOfPrefix,
123906f32e7eSjoerg                           (ASTMigrateActions &
124006f32e7eSjoerg                            FrontendOptions::ObjCMT_AtomicProperty) != 0,
124106f32e7eSjoerg                           (ASTMigrateActions &
124206f32e7eSjoerg                            FrontendOptions::ObjCMT_NsAtomicIOSOnlyProperty) != 0,
124306f32e7eSjoerg                           /*AvailabilityArgsMatch*/false);
124406f32e7eSjoerg     Editor->commit(commit);
124506f32e7eSjoerg     return true;
124606f32e7eSjoerg   }
124706f32e7eSjoerg   return false;
124806f32e7eSjoerg }
124906f32e7eSjoerg 
migrateNsReturnsInnerPointer(ASTContext & Ctx,ObjCMethodDecl * OM)125006f32e7eSjoerg void ObjCMigrateASTConsumer::migrateNsReturnsInnerPointer(ASTContext &Ctx,
125106f32e7eSjoerg                                                           ObjCMethodDecl *OM) {
125206f32e7eSjoerg   if (OM->isImplicit() ||
125306f32e7eSjoerg       !OM->isInstanceMethod() ||
125406f32e7eSjoerg       OM->hasAttr<ObjCReturnsInnerPointerAttr>())
125506f32e7eSjoerg     return;
125606f32e7eSjoerg 
125706f32e7eSjoerg   QualType RT = OM->getReturnType();
125806f32e7eSjoerg   if (!TypeIsInnerPointer(RT) ||
125906f32e7eSjoerg       !NSAPIObj->isMacroDefined("NS_RETURNS_INNER_POINTER"))
126006f32e7eSjoerg     return;
126106f32e7eSjoerg 
126206f32e7eSjoerg   edit::Commit commit(*Editor);
126306f32e7eSjoerg   commit.insertBefore(OM->getEndLoc(), " NS_RETURNS_INNER_POINTER");
126406f32e7eSjoerg   Editor->commit(commit);
126506f32e7eSjoerg }
126606f32e7eSjoerg 
migratePropertyNsReturnsInnerPointer(ASTContext & Ctx,ObjCPropertyDecl * P)126706f32e7eSjoerg void ObjCMigrateASTConsumer::migratePropertyNsReturnsInnerPointer(ASTContext &Ctx,
126806f32e7eSjoerg                                                                   ObjCPropertyDecl *P) {
126906f32e7eSjoerg   QualType T = P->getType();
127006f32e7eSjoerg 
127106f32e7eSjoerg   if (!TypeIsInnerPointer(T) ||
127206f32e7eSjoerg       !NSAPIObj->isMacroDefined("NS_RETURNS_INNER_POINTER"))
127306f32e7eSjoerg     return;
127406f32e7eSjoerg   edit::Commit commit(*Editor);
127506f32e7eSjoerg   commit.insertBefore(P->getEndLoc(), " NS_RETURNS_INNER_POINTER ");
127606f32e7eSjoerg   Editor->commit(commit);
127706f32e7eSjoerg }
127806f32e7eSjoerg 
migrateAllMethodInstaceType(ASTContext & Ctx,ObjCContainerDecl * CDecl)127906f32e7eSjoerg void ObjCMigrateASTConsumer::migrateAllMethodInstaceType(ASTContext &Ctx,
128006f32e7eSjoerg                                                  ObjCContainerDecl *CDecl) {
128106f32e7eSjoerg   if (CDecl->isDeprecated() || IsCategoryNameWithDeprecatedSuffix(CDecl))
128206f32e7eSjoerg     return;
128306f32e7eSjoerg 
128406f32e7eSjoerg   // migrate methods which can have instancetype as their result type.
128506f32e7eSjoerg   for (auto *Method : CDecl->methods()) {
128606f32e7eSjoerg     if (Method->isDeprecated())
128706f32e7eSjoerg       continue;
128806f32e7eSjoerg     migrateMethodInstanceType(Ctx, CDecl, Method);
128906f32e7eSjoerg   }
129006f32e7eSjoerg }
129106f32e7eSjoerg 
migrateFactoryMethod(ASTContext & Ctx,ObjCContainerDecl * CDecl,ObjCMethodDecl * OM,ObjCInstanceTypeFamily OIT_Family)129206f32e7eSjoerg void ObjCMigrateASTConsumer::migrateFactoryMethod(ASTContext &Ctx,
129306f32e7eSjoerg                                                   ObjCContainerDecl *CDecl,
129406f32e7eSjoerg                                                   ObjCMethodDecl *OM,
129506f32e7eSjoerg                                                   ObjCInstanceTypeFamily OIT_Family) {
129606f32e7eSjoerg   if (OM->isInstanceMethod() ||
129706f32e7eSjoerg       OM->getReturnType() == Ctx.getObjCInstanceType() ||
129806f32e7eSjoerg       !OM->getReturnType()->isObjCIdType())
129906f32e7eSjoerg     return;
130006f32e7eSjoerg 
130106f32e7eSjoerg   // Candidate factory methods are + (id) NaMeXXX : ... which belong to a class
130206f32e7eSjoerg   // NSYYYNamE with matching names be at least 3 characters long.
130306f32e7eSjoerg   ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(CDecl);
130406f32e7eSjoerg   if (!IDecl) {
130506f32e7eSjoerg     if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(CDecl))
130606f32e7eSjoerg       IDecl = CatDecl->getClassInterface();
130706f32e7eSjoerg     else if (ObjCImplDecl *ImpDecl = dyn_cast<ObjCImplDecl>(CDecl))
130806f32e7eSjoerg       IDecl = ImpDecl->getClassInterface();
130906f32e7eSjoerg   }
131006f32e7eSjoerg   if (!IDecl)
131106f32e7eSjoerg     return;
131206f32e7eSjoerg 
1313*13fbcb42Sjoerg   std::string StringClassName = std::string(IDecl->getName());
131406f32e7eSjoerg   StringRef LoweredClassName(StringClassName);
131506f32e7eSjoerg   std::string StringLoweredClassName = LoweredClassName.lower();
131606f32e7eSjoerg   LoweredClassName = StringLoweredClassName;
131706f32e7eSjoerg 
131806f32e7eSjoerg   IdentifierInfo *MethodIdName = OM->getSelector().getIdentifierInfoForSlot(0);
131906f32e7eSjoerg   // Handle method with no name at its first selector slot; e.g. + (id):(int)x.
132006f32e7eSjoerg   if (!MethodIdName)
132106f32e7eSjoerg     return;
132206f32e7eSjoerg 
1323*13fbcb42Sjoerg   std::string MethodName = std::string(MethodIdName->getName());
132406f32e7eSjoerg   if (OIT_Family == OIT_Singleton || OIT_Family == OIT_ReturnsSelf) {
132506f32e7eSjoerg     StringRef STRefMethodName(MethodName);
132606f32e7eSjoerg     size_t len = 0;
132706f32e7eSjoerg     if (STRefMethodName.startswith("standard"))
132806f32e7eSjoerg       len = strlen("standard");
132906f32e7eSjoerg     else if (STRefMethodName.startswith("shared"))
133006f32e7eSjoerg       len = strlen("shared");
133106f32e7eSjoerg     else if (STRefMethodName.startswith("default"))
133206f32e7eSjoerg       len = strlen("default");
133306f32e7eSjoerg     else
133406f32e7eSjoerg       return;
1335*13fbcb42Sjoerg     MethodName = std::string(STRefMethodName.substr(len));
133606f32e7eSjoerg   }
133706f32e7eSjoerg   std::string MethodNameSubStr = MethodName.substr(0, 3);
133806f32e7eSjoerg   StringRef MethodNamePrefix(MethodNameSubStr);
133906f32e7eSjoerg   std::string StringLoweredMethodNamePrefix = MethodNamePrefix.lower();
134006f32e7eSjoerg   MethodNamePrefix = StringLoweredMethodNamePrefix;
134106f32e7eSjoerg   size_t Ix = LoweredClassName.rfind(MethodNamePrefix);
134206f32e7eSjoerg   if (Ix == StringRef::npos)
134306f32e7eSjoerg     return;
1344*13fbcb42Sjoerg   std::string ClassNamePostfix = std::string(LoweredClassName.substr(Ix));
134506f32e7eSjoerg   StringRef LoweredMethodName(MethodName);
134606f32e7eSjoerg   std::string StringLoweredMethodName = LoweredMethodName.lower();
134706f32e7eSjoerg   LoweredMethodName = StringLoweredMethodName;
134806f32e7eSjoerg   if (!LoweredMethodName.startswith(ClassNamePostfix))
134906f32e7eSjoerg     return;
135006f32e7eSjoerg   if (OIT_Family == OIT_ReturnsSelf)
135106f32e7eSjoerg     ReplaceWithClasstype(*this, OM);
135206f32e7eSjoerg   else
135306f32e7eSjoerg     ReplaceWithInstancetype(Ctx, *this, OM);
135406f32e7eSjoerg }
135506f32e7eSjoerg 
IsVoidStarType(QualType Ty)135606f32e7eSjoerg static bool IsVoidStarType(QualType Ty) {
135706f32e7eSjoerg   if (!Ty->isPointerType())
135806f32e7eSjoerg     return false;
135906f32e7eSjoerg 
136006f32e7eSjoerg   while (const TypedefType *TD = dyn_cast<TypedefType>(Ty.getTypePtr()))
136106f32e7eSjoerg     Ty = TD->getDecl()->getUnderlyingType();
136206f32e7eSjoerg 
136306f32e7eSjoerg   // Is the type void*?
1364*13fbcb42Sjoerg   const PointerType* PT = Ty->castAs<PointerType>();
136506f32e7eSjoerg   if (PT->getPointeeType().getUnqualifiedType()->isVoidType())
136606f32e7eSjoerg     return true;
136706f32e7eSjoerg   return IsVoidStarType(PT->getPointeeType());
136806f32e7eSjoerg }
136906f32e7eSjoerg 
137006f32e7eSjoerg /// AuditedType - This routine audits the type AT and returns false if it is one of known
137106f32e7eSjoerg /// CF object types or of the "void *" variety. It returns true if we don't care about the type
137206f32e7eSjoerg /// such as a non-pointer or pointers which have no ownership issues (such as "int *").
AuditedType(QualType AT)137306f32e7eSjoerg static bool AuditedType (QualType AT) {
137406f32e7eSjoerg   if (!AT->isAnyPointerType() && !AT->isBlockPointerType())
137506f32e7eSjoerg     return true;
137606f32e7eSjoerg   // FIXME. There isn't much we can say about CF pointer type; or is there?
137706f32e7eSjoerg   if (ento::coreFoundation::isCFObjectRef(AT) ||
137806f32e7eSjoerg       IsVoidStarType(AT) ||
137906f32e7eSjoerg       // If an ObjC object is type, assuming that it is not a CF function and
138006f32e7eSjoerg       // that it is an un-audited function.
138106f32e7eSjoerg       AT->isObjCObjectPointerType() || AT->isObjCBuiltinType())
138206f32e7eSjoerg     return false;
138306f32e7eSjoerg   // All other pointers are assumed audited as harmless.
138406f32e7eSjoerg   return true;
138506f32e7eSjoerg }
138606f32e7eSjoerg 
AnnotateImplicitBridging(ASTContext & Ctx)138706f32e7eSjoerg void ObjCMigrateASTConsumer::AnnotateImplicitBridging(ASTContext &Ctx) {
138806f32e7eSjoerg   if (CFFunctionIBCandidates.empty())
138906f32e7eSjoerg     return;
139006f32e7eSjoerg   if (!NSAPIObj->isMacroDefined("CF_IMPLICIT_BRIDGING_ENABLED")) {
139106f32e7eSjoerg     CFFunctionIBCandidates.clear();
139206f32e7eSjoerg     FileId = FileID();
139306f32e7eSjoerg     return;
139406f32e7eSjoerg   }
139506f32e7eSjoerg   // Insert CF_IMPLICIT_BRIDGING_ENABLE/CF_IMPLICIT_BRIDGING_DISABLED
139606f32e7eSjoerg   const Decl *FirstFD = CFFunctionIBCandidates[0];
139706f32e7eSjoerg   const Decl *LastFD  =
139806f32e7eSjoerg     CFFunctionIBCandidates[CFFunctionIBCandidates.size()-1];
139906f32e7eSjoerg   const char *PragmaString = "\nCF_IMPLICIT_BRIDGING_ENABLED\n\n";
140006f32e7eSjoerg   edit::Commit commit(*Editor);
140106f32e7eSjoerg   commit.insertBefore(FirstFD->getBeginLoc(), PragmaString);
140206f32e7eSjoerg   PragmaString = "\n\nCF_IMPLICIT_BRIDGING_DISABLED\n";
140306f32e7eSjoerg   SourceLocation EndLoc = LastFD->getEndLoc();
140406f32e7eSjoerg   // get location just past end of function location.
140506f32e7eSjoerg   EndLoc = PP.getLocForEndOfToken(EndLoc);
140606f32e7eSjoerg   if (isa<FunctionDecl>(LastFD)) {
140706f32e7eSjoerg     // For Methods, EndLoc points to the ending semcolon. So,
140806f32e7eSjoerg     // not of these extra work is needed.
140906f32e7eSjoerg     Token Tok;
141006f32e7eSjoerg     // get locaiton of token that comes after end of function.
141106f32e7eSjoerg     bool Failed = PP.getRawToken(EndLoc, Tok, /*IgnoreWhiteSpace=*/true);
141206f32e7eSjoerg     if (!Failed)
141306f32e7eSjoerg       EndLoc = Tok.getLocation();
141406f32e7eSjoerg   }
141506f32e7eSjoerg   commit.insertAfterToken(EndLoc, PragmaString);
141606f32e7eSjoerg   Editor->commit(commit);
141706f32e7eSjoerg   FileId = FileID();
141806f32e7eSjoerg   CFFunctionIBCandidates.clear();
141906f32e7eSjoerg }
142006f32e7eSjoerg 
migrateCFAnnotation(ASTContext & Ctx,const Decl * Decl)142106f32e7eSjoerg void ObjCMigrateASTConsumer::migrateCFAnnotation(ASTContext &Ctx, const Decl *Decl) {
142206f32e7eSjoerg   if (Decl->isDeprecated())
142306f32e7eSjoerg     return;
142406f32e7eSjoerg 
142506f32e7eSjoerg   if (Decl->hasAttr<CFAuditedTransferAttr>()) {
142606f32e7eSjoerg     assert(CFFunctionIBCandidates.empty() &&
142706f32e7eSjoerg            "Cannot have audited functions/methods inside user "
142806f32e7eSjoerg            "provided CF_IMPLICIT_BRIDGING_ENABLE");
142906f32e7eSjoerg     return;
143006f32e7eSjoerg   }
143106f32e7eSjoerg 
143206f32e7eSjoerg   // Finction must be annotated first.
143306f32e7eSjoerg   if (const FunctionDecl *FuncDecl = dyn_cast<FunctionDecl>(Decl)) {
143406f32e7eSjoerg     CF_BRIDGING_KIND AuditKind = migrateAddFunctionAnnotation(Ctx, FuncDecl);
143506f32e7eSjoerg     if (AuditKind == CF_BRIDGING_ENABLE) {
143606f32e7eSjoerg       CFFunctionIBCandidates.push_back(Decl);
143706f32e7eSjoerg       if (FileId.isInvalid())
143806f32e7eSjoerg         FileId = PP.getSourceManager().getFileID(Decl->getLocation());
143906f32e7eSjoerg     }
144006f32e7eSjoerg     else if (AuditKind == CF_BRIDGING_MAY_INCLUDE) {
144106f32e7eSjoerg       if (!CFFunctionIBCandidates.empty()) {
144206f32e7eSjoerg         CFFunctionIBCandidates.push_back(Decl);
144306f32e7eSjoerg         if (FileId.isInvalid())
144406f32e7eSjoerg           FileId = PP.getSourceManager().getFileID(Decl->getLocation());
144506f32e7eSjoerg       }
144606f32e7eSjoerg     }
144706f32e7eSjoerg     else
144806f32e7eSjoerg       AnnotateImplicitBridging(Ctx);
144906f32e7eSjoerg   }
145006f32e7eSjoerg   else {
145106f32e7eSjoerg     migrateAddMethodAnnotation(Ctx, cast<ObjCMethodDecl>(Decl));
145206f32e7eSjoerg     AnnotateImplicitBridging(Ctx);
145306f32e7eSjoerg   }
145406f32e7eSjoerg }
145506f32e7eSjoerg 
AddCFAnnotations(ASTContext & Ctx,const RetainSummary * RS,const FunctionDecl * FuncDecl,bool ResultAnnotated)145606f32e7eSjoerg void ObjCMigrateASTConsumer::AddCFAnnotations(ASTContext &Ctx,
145706f32e7eSjoerg                                               const RetainSummary *RS,
145806f32e7eSjoerg                                               const FunctionDecl *FuncDecl,
145906f32e7eSjoerg                                               bool ResultAnnotated) {
146006f32e7eSjoerg   // Annotate function.
146106f32e7eSjoerg   if (!ResultAnnotated) {
146206f32e7eSjoerg     RetEffect Ret = RS->getRetEffect();
146306f32e7eSjoerg     const char *AnnotationString = nullptr;
146406f32e7eSjoerg     if (Ret.getObjKind() == ObjKind::CF) {
146506f32e7eSjoerg       if (Ret.isOwned() && NSAPIObj->isMacroDefined("CF_RETURNS_RETAINED"))
146606f32e7eSjoerg         AnnotationString = " CF_RETURNS_RETAINED";
146706f32e7eSjoerg       else if (Ret.notOwned() &&
146806f32e7eSjoerg                NSAPIObj->isMacroDefined("CF_RETURNS_NOT_RETAINED"))
146906f32e7eSjoerg         AnnotationString = " CF_RETURNS_NOT_RETAINED";
147006f32e7eSjoerg     }
147106f32e7eSjoerg     else if (Ret.getObjKind() == ObjKind::ObjC) {
147206f32e7eSjoerg       if (Ret.isOwned() && NSAPIObj->isMacroDefined("NS_RETURNS_RETAINED"))
147306f32e7eSjoerg         AnnotationString = " NS_RETURNS_RETAINED";
147406f32e7eSjoerg     }
147506f32e7eSjoerg 
147606f32e7eSjoerg     if (AnnotationString) {
147706f32e7eSjoerg       edit::Commit commit(*Editor);
147806f32e7eSjoerg       commit.insertAfterToken(FuncDecl->getEndLoc(), AnnotationString);
147906f32e7eSjoerg       Editor->commit(commit);
148006f32e7eSjoerg     }
148106f32e7eSjoerg   }
148206f32e7eSjoerg   unsigned i = 0;
148306f32e7eSjoerg   for (FunctionDecl::param_const_iterator pi = FuncDecl->param_begin(),
148406f32e7eSjoerg        pe = FuncDecl->param_end(); pi != pe; ++pi, ++i) {
148506f32e7eSjoerg     const ParmVarDecl *pd = *pi;
148606f32e7eSjoerg     ArgEffect AE = RS->getArg(i);
148706f32e7eSjoerg     if (AE.getKind() == DecRef && AE.getObjKind() == ObjKind::CF &&
148806f32e7eSjoerg         !pd->hasAttr<CFConsumedAttr>() &&
148906f32e7eSjoerg         NSAPIObj->isMacroDefined("CF_CONSUMED")) {
149006f32e7eSjoerg       edit::Commit commit(*Editor);
149106f32e7eSjoerg       commit.insertBefore(pd->getLocation(), "CF_CONSUMED ");
149206f32e7eSjoerg       Editor->commit(commit);
149306f32e7eSjoerg     } else if (AE.getKind() == DecRef && AE.getObjKind() == ObjKind::ObjC &&
149406f32e7eSjoerg                !pd->hasAttr<NSConsumedAttr>() &&
149506f32e7eSjoerg                NSAPIObj->isMacroDefined("NS_CONSUMED")) {
149606f32e7eSjoerg       edit::Commit commit(*Editor);
149706f32e7eSjoerg       commit.insertBefore(pd->getLocation(), "NS_CONSUMED ");
149806f32e7eSjoerg       Editor->commit(commit);
149906f32e7eSjoerg     }
150006f32e7eSjoerg   }
150106f32e7eSjoerg }
150206f32e7eSjoerg 
150306f32e7eSjoerg ObjCMigrateASTConsumer::CF_BRIDGING_KIND
migrateAddFunctionAnnotation(ASTContext & Ctx,const FunctionDecl * FuncDecl)150406f32e7eSjoerg   ObjCMigrateASTConsumer::migrateAddFunctionAnnotation(
150506f32e7eSjoerg                                                   ASTContext &Ctx,
150606f32e7eSjoerg                                                   const FunctionDecl *FuncDecl) {
150706f32e7eSjoerg   if (FuncDecl->hasBody())
150806f32e7eSjoerg     return CF_BRIDGING_NONE;
150906f32e7eSjoerg 
151006f32e7eSjoerg   const RetainSummary *RS =
151106f32e7eSjoerg       getSummaryManager(Ctx).getSummary(AnyCall(FuncDecl));
151206f32e7eSjoerg   bool FuncIsReturnAnnotated = (FuncDecl->hasAttr<CFReturnsRetainedAttr>() ||
151306f32e7eSjoerg                                 FuncDecl->hasAttr<CFReturnsNotRetainedAttr>() ||
151406f32e7eSjoerg                                 FuncDecl->hasAttr<NSReturnsRetainedAttr>() ||
151506f32e7eSjoerg                                 FuncDecl->hasAttr<NSReturnsNotRetainedAttr>() ||
151606f32e7eSjoerg                                 FuncDecl->hasAttr<NSReturnsAutoreleasedAttr>());
151706f32e7eSjoerg 
151806f32e7eSjoerg   // Trivial case of when function is annotated and has no argument.
151906f32e7eSjoerg   if (FuncIsReturnAnnotated && FuncDecl->getNumParams() == 0)
152006f32e7eSjoerg     return CF_BRIDGING_NONE;
152106f32e7eSjoerg 
152206f32e7eSjoerg   bool ReturnCFAudited = false;
152306f32e7eSjoerg   if (!FuncIsReturnAnnotated) {
152406f32e7eSjoerg     RetEffect Ret = RS->getRetEffect();
152506f32e7eSjoerg     if (Ret.getObjKind() == ObjKind::CF &&
152606f32e7eSjoerg         (Ret.isOwned() || Ret.notOwned()))
152706f32e7eSjoerg       ReturnCFAudited = true;
152806f32e7eSjoerg     else if (!AuditedType(FuncDecl->getReturnType()))
152906f32e7eSjoerg       return CF_BRIDGING_NONE;
153006f32e7eSjoerg   }
153106f32e7eSjoerg 
153206f32e7eSjoerg   // At this point result type is audited for potential inclusion.
153306f32e7eSjoerg   unsigned i = 0;
153406f32e7eSjoerg   bool ArgCFAudited = false;
153506f32e7eSjoerg   for (FunctionDecl::param_const_iterator pi = FuncDecl->param_begin(),
153606f32e7eSjoerg        pe = FuncDecl->param_end(); pi != pe; ++pi, ++i) {
153706f32e7eSjoerg     const ParmVarDecl *pd = *pi;
153806f32e7eSjoerg     ArgEffect AE = RS->getArg(i);
153906f32e7eSjoerg     if ((AE.getKind() == DecRef /*CFConsumed annotated*/ ||
154006f32e7eSjoerg          AE.getKind() == IncRef) && AE.getObjKind() == ObjKind::CF) {
154106f32e7eSjoerg       if (AE.getKind() == DecRef && !pd->hasAttr<CFConsumedAttr>())
154206f32e7eSjoerg         ArgCFAudited = true;
154306f32e7eSjoerg       else if (AE.getKind() == IncRef)
154406f32e7eSjoerg         ArgCFAudited = true;
154506f32e7eSjoerg     } else {
154606f32e7eSjoerg       QualType AT = pd->getType();
154706f32e7eSjoerg       if (!AuditedType(AT)) {
154806f32e7eSjoerg         AddCFAnnotations(Ctx, RS, FuncDecl, FuncIsReturnAnnotated);
154906f32e7eSjoerg         return CF_BRIDGING_NONE;
155006f32e7eSjoerg       }
155106f32e7eSjoerg     }
155206f32e7eSjoerg   }
155306f32e7eSjoerg   if (ReturnCFAudited || ArgCFAudited)
155406f32e7eSjoerg     return CF_BRIDGING_ENABLE;
155506f32e7eSjoerg 
155606f32e7eSjoerg   return CF_BRIDGING_MAY_INCLUDE;
155706f32e7eSjoerg }
155806f32e7eSjoerg 
migrateARCSafeAnnotation(ASTContext & Ctx,ObjCContainerDecl * CDecl)155906f32e7eSjoerg void ObjCMigrateASTConsumer::migrateARCSafeAnnotation(ASTContext &Ctx,
156006f32e7eSjoerg                                                  ObjCContainerDecl *CDecl) {
156106f32e7eSjoerg   if (!isa<ObjCInterfaceDecl>(CDecl) || CDecl->isDeprecated())
156206f32e7eSjoerg     return;
156306f32e7eSjoerg 
156406f32e7eSjoerg   // migrate methods which can have instancetype as their result type.
156506f32e7eSjoerg   for (const auto *Method : CDecl->methods())
156606f32e7eSjoerg     migrateCFAnnotation(Ctx, Method);
156706f32e7eSjoerg }
156806f32e7eSjoerg 
AddCFAnnotations(ASTContext & Ctx,const RetainSummary * RS,const ObjCMethodDecl * MethodDecl,bool ResultAnnotated)156906f32e7eSjoerg void ObjCMigrateASTConsumer::AddCFAnnotations(ASTContext &Ctx,
157006f32e7eSjoerg                                               const RetainSummary *RS,
157106f32e7eSjoerg                                               const ObjCMethodDecl *MethodDecl,
157206f32e7eSjoerg                                               bool ResultAnnotated) {
157306f32e7eSjoerg   // Annotate function.
157406f32e7eSjoerg   if (!ResultAnnotated) {
157506f32e7eSjoerg     RetEffect Ret = RS->getRetEffect();
157606f32e7eSjoerg     const char *AnnotationString = nullptr;
157706f32e7eSjoerg     if (Ret.getObjKind() == ObjKind::CF) {
157806f32e7eSjoerg       if (Ret.isOwned() && NSAPIObj->isMacroDefined("CF_RETURNS_RETAINED"))
157906f32e7eSjoerg         AnnotationString = " CF_RETURNS_RETAINED";
158006f32e7eSjoerg       else if (Ret.notOwned() &&
158106f32e7eSjoerg                NSAPIObj->isMacroDefined("CF_RETURNS_NOT_RETAINED"))
158206f32e7eSjoerg         AnnotationString = " CF_RETURNS_NOT_RETAINED";
158306f32e7eSjoerg     }
158406f32e7eSjoerg     else if (Ret.getObjKind() == ObjKind::ObjC) {
158506f32e7eSjoerg       ObjCMethodFamily OMF = MethodDecl->getMethodFamily();
158606f32e7eSjoerg       switch (OMF) {
158706f32e7eSjoerg         case clang::OMF_alloc:
158806f32e7eSjoerg         case clang::OMF_new:
158906f32e7eSjoerg         case clang::OMF_copy:
159006f32e7eSjoerg         case clang::OMF_init:
159106f32e7eSjoerg         case clang::OMF_mutableCopy:
159206f32e7eSjoerg           break;
159306f32e7eSjoerg 
159406f32e7eSjoerg         default:
159506f32e7eSjoerg           if (Ret.isOwned() && NSAPIObj->isMacroDefined("NS_RETURNS_RETAINED"))
159606f32e7eSjoerg             AnnotationString = " NS_RETURNS_RETAINED";
159706f32e7eSjoerg           break;
159806f32e7eSjoerg       }
159906f32e7eSjoerg     }
160006f32e7eSjoerg 
160106f32e7eSjoerg     if (AnnotationString) {
160206f32e7eSjoerg       edit::Commit commit(*Editor);
160306f32e7eSjoerg       commit.insertBefore(MethodDecl->getEndLoc(), AnnotationString);
160406f32e7eSjoerg       Editor->commit(commit);
160506f32e7eSjoerg     }
160606f32e7eSjoerg   }
160706f32e7eSjoerg   unsigned i = 0;
160806f32e7eSjoerg   for (ObjCMethodDecl::param_const_iterator pi = MethodDecl->param_begin(),
160906f32e7eSjoerg        pe = MethodDecl->param_end(); pi != pe; ++pi, ++i) {
161006f32e7eSjoerg     const ParmVarDecl *pd = *pi;
161106f32e7eSjoerg     ArgEffect AE = RS->getArg(i);
161206f32e7eSjoerg     if (AE.getKind() == DecRef
161306f32e7eSjoerg         && AE.getObjKind() == ObjKind::CF
161406f32e7eSjoerg         && !pd->hasAttr<CFConsumedAttr>() &&
161506f32e7eSjoerg         NSAPIObj->isMacroDefined("CF_CONSUMED")) {
161606f32e7eSjoerg       edit::Commit commit(*Editor);
161706f32e7eSjoerg       commit.insertBefore(pd->getLocation(), "CF_CONSUMED ");
161806f32e7eSjoerg       Editor->commit(commit);
161906f32e7eSjoerg     }
162006f32e7eSjoerg   }
162106f32e7eSjoerg }
162206f32e7eSjoerg 
migrateAddMethodAnnotation(ASTContext & Ctx,const ObjCMethodDecl * MethodDecl)162306f32e7eSjoerg void ObjCMigrateASTConsumer::migrateAddMethodAnnotation(
162406f32e7eSjoerg                                             ASTContext &Ctx,
162506f32e7eSjoerg                                             const ObjCMethodDecl *MethodDecl) {
162606f32e7eSjoerg   if (MethodDecl->hasBody() || MethodDecl->isImplicit())
162706f32e7eSjoerg     return;
162806f32e7eSjoerg 
162906f32e7eSjoerg   const RetainSummary *RS =
163006f32e7eSjoerg       getSummaryManager(Ctx).getSummary(AnyCall(MethodDecl));
163106f32e7eSjoerg 
163206f32e7eSjoerg   bool MethodIsReturnAnnotated =
163306f32e7eSjoerg       (MethodDecl->hasAttr<CFReturnsRetainedAttr>() ||
163406f32e7eSjoerg        MethodDecl->hasAttr<CFReturnsNotRetainedAttr>() ||
163506f32e7eSjoerg        MethodDecl->hasAttr<NSReturnsRetainedAttr>() ||
163606f32e7eSjoerg        MethodDecl->hasAttr<NSReturnsNotRetainedAttr>() ||
163706f32e7eSjoerg        MethodDecl->hasAttr<NSReturnsAutoreleasedAttr>());
163806f32e7eSjoerg 
163906f32e7eSjoerg   if (RS->getReceiverEffect().getKind() == DecRef &&
164006f32e7eSjoerg       !MethodDecl->hasAttr<NSConsumesSelfAttr>() &&
164106f32e7eSjoerg       MethodDecl->getMethodFamily() != OMF_init &&
164206f32e7eSjoerg       MethodDecl->getMethodFamily() != OMF_release &&
164306f32e7eSjoerg       NSAPIObj->isMacroDefined("NS_CONSUMES_SELF")) {
164406f32e7eSjoerg     edit::Commit commit(*Editor);
164506f32e7eSjoerg     commit.insertBefore(MethodDecl->getEndLoc(), " NS_CONSUMES_SELF");
164606f32e7eSjoerg     Editor->commit(commit);
164706f32e7eSjoerg   }
164806f32e7eSjoerg 
164906f32e7eSjoerg   // Trivial case of when function is annotated and has no argument.
165006f32e7eSjoerg   if (MethodIsReturnAnnotated &&
165106f32e7eSjoerg       (MethodDecl->param_begin() == MethodDecl->param_end()))
165206f32e7eSjoerg     return;
165306f32e7eSjoerg 
165406f32e7eSjoerg   if (!MethodIsReturnAnnotated) {
165506f32e7eSjoerg     RetEffect Ret = RS->getRetEffect();
165606f32e7eSjoerg     if ((Ret.getObjKind() == ObjKind::CF ||
165706f32e7eSjoerg          Ret.getObjKind() == ObjKind::ObjC) &&
165806f32e7eSjoerg         (Ret.isOwned() || Ret.notOwned())) {
165906f32e7eSjoerg       AddCFAnnotations(Ctx, RS, MethodDecl, false);
166006f32e7eSjoerg       return;
166106f32e7eSjoerg     } else if (!AuditedType(MethodDecl->getReturnType()))
166206f32e7eSjoerg       return;
166306f32e7eSjoerg   }
166406f32e7eSjoerg 
166506f32e7eSjoerg   // At this point result type is either annotated or audited.
166606f32e7eSjoerg   unsigned i = 0;
166706f32e7eSjoerg   for (ObjCMethodDecl::param_const_iterator pi = MethodDecl->param_begin(),
166806f32e7eSjoerg        pe = MethodDecl->param_end(); pi != pe; ++pi, ++i) {
166906f32e7eSjoerg     const ParmVarDecl *pd = *pi;
167006f32e7eSjoerg     ArgEffect AE = RS->getArg(i);
167106f32e7eSjoerg     if ((AE.getKind() == DecRef && !pd->hasAttr<CFConsumedAttr>()) ||
167206f32e7eSjoerg         AE.getKind() == IncRef || !AuditedType(pd->getType())) {
167306f32e7eSjoerg       AddCFAnnotations(Ctx, RS, MethodDecl, MethodIsReturnAnnotated);
167406f32e7eSjoerg       return;
167506f32e7eSjoerg     }
167606f32e7eSjoerg   }
167706f32e7eSjoerg }
167806f32e7eSjoerg 
167906f32e7eSjoerg namespace {
168006f32e7eSjoerg class SuperInitChecker : public RecursiveASTVisitor<SuperInitChecker> {
168106f32e7eSjoerg public:
shouldVisitTemplateInstantiations() const168206f32e7eSjoerg   bool shouldVisitTemplateInstantiations() const { return false; }
shouldWalkTypesOfTypeLocs() const168306f32e7eSjoerg   bool shouldWalkTypesOfTypeLocs() const { return false; }
168406f32e7eSjoerg 
VisitObjCMessageExpr(ObjCMessageExpr * E)168506f32e7eSjoerg   bool VisitObjCMessageExpr(ObjCMessageExpr *E) {
168606f32e7eSjoerg     if (E->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
168706f32e7eSjoerg       if (E->getMethodFamily() == OMF_init)
168806f32e7eSjoerg         return false;
168906f32e7eSjoerg     }
169006f32e7eSjoerg     return true;
169106f32e7eSjoerg   }
169206f32e7eSjoerg };
169306f32e7eSjoerg } // end anonymous namespace
169406f32e7eSjoerg 
hasSuperInitCall(const ObjCMethodDecl * MD)169506f32e7eSjoerg static bool hasSuperInitCall(const ObjCMethodDecl *MD) {
169606f32e7eSjoerg   return !SuperInitChecker().TraverseStmt(MD->getBody());
169706f32e7eSjoerg }
169806f32e7eSjoerg 
inferDesignatedInitializers(ASTContext & Ctx,const ObjCImplementationDecl * ImplD)169906f32e7eSjoerg void ObjCMigrateASTConsumer::inferDesignatedInitializers(
170006f32e7eSjoerg     ASTContext &Ctx,
170106f32e7eSjoerg     const ObjCImplementationDecl *ImplD) {
170206f32e7eSjoerg 
170306f32e7eSjoerg   const ObjCInterfaceDecl *IFace = ImplD->getClassInterface();
170406f32e7eSjoerg   if (!IFace || IFace->hasDesignatedInitializers())
170506f32e7eSjoerg     return;
170606f32e7eSjoerg   if (!NSAPIObj->isMacroDefined("NS_DESIGNATED_INITIALIZER"))
170706f32e7eSjoerg     return;
170806f32e7eSjoerg 
170906f32e7eSjoerg   for (const auto *MD : ImplD->instance_methods()) {
171006f32e7eSjoerg     if (MD->isDeprecated() ||
171106f32e7eSjoerg         MD->getMethodFamily() != OMF_init ||
171206f32e7eSjoerg         MD->isDesignatedInitializerForTheInterface())
171306f32e7eSjoerg       continue;
171406f32e7eSjoerg     const ObjCMethodDecl *IFaceM = IFace->getMethod(MD->getSelector(),
171506f32e7eSjoerg                                                     /*isInstance=*/true);
171606f32e7eSjoerg     if (!IFaceM)
171706f32e7eSjoerg       continue;
171806f32e7eSjoerg     if (hasSuperInitCall(MD)) {
171906f32e7eSjoerg       edit::Commit commit(*Editor);
172006f32e7eSjoerg       commit.insert(IFaceM->getEndLoc(), " NS_DESIGNATED_INITIALIZER");
172106f32e7eSjoerg       Editor->commit(commit);
172206f32e7eSjoerg     }
172306f32e7eSjoerg   }
172406f32e7eSjoerg }
172506f32e7eSjoerg 
InsertFoundation(ASTContext & Ctx,SourceLocation Loc)172606f32e7eSjoerg bool ObjCMigrateASTConsumer::InsertFoundation(ASTContext &Ctx,
172706f32e7eSjoerg                                               SourceLocation  Loc) {
172806f32e7eSjoerg   if (FoundationIncluded)
172906f32e7eSjoerg     return true;
173006f32e7eSjoerg   if (Loc.isInvalid())
173106f32e7eSjoerg     return false;
173206f32e7eSjoerg   auto *nsEnumId = &Ctx.Idents.get("NS_ENUM");
173306f32e7eSjoerg   if (PP.getMacroDefinitionAtLoc(nsEnumId, Loc)) {
173406f32e7eSjoerg     FoundationIncluded = true;
173506f32e7eSjoerg     return true;
173606f32e7eSjoerg   }
173706f32e7eSjoerg   edit::Commit commit(*Editor);
173806f32e7eSjoerg   if (Ctx.getLangOpts().Modules)
173906f32e7eSjoerg     commit.insert(Loc, "#ifndef NS_ENUM\n@import Foundation;\n#endif\n");
174006f32e7eSjoerg   else
174106f32e7eSjoerg     commit.insert(Loc, "#ifndef NS_ENUM\n#import <Foundation/Foundation.h>\n#endif\n");
174206f32e7eSjoerg   Editor->commit(commit);
174306f32e7eSjoerg   FoundationIncluded = true;
174406f32e7eSjoerg   return true;
174506f32e7eSjoerg }
174606f32e7eSjoerg 
174706f32e7eSjoerg namespace {
174806f32e7eSjoerg 
174906f32e7eSjoerg class RewritesReceiver : public edit::EditsReceiver {
175006f32e7eSjoerg   Rewriter &Rewrite;
175106f32e7eSjoerg 
175206f32e7eSjoerg public:
RewritesReceiver(Rewriter & Rewrite)175306f32e7eSjoerg   RewritesReceiver(Rewriter &Rewrite) : Rewrite(Rewrite) { }
175406f32e7eSjoerg 
insert(SourceLocation loc,StringRef text)175506f32e7eSjoerg   void insert(SourceLocation loc, StringRef text) override {
175606f32e7eSjoerg     Rewrite.InsertText(loc, text);
175706f32e7eSjoerg   }
replace(CharSourceRange range,StringRef text)175806f32e7eSjoerg   void replace(CharSourceRange range, StringRef text) override {
175906f32e7eSjoerg     Rewrite.ReplaceText(range.getBegin(), Rewrite.getRangeSize(range), text);
176006f32e7eSjoerg   }
176106f32e7eSjoerg };
176206f32e7eSjoerg 
176306f32e7eSjoerg class JSONEditWriter : public edit::EditsReceiver {
176406f32e7eSjoerg   SourceManager &SourceMgr;
176506f32e7eSjoerg   llvm::raw_ostream &OS;
176606f32e7eSjoerg 
176706f32e7eSjoerg public:
JSONEditWriter(SourceManager & SM,llvm::raw_ostream & OS)176806f32e7eSjoerg   JSONEditWriter(SourceManager &SM, llvm::raw_ostream &OS)
176906f32e7eSjoerg     : SourceMgr(SM), OS(OS) {
177006f32e7eSjoerg     OS << "[\n";
177106f32e7eSjoerg   }
~JSONEditWriter()177206f32e7eSjoerg   ~JSONEditWriter() override { OS << "]\n"; }
177306f32e7eSjoerg 
177406f32e7eSjoerg private:
177506f32e7eSjoerg   struct EntryWriter {
177606f32e7eSjoerg     SourceManager &SourceMgr;
177706f32e7eSjoerg     llvm::raw_ostream &OS;
177806f32e7eSjoerg 
EntryWriter__anon18060fa80411::JSONEditWriter::EntryWriter177906f32e7eSjoerg     EntryWriter(SourceManager &SM, llvm::raw_ostream &OS)
178006f32e7eSjoerg       : SourceMgr(SM), OS(OS) {
178106f32e7eSjoerg       OS << " {\n";
178206f32e7eSjoerg     }
~EntryWriter__anon18060fa80411::JSONEditWriter::EntryWriter178306f32e7eSjoerg     ~EntryWriter() {
178406f32e7eSjoerg       OS << " },\n";
178506f32e7eSjoerg     }
178606f32e7eSjoerg 
writeLoc__anon18060fa80411::JSONEditWriter::EntryWriter178706f32e7eSjoerg     void writeLoc(SourceLocation Loc) {
178806f32e7eSjoerg       FileID FID;
178906f32e7eSjoerg       unsigned Offset;
179006f32e7eSjoerg       std::tie(FID, Offset) = SourceMgr.getDecomposedLoc(Loc);
179106f32e7eSjoerg       assert(FID.isValid());
179206f32e7eSjoerg       SmallString<200> Path =
179306f32e7eSjoerg           StringRef(SourceMgr.getFileEntryForID(FID)->getName());
179406f32e7eSjoerg       llvm::sys::fs::make_absolute(Path);
179506f32e7eSjoerg       OS << "  \"file\": \"";
179606f32e7eSjoerg       OS.write_escaped(Path.str()) << "\",\n";
179706f32e7eSjoerg       OS << "  \"offset\": " << Offset << ",\n";
179806f32e7eSjoerg     }
179906f32e7eSjoerg 
writeRemove__anon18060fa80411::JSONEditWriter::EntryWriter180006f32e7eSjoerg     void writeRemove(CharSourceRange Range) {
180106f32e7eSjoerg       assert(Range.isCharRange());
180206f32e7eSjoerg       std::pair<FileID, unsigned> Begin =
180306f32e7eSjoerg           SourceMgr.getDecomposedLoc(Range.getBegin());
180406f32e7eSjoerg       std::pair<FileID, unsigned> End =
180506f32e7eSjoerg           SourceMgr.getDecomposedLoc(Range.getEnd());
180606f32e7eSjoerg       assert(Begin.first == End.first);
180706f32e7eSjoerg       assert(Begin.second <= End.second);
180806f32e7eSjoerg       unsigned Length = End.second - Begin.second;
180906f32e7eSjoerg 
181006f32e7eSjoerg       OS << "  \"remove\": " << Length << ",\n";
181106f32e7eSjoerg     }
181206f32e7eSjoerg 
writeText__anon18060fa80411::JSONEditWriter::EntryWriter181306f32e7eSjoerg     void writeText(StringRef Text) {
181406f32e7eSjoerg       OS << "  \"text\": \"";
181506f32e7eSjoerg       OS.write_escaped(Text) << "\",\n";
181606f32e7eSjoerg     }
181706f32e7eSjoerg   };
181806f32e7eSjoerg 
insert(SourceLocation Loc,StringRef Text)181906f32e7eSjoerg   void insert(SourceLocation Loc, StringRef Text) override {
182006f32e7eSjoerg     EntryWriter Writer(SourceMgr, OS);
182106f32e7eSjoerg     Writer.writeLoc(Loc);
182206f32e7eSjoerg     Writer.writeText(Text);
182306f32e7eSjoerg   }
182406f32e7eSjoerg 
replace(CharSourceRange Range,StringRef Text)182506f32e7eSjoerg   void replace(CharSourceRange Range, StringRef Text) override {
182606f32e7eSjoerg     EntryWriter Writer(SourceMgr, OS);
182706f32e7eSjoerg     Writer.writeLoc(Range.getBegin());
182806f32e7eSjoerg     Writer.writeRemove(Range);
182906f32e7eSjoerg     Writer.writeText(Text);
183006f32e7eSjoerg   }
183106f32e7eSjoerg 
remove(CharSourceRange Range)183206f32e7eSjoerg   void remove(CharSourceRange Range) override {
183306f32e7eSjoerg     EntryWriter Writer(SourceMgr, OS);
183406f32e7eSjoerg     Writer.writeLoc(Range.getBegin());
183506f32e7eSjoerg     Writer.writeRemove(Range);
183606f32e7eSjoerg   }
183706f32e7eSjoerg };
183806f32e7eSjoerg 
183906f32e7eSjoerg } // end anonymous namespace
184006f32e7eSjoerg 
HandleTranslationUnit(ASTContext & Ctx)184106f32e7eSjoerg void ObjCMigrateASTConsumer::HandleTranslationUnit(ASTContext &Ctx) {
184206f32e7eSjoerg 
184306f32e7eSjoerg   TranslationUnitDecl *TU = Ctx.getTranslationUnitDecl();
184406f32e7eSjoerg   if (ASTMigrateActions & FrontendOptions::ObjCMT_MigrateDecls) {
184506f32e7eSjoerg     for (DeclContext::decl_iterator D = TU->decls_begin(), DEnd = TU->decls_end();
184606f32e7eSjoerg          D != DEnd; ++D) {
184706f32e7eSjoerg       FileID FID = PP.getSourceManager().getFileID((*D)->getLocation());
184806f32e7eSjoerg       if (FID.isValid())
184906f32e7eSjoerg         if (FileId.isValid() && FileId != FID) {
185006f32e7eSjoerg           if (ASTMigrateActions & FrontendOptions::ObjCMT_Annotation)
185106f32e7eSjoerg             AnnotateImplicitBridging(Ctx);
185206f32e7eSjoerg         }
185306f32e7eSjoerg 
185406f32e7eSjoerg       if (ObjCInterfaceDecl *CDecl = dyn_cast<ObjCInterfaceDecl>(*D))
185506f32e7eSjoerg         if (canModify(CDecl))
185606f32e7eSjoerg           migrateObjCContainerDecl(Ctx, CDecl);
185706f32e7eSjoerg       if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(*D)) {
185806f32e7eSjoerg         if (canModify(CatDecl))
185906f32e7eSjoerg           migrateObjCContainerDecl(Ctx, CatDecl);
186006f32e7eSjoerg       }
186106f32e7eSjoerg       else if (ObjCProtocolDecl *PDecl = dyn_cast<ObjCProtocolDecl>(*D)) {
186206f32e7eSjoerg         ObjCProtocolDecls.insert(PDecl->getCanonicalDecl());
186306f32e7eSjoerg         if (canModify(PDecl))
186406f32e7eSjoerg           migrateObjCContainerDecl(Ctx, PDecl);
186506f32e7eSjoerg       }
186606f32e7eSjoerg       else if (const ObjCImplementationDecl *ImpDecl =
186706f32e7eSjoerg                dyn_cast<ObjCImplementationDecl>(*D)) {
186806f32e7eSjoerg         if ((ASTMigrateActions & FrontendOptions::ObjCMT_ProtocolConformance) &&
186906f32e7eSjoerg             canModify(ImpDecl))
187006f32e7eSjoerg           migrateProtocolConformance(Ctx, ImpDecl);
187106f32e7eSjoerg       }
187206f32e7eSjoerg       else if (const EnumDecl *ED = dyn_cast<EnumDecl>(*D)) {
187306f32e7eSjoerg         if (!(ASTMigrateActions & FrontendOptions::ObjCMT_NsMacros))
187406f32e7eSjoerg           continue;
187506f32e7eSjoerg         if (!canModify(ED))
187606f32e7eSjoerg           continue;
187706f32e7eSjoerg         DeclContext::decl_iterator N = D;
187806f32e7eSjoerg         if (++N != DEnd) {
187906f32e7eSjoerg           const TypedefDecl *TD = dyn_cast<TypedefDecl>(*N);
188006f32e7eSjoerg           if (migrateNSEnumDecl(Ctx, ED, TD) && TD)
188106f32e7eSjoerg             D++;
188206f32e7eSjoerg         }
188306f32e7eSjoerg         else
188406f32e7eSjoerg           migrateNSEnumDecl(Ctx, ED, /*TypedefDecl */nullptr);
188506f32e7eSjoerg       }
188606f32e7eSjoerg       else if (const TypedefDecl *TD = dyn_cast<TypedefDecl>(*D)) {
188706f32e7eSjoerg         if (!(ASTMigrateActions & FrontendOptions::ObjCMT_NsMacros))
188806f32e7eSjoerg           continue;
188906f32e7eSjoerg         if (!canModify(TD))
189006f32e7eSjoerg           continue;
189106f32e7eSjoerg         DeclContext::decl_iterator N = D;
189206f32e7eSjoerg         if (++N == DEnd)
189306f32e7eSjoerg           continue;
189406f32e7eSjoerg         if (const EnumDecl *ED = dyn_cast<EnumDecl>(*N)) {
189506f32e7eSjoerg           if (canModify(ED)) {
189606f32e7eSjoerg             if (++N != DEnd)
189706f32e7eSjoerg               if (const TypedefDecl *TDF = dyn_cast<TypedefDecl>(*N)) {
189806f32e7eSjoerg                 // prefer typedef-follows-enum to enum-follows-typedef pattern.
189906f32e7eSjoerg                 if (migrateNSEnumDecl(Ctx, ED, TDF)) {
190006f32e7eSjoerg                   ++D; ++D;
190106f32e7eSjoerg                   CacheObjCNSIntegerTypedefed(TD);
190206f32e7eSjoerg                   continue;
190306f32e7eSjoerg                 }
190406f32e7eSjoerg               }
190506f32e7eSjoerg             if (migrateNSEnumDecl(Ctx, ED, TD)) {
190606f32e7eSjoerg               ++D;
190706f32e7eSjoerg               continue;
190806f32e7eSjoerg             }
190906f32e7eSjoerg           }
191006f32e7eSjoerg         }
191106f32e7eSjoerg         CacheObjCNSIntegerTypedefed(TD);
191206f32e7eSjoerg       }
191306f32e7eSjoerg       else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(*D)) {
191406f32e7eSjoerg         if ((ASTMigrateActions & FrontendOptions::ObjCMT_Annotation) &&
191506f32e7eSjoerg             canModify(FD))
191606f32e7eSjoerg           migrateCFAnnotation(Ctx, FD);
191706f32e7eSjoerg       }
191806f32e7eSjoerg 
191906f32e7eSjoerg       if (ObjCContainerDecl *CDecl = dyn_cast<ObjCContainerDecl>(*D)) {
192006f32e7eSjoerg         bool CanModify = canModify(CDecl);
192106f32e7eSjoerg         // migrate methods which can have instancetype as their result type.
192206f32e7eSjoerg         if ((ASTMigrateActions & FrontendOptions::ObjCMT_Instancetype) &&
192306f32e7eSjoerg             CanModify)
192406f32e7eSjoerg           migrateAllMethodInstaceType(Ctx, CDecl);
192506f32e7eSjoerg         // annotate methods with CF annotations.
192606f32e7eSjoerg         if ((ASTMigrateActions & FrontendOptions::ObjCMT_Annotation) &&
192706f32e7eSjoerg             CanModify)
192806f32e7eSjoerg           migrateARCSafeAnnotation(Ctx, CDecl);
192906f32e7eSjoerg       }
193006f32e7eSjoerg 
193106f32e7eSjoerg       if (const ObjCImplementationDecl *
193206f32e7eSjoerg             ImplD = dyn_cast<ObjCImplementationDecl>(*D)) {
193306f32e7eSjoerg         if ((ASTMigrateActions & FrontendOptions::ObjCMT_DesignatedInitializer) &&
193406f32e7eSjoerg             canModify(ImplD))
193506f32e7eSjoerg           inferDesignatedInitializers(Ctx, ImplD);
193606f32e7eSjoerg       }
193706f32e7eSjoerg     }
193806f32e7eSjoerg     if (ASTMigrateActions & FrontendOptions::ObjCMT_Annotation)
193906f32e7eSjoerg       AnnotateImplicitBridging(Ctx);
194006f32e7eSjoerg   }
194106f32e7eSjoerg 
194206f32e7eSjoerg  if (IsOutputFile) {
194306f32e7eSjoerg    std::error_code EC;
194406f32e7eSjoerg    llvm::raw_fd_ostream OS(MigrateDir, EC, llvm::sys::fs::OF_None);
194506f32e7eSjoerg    if (EC) {
194606f32e7eSjoerg       DiagnosticsEngine &Diags = Ctx.getDiagnostics();
194706f32e7eSjoerg       Diags.Report(Diags.getCustomDiagID(DiagnosticsEngine::Error, "%0"))
194806f32e7eSjoerg           << EC.message();
194906f32e7eSjoerg       return;
195006f32e7eSjoerg     }
195106f32e7eSjoerg 
195206f32e7eSjoerg    JSONEditWriter Writer(Ctx.getSourceManager(), OS);
195306f32e7eSjoerg    Editor->applyRewrites(Writer);
195406f32e7eSjoerg    return;
195506f32e7eSjoerg  }
195606f32e7eSjoerg 
195706f32e7eSjoerg   Rewriter rewriter(Ctx.getSourceManager(), Ctx.getLangOpts());
195806f32e7eSjoerg   RewritesReceiver Rec(rewriter);
195906f32e7eSjoerg   Editor->applyRewrites(Rec);
196006f32e7eSjoerg 
196106f32e7eSjoerg   for (Rewriter::buffer_iterator
196206f32e7eSjoerg         I = rewriter.buffer_begin(), E = rewriter.buffer_end(); I != E; ++I) {
196306f32e7eSjoerg     FileID FID = I->first;
196406f32e7eSjoerg     RewriteBuffer &buf = I->second;
1965*13fbcb42Sjoerg     Optional<FileEntryRef> file = Ctx.getSourceManager().getFileEntryRefForID(FID);
196606f32e7eSjoerg     assert(file);
196706f32e7eSjoerg     SmallString<512> newText;
196806f32e7eSjoerg     llvm::raw_svector_ostream vecOS(newText);
196906f32e7eSjoerg     buf.write(vecOS);
197006f32e7eSjoerg     std::unique_ptr<llvm::MemoryBuffer> memBuf(
197106f32e7eSjoerg         llvm::MemoryBuffer::getMemBufferCopy(
197206f32e7eSjoerg             StringRef(newText.data(), newText.size()), file->getName()));
197306f32e7eSjoerg     SmallString<64> filePath(file->getName());
197406f32e7eSjoerg     FileMgr.FixupRelativePath(filePath);
197506f32e7eSjoerg     Remapper.remap(filePath.str(), std::move(memBuf));
197606f32e7eSjoerg   }
197706f32e7eSjoerg 
197806f32e7eSjoerg   if (IsOutputFile) {
197906f32e7eSjoerg     Remapper.flushToFile(MigrateDir, Ctx.getDiagnostics());
198006f32e7eSjoerg   } else {
198106f32e7eSjoerg     Remapper.flushToDisk(MigrateDir, Ctx.getDiagnostics());
198206f32e7eSjoerg   }
198306f32e7eSjoerg }
198406f32e7eSjoerg 
BeginInvocation(CompilerInstance & CI)198506f32e7eSjoerg bool MigrateSourceAction::BeginInvocation(CompilerInstance &CI) {
198606f32e7eSjoerg   CI.getDiagnostics().setIgnoreAllWarnings(true);
198706f32e7eSjoerg   return true;
198806f32e7eSjoerg }
198906f32e7eSjoerg 
getWhiteListFilenames(StringRef DirPath)199006f32e7eSjoerg static std::vector<std::string> getWhiteListFilenames(StringRef DirPath) {
199106f32e7eSjoerg   using namespace llvm::sys::fs;
199206f32e7eSjoerg   using namespace llvm::sys::path;
199306f32e7eSjoerg 
199406f32e7eSjoerg   std::vector<std::string> Filenames;
199506f32e7eSjoerg   if (DirPath.empty() || !is_directory(DirPath))
199606f32e7eSjoerg     return Filenames;
199706f32e7eSjoerg 
199806f32e7eSjoerg   std::error_code EC;
199906f32e7eSjoerg   directory_iterator DI = directory_iterator(DirPath, EC);
200006f32e7eSjoerg   directory_iterator DE;
200106f32e7eSjoerg   for (; !EC && DI != DE; DI = DI.increment(EC)) {
200206f32e7eSjoerg     if (is_regular_file(DI->path()))
2003*13fbcb42Sjoerg       Filenames.push_back(std::string(filename(DI->path())));
200406f32e7eSjoerg   }
200506f32e7eSjoerg 
200606f32e7eSjoerg   return Filenames;
200706f32e7eSjoerg }
200806f32e7eSjoerg 
200906f32e7eSjoerg std::unique_ptr<ASTConsumer>
CreateASTConsumer(CompilerInstance & CI,StringRef InFile)201006f32e7eSjoerg MigrateSourceAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
201106f32e7eSjoerg   PPConditionalDirectiveRecord *
201206f32e7eSjoerg     PPRec = new PPConditionalDirectiveRecord(CI.getSourceManager());
201306f32e7eSjoerg   unsigned ObjCMTAction = CI.getFrontendOpts().ObjCMTAction;
201406f32e7eSjoerg   unsigned ObjCMTOpts = ObjCMTAction;
201506f32e7eSjoerg   // These are companion flags, they do not enable transformations.
201606f32e7eSjoerg   ObjCMTOpts &= ~(FrontendOptions::ObjCMT_AtomicProperty |
201706f32e7eSjoerg                   FrontendOptions::ObjCMT_NsAtomicIOSOnlyProperty);
201806f32e7eSjoerg   if (ObjCMTOpts == FrontendOptions::ObjCMT_None) {
201906f32e7eSjoerg     // If no specific option was given, enable literals+subscripting transforms
202006f32e7eSjoerg     // by default.
202106f32e7eSjoerg     ObjCMTAction |= FrontendOptions::ObjCMT_Literals |
202206f32e7eSjoerg                     FrontendOptions::ObjCMT_Subscripting;
202306f32e7eSjoerg   }
202406f32e7eSjoerg   CI.getPreprocessor().addPPCallbacks(std::unique_ptr<PPCallbacks>(PPRec));
202506f32e7eSjoerg   std::vector<std::string> WhiteList =
202606f32e7eSjoerg     getWhiteListFilenames(CI.getFrontendOpts().ObjCMTWhiteListPath);
202706f32e7eSjoerg   return std::make_unique<ObjCMigrateASTConsumer>(
202806f32e7eSjoerg       CI.getFrontendOpts().OutputFile, ObjCMTAction, Remapper,
202906f32e7eSjoerg       CI.getFileManager(), PPRec, CI.getPreprocessor(),
203006f32e7eSjoerg       /*isOutputFile=*/true, WhiteList);
203106f32e7eSjoerg }
203206f32e7eSjoerg 
203306f32e7eSjoerg namespace {
203406f32e7eSjoerg struct EditEntry {
2035*13fbcb42Sjoerg   Optional<FileEntryRef> File;
2036*13fbcb42Sjoerg   unsigned Offset = 0;
2037*13fbcb42Sjoerg   unsigned RemoveLen = 0;
203806f32e7eSjoerg   std::string Text;
203906f32e7eSjoerg };
204006f32e7eSjoerg } // end anonymous namespace
204106f32e7eSjoerg 
204206f32e7eSjoerg namespace llvm {
204306f32e7eSjoerg template<> struct DenseMapInfo<EditEntry> {
getEmptyKeyllvm::DenseMapInfo204406f32e7eSjoerg   static inline EditEntry getEmptyKey() {
204506f32e7eSjoerg     EditEntry Entry;
204606f32e7eSjoerg     Entry.Offset = unsigned(-1);
204706f32e7eSjoerg     return Entry;
204806f32e7eSjoerg   }
getTombstoneKeyllvm::DenseMapInfo204906f32e7eSjoerg   static inline EditEntry getTombstoneKey() {
205006f32e7eSjoerg     EditEntry Entry;
205106f32e7eSjoerg     Entry.Offset = unsigned(-2);
205206f32e7eSjoerg     return Entry;
205306f32e7eSjoerg   }
getHashValuellvm::DenseMapInfo205406f32e7eSjoerg   static unsigned getHashValue(const EditEntry& Val) {
2055*13fbcb42Sjoerg     return (unsigned)llvm::hash_combine(Val.File, Val.Offset, Val.RemoveLen,
2056*13fbcb42Sjoerg                                         Val.Text);
205706f32e7eSjoerg   }
isEqualllvm::DenseMapInfo205806f32e7eSjoerg   static bool isEqual(const EditEntry &LHS, const EditEntry &RHS) {
205906f32e7eSjoerg     return LHS.File == RHS.File &&
206006f32e7eSjoerg         LHS.Offset == RHS.Offset &&
206106f32e7eSjoerg         LHS.RemoveLen == RHS.RemoveLen &&
206206f32e7eSjoerg         LHS.Text == RHS.Text;
206306f32e7eSjoerg   }
206406f32e7eSjoerg };
206506f32e7eSjoerg } // end namespace llvm
206606f32e7eSjoerg 
206706f32e7eSjoerg namespace {
206806f32e7eSjoerg class RemapFileParser {
206906f32e7eSjoerg   FileManager &FileMgr;
207006f32e7eSjoerg 
207106f32e7eSjoerg public:
RemapFileParser(FileManager & FileMgr)207206f32e7eSjoerg   RemapFileParser(FileManager &FileMgr) : FileMgr(FileMgr) { }
207306f32e7eSjoerg 
parse(StringRef File,SmallVectorImpl<EditEntry> & Entries)207406f32e7eSjoerg   bool parse(StringRef File, SmallVectorImpl<EditEntry> &Entries) {
207506f32e7eSjoerg     using namespace llvm::yaml;
207606f32e7eSjoerg 
207706f32e7eSjoerg     llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> FileBufOrErr =
207806f32e7eSjoerg         llvm::MemoryBuffer::getFile(File);
207906f32e7eSjoerg     if (!FileBufOrErr)
208006f32e7eSjoerg       return true;
208106f32e7eSjoerg 
208206f32e7eSjoerg     llvm::SourceMgr SM;
208306f32e7eSjoerg     Stream YAMLStream(FileBufOrErr.get()->getMemBufferRef(), SM);
208406f32e7eSjoerg     document_iterator I = YAMLStream.begin();
208506f32e7eSjoerg     if (I == YAMLStream.end())
208606f32e7eSjoerg       return true;
208706f32e7eSjoerg     Node *Root = I->getRoot();
208806f32e7eSjoerg     if (!Root)
208906f32e7eSjoerg       return true;
209006f32e7eSjoerg 
209106f32e7eSjoerg     SequenceNode *SeqNode = dyn_cast<SequenceNode>(Root);
209206f32e7eSjoerg     if (!SeqNode)
209306f32e7eSjoerg       return true;
209406f32e7eSjoerg 
209506f32e7eSjoerg     for (SequenceNode::iterator
209606f32e7eSjoerg            AI = SeqNode->begin(), AE = SeqNode->end(); AI != AE; ++AI) {
209706f32e7eSjoerg       MappingNode *MapNode = dyn_cast<MappingNode>(&*AI);
209806f32e7eSjoerg       if (!MapNode)
209906f32e7eSjoerg         continue;
210006f32e7eSjoerg       parseEdit(MapNode, Entries);
210106f32e7eSjoerg     }
210206f32e7eSjoerg 
210306f32e7eSjoerg     return false;
210406f32e7eSjoerg   }
210506f32e7eSjoerg 
210606f32e7eSjoerg private:
parseEdit(llvm::yaml::MappingNode * Node,SmallVectorImpl<EditEntry> & Entries)210706f32e7eSjoerg   void parseEdit(llvm::yaml::MappingNode *Node,
210806f32e7eSjoerg                  SmallVectorImpl<EditEntry> &Entries) {
210906f32e7eSjoerg     using namespace llvm::yaml;
211006f32e7eSjoerg     EditEntry Entry;
211106f32e7eSjoerg     bool Ignore = false;
211206f32e7eSjoerg 
211306f32e7eSjoerg     for (MappingNode::iterator
211406f32e7eSjoerg            KVI = Node->begin(), KVE = Node->end(); KVI != KVE; ++KVI) {
211506f32e7eSjoerg       ScalarNode *KeyString = dyn_cast<ScalarNode>((*KVI).getKey());
211606f32e7eSjoerg       if (!KeyString)
211706f32e7eSjoerg         continue;
211806f32e7eSjoerg       SmallString<10> KeyStorage;
211906f32e7eSjoerg       StringRef Key = KeyString->getValue(KeyStorage);
212006f32e7eSjoerg 
212106f32e7eSjoerg       ScalarNode *ValueString = dyn_cast<ScalarNode>((*KVI).getValue());
212206f32e7eSjoerg       if (!ValueString)
212306f32e7eSjoerg         continue;
212406f32e7eSjoerg       SmallString<64> ValueStorage;
212506f32e7eSjoerg       StringRef Val = ValueString->getValue(ValueStorage);
212606f32e7eSjoerg 
212706f32e7eSjoerg       if (Key == "file") {
2128*13fbcb42Sjoerg         if (auto File = FileMgr.getOptionalFileRef(Val))
2129*13fbcb42Sjoerg           Entry.File = File;
213006f32e7eSjoerg         else
213106f32e7eSjoerg           Ignore = true;
213206f32e7eSjoerg       } else if (Key == "offset") {
213306f32e7eSjoerg         if (Val.getAsInteger(10, Entry.Offset))
213406f32e7eSjoerg           Ignore = true;
213506f32e7eSjoerg       } else if (Key == "remove") {
213606f32e7eSjoerg         if (Val.getAsInteger(10, Entry.RemoveLen))
213706f32e7eSjoerg           Ignore = true;
213806f32e7eSjoerg       } else if (Key == "text") {
2139*13fbcb42Sjoerg         Entry.Text = std::string(Val);
214006f32e7eSjoerg       }
214106f32e7eSjoerg     }
214206f32e7eSjoerg 
214306f32e7eSjoerg     if (!Ignore)
214406f32e7eSjoerg       Entries.push_back(Entry);
214506f32e7eSjoerg   }
214606f32e7eSjoerg };
214706f32e7eSjoerg } // end anonymous namespace
214806f32e7eSjoerg 
reportDiag(const Twine & Err,DiagnosticsEngine & Diag)214906f32e7eSjoerg static bool reportDiag(const Twine &Err, DiagnosticsEngine &Diag) {
215006f32e7eSjoerg   Diag.Report(Diag.getCustomDiagID(DiagnosticsEngine::Error, "%0"))
215106f32e7eSjoerg       << Err.str();
215206f32e7eSjoerg   return true;
215306f32e7eSjoerg }
215406f32e7eSjoerg 
applyEditsToTemp(FileEntryRef FE,ArrayRef<EditEntry> Edits,FileManager & FileMgr,DiagnosticsEngine & Diag)2155*13fbcb42Sjoerg static std::string applyEditsToTemp(FileEntryRef FE,
215606f32e7eSjoerg                                     ArrayRef<EditEntry> Edits,
215706f32e7eSjoerg                                     FileManager &FileMgr,
215806f32e7eSjoerg                                     DiagnosticsEngine &Diag) {
215906f32e7eSjoerg   using namespace llvm::sys;
216006f32e7eSjoerg 
216106f32e7eSjoerg   SourceManager SM(Diag, FileMgr);
216206f32e7eSjoerg   FileID FID = SM.createFileID(FE, SourceLocation(), SrcMgr::C_User);
216306f32e7eSjoerg   LangOptions LangOpts;
216406f32e7eSjoerg   edit::EditedSource Editor(SM, LangOpts);
216506f32e7eSjoerg   for (ArrayRef<EditEntry>::iterator
216606f32e7eSjoerg         I = Edits.begin(), E = Edits.end(); I != E; ++I) {
216706f32e7eSjoerg     const EditEntry &Entry = *I;
216806f32e7eSjoerg     assert(Entry.File == FE);
216906f32e7eSjoerg     SourceLocation Loc =
217006f32e7eSjoerg         SM.getLocForStartOfFile(FID).getLocWithOffset(Entry.Offset);
217106f32e7eSjoerg     CharSourceRange Range;
217206f32e7eSjoerg     if (Entry.RemoveLen != 0) {
217306f32e7eSjoerg       Range = CharSourceRange::getCharRange(Loc,
217406f32e7eSjoerg                                          Loc.getLocWithOffset(Entry.RemoveLen));
217506f32e7eSjoerg     }
217606f32e7eSjoerg 
217706f32e7eSjoerg     edit::Commit commit(Editor);
217806f32e7eSjoerg     if (Range.isInvalid()) {
217906f32e7eSjoerg       commit.insert(Loc, Entry.Text);
218006f32e7eSjoerg     } else if (Entry.Text.empty()) {
218106f32e7eSjoerg       commit.remove(Range);
218206f32e7eSjoerg     } else {
218306f32e7eSjoerg       commit.replace(Range, Entry.Text);
218406f32e7eSjoerg     }
218506f32e7eSjoerg     Editor.commit(commit);
218606f32e7eSjoerg   }
218706f32e7eSjoerg 
218806f32e7eSjoerg   Rewriter rewriter(SM, LangOpts);
218906f32e7eSjoerg   RewritesReceiver Rec(rewriter);
219006f32e7eSjoerg   Editor.applyRewrites(Rec, /*adjustRemovals=*/false);
219106f32e7eSjoerg 
219206f32e7eSjoerg   const RewriteBuffer *Buf = rewriter.getRewriteBufferFor(FID);
219306f32e7eSjoerg   SmallString<512> NewText;
219406f32e7eSjoerg   llvm::raw_svector_ostream OS(NewText);
219506f32e7eSjoerg   Buf->write(OS);
219606f32e7eSjoerg 
219706f32e7eSjoerg   SmallString<64> TempPath;
219806f32e7eSjoerg   int FD;
2199*13fbcb42Sjoerg   if (fs::createTemporaryFile(path::filename(FE.getName()),
2200*13fbcb42Sjoerg                               path::extension(FE.getName()).drop_front(), FD,
220106f32e7eSjoerg                               TempPath)) {
220206f32e7eSjoerg     reportDiag("Could not create file: " + TempPath.str(), Diag);
220306f32e7eSjoerg     return std::string();
220406f32e7eSjoerg   }
220506f32e7eSjoerg 
220606f32e7eSjoerg   llvm::raw_fd_ostream TmpOut(FD, /*shouldClose=*/true);
220706f32e7eSjoerg   TmpOut.write(NewText.data(), NewText.size());
220806f32e7eSjoerg   TmpOut.close();
220906f32e7eSjoerg 
2210*13fbcb42Sjoerg   return std::string(TempPath.str());
221106f32e7eSjoerg }
221206f32e7eSjoerg 
getFileRemappingsFromFileList(std::vector<std::pair<std::string,std::string>> & remap,ArrayRef<StringRef> remapFiles,DiagnosticConsumer * DiagClient)221306f32e7eSjoerg bool arcmt::getFileRemappingsFromFileList(
221406f32e7eSjoerg                         std::vector<std::pair<std::string,std::string> > &remap,
221506f32e7eSjoerg                         ArrayRef<StringRef> remapFiles,
221606f32e7eSjoerg                         DiagnosticConsumer *DiagClient) {
221706f32e7eSjoerg   bool hasErrorOccurred = false;
221806f32e7eSjoerg 
221906f32e7eSjoerg   FileSystemOptions FSOpts;
222006f32e7eSjoerg   FileManager FileMgr(FSOpts);
222106f32e7eSjoerg   RemapFileParser Parser(FileMgr);
222206f32e7eSjoerg 
222306f32e7eSjoerg   IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
222406f32e7eSjoerg   IntrusiveRefCntPtr<DiagnosticsEngine> Diags(
222506f32e7eSjoerg       new DiagnosticsEngine(DiagID, new DiagnosticOptions,
222606f32e7eSjoerg                             DiagClient, /*ShouldOwnClient=*/false));
222706f32e7eSjoerg 
2228*13fbcb42Sjoerg   typedef llvm::DenseMap<FileEntryRef, std::vector<EditEntry> >
222906f32e7eSjoerg       FileEditEntriesTy;
223006f32e7eSjoerg   FileEditEntriesTy FileEditEntries;
223106f32e7eSjoerg 
223206f32e7eSjoerg   llvm::DenseSet<EditEntry> EntriesSet;
223306f32e7eSjoerg 
223406f32e7eSjoerg   for (ArrayRef<StringRef>::iterator
223506f32e7eSjoerg          I = remapFiles.begin(), E = remapFiles.end(); I != E; ++I) {
223606f32e7eSjoerg     SmallVector<EditEntry, 16> Entries;
223706f32e7eSjoerg     if (Parser.parse(*I, Entries))
223806f32e7eSjoerg       continue;
223906f32e7eSjoerg 
224006f32e7eSjoerg     for (SmallVectorImpl<EditEntry>::iterator
224106f32e7eSjoerg            EI = Entries.begin(), EE = Entries.end(); EI != EE; ++EI) {
224206f32e7eSjoerg       EditEntry &Entry = *EI;
224306f32e7eSjoerg       if (!Entry.File)
224406f32e7eSjoerg         continue;
224506f32e7eSjoerg       std::pair<llvm::DenseSet<EditEntry>::iterator, bool>
224606f32e7eSjoerg         Insert = EntriesSet.insert(Entry);
224706f32e7eSjoerg       if (!Insert.second)
224806f32e7eSjoerg         continue;
224906f32e7eSjoerg 
2250*13fbcb42Sjoerg       FileEditEntries[*Entry.File].push_back(Entry);
225106f32e7eSjoerg     }
225206f32e7eSjoerg   }
225306f32e7eSjoerg 
225406f32e7eSjoerg   for (FileEditEntriesTy::iterator
225506f32e7eSjoerg          I = FileEditEntries.begin(), E = FileEditEntries.end(); I != E; ++I) {
225606f32e7eSjoerg     std::string TempFile = applyEditsToTemp(I->first, I->second,
225706f32e7eSjoerg                                             FileMgr, *Diags);
225806f32e7eSjoerg     if (TempFile.empty()) {
225906f32e7eSjoerg       hasErrorOccurred = true;
226006f32e7eSjoerg       continue;
226106f32e7eSjoerg     }
226206f32e7eSjoerg 
2263*13fbcb42Sjoerg     remap.emplace_back(std::string(I->first.getName()), TempFile);
226406f32e7eSjoerg   }
226506f32e7eSjoerg 
226606f32e7eSjoerg   return hasErrorOccurred;
226706f32e7eSjoerg }
2268