TransGCAttrs.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350
  1. //===--- TransGCAttrs.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. #include "Transforms.h"
  9. #include "Internals.h"
  10. #include "clang/AST/ASTContext.h"
  11. #include "clang/Basic/SourceManager.h"
  12. #include "clang/Lex/Lexer.h"
  13. #include "clang/Sema/SemaDiagnostic.h"
  14. #include "llvm/ADT/SmallString.h"
  15. #include "llvm/ADT/TinyPtrVector.h"
  16. #include "llvm/Support/SaveAndRestore.h"
  17. using namespace clang;
  18. using namespace arcmt;
  19. using namespace trans;
  20. namespace {
  21. /// Collects all the places where GC attributes __strong/__weak occur.
  22. class GCAttrsCollector : public RecursiveASTVisitor<GCAttrsCollector> {
  23. MigrationContext &MigrateCtx;
  24. bool FullyMigratable;
  25. std::vector<ObjCPropertyDecl *> &AllProps;
  26. typedef RecursiveASTVisitor<GCAttrsCollector> base;
  27. public:
  28. GCAttrsCollector(MigrationContext &ctx,
  29. std::vector<ObjCPropertyDecl *> &AllProps)
  30. : MigrateCtx(ctx), FullyMigratable(false),
  31. AllProps(AllProps) { }
  32. bool shouldWalkTypesOfTypeLocs() const { return false; }
  33. bool VisitAttributedTypeLoc(AttributedTypeLoc TL) {
  34. handleAttr(TL);
  35. return true;
  36. }
  37. bool TraverseDecl(Decl *D) {
  38. if (!D || D->isImplicit())
  39. return true;
  40. SaveAndRestore Save(FullyMigratable, isMigratable(D));
  41. if (ObjCPropertyDecl *PropD = dyn_cast<ObjCPropertyDecl>(D)) {
  42. lookForAttribute(PropD, PropD->getTypeSourceInfo());
  43. AllProps.push_back(PropD);
  44. } else if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
  45. lookForAttribute(DD, DD->getTypeSourceInfo());
  46. }
  47. return base::TraverseDecl(D);
  48. }
  49. void lookForAttribute(Decl *D, TypeSourceInfo *TInfo) {
  50. if (!TInfo)
  51. return;
  52. TypeLoc TL = TInfo->getTypeLoc();
  53. while (TL) {
  54. if (QualifiedTypeLoc QL = TL.getAs<QualifiedTypeLoc>()) {
  55. TL = QL.getUnqualifiedLoc();
  56. } else if (AttributedTypeLoc Attr = TL.getAs<AttributedTypeLoc>()) {
  57. if (handleAttr(Attr, D))
  58. break;
  59. TL = Attr.getModifiedLoc();
  60. } else if (MacroQualifiedTypeLoc MDTL =
  61. TL.getAs<MacroQualifiedTypeLoc>()) {
  62. TL = MDTL.getInnerLoc();
  63. } else if (ArrayTypeLoc Arr = TL.getAs<ArrayTypeLoc>()) {
  64. TL = Arr.getElementLoc();
  65. } else if (PointerTypeLoc PT = TL.getAs<PointerTypeLoc>()) {
  66. TL = PT.getPointeeLoc();
  67. } else if (ReferenceTypeLoc RT = TL.getAs<ReferenceTypeLoc>())
  68. TL = RT.getPointeeLoc();
  69. else
  70. break;
  71. }
  72. }
  73. bool handleAttr(AttributedTypeLoc TL, Decl *D = nullptr) {
  74. auto *OwnershipAttr = TL.getAttrAs<ObjCOwnershipAttr>();
  75. if (!OwnershipAttr)
  76. return false;
  77. SourceLocation Loc = OwnershipAttr->getLocation();
  78. SourceLocation OrigLoc = Loc;
  79. if (MigrateCtx.AttrSet.count(OrigLoc))
  80. return true;
  81. ASTContext &Ctx = MigrateCtx.Pass.Ctx;
  82. SourceManager &SM = Ctx.getSourceManager();
  83. if (Loc.isMacroID())
  84. Loc = SM.getImmediateExpansionRange(Loc).getBegin();
  85. StringRef Spell = OwnershipAttr->getKind()->getName();
  86. MigrationContext::GCAttrOccurrence::AttrKind Kind;
  87. if (Spell == "strong")
  88. Kind = MigrationContext::GCAttrOccurrence::Strong;
  89. else if (Spell == "weak")
  90. Kind = MigrationContext::GCAttrOccurrence::Weak;
  91. else
  92. return false;
  93. MigrateCtx.AttrSet.insert(OrigLoc);
  94. MigrateCtx.GCAttrs.push_back(MigrationContext::GCAttrOccurrence());
  95. MigrationContext::GCAttrOccurrence &Attr = MigrateCtx.GCAttrs.back();
  96. Attr.Kind = Kind;
  97. Attr.Loc = Loc;
  98. Attr.ModifiedType = TL.getModifiedLoc().getType();
  99. Attr.Dcl = D;
  100. Attr.FullyMigratable = FullyMigratable;
  101. return true;
  102. }
  103. bool isMigratable(Decl *D) {
  104. if (isa<TranslationUnitDecl>(D))
  105. return false;
  106. if (isInMainFile(D))
  107. return true;
  108. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
  109. return FD->hasBody();
  110. if (ObjCContainerDecl *ContD = dyn_cast<ObjCContainerDecl>(D))
  111. return hasObjCImpl(ContD);
  112. if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
  113. for (const auto *MI : RD->methods()) {
  114. if (MI->isOutOfLine())
  115. return true;
  116. }
  117. return false;
  118. }
  119. return isMigratable(cast<Decl>(D->getDeclContext()));
  120. }
  121. static bool hasObjCImpl(Decl *D) {
  122. if (!D)
  123. return false;
  124. if (ObjCContainerDecl *ContD = dyn_cast<ObjCContainerDecl>(D)) {
  125. if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(ContD))
  126. return ID->getImplementation() != nullptr;
  127. if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(ContD))
  128. return CD->getImplementation() != nullptr;
  129. return isa<ObjCImplDecl>(ContD);
  130. }
  131. return false;
  132. }
  133. bool isInMainFile(Decl *D) {
  134. if (!D)
  135. return false;
  136. for (auto *I : D->redecls())
  137. if (!isInMainFile(I->getLocation()))
  138. return false;
  139. return true;
  140. }
  141. bool isInMainFile(SourceLocation Loc) {
  142. if (Loc.isInvalid())
  143. return false;
  144. SourceManager &SM = MigrateCtx.Pass.Ctx.getSourceManager();
  145. return SM.isInFileID(SM.getExpansionLoc(Loc), SM.getMainFileID());
  146. }
  147. };
  148. } // anonymous namespace
  149. static void errorForGCAttrsOnNonObjC(MigrationContext &MigrateCtx) {
  150. TransformActions &TA = MigrateCtx.Pass.TA;
  151. for (unsigned i = 0, e = MigrateCtx.GCAttrs.size(); i != e; ++i) {
  152. MigrationContext::GCAttrOccurrence &Attr = MigrateCtx.GCAttrs[i];
  153. if (Attr.FullyMigratable && Attr.Dcl) {
  154. if (Attr.ModifiedType.isNull())
  155. continue;
  156. if (!Attr.ModifiedType->isObjCRetainableType()) {
  157. TA.reportError("GC managed memory will become unmanaged in ARC",
  158. Attr.Loc);
  159. }
  160. }
  161. }
  162. }
  163. static void checkWeakGCAttrs(MigrationContext &MigrateCtx) {
  164. TransformActions &TA = MigrateCtx.Pass.TA;
  165. for (unsigned i = 0, e = MigrateCtx.GCAttrs.size(); i != e; ++i) {
  166. MigrationContext::GCAttrOccurrence &Attr = MigrateCtx.GCAttrs[i];
  167. if (Attr.Kind == MigrationContext::GCAttrOccurrence::Weak) {
  168. if (Attr.ModifiedType.isNull() ||
  169. !Attr.ModifiedType->isObjCRetainableType())
  170. continue;
  171. if (!canApplyWeak(MigrateCtx.Pass.Ctx, Attr.ModifiedType,
  172. /*AllowOnUnknownClass=*/true)) {
  173. Transaction Trans(TA);
  174. if (!MigrateCtx.RemovedAttrSet.count(Attr.Loc))
  175. TA.replaceText(Attr.Loc, "__weak", "__unsafe_unretained");
  176. TA.clearDiagnostic(diag::err_arc_weak_no_runtime,
  177. diag::err_arc_unsupported_weak_class,
  178. Attr.Loc);
  179. }
  180. }
  181. }
  182. }
  183. typedef llvm::TinyPtrVector<ObjCPropertyDecl *> IndivPropsTy;
  184. static void checkAllAtProps(MigrationContext &MigrateCtx,
  185. SourceLocation AtLoc,
  186. IndivPropsTy &IndProps) {
  187. if (IndProps.empty())
  188. return;
  189. for (IndivPropsTy::iterator
  190. PI = IndProps.begin(), PE = IndProps.end(); PI != PE; ++PI) {
  191. QualType T = (*PI)->getType();
  192. if (T.isNull() || !T->isObjCRetainableType())
  193. return;
  194. }
  195. SmallVector<std::pair<AttributedTypeLoc, ObjCPropertyDecl *>, 4> ATLs;
  196. bool hasWeak = false, hasStrong = false;
  197. ObjCPropertyAttribute::Kind Attrs = ObjCPropertyAttribute::kind_noattr;
  198. for (IndivPropsTy::iterator
  199. PI = IndProps.begin(), PE = IndProps.end(); PI != PE; ++PI) {
  200. ObjCPropertyDecl *PD = *PI;
  201. Attrs = PD->getPropertyAttributesAsWritten();
  202. TypeSourceInfo *TInfo = PD->getTypeSourceInfo();
  203. if (!TInfo)
  204. return;
  205. TypeLoc TL = TInfo->getTypeLoc();
  206. if (AttributedTypeLoc ATL =
  207. TL.getAs<AttributedTypeLoc>()) {
  208. ATLs.push_back(std::make_pair(ATL, PD));
  209. if (TInfo->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
  210. hasWeak = true;
  211. } else if (TInfo->getType().getObjCLifetime() == Qualifiers::OCL_Strong)
  212. hasStrong = true;
  213. else
  214. return;
  215. }
  216. }
  217. if (ATLs.empty())
  218. return;
  219. if (hasWeak && hasStrong)
  220. return;
  221. TransformActions &TA = MigrateCtx.Pass.TA;
  222. Transaction Trans(TA);
  223. if (GCAttrsCollector::hasObjCImpl(
  224. cast<Decl>(IndProps.front()->getDeclContext()))) {
  225. if (hasWeak)
  226. MigrateCtx.AtPropsWeak.insert(AtLoc);
  227. } else {
  228. StringRef toAttr = "strong";
  229. if (hasWeak) {
  230. if (canApplyWeak(MigrateCtx.Pass.Ctx, IndProps.front()->getType(),
  231. /*AllowOnUnknownClass=*/true))
  232. toAttr = "weak";
  233. else
  234. toAttr = "unsafe_unretained";
  235. }
  236. if (Attrs & ObjCPropertyAttribute::kind_assign)
  237. MigrateCtx.rewritePropertyAttribute("assign", toAttr, AtLoc);
  238. else
  239. MigrateCtx.addPropertyAttribute(toAttr, AtLoc);
  240. }
  241. for (unsigned i = 0, e = ATLs.size(); i != e; ++i) {
  242. SourceLocation Loc = ATLs[i].first.getAttr()->getLocation();
  243. if (Loc.isMacroID())
  244. Loc = MigrateCtx.Pass.Ctx.getSourceManager()
  245. .getImmediateExpansionRange(Loc)
  246. .getBegin();
  247. TA.remove(Loc);
  248. TA.clearDiagnostic(diag::err_objc_property_attr_mutually_exclusive, AtLoc);
  249. TA.clearDiagnostic(diag::err_arc_inconsistent_property_ownership,
  250. ATLs[i].second->getLocation());
  251. MigrateCtx.RemovedAttrSet.insert(Loc);
  252. }
  253. }
  254. static void checkAllProps(MigrationContext &MigrateCtx,
  255. std::vector<ObjCPropertyDecl *> &AllProps) {
  256. typedef llvm::TinyPtrVector<ObjCPropertyDecl *> IndivPropsTy;
  257. llvm::DenseMap<SourceLocation, IndivPropsTy> AtProps;
  258. for (unsigned i = 0, e = AllProps.size(); i != e; ++i) {
  259. ObjCPropertyDecl *PD = AllProps[i];
  260. if (PD->getPropertyAttributesAsWritten() &
  261. (ObjCPropertyAttribute::kind_assign |
  262. ObjCPropertyAttribute::kind_readonly)) {
  263. SourceLocation AtLoc = PD->getAtLoc();
  264. if (AtLoc.isInvalid())
  265. continue;
  266. AtProps[AtLoc].push_back(PD);
  267. }
  268. }
  269. for (auto I = AtProps.begin(), E = AtProps.end(); I != E; ++I) {
  270. SourceLocation AtLoc = I->first;
  271. IndivPropsTy &IndProps = I->second;
  272. checkAllAtProps(MigrateCtx, AtLoc, IndProps);
  273. }
  274. }
  275. void GCAttrsTraverser::traverseTU(MigrationContext &MigrateCtx) {
  276. std::vector<ObjCPropertyDecl *> AllProps;
  277. GCAttrsCollector(MigrateCtx, AllProps).TraverseDecl(
  278. MigrateCtx.Pass.Ctx.getTranslationUnitDecl());
  279. errorForGCAttrsOnNonObjC(MigrateCtx);
  280. checkAllProps(MigrateCtx, AllProps);
  281. checkWeakGCAttrs(MigrateCtx);
  282. }
  283. void MigrationContext::dumpGCAttrs() {
  284. llvm::errs() << "\n################\n";
  285. for (unsigned i = 0, e = GCAttrs.size(); i != e; ++i) {
  286. GCAttrOccurrence &Attr = GCAttrs[i];
  287. llvm::errs() << "KIND: "
  288. << (Attr.Kind == GCAttrOccurrence::Strong ? "strong" : "weak");
  289. llvm::errs() << "\nLOC: ";
  290. Attr.Loc.print(llvm::errs(), Pass.Ctx.getSourceManager());
  291. llvm::errs() << "\nTYPE: ";
  292. Attr.ModifiedType.dump();
  293. if (Attr.Dcl) {
  294. llvm::errs() << "DECL:\n";
  295. Attr.Dcl->dump();
  296. } else {
  297. llvm::errs() << "DECL: NONE";
  298. }
  299. llvm::errs() << "\nMIGRATABLE: " << Attr.FullyMigratable;
  300. llvm::errs() << "\n----------------\n";
  301. }
  302. llvm::errs() << "\n################\n";
  303. }