Coverage Report

Created: 2021-08-24 07:12

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