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