Coverage Report

Created: 2020-02-25 14:32

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