Coverage Report

Created: 2021-09-21 08:58

/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/lib/ARCMigrate/TransUnbridgedCasts.cpp
Line
Count
Source (jump to first uncovered line)
1
//===--- TransUnbridgedCasts.cpp - Transformations to ARC mode ------------===//
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
// rewriteUnbridgedCasts:
10
//
11
// A cast of non-objc pointer to an objc one is checked. If the non-objc pointer
12
// is from a file-level variable, __bridge cast is used to convert it.
13
// For the result of a function call that we know is +1/+0,
14
// __bridge/CFBridgingRelease is used.
15
//
16
//  NSString *str = (NSString *)kUTTypePlainText;
17
//  str = b ? kUTTypeRTF : kUTTypePlainText;
18
//  NSString *_uuidString = (NSString *)CFUUIDCreateString(kCFAllocatorDefault,
19
//                                                         _uuid);
20
// ---->
21
//  NSString *str = (__bridge NSString *)kUTTypePlainText;
22
//  str = (__bridge NSString *)(b ? kUTTypeRTF : kUTTypePlainText);
23
// NSString *_uuidString = (NSString *)
24
//            CFBridgingRelease(CFUUIDCreateString(kCFAllocatorDefault, _uuid));
25
//
26
// For a C pointer to ObjC, for casting 'self', __bridge is used.
27
//
28
//  CFStringRef str = (CFStringRef)self;
29
// ---->
30
//  CFStringRef str = (__bridge CFStringRef)self;
31
//
32
// Uses of Block_copy/Block_release macros are rewritten:
33
//
34
//  c = Block_copy(b);
35
//  Block_release(c);
36
// ---->
37
//  c = [b copy];
38
//  <removed>
39
//
40
//===----------------------------------------------------------------------===//
41
42
#include "Transforms.h"
43
#include "Internals.h"
44
#include "clang/AST/ASTContext.h"
45
#include "clang/AST/Attr.h"
46
#include "clang/AST/ParentMap.h"
47
#include "clang/Analysis/DomainSpecific/CocoaConventions.h"
48
#include "clang/Basic/SourceManager.h"
49
#include "clang/Lex/Lexer.h"
50
#include "clang/Sema/SemaDiagnostic.h"
51
#include "llvm/ADT/SmallString.h"
52
53
using namespace clang;
54
using namespace arcmt;
55
using namespace trans;
56
57
namespace {
58
59
class UnbridgedCastRewriter : public RecursiveASTVisitor<UnbridgedCastRewriter>{
60
  MigrationPass &Pass;
61
  IdentifierInfo *SelfII;
62
  std::unique_ptr<ParentMap> StmtMap;
63
  Decl *ParentD;
64
  Stmt *Body;
65
  mutable std::unique_ptr<ExprSet> Removables;
66
67
public:
68
  UnbridgedCastRewriter(MigrationPass &pass)
69
425
    : Pass(pass), ParentD(nullptr), Body(nullptr) {
70
425
    SelfII = &Pass.Ctx.Idents.get("self");
71
425
  }
72
73
425
  void transformBody(Stmt *body, Decl *ParentD) {
74
425
    this->ParentD = ParentD;
75
425
    Body = body;
76
425
    StmtMap.reset(new ParentMap(body));
77
425
    TraverseStmt(body);
78
425
  }
79
80
22
  bool TraverseBlockDecl(BlockDecl *D) {
81
    // ParentMap does not enter into a BlockDecl to record its stmts, so use a
82
    // new UnbridgedCastRewriter to handle the block.
83
22
    UnbridgedCastRewriter(Pass).transformBody(D->getBody(), D);
84
22
    return true;
85
22
  }
86
87
1.87k
  bool VisitCastExpr(CastExpr *E) {
88
1.87k
    if (E->getCastKind() != CK_CPointerToObjCPointerCast &&
89
1.87k
        
E->getCastKind() != CK_BitCast1.79k
&&
90
1.87k
        
E->getCastKind() != CK_AnyPointerToBlockPointerCast1.57k
)
91
1.56k
      return true;
92
93
307
    QualType castType = E->getType();
94
307
    Expr *castExpr = E->getSubExpr();
95
307
    QualType castExprType = castExpr->getType();
96
97
307
    if (castType->isObjCRetainableType() == castExprType->isObjCRetainableType())
98
127
      return true;
99
100
180
    bool exprRetainable = castExprType->isObjCIndirectLifetimeType();
101
180
    bool castRetainable = castType->isObjCIndirectLifetimeType();
102
180
    if (exprRetainable == castRetainable) 
return true2
;
103
104
178
    if (castExpr->isNullPointerConstant(Pass.Ctx,
105
178
                                        Expr::NPC_ValueDependentIsNull))
106
0
      return true;
107
108
178
    SourceLocation loc = castExpr->getExprLoc();
109
178
    if (loc.isValid() && Pass.Ctx.getSourceManager().isInSystemHeader(loc))
110
0
      return true;
111
112
178
    if (castType->isObjCRetainableType())
113
85
      transformNonObjCToObjCCast(E);
114
93
    else
115
93
      transformObjCToNonObjCCast(E);
116
117
178
    return true;
118
178
  }
119
120
private:
121
85
  void transformNonObjCToObjCCast(CastExpr *E) {
122
85
    if (!E) 
return0
;
123
124
    // Global vars are assumed that are cast as unretained.
125
85
    if (isGlobalVar(E))
126
14
      if (E->getSubExpr()->getType()->isPointerType()) {
127
14
        castToObjCObject(E, /*retained=*/false);
128
14
        return;
129
14
      }
130
131
    // If the cast is directly over the result of a Core Foundation function
132
    // try to figure out whether it should be cast as retained or unretained.
133
71
    Expr *inner = E->IgnoreParenCasts();
134
71
    if (CallExpr *callE = dyn_cast<CallExpr>(inner)) {
135
17
      if (FunctionDecl *FD = callE->getDirectCallee()) {
136
17
        if (FD->hasAttr<CFReturnsRetainedAttr>()) {
137
0
          castToObjCObject(E, /*retained=*/true);
138
0
          return;
139
0
        }
140
17
        if (FD->hasAttr<CFReturnsNotRetainedAttr>()) {
141
0
          castToObjCObject(E, /*retained=*/false);
142
0
          return;
143
0
        }
144
17
        if (FD->isGlobal() &&
145
17
            FD->getIdentifier() &&
146
17
            ento::cocoa::isRefType(E->getSubExpr()->getType(), "CF",
147
17
                                   FD->getIdentifier()->getName())) {
148
13
          StringRef fname = FD->getIdentifier()->getName();
149
13
          if (fname.endswith("Retain") ||
150
13
              
fname.find("Create") != StringRef::npos4
||
151
13
              
fname.find("Copy") != StringRef::npos0
) {
152
            // Do not migrate to couple of bridge transfer casts which
153
            // cancel each other out. Leave it unchanged so error gets user
154
            // attention instead.
155
13
            if (FD->getName() == "CFRetain" &&
156
13
                
FD->getNumParams() == 19
&&
157
13
                
FD->getParent()->isTranslationUnit()9
&&
158
13
                
FD->isExternallyVisible()9
) {
159
9
              Expr *Arg = callE->getArg(0);
160
9
              if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg)) {
161
8
                const Expr *sub = ICE->getSubExpr();
162
8
                QualType T = sub->getType();
163
8
                if (T->isObjCObjectPointerType())
164
3
                  return;
165
8
              }
166
9
            }
167
10
            castToObjCObject(E, /*retained=*/true);
168
10
            return;
169
13
          }
170
171
0
          if (fname.find("Get") != StringRef::npos) {
172
0
            castToObjCObject(E, /*retained=*/false);
173
0
            return;
174
0
          }
175
0
        }
176
17
      }
177
17
    }
178
179
    // If returning an ivar or a member of an ivar from a +0 method, use
180
    // a __bridge cast.
181
58
    Expr *base = inner->IgnoreParenImpCasts();
182
61
    while (isa<MemberExpr>(base))
183
3
      base = cast<MemberExpr>(base)->getBase()->IgnoreParenImpCasts();
184
58
    if (isa<ObjCIvarRefExpr>(base) &&
185
58
        
isa<ReturnStmt>(StmtMap->getParentIgnoreParenCasts(E))9
) {
186
7
      if (ObjCMethodDecl *method = dyn_cast_or_null<ObjCMethodDecl>(ParentD)) {
187
7
        if (!method->hasAttr<NSReturnsRetainedAttr>()) {
188
6
          castToObjCObject(E, /*retained=*/false);
189
6
          return;
190
6
        }
191
7
      }
192
7
    }
193
58
  }
194
195
30
  void castToObjCObject(CastExpr *E, bool retained) {
196
30
    rewriteToBridgedCast(E, retained ? 
OBC_BridgeTransfer10
:
OBC_Bridge20
);
197
30
  }
198
199
57
  void rewriteToBridgedCast(CastExpr *E, ObjCBridgeCastKind Kind) {
200
57
    Transaction Trans(Pass.TA);
201
57
    rewriteToBridgedCast(E, Kind, Trans);
202
57
  }
203
204
  void rewriteToBridgedCast(CastExpr *E, ObjCBridgeCastKind Kind,
205
67
                            Transaction &Trans) {
206
67
    TransformActions &TA = Pass.TA;
207
208
    // We will remove the compiler diagnostic.
209
67
    if (!TA.hasDiagnostic(diag::err_arc_mismatched_cast,
210
67
                          diag::err_arc_cast_requires_bridge,
211
67
                          E->getBeginLoc())) {
212
8
      Trans.abort();
213
8
      return;
214
8
    }
215
216
59
    StringRef bridge;
217
59
    switch(Kind) {
218
23
    case OBC_Bridge:
219
23
      bridge = "__bridge "; break;
220
10
    case OBC_BridgeTransfer:
221
10
      bridge = "__bridge_transfer "; break;
222
26
    case OBC_BridgeRetained:
223
26
      bridge = "__bridge_retained "; break;
224
59
    }
225
226
59
    TA.clearDiagnostic(diag::err_arc_mismatched_cast,
227
59
                       diag::err_arc_cast_requires_bridge, E->getBeginLoc());
228
59
    if (Kind == OBC_Bridge || 
!Pass.CFBridgingFunctionsDefined()36
) {
229
23
      if (CStyleCastExpr *CCE = dyn_cast<CStyleCastExpr>(E)) {
230
9
        TA.insertAfterToken(CCE->getLParenLoc(), bridge);
231
14
      } else {
232
14
        SourceLocation insertLoc = E->getSubExpr()->getBeginLoc();
233
14
        SmallString<128> newCast;
234
14
        newCast += '(';
235
14
        newCast += bridge;
236
14
        newCast += E->getType().getAsString(Pass.Ctx.getPrintingPolicy());
237
14
        newCast += ')';
238
239
14
        if (isa<ParenExpr>(E->getSubExpr())) {
240
0
          TA.insert(insertLoc, newCast.str());
241
14
        } else {
242
14
          newCast += '(';
243
14
          TA.insert(insertLoc, newCast.str());
244
14
          TA.insertAfterToken(E->getEndLoc(), ")");
245
14
        }
246
14
      }
247
36
    } else {
248
36
      assert(Kind == OBC_BridgeTransfer || Kind == OBC_BridgeRetained);
249
0
      SmallString<32> BridgeCall;
250
251
36
      Expr *WrapE = E->getSubExpr();
252
36
      SourceLocation InsertLoc = WrapE->getBeginLoc();
253
254
36
      SourceManager &SM = Pass.Ctx.getSourceManager();
255
36
      char PrevChar = *SM.getCharacterData(InsertLoc.getLocWithOffset(-1));
256
36
      if (Lexer::isAsciiIdentifierContinueChar(PrevChar,
257
36
                                               Pass.Ctx.getLangOpts()))
258
0
        BridgeCall += ' ';
259
260
36
      if (Kind == OBC_BridgeTransfer)
261
10
        BridgeCall += "CFBridgingRelease";
262
26
      else
263
26
        BridgeCall += "CFBridgingRetain";
264
265
36
      if (isa<ParenExpr>(WrapE)) {
266
0
        TA.insert(InsertLoc, BridgeCall);
267
36
      } else {
268
36
        BridgeCall += '(';
269
36
        TA.insert(InsertLoc, BridgeCall);
270
36
        TA.insertAfterToken(WrapE->getEndLoc(), ")");
271
36
      }
272
36
    }
273
59
  }
274
275
10
  void rewriteCastForCFRetain(CastExpr *castE, CallExpr *callE) {
276
10
    Transaction Trans(Pass.TA);
277
10
    Pass.TA.replace(callE->getSourceRange(), callE->getArg(0)->getSourceRange());
278
10
    rewriteToBridgedCast(castE, OBC_BridgeRetained, Trans);
279
10
  }
280
281
8
  void getBlockMacroRanges(CastExpr *E, SourceRange &Outer, SourceRange &Inner) {
282
8
    SourceManager &SM = Pass.Ctx.getSourceManager();
283
8
    SourceLocation Loc = E->getExprLoc();
284
8
    assert(Loc.isMacroID());
285
0
    CharSourceRange MacroRange = SM.getImmediateExpansionRange(Loc);
286
8
    SourceRange SubRange = E->getSubExpr()->IgnoreParenImpCasts()->getSourceRange();
287
8
    SourceLocation InnerBegin = SM.getImmediateMacroCallerLoc(SubRange.getBegin());
288
8
    SourceLocation InnerEnd = SM.getImmediateMacroCallerLoc(SubRange.getEnd());
289
290
8
    Outer = MacroRange.getAsRange();
291
8
    Inner = SourceRange(InnerBegin, InnerEnd);
292
8
  }
293
294
4
  void rewriteBlockCopyMacro(CastExpr *E) {
295
4
    SourceRange OuterRange, InnerRange;
296
4
    getBlockMacroRanges(E, OuterRange, InnerRange);
297
298
4
    Transaction Trans(Pass.TA);
299
4
    Pass.TA.replace(OuterRange, InnerRange);
300
4
    Pass.TA.insert(InnerRange.getBegin(), "[");
301
4
    Pass.TA.insertAfterToken(InnerRange.getEnd(), " copy]");
302
4
    Pass.TA.clearDiagnostic(diag::err_arc_mismatched_cast,
303
4
                            diag::err_arc_cast_requires_bridge,
304
4
                            OuterRange);
305
4
  }
306
307
4
  void removeBlockReleaseMacro(CastExpr *E) {
308
4
    SourceRange OuterRange, InnerRange;
309
4
    getBlockMacroRanges(E, OuterRange, InnerRange);
310
311
4
    Transaction Trans(Pass.TA);
312
4
    Pass.TA.clearDiagnostic(diag::err_arc_mismatched_cast,
313
4
                            diag::err_arc_cast_requires_bridge,
314
4
                            OuterRange);
315
4
    if (!hasSideEffects(E, Pass.Ctx)) {
316
4
      if (tryRemoving(cast<Expr>(StmtMap->getParentIgnoreParenCasts(E))))
317
4
        return;
318
4
    }
319
0
    Pass.TA.replace(OuterRange, InnerRange);
320
0
  }
321
322
4
  bool tryRemoving(Expr *E) const {
323
4
    if (!Removables) {
324
4
      Removables.reset(new ExprSet);
325
4
      collectRemovables(Body, *Removables);
326
4
    }
327
328
4
    if (Removables->count(E)) {
329
4
      Pass.TA.removeStmt(E);
330
4
      return true;
331
4
    }
332
333
0
    return false;
334
4
  }
335
336
93
  void transformObjCToNonObjCCast(CastExpr *E) {
337
93
    SourceLocation CastLoc = E->getExprLoc();
338
93
    if (CastLoc.isMacroID()) {
339
8
      StringRef MacroName = Lexer::getImmediateMacroName(CastLoc,
340
8
                                                    Pass.Ctx.getSourceManager(),
341
8
                                                    Pass.Ctx.getLangOpts());
342
8
      if (MacroName == "Block_copy") {
343
4
        rewriteBlockCopyMacro(E);
344
4
        return;
345
4
      }
346
4
      if (MacroName == "Block_release") {
347
4
        removeBlockReleaseMacro(E);
348
4
        return;
349
4
      }
350
4
    }
351
352
85
    if (isSelf(E->getSubExpr()))
353
4
      return rewriteToBridgedCast(E, OBC_Bridge);
354
355
81
    CallExpr *callE;
356
81
    if (isPassedToCFRetain(E, callE))
357
10
      return rewriteCastForCFRetain(E, callE);
358
359
71
    ObjCMethodFamily family = getFamilyOfMessage(E->getSubExpr());
360
71
    if (family == OMF_retain)
361
4
      return rewriteToBridgedCast(E, OBC_BridgeRetained);
362
363
67
    if (family == OMF_autorelease || 
family == OMF_release66
) {
364
1
      std::string err = "it is not safe to cast to '";
365
1
      err += E->getType().getAsString(Pass.Ctx.getPrintingPolicy());
366
1
      err += "' the result of '";
367
1
      err += family == OMF_autorelease ? "autorelease" : 
"release"0
;
368
1
      err += "' message; a __bridge cast may result in a pointer to a "
369
1
          "destroyed object and a __bridge_retained may leak the object";
370
1
      Pass.TA.reportError(err, E->getBeginLoc(),
371
1
                          E->getSubExpr()->getSourceRange());
372
1
      Stmt *parent = E;
373
1
      do {
374
1
        parent = StmtMap->getParentIgnoreParenImpCasts(parent);
375
1
      } while (parent && isa<FullExpr>(parent));
376
377
1
      if (ReturnStmt *retS = dyn_cast_or_null<ReturnStmt>(parent)) {
378
1
        std::string note = "remove the cast and change return type of function "
379
1
            "to '";
380
1
        note += E->getSubExpr()->getType().getAsString(Pass.Ctx.getPrintingPolicy());
381
1
        note += "' to have the object automatically autoreleased";
382
1
        Pass.TA.reportNote(note, retS->getBeginLoc());
383
1
      }
384
1
    }
385
386
67
    Expr *subExpr = E->getSubExpr();
387
388
    // Look through pseudo-object expressions.
389
67
    if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(subExpr)) {
390
2
      subExpr = pseudo->getResultExpr();
391
2
      assert(subExpr && "no result for pseudo-object of non-void type?");
392
2
    }
393
394
67
    if (ImplicitCastExpr *implCE = dyn_cast<ImplicitCastExpr>(subExpr)) {
395
67
      if (implCE->getCastKind() == CK_ARCConsumeObject)
396
8
        return rewriteToBridgedCast(E, OBC_BridgeRetained);
397
59
      if (implCE->getCastKind() == CK_ARCReclaimReturnedObject)
398
7
        return rewriteToBridgedCast(E, OBC_Bridge);
399
59
    }
400
401
52
    bool isConsumed = false;
402
52
    if (isPassedToCParamWithKnownOwnership(E, isConsumed))
403
4
      return rewriteToBridgedCast(E, isConsumed ? OBC_BridgeRetained
404
4
                                                : 
OBC_Bridge0
);
405
52
  }
406
407
71
  static ObjCMethodFamily getFamilyOfMessage(Expr *E) {
408
71
    E = E->IgnoreParenCasts();
409
71
    if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(E))
410
17
      return ME->getMethodFamily();
411
412
54
    return OMF_None;
413
71
  }
414
415
81
  bool isPassedToCFRetain(Expr *E, CallExpr *&callE) const {
416
81
    if ((callE = dyn_cast_or_null<CallExpr>(
417
81
                                     StmtMap->getParentIgnoreParenImpCasts(E))))
418
16
      if (FunctionDecl *
419
16
            FD = dyn_cast_or_null<FunctionDecl>(callE->getCalleeDecl()))
420
16
        if (FD->getName() == "CFRetain" && 
FD->getNumParams() == 110
&&
421
16
            
FD->getParent()->isTranslationUnit()10
&&
422
16
            
FD->isExternallyVisible()10
)
423
10
          return true;
424
425
71
    return false;
426
81
  }
427
428
52
  bool isPassedToCParamWithKnownOwnership(Expr *E, bool &isConsumed) const {
429
52
    if (CallExpr *callE = dyn_cast_or_null<CallExpr>(
430
52
                                     StmtMap->getParentIgnoreParenImpCasts(E)))
431
6
      if (FunctionDecl *
432
6
            FD = dyn_cast_or_null<FunctionDecl>(callE->getCalleeDecl())) {
433
6
        unsigned i = 0;
434
7
        for (unsigned e = callE->getNumArgs(); i != e; 
++i1
) {
435
7
          Expr *arg = callE->getArg(i);
436
7
          if (arg == E || 
arg->IgnoreParenImpCasts() == E2
)
437
6
            break;
438
7
        }
439
6
        if (i < callE->getNumArgs() && i < FD->getNumParams()) {
440
5
          ParmVarDecl *PD = FD->getParamDecl(i);
441
5
          if (PD->hasAttr<CFConsumedAttr>()) {
442
4
            isConsumed = true;
443
4
            return true;
444
4
          }
445
5
        }
446
6
      }
447
448
48
    return false;
449
52
  }
450
451
85
  bool isSelf(Expr *E) const {
452
85
    E = E->IgnoreParenLValueCasts();
453
85
    if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
454
16
      if (ImplicitParamDecl *IPD = dyn_cast<ImplicitParamDecl>(DRE->getDecl()))
455
4
        if (IPD->getIdentifier() == SelfII)
456
4
          return true;
457
458
81
    return false;
459
85
  }
460
};
461
462
} // end anonymous namespace
463
464
85
void trans::rewriteUnbridgedCasts(MigrationPass &pass) {
465
85
  BodyTransform<UnbridgedCastRewriter> trans(pass);
466
85
  trans.TraverseDecl(pass.Ctx.getTranslationUnitDecl());
467
85
}