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