blob: 7b1f20408d5e077a05abc1aada9577177eed6363 [file] [log] [blame]
Fangrui Song524b3c12019-03-01 06:49:51 +00001//===-- RewriteModernObjC.cpp - Playground for the code rewriter ----------===//
Fariborz Jahanian11671902012-02-07 17:11:38 +00002//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// 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
Fariborz Jahanian11671902012-02-07 17:11:38 +00006//
7//===----------------------------------------------------------------------===//
8//
9// Hacks and fun related to the code rewriter.
10//
11//===----------------------------------------------------------------------===//
12
Ted Kremenekcdf81492012-09-01 05:09:24 +000013#include "clang/Rewrite/Frontend/ASTConsumers.h"
Fariborz Jahanian11671902012-02-07 17:11:38 +000014#include "clang/AST/AST.h"
15#include "clang/AST/ASTConsumer.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000016#include "clang/AST/Attr.h"
Fariborz Jahanian11671902012-02-07 17:11:38 +000017#include "clang/AST/ParentMap.h"
Jordan Rosea7d03842013-02-08 22:30:41 +000018#include "clang/Basic/CharInfo.h"
Fariborz Jahanian11671902012-02-07 17:11:38 +000019#include "clang/Basic/Diagnostic.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000020#include "clang/Basic/IdentifierTable.h"
21#include "clang/Basic/SourceManager.h"
Benjamin Kramerd7d2b1f2012-12-01 16:35:25 +000022#include "clang/Basic/TargetInfo.h"
NAKAMURA Takumi7f633df2017-07-18 08:55:03 +000023#include "clang/Config/config.h"
Fariborz Jahanian11671902012-02-07 17:11:38 +000024#include "clang/Lex/Lexer.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000025#include "clang/Rewrite/Core/Rewriter.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000026#include "llvm/ADT/DenseSet.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000027#include "llvm/ADT/SmallPtrSet.h"
28#include "llvm/ADT/StringExtras.h"
Fariborz Jahanian11671902012-02-07 17:11:38 +000029#include "llvm/Support/MemoryBuffer.h"
30#include "llvm/Support/raw_ostream.h"
Ahmed Charlesdfca6f92014-03-09 11:36:40 +000031#include <memory>
Fariborz Jahanian11671902012-02-07 17:11:38 +000032
NAKAMURA Takumid9739822017-10-18 05:21:17 +000033#if CLANG_ENABLE_OBJC_REWRITER
Alp Toker0621cb22014-07-16 16:48:33 +000034
Fariborz Jahanian11671902012-02-07 17:11:38 +000035using namespace clang;
36using llvm::utostr;
37
38namespace {
39 class RewriteModernObjC : public ASTConsumer {
40 protected:
Fangrui Song6907ce22018-07-30 19:24:48 +000041
Fariborz Jahanian11671902012-02-07 17:11:38 +000042 enum {
43 BLOCK_FIELD_IS_OBJECT = 3, /* id, NSObject, __attribute__((NSObject)),
44 block, ... */
45 BLOCK_FIELD_IS_BLOCK = 7, /* a block variable */
Fangrui Song6907ce22018-07-30 19:24:48 +000046 BLOCK_FIELD_IS_BYREF = 8, /* the on stack structure holding the
Fariborz Jahanian11671902012-02-07 17:11:38 +000047 __block variable */
48 BLOCK_FIELD_IS_WEAK = 16, /* declared __weak, only used in byref copy
49 helpers */
50 BLOCK_BYREF_CALLER = 128, /* called from __block (byref) copy/dispose
51 support routines */
52 BLOCK_BYREF_CURRENT_MAX = 256
53 };
Fangrui Song6907ce22018-07-30 19:24:48 +000054
Fariborz Jahanian11671902012-02-07 17:11:38 +000055 enum {
56 BLOCK_NEEDS_FREE = (1 << 24),
57 BLOCK_HAS_COPY_DISPOSE = (1 << 25),
58 BLOCK_HAS_CXX_OBJ = (1 << 26),
59 BLOCK_IS_GC = (1 << 27),
60 BLOCK_IS_GLOBAL = (1 << 28),
61 BLOCK_HAS_DESCRIPTOR = (1 << 29)
62 };
Fangrui Song6907ce22018-07-30 19:24:48 +000063
Fariborz Jahanian11671902012-02-07 17:11:38 +000064 Rewriter Rewrite;
65 DiagnosticsEngine &Diags;
66 const LangOptions &LangOpts;
67 ASTContext *Context;
68 SourceManager *SM;
69 TranslationUnitDecl *TUDecl;
70 FileID MainFileID;
71 const char *MainFileStart, *MainFileEnd;
72 Stmt *CurrentBody;
73 ParentMap *PropParentMap; // created lazily.
74 std::string InFileName;
Peter Collingbourne03f89072016-07-15 00:55:40 +000075 std::unique_ptr<raw_ostream> OutFile;
Fariborz Jahanian11671902012-02-07 17:11:38 +000076 std::string Preamble;
Fangrui Song6907ce22018-07-30 19:24:48 +000077
Fariborz Jahanian11671902012-02-07 17:11:38 +000078 TypeDecl *ProtocolTypeDecl;
79 VarDecl *GlobalVarDecl;
Fariborz Jahaniane0050702012-03-23 00:00:49 +000080 Expr *GlobalConstructionExp;
Fariborz Jahanian11671902012-02-07 17:11:38 +000081 unsigned RewriteFailedDiag;
Fariborz Jahanianbdf975e2012-03-22 19:54:39 +000082 unsigned GlobalBlockRewriteFailedDiag;
Fariborz Jahanian11671902012-02-07 17:11:38 +000083 // ObjC string constant support.
84 unsigned NumObjCStringLiterals;
85 VarDecl *ConstantStringClassReference;
86 RecordDecl *NSStringRecord;
87
88 // ObjC foreach break/continue generation support.
89 int BcLabelCount;
Fangrui Song6907ce22018-07-30 19:24:48 +000090
Fariborz Jahanian11671902012-02-07 17:11:38 +000091 unsigned TryFinallyContainsReturnDiag;
92 // Needed for super.
93 ObjCMethodDecl *CurMethodDef;
94 RecordDecl *SuperStructDecl;
95 RecordDecl *ConstantStringDecl;
Fangrui Song6907ce22018-07-30 19:24:48 +000096
Fariborz Jahanian11671902012-02-07 17:11:38 +000097 FunctionDecl *MsgSendFunctionDecl;
98 FunctionDecl *MsgSendSuperFunctionDecl;
99 FunctionDecl *MsgSendStretFunctionDecl;
100 FunctionDecl *MsgSendSuperStretFunctionDecl;
101 FunctionDecl *MsgSendFpretFunctionDecl;
102 FunctionDecl *GetClassFunctionDecl;
103 FunctionDecl *GetMetaClassFunctionDecl;
104 FunctionDecl *GetSuperClassFunctionDecl;
105 FunctionDecl *SelGetUidFunctionDecl;
106 FunctionDecl *CFStringFunctionDecl;
Benjamin Kramer60509af2013-09-09 14:48:42 +0000107 FunctionDecl *SuperConstructorFunctionDecl;
Fariborz Jahanian11671902012-02-07 17:11:38 +0000108 FunctionDecl *CurFunctionDef;
Fariborz Jahanian11671902012-02-07 17:11:38 +0000109
110 /* Misc. containers needed for meta-data rewrite. */
111 SmallVector<ObjCImplementationDecl *, 8> ClassImplementation;
112 SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation;
113 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCSynthesizedStructs;
114 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> ObjCSynthesizedProtocols;
Fariborz Jahaniand268b0c2012-02-17 22:20:12 +0000115 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCWrittenInterfaces;
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +0000116 llvm::SmallPtrSet<TagDecl*, 32> GlobalDefinedTags;
Fariborz Jahaniand268b0c2012-02-17 22:20:12 +0000117 SmallVector<ObjCInterfaceDecl*, 32> ObjCInterfacesSeen;
Fariborz Jahanian07a423d2012-03-14 23:18:19 +0000118 /// DefinedNonLazyClasses - List of defined "non-lazy" classes.
119 SmallVector<ObjCInterfaceDecl*, 8> DefinedNonLazyClasses;
Fangrui Song6907ce22018-07-30 19:24:48 +0000120
Fariborz Jahanian07a423d2012-03-14 23:18:19 +0000121 /// DefinedNonLazyCategories - List of defined "non-lazy" categories.
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000122 SmallVector<ObjCCategoryDecl *, 8> DefinedNonLazyCategories;
Fangrui Song6907ce22018-07-30 19:24:48 +0000123
Fariborz Jahanian11671902012-02-07 17:11:38 +0000124 SmallVector<Stmt *, 32> Stmts;
125 SmallVector<int, 8> ObjCBcLabelNo;
126 // Remember all the @protocol(<expr>) expressions.
127 llvm::SmallPtrSet<ObjCProtocolDecl *, 32> ProtocolExprDecls;
Fangrui Song6907ce22018-07-30 19:24:48 +0000128
Fariborz Jahanian11671902012-02-07 17:11:38 +0000129 llvm::DenseSet<uint64_t> CopyDestroyCache;
130
131 // Block expressions.
132 SmallVector<BlockExpr *, 32> Blocks;
133 SmallVector<int, 32> InnerDeclRefsCount;
John McCall113bee02012-03-10 09:33:50 +0000134 SmallVector<DeclRefExpr *, 32> InnerDeclRefs;
Fangrui Song6907ce22018-07-30 19:24:48 +0000135
John McCall113bee02012-03-10 09:33:50 +0000136 SmallVector<DeclRefExpr *, 32> BlockDeclRefs;
Fariborz Jahanian11671902012-02-07 17:11:38 +0000137
138 // Block related declarations.
139 SmallVector<ValueDecl *, 8> BlockByCopyDecls;
140 llvm::SmallPtrSet<ValueDecl *, 8> BlockByCopyDeclsPtrSet;
141 SmallVector<ValueDecl *, 8> BlockByRefDecls;
142 llvm::SmallPtrSet<ValueDecl *, 8> BlockByRefDeclsPtrSet;
143 llvm::DenseMap<ValueDecl *, unsigned> BlockByRefDeclNo;
144 llvm::SmallPtrSet<ValueDecl *, 8> ImportedBlockDecls;
145 llvm::SmallPtrSet<VarDecl *, 8> ImportedLocalExternalDecls;
Fangrui Song6907ce22018-07-30 19:24:48 +0000146
Fariborz Jahanian11671902012-02-07 17:11:38 +0000147 llvm::DenseMap<BlockExpr *, std::string> RewrittenBlockExprs;
Fangrui Song6907ce22018-07-30 19:24:48 +0000148 llvm::DenseMap<ObjCInterfaceDecl *,
Mandeep Singh Granga2baff02017-07-06 18:49:57 +0000149 llvm::SmallSetVector<ObjCIvarDecl *, 8> > ReferencedIvars;
Fangrui Song6907ce22018-07-30 19:24:48 +0000150
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +0000151 // ivar bitfield grouping containers
152 llvm::DenseSet<const ObjCInterfaceDecl *> ObjCInterefaceHasBitfieldGroups;
153 llvm::DenseMap<const ObjCIvarDecl* , unsigned> IvarGroupNumber;
154 // This container maps an <class, group number for ivar> tuple to the type
155 // of the struct where the bitfield belongs.
156 llvm::DenseMap<std::pair<const ObjCInterfaceDecl*, unsigned>, QualType> GroupRecordType;
Fariborz Jahaniane4996132013-02-07 22:50:40 +0000157 SmallVector<FunctionDecl*, 32> FunctionDefinitionsSeen;
Fangrui Song6907ce22018-07-30 19:24:48 +0000158
Fariborz Jahanian11671902012-02-07 17:11:38 +0000159 // This maps an original source AST to it's rewritten form. This allows
160 // us to avoid rewriting the same node twice (which is very uncommon).
161 // This is needed to support some of the exotic property rewriting.
162 llvm::DenseMap<Stmt *, Stmt *> ReplacedNodes;
163
164 // Needed for header files being rewritten
165 bool IsHeader;
166 bool SilenceRewriteMacroWarning;
Fariborz Jahaniane4c7e852013-02-08 00:27:34 +0000167 bool GenerateLineInfo;
Fariborz Jahanian11671902012-02-07 17:11:38 +0000168 bool objc_impl_method;
Fangrui Song6907ce22018-07-30 19:24:48 +0000169
Fariborz Jahanian11671902012-02-07 17:11:38 +0000170 bool DisableReplaceStmt;
171 class DisableReplaceStmtScope {
172 RewriteModernObjC &R;
173 bool SavedValue;
Fangrui Song6907ce22018-07-30 19:24:48 +0000174
Fariborz Jahanian11671902012-02-07 17:11:38 +0000175 public:
176 DisableReplaceStmtScope(RewriteModernObjC &R)
177 : R(R), SavedValue(R.DisableReplaceStmt) {
178 R.DisableReplaceStmt = true;
179 }
180 ~DisableReplaceStmtScope() {
181 R.DisableReplaceStmt = SavedValue;
182 }
183 };
184 void InitializeCommon(ASTContext &context);
185
186 public:
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +0000187 llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames;
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000188
Fariborz Jahanian11671902012-02-07 17:11:38 +0000189 // Top Level Driver code.
Craig Topperfb6b25b2014-03-15 04:29:04 +0000190 bool HandleTopLevelDecl(DeclGroupRef D) override {
Fariborz Jahanian11671902012-02-07 17:11:38 +0000191 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
192 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(*I)) {
193 if (!Class->isThisDeclarationADefinition()) {
194 RewriteForwardClassDecl(D);
195 break;
Fariborz Jahaniand268b0c2012-02-17 22:20:12 +0000196 } else {
197 // Keep track of all interface declarations seen.
Fariborz Jahanian0ed6cb72012-02-24 21:42:38 +0000198 ObjCInterfacesSeen.push_back(Class);
Fariborz Jahaniand268b0c2012-02-17 22:20:12 +0000199 break;
Fariborz Jahanian11671902012-02-07 17:11:38 +0000200 }
201 }
202
203 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>(*I)) {
204 if (!Proto->isThisDeclarationADefinition()) {
205 RewriteForwardProtocolDecl(D);
206 break;
207 }
208 }
209
Fariborz Jahaniane4996132013-02-07 22:50:40 +0000210 if (FunctionDecl *FDecl = dyn_cast<FunctionDecl>(*I)) {
211 // Under modern abi, we cannot translate body of the function
212 // yet until all class extensions and its implementation is seen.
213 // This is because they may introduce new bitfields which must go
214 // into their grouping struct.
215 if (FDecl->isThisDeclarationADefinition() &&
216 // Not c functions defined inside an objc container.
217 !FDecl->isTopLevelDeclInObjCContainer()) {
218 FunctionDefinitionsSeen.push_back(FDecl);
219 break;
220 }
221 }
Fariborz Jahanian11671902012-02-07 17:11:38 +0000222 HandleTopLevelSingleDecl(*I);
223 }
224 return true;
225 }
Craig Topperfb6b25b2014-03-15 04:29:04 +0000226
227 void HandleTopLevelDeclInObjCContainer(DeclGroupRef D) override {
Fariborz Jahaniand2940622013-10-07 19:54:22 +0000228 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
229 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(*I)) {
230 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
231 RewriteBlockPointerDecl(TD);
232 else if (TD->getUnderlyingType()->isFunctionPointerType())
233 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
234 else
235 RewriteObjCQualifiedInterfaceTypes(TD);
236 }
237 }
Fariborz Jahaniand2940622013-10-07 19:54:22 +0000238 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000239
Fariborz Jahanian11671902012-02-07 17:11:38 +0000240 void HandleTopLevelSingleDecl(Decl *D);
241 void HandleDeclInMainFile(Decl *D);
Peter Collingbourne03f89072016-07-15 00:55:40 +0000242 RewriteModernObjC(std::string inFile, std::unique_ptr<raw_ostream> OS,
243 DiagnosticsEngine &D, const LangOptions &LOpts,
244 bool silenceMacroWarn, bool LineInfo);
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000245
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +0000246 ~RewriteModernObjC() override {}
Craig Topperfb6b25b2014-03-15 04:29:04 +0000247
248 void HandleTranslationUnit(ASTContext &C) override;
Fariborz Jahanian11671902012-02-07 17:11:38 +0000249
250 void ReplaceStmt(Stmt *Old, Stmt *New) {
Daniel Jasper4475a242014-10-23 19:47:36 +0000251 ReplaceStmtWithRange(Old, New, Old->getSourceRange());
Fariborz Jahanian11671902012-02-07 17:11:38 +0000252 }
253
254 void ReplaceStmtWithRange(Stmt *Old, Stmt *New, SourceRange SrcRange) {
Richard Trieuddd01ce2014-06-09 22:53:25 +0000255 assert(Old != nullptr && New != nullptr && "Expected non-null Stmt's");
Daniel Jasper4475a242014-10-23 19:47:36 +0000256
257 Stmt *ReplacingStmt = ReplacedNodes[Old];
258 if (ReplacingStmt)
259 return; // We can't rewrite the same node twice.
260
Fariborz Jahanian11671902012-02-07 17:11:38 +0000261 if (DisableReplaceStmt)
262 return;
263
264 // Measure the old text.
265 int Size = Rewrite.getRangeSize(SrcRange);
266 if (Size == -1) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000267 Diags.Report(Context->getFullLoc(Old->getBeginLoc()), RewriteFailedDiag)
268 << Old->getSourceRange();
Fariborz Jahanian11671902012-02-07 17:11:38 +0000269 return;
270 }
271 // Get the new text.
272 std::string SStr;
273 llvm::raw_string_ostream S(SStr);
Craig Topper8ae12032014-05-07 06:21:57 +0000274 New->printPretty(S, nullptr, PrintingPolicy(LangOpts));
Fariborz Jahanian11671902012-02-07 17:11:38 +0000275 const std::string &Str = S.str();
276
277 // If replacement succeeded or warning disabled return with no warning.
278 if (!Rewrite.ReplaceText(SrcRange.getBegin(), Size, Str)) {
279 ReplacedNodes[Old] = New;
280 return;
281 }
282 if (SilenceRewriteMacroWarning)
283 return;
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000284 Diags.Report(Context->getFullLoc(Old->getBeginLoc()), RewriteFailedDiag)
285 << Old->getSourceRange();
Fariborz Jahanian11671902012-02-07 17:11:38 +0000286 }
287
288 void InsertText(SourceLocation Loc, StringRef Str,
289 bool InsertAfter = true) {
290 // If insertion succeeded or warning disabled return with no warning.
291 if (!Rewrite.InsertText(Loc, Str, InsertAfter) ||
292 SilenceRewriteMacroWarning)
293 return;
294
295 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
296 }
297
298 void ReplaceText(SourceLocation Start, unsigned OrigLength,
299 StringRef Str) {
300 // If removal succeeded or warning disabled return with no warning.
301 if (!Rewrite.ReplaceText(Start, OrigLength, Str) ||
302 SilenceRewriteMacroWarning)
303 return;
304
305 Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
306 }
307
308 // Syntactic Rewriting.
309 void RewriteRecordBody(RecordDecl *RD);
310 void RewriteInclude();
Fariborz Jahanianaa4a2422012-11-06 17:30:23 +0000311 void RewriteLineDirective(const Decl *D);
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +0000312 void ConvertSourceLocationToLineDirective(SourceLocation Loc,
313 std::string &LineString);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000314 void RewriteForwardClassDecl(DeclGroupRef D);
Craig Topper5603df42013-07-05 19:34:19 +0000315 void RewriteForwardClassDecl(const SmallVectorImpl<Decl *> &DG);
Fangrui Song6907ce22018-07-30 19:24:48 +0000316 void RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
Fariborz Jahanian11671902012-02-07 17:11:38 +0000317 const std::string &typedefString);
318 void RewriteImplementations();
319 void RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
320 ObjCImplementationDecl *IMD,
321 ObjCCategoryImplDecl *CID);
322 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
323 void RewriteImplementationDecl(Decl *Dcl);
324 void RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
325 ObjCMethodDecl *MDecl, std::string &ResultStr);
326 void RewriteTypeIntoString(QualType T, std::string &ResultStr,
327 const FunctionType *&FPRetType);
328 void RewriteByRefString(std::string &ResultStr, const std::string &Name,
329 ValueDecl *VD, bool def=false);
330 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
331 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
332 void RewriteForwardProtocolDecl(DeclGroupRef D);
Craig Topper5603df42013-07-05 19:34:19 +0000333 void RewriteForwardProtocolDecl(const SmallVectorImpl<Decl *> &DG);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000334 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
335 void RewriteProperty(ObjCPropertyDecl *prop);
336 void RewriteFunctionDecl(FunctionDecl *FD);
337 void RewriteBlockPointerType(std::string& Str, QualType Type);
338 void RewriteBlockPointerTypeVariable(std::string& Str, ValueDecl *VD);
Fariborz Jahanianca357d92012-04-19 00:50:01 +0000339 void RewriteBlockLiteralFunctionDecl(FunctionDecl *FD);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000340 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
341 void RewriteTypeOfDecl(VarDecl *VD);
342 void RewriteObjCQualifiedInterfaceTypes(Expr *E);
Fangrui Song6907ce22018-07-30 19:24:48 +0000343
Fariborz Jahanian89919cc2012-05-08 23:54:35 +0000344 std::string getIvarAccessString(ObjCIvarDecl *D);
Fangrui Song6907ce22018-07-30 19:24:48 +0000345
Fariborz Jahanian11671902012-02-07 17:11:38 +0000346 // Expression Rewriting.
347 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
348 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
349 Stmt *RewritePropertyOrImplicitGetter(PseudoObjectExpr *Pseudo);
350 Stmt *RewritePropertyOrImplicitSetter(PseudoObjectExpr *Pseudo);
351 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
352 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
353 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian307b7ad2012-03-27 20:17:30 +0000354 Stmt *RewriteObjCBoolLiteralExpr(ObjCBoolLiteralExpr *Exp);
Patrick Beard0caa3942012-04-19 00:25:12 +0000355 Stmt *RewriteObjCBoxedExpr(ObjCBoxedExpr *Exp);
Fariborz Jahanian991a08d2012-03-30 23:35:47 +0000356 Stmt *RewriteObjCArrayLiteralExpr(ObjCArrayLiteral *Exp);
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +0000357 Stmt *RewriteObjCDictionaryLiteralExpr(ObjCDictionaryLiteral *Exp);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000358 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000359 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
Fariborz Jahanian9b43c3f2012-05-23 23:47:20 +0000360 Stmt *RewriteObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000361 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
362 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
363 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
364 SourceLocation OrigEnd);
365 Stmt *RewriteBreakStmt(BreakStmt *S);
366 Stmt *RewriteContinueStmt(ContinueStmt *S);
367 void RewriteCastExpr(CStyleCastExpr *CE);
Fariborz Jahanian2c00acd2012-04-10 00:08:18 +0000368 void RewriteImplicitCastObjCExpr(CastExpr *IE);
Fangrui Song6907ce22018-07-30 19:24:48 +0000369
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +0000370 // Computes ivar bitfield group no.
371 unsigned ObjCIvarBitfieldGroupNo(ObjCIvarDecl *IV);
372 // Names field decl. for ivar bitfield group.
373 void ObjCIvarBitfieldGroupDecl(ObjCIvarDecl *IV, std::string &Result);
374 // Names struct type for ivar bitfield group.
375 void ObjCIvarBitfieldGroupType(ObjCIvarDecl *IV, std::string &Result);
376 // Names symbol for ivar bitfield group field offset.
377 void ObjCIvarBitfieldGroupOffset(ObjCIvarDecl *IV, std::string &Result);
378 // Given an ivar bitfield, it builds (or finds) its group record type.
379 QualType GetGroupRecordTypeForObjCIvarBitfield(ObjCIvarDecl *IV);
380 QualType SynthesizeBitfieldGroupStructType(
381 ObjCIvarDecl *IV,
382 SmallVectorImpl<ObjCIvarDecl *> &IVars);
Fangrui Song6907ce22018-07-30 19:24:48 +0000383
Fariborz Jahanian11671902012-02-07 17:11:38 +0000384 // Block rewriting.
385 void RewriteBlocksInFunctionProtoType(QualType funcType, NamedDecl *D);
Fangrui Song6907ce22018-07-30 19:24:48 +0000386
Fariborz Jahanian11671902012-02-07 17:11:38 +0000387 // Block specific rewrite rules.
388 void RewriteBlockPointerDecl(NamedDecl *VD);
Fariborz Jahanian847713a2012-04-24 19:38:45 +0000389 void RewriteByRefVar(VarDecl *VD, bool firstDecl, bool lastDecl);
John McCall113bee02012-03-10 09:33:50 +0000390 Stmt *RewriteBlockDeclRefExpr(DeclRefExpr *VD);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000391 Stmt *RewriteLocalVariableExternalStorage(DeclRefExpr *DRE);
392 void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
Fangrui Song6907ce22018-07-30 19:24:48 +0000393
Fariborz Jahanian11671902012-02-07 17:11:38 +0000394 void RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
395 std::string &Result);
Fangrui Song6907ce22018-07-30 19:24:48 +0000396
Fariborz Jahanian265a4212012-02-28 22:45:07 +0000397 void RewriteObjCFieldDecl(FieldDecl *fieldDecl, std::string &Result);
Fariborz Jahanian144b7222012-05-01 17:46:45 +0000398 bool IsTagDefinedInsideClass(ObjCContainerDecl *IDecl, TagDecl *Tag,
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +0000399 bool &IsNamedDefinition);
Fangrui Song6907ce22018-07-30 19:24:48 +0000400 void RewriteLocallyDefinedNamedAggregates(FieldDecl *fieldDecl,
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +0000401 std::string &Result);
Fangrui Song6907ce22018-07-30 19:24:48 +0000402
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +0000403 bool RewriteObjCFieldDeclType(QualType &Type, std::string &Result);
Fangrui Song6907ce22018-07-30 19:24:48 +0000404
Fariborz Jahanian5e49eb92012-02-22 18:13:25 +0000405 void RewriteIvarOffsetSymbols(ObjCInterfaceDecl *CDecl,
406 std::string &Result);
Craig Topperfb6b25b2014-03-15 04:29:04 +0000407
408 void Initialize(ASTContext &context) override;
409
Benjamin Kramer474261a2012-06-02 10:20:41 +0000410 // Misc. AST transformation routines. Sometimes they end up calling
Fariborz Jahanian11671902012-02-07 17:11:38 +0000411 // rewriting routines on the new ASTs.
412 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
Craig Toppercf2126e2015-10-22 03:13:07 +0000413 ArrayRef<Expr *> Args,
Fariborz Jahanian11671902012-02-07 17:11:38 +0000414 SourceLocation StartLoc=SourceLocation(),
415 SourceLocation EndLoc=SourceLocation());
Fangrui Song6907ce22018-07-30 19:24:48 +0000416
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +0000417 Expr *SynthMsgSendStretCallExpr(FunctionDecl *MsgSendStretFlavor,
Fangrui Song6907ce22018-07-30 19:24:48 +0000418 QualType returnType,
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +0000419 SmallVectorImpl<QualType> &ArgTypes,
420 SmallVectorImpl<Expr*> &MsgExprs,
421 ObjCMethodDecl *Method);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000422
423 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp,
424 SourceLocation StartLoc=SourceLocation(),
425 SourceLocation EndLoc=SourceLocation());
Fangrui Song6907ce22018-07-30 19:24:48 +0000426
Fariborz Jahanian11671902012-02-07 17:11:38 +0000427 void SynthCountByEnumWithState(std::string &buf);
428 void SynthMsgSendFunctionDecl();
429 void SynthMsgSendSuperFunctionDecl();
430 void SynthMsgSendStretFunctionDecl();
431 void SynthMsgSendFpretFunctionDecl();
432 void SynthMsgSendSuperStretFunctionDecl();
433 void SynthGetClassFunctionDecl();
434 void SynthGetMetaClassFunctionDecl();
435 void SynthGetSuperClassFunctionDecl();
436 void SynthSelGetUidFunctionDecl();
Benjamin Kramer60509af2013-09-09 14:48:42 +0000437 void SynthSuperConstructorFunctionDecl();
Fangrui Song6907ce22018-07-30 19:24:48 +0000438
Fariborz Jahanian11671902012-02-07 17:11:38 +0000439 // Rewriting metadata
440 template<typename MethodIterator>
441 void RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
442 MethodIterator MethodEnd,
443 bool IsInstanceMethod,
444 StringRef prefix,
445 StringRef ClassName,
446 std::string &Result);
Fariborz Jahaniane18961b2012-02-08 19:53:58 +0000447 void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
448 std::string &Result);
Fariborz Jahanian95badad2012-04-30 16:57:52 +0000449 void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanian11671902012-02-07 17:11:38 +0000450 std::string &Result);
Fariborz Jahanian95badad2012-04-30 16:57:52 +0000451 void RewriteClassSetupInitHook(std::string &Result);
Fangrui Song6907ce22018-07-30 19:24:48 +0000452
Fariborz Jahanian95badad2012-04-30 16:57:52 +0000453 void RewriteMetaDataIntoBuffer(std::string &Result);
454 void WriteImageInfo(std::string &Result);
455 void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
Fariborz Jahanian11671902012-02-07 17:11:38 +0000456 std::string &Result);
Fariborz Jahanian95badad2012-04-30 16:57:52 +0000457 void RewriteCategorySetupInitHook(std::string &Result);
Fangrui Song6907ce22018-07-30 19:24:48 +0000458
Fariborz Jahanian11671902012-02-07 17:11:38 +0000459 // Rewriting ivar
Fariborz Jahanian95badad2012-04-30 16:57:52 +0000460 void RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
Fariborz Jahanian11671902012-02-07 17:11:38 +0000461 std::string &Result);
Fariborz Jahanian95badad2012-04-30 16:57:52 +0000462 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000463
Fangrui Song6907ce22018-07-30 19:24:48 +0000464
Fariborz Jahanian11671902012-02-07 17:11:38 +0000465 std::string SynthesizeByrefCopyDestroyHelper(VarDecl *VD, int flag);
466 std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
467 StringRef funcName, std::string Tag);
468 std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
469 StringRef funcName, std::string Tag);
Fangrui Song6907ce22018-07-30 19:24:48 +0000470 std::string SynthesizeBlockImpl(BlockExpr *CE,
Fariborz Jahanian11671902012-02-07 17:11:38 +0000471 std::string Tag, std::string Desc);
Fangrui Song6907ce22018-07-30 19:24:48 +0000472 std::string SynthesizeBlockDescriptor(std::string DescTag,
Fariborz Jahanian11671902012-02-07 17:11:38 +0000473 std::string ImplTag,
474 int i, StringRef funcName,
475 unsigned hasCopy);
476 Stmt *SynthesizeBlockCall(CallExpr *Exp, const Expr* BlockExp);
477 void SynthesizeBlockLiterals(SourceLocation FunLocStart,
478 StringRef FunName);
479 FunctionDecl *SynthBlockInitFunctionDecl(StringRef name);
480 Stmt *SynthBlockInitExpr(BlockExpr *Exp,
Craig Topper5603df42013-07-05 19:34:19 +0000481 const SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000482
483 // Misc. helper routines.
484 QualType getProtocolType();
485 void WarnAboutReturnGotoStmts(Stmt *S);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000486 void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
487 void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
488 void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
489
490 bool IsDeclStmtInForeachHeader(DeclStmt *DS);
491 void CollectBlockDeclRefInfo(BlockExpr *Exp);
492 void GetBlockDeclRefExprs(Stmt *S);
Craig Topper5603df42013-07-05 19:34:19 +0000493 void GetInnerBlockDeclRefExprs(Stmt *S,
494 SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs,
Craig Topper4dd9b432014-08-17 23:49:53 +0000495 llvm::SmallPtrSetImpl<const DeclContext *> &InnerContexts);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000496
497 // We avoid calling Type::isBlockPointerType(), since it operates on the
498 // canonical type. We only care if the top-level type is a closure pointer.
499 bool isTopLevelBlockPointerType(QualType T) {
500 return isa<BlockPointerType>(T);
501 }
502
503 /// convertBlockPointerToFunctionPointer - Converts a block-pointer type
504 /// to a function pointer type and upon success, returns true; false
505 /// otherwise.
506 bool convertBlockPointerToFunctionPointer(QualType &T) {
507 if (isTopLevelBlockPointerType(T)) {
508 const BlockPointerType *BPT = T->getAs<BlockPointerType>();
509 T = Context->getPointerType(BPT->getPointeeType());
510 return true;
511 }
512 return false;
513 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000514
Fariborz Jahanianc3cdc412012-02-13 18:57:49 +0000515 bool convertObjCTypeToCStyleType(QualType &T);
Fangrui Song6907ce22018-07-30 19:24:48 +0000516
Fariborz Jahanian11671902012-02-07 17:11:38 +0000517 bool needToScanForQualifiers(QualType T);
518 QualType getSuperStructType();
519 QualType getConstantStringStructType();
520 QualType convertFunctionTypeOfBlocks(const FunctionType *FT);
Fangrui Song6907ce22018-07-30 19:24:48 +0000521
Fariborz Jahanian11671902012-02-07 17:11:38 +0000522 void convertToUnqualifiedObjCType(QualType &T) {
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +0000523 if (T->isObjCQualifiedIdType()) {
524 bool isConst = T.isConstQualified();
Fangrui Song6907ce22018-07-30 19:24:48 +0000525 T = isConst ? Context->getObjCIdType().withConst()
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +0000526 : Context->getObjCIdType();
527 }
Fariborz Jahanian11671902012-02-07 17:11:38 +0000528 else if (T->isObjCQualifiedClassType())
529 T = Context->getObjCClassType();
530 else if (T->isObjCObjectPointerType() &&
531 T->getPointeeType()->isObjCQualifiedInterfaceType()) {
532 if (const ObjCObjectPointerType * OBJPT =
533 T->getAsObjCInterfacePointerType()) {
534 const ObjCInterfaceType *IFaceT = OBJPT->getInterfaceType();
535 T = QualType(IFaceT, 0);
536 T = Context->getPointerType(T);
537 }
538 }
539 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000540
Fariborz Jahanian11671902012-02-07 17:11:38 +0000541 // FIXME: This predicate seems like it would be useful to add to ASTContext.
542 bool isObjCType(QualType T) {
Erik Pilkingtonfa983902018-10-30 20:31:30 +0000543 if (!LangOpts.ObjC)
Fariborz Jahanian11671902012-02-07 17:11:38 +0000544 return false;
545
546 QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
547
548 if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
549 OCT == Context->getCanonicalType(Context->getObjCClassType()))
550 return true;
551
552 if (const PointerType *PT = OCT->getAs<PointerType>()) {
553 if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
554 PT->getPointeeType()->isObjCQualifiedIdType())
555 return true;
556 }
557 return false;
558 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000559
Fariborz Jahanian11671902012-02-07 17:11:38 +0000560 bool PointerTypeTakesAnyBlockArguments(QualType QT);
561 bool PointerTypeTakesAnyObjCQualifiedType(QualType QT);
562 void GetExtentOfArgList(const char *Name, const char *&LParen,
563 const char *&RParen);
Fangrui Song6907ce22018-07-30 19:24:48 +0000564
Fariborz Jahanian11671902012-02-07 17:11:38 +0000565 void QuoteDoublequotes(std::string &From, std::string &To) {
566 for (unsigned i = 0; i < From.length(); i++) {
567 if (From[i] == '"')
568 To += "\\\"";
569 else
570 To += From[i];
571 }
572 }
573
574 QualType getSimpleFunctionType(QualType result,
Jordan Rose5c382722013-03-08 21:51:21 +0000575 ArrayRef<QualType> args,
Fariborz Jahanian11671902012-02-07 17:11:38 +0000576 bool variadic = false) {
577 if (result == Context->getObjCInstanceType())
578 result = Context->getObjCIdType();
579 FunctionProtoType::ExtProtoInfo fpi;
580 fpi.Variadic = variadic;
Jordan Rose5c382722013-03-08 21:51:21 +0000581 return Context->getFunctionType(result, args, fpi);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000582 }
583
584 // Helper function: create a CStyleCastExpr with trivial type source info.
585 CStyleCastExpr* NoTypeInfoCStyleCastExpr(ASTContext *Ctx, QualType Ty,
586 CastKind Kind, Expr *E) {
587 TypeSourceInfo *TInfo = Ctx->getTrivialTypeSourceInfo(Ty, SourceLocation());
Craig Topper8ae12032014-05-07 06:21:57 +0000588 return CStyleCastExpr::Create(*Ctx, Ty, VK_RValue, Kind, E, nullptr,
589 TInfo, SourceLocation(), SourceLocation());
Fariborz Jahanian11671902012-02-07 17:11:38 +0000590 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000591
Fariborz Jahanian07a423d2012-03-14 23:18:19 +0000592 bool ImplementationIsNonLazy(const ObjCImplDecl *OD) const {
593 IdentifierInfo* II = &Context->Idents.get("load");
594 Selector LoadSel = Context->Selectors.getSelector(0, &II);
Craig Topper8ae12032014-05-07 06:21:57 +0000595 return OD->getClassMethod(LoadSel) != nullptr;
Fariborz Jahanian07a423d2012-03-14 23:18:19 +0000596 }
Benjamin Kramerfc188422014-02-25 12:26:11 +0000597
598 StringLiteral *getStringLiteral(StringRef Str) {
599 QualType StrType = Context->getConstantArrayType(
600 Context->CharTy, llvm::APInt(32, Str.size() + 1), ArrayType::Normal,
601 0);
602 return StringLiteral::Create(*Context, Str, StringLiteral::Ascii,
603 /*Pascal=*/false, StrType, SourceLocation());
604 }
Fariborz Jahanian11671902012-02-07 17:11:38 +0000605 };
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000606} // end anonymous namespace
Fariborz Jahanian11671902012-02-07 17:11:38 +0000607
608void RewriteModernObjC::RewriteBlocksInFunctionProtoType(QualType funcType,
609 NamedDecl *D) {
610 if (const FunctionProtoType *fproto
611 = dyn_cast<FunctionProtoType>(funcType.IgnoreParens())) {
Aaron Ballman40bd0aa2014-03-17 15:23:01 +0000612 for (const auto &I : fproto->param_types())
613 if (isTopLevelBlockPointerType(I)) {
Fariborz Jahanian11671902012-02-07 17:11:38 +0000614 // All the args are checked/rewritten. Don't call twice!
615 RewriteBlockPointerDecl(D);
616 break;
617 }
618 }
619}
620
621void RewriteModernObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
622 const PointerType *PT = funcType->getAs<PointerType>();
623 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
624 RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND);
625}
626
627static bool IsHeaderFile(const std::string &Filename) {
628 std::string::size_type DotPos = Filename.rfind('.');
629
630 if (DotPos == std::string::npos) {
631 // no file extension
632 return false;
633 }
634
635 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
636 // C header: .h
637 // C++ header: .hh or .H;
638 return Ext == "h" || Ext == "hh" || Ext == "H";
639}
640
Peter Collingbourne03f89072016-07-15 00:55:40 +0000641RewriteModernObjC::RewriteModernObjC(std::string inFile,
642 std::unique_ptr<raw_ostream> OS,
643 DiagnosticsEngine &D,
644 const LangOptions &LOpts,
645 bool silenceMacroWarn, bool LineInfo)
646 : Diags(D), LangOpts(LOpts), InFileName(inFile), OutFile(std::move(OS)),
647 SilenceRewriteMacroWarning(silenceMacroWarn), GenerateLineInfo(LineInfo) {
Fariborz Jahanian11671902012-02-07 17:11:38 +0000648 IsHeader = IsHeaderFile(inFile);
649 RewriteFailedDiag = Diags.getCustomDiagID(DiagnosticsEngine::Warning,
650 "rewriting sub-expression within a macro (may not be correct)");
Fariborz Jahanianbdf975e2012-03-22 19:54:39 +0000651 // FIXME. This should be an error. But if block is not called, it is OK. And it
652 // may break including some headers.
653 GlobalBlockRewriteFailedDiag = Diags.getCustomDiagID(DiagnosticsEngine::Warning,
654 "rewriting block literal declared in global scope is not implemented");
Fangrui Song6907ce22018-07-30 19:24:48 +0000655
Fariborz Jahanian11671902012-02-07 17:11:38 +0000656 TryFinallyContainsReturnDiag = Diags.getCustomDiagID(
657 DiagnosticsEngine::Warning,
658 "rewriter doesn't support user-specified control flow semantics "
659 "for @try/@finally (code may not execute properly)");
660}
661
David Blaikie6beb6aa2014-08-10 19:56:51 +0000662std::unique_ptr<ASTConsumer> clang::CreateModernObjCRewriter(
Peter Collingbourne03f89072016-07-15 00:55:40 +0000663 const std::string &InFile, std::unique_ptr<raw_ostream> OS,
664 DiagnosticsEngine &Diags, const LangOptions &LOpts,
665 bool SilenceRewriteMacroWarning, bool LineInfo) {
666 return llvm::make_unique<RewriteModernObjC>(InFile, std::move(OS), Diags,
667 LOpts, SilenceRewriteMacroWarning,
668 LineInfo);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000669}
670
671void RewriteModernObjC::InitializeCommon(ASTContext &context) {
672 Context = &context;
673 SM = &Context->getSourceManager();
674 TUDecl = Context->getTranslationUnitDecl();
Craig Topper8ae12032014-05-07 06:21:57 +0000675 MsgSendFunctionDecl = nullptr;
676 MsgSendSuperFunctionDecl = nullptr;
677 MsgSendStretFunctionDecl = nullptr;
678 MsgSendSuperStretFunctionDecl = nullptr;
679 MsgSendFpretFunctionDecl = nullptr;
680 GetClassFunctionDecl = nullptr;
681 GetMetaClassFunctionDecl = nullptr;
682 GetSuperClassFunctionDecl = nullptr;
683 SelGetUidFunctionDecl = nullptr;
684 CFStringFunctionDecl = nullptr;
685 ConstantStringClassReference = nullptr;
686 NSStringRecord = nullptr;
687 CurMethodDef = nullptr;
688 CurFunctionDef = nullptr;
689 GlobalVarDecl = nullptr;
690 GlobalConstructionExp = nullptr;
691 SuperStructDecl = nullptr;
692 ProtocolTypeDecl = nullptr;
693 ConstantStringDecl = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +0000694 BcLabelCount = 0;
Craig Topper8ae12032014-05-07 06:21:57 +0000695 SuperConstructorFunctionDecl = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +0000696 NumObjCStringLiterals = 0;
Craig Topper8ae12032014-05-07 06:21:57 +0000697 PropParentMap = nullptr;
698 CurrentBody = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +0000699 DisableReplaceStmt = false;
700 objc_impl_method = false;
701
702 // Get the ID and start/end of the main file.
703 MainFileID = SM->getMainFileID();
704 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
705 MainFileStart = MainBuf->getBufferStart();
706 MainFileEnd = MainBuf->getBufferEnd();
707
David Blaikiebbafb8a2012-03-11 07:00:24 +0000708 Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOpts());
Fariborz Jahanian11671902012-02-07 17:11:38 +0000709}
710
711//===----------------------------------------------------------------------===//
712// Top Level Driver Code
713//===----------------------------------------------------------------------===//
714
715void RewriteModernObjC::HandleTopLevelSingleDecl(Decl *D) {
716 if (Diags.hasErrorOccurred())
717 return;
718
719 // Two cases: either the decl could be in the main file, or it could be in a
720 // #included file. If the former, rewrite it now. If the later, check to see
721 // if we rewrote the #include/#import.
722 SourceLocation Loc = D->getLocation();
723 Loc = SM->getExpansionLoc(Loc);
724
725 // If this is for a builtin, ignore it.
726 if (Loc.isInvalid()) return;
727
728 // Look for built-in declarations that we need to refer during the rewrite.
729 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
730 RewriteFunctionDecl(FD);
731 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
732 // declared in <Foundation/NSString.h>
733 if (FVD->getName() == "_NSConstantStringClassReference") {
734 ConstantStringClassReference = FVD;
735 return;
736 }
Fariborz Jahanian11671902012-02-07 17:11:38 +0000737 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
738 RewriteCategoryDecl(CD);
739 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
740 if (PD->isThisDeclarationADefinition())
741 RewriteProtocolDecl(PD);
742 } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) {
743 // Recurse into linkage specifications
744 for (DeclContext::decl_iterator DI = LSD->decls_begin(),
745 DIEnd = LSD->decls_end();
746 DI != DIEnd; ) {
747 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>((*DI))) {
748 if (!IFace->isThisDeclarationADefinition()) {
749 SmallVector<Decl *, 8> DG;
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000750 SourceLocation StartLoc = IFace->getBeginLoc();
Fariborz Jahanian11671902012-02-07 17:11:38 +0000751 do {
752 if (isa<ObjCInterfaceDecl>(*DI) &&
753 !cast<ObjCInterfaceDecl>(*DI)->isThisDeclarationADefinition() &&
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000754 StartLoc == (*DI)->getBeginLoc())
Fariborz Jahanian11671902012-02-07 17:11:38 +0000755 DG.push_back(*DI);
756 else
757 break;
Fangrui Song6907ce22018-07-30 19:24:48 +0000758
Fariborz Jahanian11671902012-02-07 17:11:38 +0000759 ++DI;
760 } while (DI != DIEnd);
761 RewriteForwardClassDecl(DG);
762 continue;
763 }
Fariborz Jahanian08ed8922012-04-03 17:35:38 +0000764 else {
765 // Keep track of all interface declarations seen.
766 ObjCInterfacesSeen.push_back(IFace);
767 ++DI;
768 continue;
769 }
Fariborz Jahanian11671902012-02-07 17:11:38 +0000770 }
771
772 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>((*DI))) {
773 if (!Proto->isThisDeclarationADefinition()) {
774 SmallVector<Decl *, 8> DG;
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000775 SourceLocation StartLoc = Proto->getBeginLoc();
Fariborz Jahanian11671902012-02-07 17:11:38 +0000776 do {
777 if (isa<ObjCProtocolDecl>(*DI) &&
778 !cast<ObjCProtocolDecl>(*DI)->isThisDeclarationADefinition() &&
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000779 StartLoc == (*DI)->getBeginLoc())
Fariborz Jahanian11671902012-02-07 17:11:38 +0000780 DG.push_back(*DI);
781 else
782 break;
Fangrui Song6907ce22018-07-30 19:24:48 +0000783
Fariborz Jahanian11671902012-02-07 17:11:38 +0000784 ++DI;
785 } while (DI != DIEnd);
786 RewriteForwardProtocolDecl(DG);
787 continue;
788 }
789 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000790
Fariborz Jahanian11671902012-02-07 17:11:38 +0000791 HandleTopLevelSingleDecl(*DI);
792 ++DI;
793 }
794 }
795 // If we have a decl in the main file, see if we should rewrite it.
Eli Friedman5ba37d52013-08-22 00:27:10 +0000796 if (SM->isWrittenInMainFile(Loc))
Fariborz Jahanian11671902012-02-07 17:11:38 +0000797 return HandleDeclInMainFile(D);
798}
799
800//===----------------------------------------------------------------------===//
801// Syntactic (non-AST) Rewriting Code
802//===----------------------------------------------------------------------===//
803
804void RewriteModernObjC::RewriteInclude() {
805 SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID);
806 StringRef MainBuf = SM->getBufferData(MainFileID);
807 const char *MainBufStart = MainBuf.begin();
808 const char *MainBufEnd = MainBuf.end();
809 size_t ImportLen = strlen("import");
810
811 // Loop over the whole file, looking for includes.
812 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
813 if (*BufPtr == '#') {
814 if (++BufPtr == MainBufEnd)
815 return;
816 while (*BufPtr == ' ' || *BufPtr == '\t')
817 if (++BufPtr == MainBufEnd)
818 return;
819 if (!strncmp(BufPtr, "import", ImportLen)) {
820 // replace import with include
821 SourceLocation ImportLoc =
822 LocStart.getLocWithOffset(BufPtr-MainBufStart);
823 ReplaceText(ImportLoc, ImportLen, "include");
824 BufPtr += ImportLen;
825 }
826 }
827 }
828}
829
Fariborz Jahanian89919cc2012-05-08 23:54:35 +0000830static void WriteInternalIvarName(const ObjCInterfaceDecl *IDecl,
831 ObjCIvarDecl *IvarDecl, std::string &Result) {
832 Result += "OBJC_IVAR_$_";
833 Result += IDecl->getName();
834 Result += "$";
835 Result += IvarDecl->getName();
836}
837
Fangrui Song6907ce22018-07-30 19:24:48 +0000838std::string
Fariborz Jahanian89919cc2012-05-08 23:54:35 +0000839RewriteModernObjC::getIvarAccessString(ObjCIvarDecl *D) {
840 const ObjCInterfaceDecl *ClassDecl = D->getContainingInterface();
Fangrui Song6907ce22018-07-30 19:24:48 +0000841
Fariborz Jahanian89919cc2012-05-08 23:54:35 +0000842 // Build name of symbol holding ivar offset.
843 std::string IvarOffsetName;
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +0000844 if (D->isBitField())
845 ObjCIvarBitfieldGroupOffset(D, IvarOffsetName);
846 else
847 WriteInternalIvarName(ClassDecl, D, IvarOffsetName);
Fangrui Song6907ce22018-07-30 19:24:48 +0000848
Fariborz Jahanian89919cc2012-05-08 23:54:35 +0000849 std::string S = "(*(";
850 QualType IvarT = D->getType();
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +0000851 if (D->isBitField())
852 IvarT = GetGroupRecordTypeForObjCIvarBitfield(D);
Fangrui Song6907ce22018-07-30 19:24:48 +0000853
Fariborz Jahanian89919cc2012-05-08 23:54:35 +0000854 if (!isa<TypedefType>(IvarT) && IvarT->isRecordType()) {
855 RecordDecl *RD = IvarT->getAs<RecordType>()->getDecl();
856 RD = RD->getDefinition();
857 if (RD && !RD->getDeclName().getAsIdentifierInfo()) {
858 // decltype(((Foo_IMPL*)0)->bar) *
Fangrui Song6907ce22018-07-30 19:24:48 +0000859 ObjCContainerDecl *CDecl =
Fariborz Jahanian89919cc2012-05-08 23:54:35 +0000860 dyn_cast<ObjCContainerDecl>(D->getDeclContext());
861 // ivar in class extensions requires special treatment.
862 if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(CDecl))
863 CDecl = CatDecl->getClassInterface();
864 std::string RecName = CDecl->getName();
865 RecName += "_IMPL";
Malcolm Parsonsf76f6502016-11-02 10:39:27 +0000866 RecordDecl *RD =
867 RecordDecl::Create(*Context, TTK_Struct, TUDecl, SourceLocation(),
868 SourceLocation(), &Context->Idents.get(RecName));
Fariborz Jahanian89919cc2012-05-08 23:54:35 +0000869 QualType PtrStructIMPL = Context->getPointerType(Context->getTagDeclType(RD));
Fangrui Song6907ce22018-07-30 19:24:48 +0000870 unsigned UnsignedIntSize =
Fariborz Jahanian89919cc2012-05-08 23:54:35 +0000871 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
872 Expr *Zero = IntegerLiteral::Create(*Context,
873 llvm::APInt(UnsignedIntSize, 0),
874 Context->UnsignedIntTy, SourceLocation());
875 Zero = NoTypeInfoCStyleCastExpr(Context, PtrStructIMPL, CK_BitCast, Zero);
876 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
877 Zero);
Craig Topper8ae12032014-05-07 06:21:57 +0000878 FieldDecl *FD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
Fariborz Jahanian89919cc2012-05-08 23:54:35 +0000879 SourceLocation(),
880 &Context->Idents.get(D->getNameAsString()),
Fariborz Jahanianf8e68e22015-04-09 18:36:50 +0000881 IvarT, nullptr,
882 /*BitWidth=*/nullptr, /*Mutable=*/true,
883 ICIS_NoInit);
884 MemberExpr *ME = new (Context)
885 MemberExpr(PE, true, SourceLocation(), FD, SourceLocation(),
886 FD->getType(), VK_LValue, OK_Ordinary);
887 IvarT = Context->getDecltypeType(ME, ME->getType());
888 }
889 }
Fariborz Jahanian89919cc2012-05-08 23:54:35 +0000890 convertObjCTypeToCStyleType(IvarT);
891 QualType castT = Context->getPointerType(IvarT);
892 std::string TypeString(castT.getAsString(Context->getPrintingPolicy()));
893 S += TypeString;
894 S += ")";
Fangrui Song6907ce22018-07-30 19:24:48 +0000895
Fariborz Jahanian89919cc2012-05-08 23:54:35 +0000896 // ((char *)self + IVAR_OFFSET_SYMBOL_NAME)
897 S += "((char *)self + ";
898 S += IvarOffsetName;
899 S += "))";
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +0000900 if (D->isBitField()) {
901 S += ".";
902 S += D->getNameAsString();
903 }
Fariborz Jahanian89919cc2012-05-08 23:54:35 +0000904 ReferencedIvars[const_cast<ObjCInterfaceDecl *>(ClassDecl)].insert(D);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000905 return S;
906}
907
Fariborz Jahanianf687e7b2012-05-03 22:52:13 +0000908/// mustSynthesizeSetterGetterMethod - returns true if setter or getter has not
909/// been found in the class implementation. In this case, it must be synthesized.
910static bool mustSynthesizeSetterGetterMethod(ObjCImplementationDecl *IMP,
911 ObjCPropertyDecl *PD,
912 bool getter) {
913 return getter ? !IMP->getInstanceMethod(PD->getGetterName())
914 : !IMP->getInstanceMethod(PD->getSetterName());
Fangrui Song6907ce22018-07-30 19:24:48 +0000915
Fariborz Jahanianf687e7b2012-05-03 22:52:13 +0000916}
917
Fariborz Jahanian11671902012-02-07 17:11:38 +0000918void RewriteModernObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
919 ObjCImplementationDecl *IMD,
920 ObjCCategoryImplDecl *CID) {
921 static bool objcGetPropertyDefined = false;
922 static bool objcSetPropertyDefined = false;
Fariborz Jahanianf687e7b2012-05-03 22:52:13 +0000923 SourceLocation startGetterSetterLoc;
Fangrui Song6907ce22018-07-30 19:24:48 +0000924
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000925 if (PID->getBeginLoc().isValid()) {
926 SourceLocation startLoc = PID->getBeginLoc();
Fariborz Jahanianf687e7b2012-05-03 22:52:13 +0000927 InsertText(startLoc, "// ");
928 const char *startBuf = SM->getCharacterData(startLoc);
929 assert((*startBuf == '@') && "bogus @synthesize location");
930 const char *semiBuf = strchr(startBuf, ';');
931 assert((*semiBuf == ';') && "@synthesize: can't find ';'");
932 startGetterSetterLoc = startLoc.getLocWithOffset(semiBuf-startBuf+1);
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000933 } else
Stephen Kelly1c301dc2018-08-09 21:09:38 +0000934 startGetterSetterLoc = IMD ? IMD->getEndLoc() : CID->getEndLoc();
Fariborz Jahanian11671902012-02-07 17:11:38 +0000935
936 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
937 return; // FIXME: is this correct?
938
939 // Generate the 'getter' function.
940 ObjCPropertyDecl *PD = PID->getPropertyDecl();
941 ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
Jordan Rose755a2ff2013-03-15 21:41:35 +0000942 assert(IMD && OID && "Synthesized ivars must be attached to @implementation");
Fariborz Jahanian11671902012-02-07 17:11:38 +0000943
Bill Wendling44426052012-12-20 19:22:21 +0000944 unsigned Attributes = PD->getPropertyAttributes();
Fariborz Jahanianf687e7b2012-05-03 22:52:13 +0000945 if (mustSynthesizeSetterGetterMethod(IMD, PD, true /*getter*/)) {
Bill Wendling44426052012-12-20 19:22:21 +0000946 bool GenGetProperty = !(Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic) &&
Fangrui Song6907ce22018-07-30 19:24:48 +0000947 (Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
Fariborz Jahanian11671902012-02-07 17:11:38 +0000948 ObjCPropertyDecl::OBJC_PR_copy));
949 std::string Getr;
950 if (GenGetProperty && !objcGetPropertyDefined) {
951 objcGetPropertyDefined = true;
952 // FIXME. Is this attribute correct in all cases?
953 Getr = "\nextern \"C\" __declspec(dllimport) "
954 "id objc_getProperty(id, SEL, long, bool);\n";
955 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000956 RewriteObjCMethodDecl(OID->getContainingInterface(),
Fariborz Jahanian11671902012-02-07 17:11:38 +0000957 PD->getGetterMethodDecl(), Getr);
958 Getr += "{ ";
959 // Synthesize an explicit cast to gain access to the ivar.
960 // See objc-act.c:objc_synthesize_new_getter() for details.
961 if (GenGetProperty) {
962 // return objc_getProperty(self, _cmd, offsetof(ClassDecl, OID), 1)
963 Getr += "typedef ";
Craig Topper8ae12032014-05-07 06:21:57 +0000964 const FunctionType *FPRetType = nullptr;
Alp Toker314cc812014-01-25 16:55:45 +0000965 RewriteTypeIntoString(PD->getGetterMethodDecl()->getReturnType(), Getr,
Fariborz Jahanian11671902012-02-07 17:11:38 +0000966 FPRetType);
967 Getr += " _TYPE";
968 if (FPRetType) {
969 Getr += ")"; // close the precedence "scope" for "*".
Fangrui Song6907ce22018-07-30 19:24:48 +0000970
Fariborz Jahanian11671902012-02-07 17:11:38 +0000971 // Now, emit the argument types (if any).
972 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)){
973 Getr += "(";
Alp Toker9cacbab2014-01-20 20:26:09 +0000974 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
Fariborz Jahanian11671902012-02-07 17:11:38 +0000975 if (i) Getr += ", ";
Alp Toker9cacbab2014-01-20 20:26:09 +0000976 std::string ParamStr =
977 FT->getParamType(i).getAsString(Context->getPrintingPolicy());
Fariborz Jahanian11671902012-02-07 17:11:38 +0000978 Getr += ParamStr;
979 }
980 if (FT->isVariadic()) {
Alp Toker9cacbab2014-01-20 20:26:09 +0000981 if (FT->getNumParams())
982 Getr += ", ";
Fariborz Jahanian11671902012-02-07 17:11:38 +0000983 Getr += "...";
984 }
985 Getr += ")";
986 } else
987 Getr += "()";
988 }
989 Getr += ";\n";
990 Getr += "return (_TYPE)";
991 Getr += "objc_getProperty(self, _cmd, ";
992 RewriteIvarOffsetComputation(OID, Getr);
993 Getr += ", 1)";
994 }
995 else
996 Getr += "return " + getIvarAccessString(OID);
997 Getr += "; }";
Fariborz Jahanianf687e7b2012-05-03 22:52:13 +0000998 InsertText(startGetterSetterLoc, Getr);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000999 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001000
1001 if (PD->isReadOnly() ||
Fariborz Jahanianf687e7b2012-05-03 22:52:13 +00001002 !mustSynthesizeSetterGetterMethod(IMD, PD, false /*setter*/))
Fariborz Jahanian11671902012-02-07 17:11:38 +00001003 return;
1004
1005 // Generate the 'setter' function.
1006 std::string Setr;
Fangrui Song6907ce22018-07-30 19:24:48 +00001007 bool GenSetProperty = Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
Fariborz Jahanian11671902012-02-07 17:11:38 +00001008 ObjCPropertyDecl::OBJC_PR_copy);
1009 if (GenSetProperty && !objcSetPropertyDefined) {
1010 objcSetPropertyDefined = true;
1011 // FIXME. Is this attribute correct in all cases?
1012 Setr = "\nextern \"C\" __declspec(dllimport) "
1013 "void objc_setProperty (id, SEL, long, id, bool, bool);\n";
1014 }
Mandeep Singh Granga2baff02017-07-06 18:49:57 +00001015
Fangrui Song6907ce22018-07-30 19:24:48 +00001016 RewriteObjCMethodDecl(OID->getContainingInterface(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00001017 PD->getSetterMethodDecl(), Setr);
1018 Setr += "{ ";
1019 // Synthesize an explicit cast to initialize the ivar.
1020 // See objc-act.c:objc_synthesize_new_setter() for details.
1021 if (GenSetProperty) {
1022 Setr += "objc_setProperty (self, _cmd, ";
1023 RewriteIvarOffsetComputation(OID, Setr);
1024 Setr += ", (id)";
1025 Setr += PD->getName();
1026 Setr += ", ";
Bill Wendling44426052012-12-20 19:22:21 +00001027 if (Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic)
Fariborz Jahanian11671902012-02-07 17:11:38 +00001028 Setr += "0, ";
1029 else
1030 Setr += "1, ";
Bill Wendling44426052012-12-20 19:22:21 +00001031 if (Attributes & ObjCPropertyDecl::OBJC_PR_copy)
Fariborz Jahanian11671902012-02-07 17:11:38 +00001032 Setr += "1)";
1033 else
1034 Setr += "0)";
1035 }
1036 else {
1037 Setr += getIvarAccessString(OID) + " = ";
1038 Setr += PD->getName();
1039 }
Fariborz Jahanianf687e7b2012-05-03 22:52:13 +00001040 Setr += "; }\n";
1041 InsertText(startGetterSetterLoc, Setr);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001042}
1043
1044static void RewriteOneForwardClassDecl(ObjCInterfaceDecl *ForwardDecl,
1045 std::string &typedefString) {
Fariborz Jahaniane8730a32013-02-08 17:15:07 +00001046 typedefString += "\n#ifndef _REWRITER_typedef_";
Fariborz Jahanian11671902012-02-07 17:11:38 +00001047 typedefString += ForwardDecl->getNameAsString();
1048 typedefString += "\n";
1049 typedefString += "#define _REWRITER_typedef_";
1050 typedefString += ForwardDecl->getNameAsString();
1051 typedefString += "\n";
1052 typedefString += "typedef struct objc_object ";
1053 typedefString += ForwardDecl->getNameAsString();
Fariborz Jahanian2cc29af2012-03-12 23:58:28 +00001054 // typedef struct { } _objc_exc_Classname;
1055 typedefString += ";\ntypedef struct {} _objc_exc_";
1056 typedefString += ForwardDecl->getNameAsString();
Fariborz Jahanian11671902012-02-07 17:11:38 +00001057 typedefString += ";\n#endif\n";
1058}
1059
1060void RewriteModernObjC::RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
1061 const std::string &typedefString) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001062 SourceLocation startLoc = ClassDecl->getBeginLoc();
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00001063 const char *startBuf = SM->getCharacterData(startLoc);
Fangrui Song6907ce22018-07-30 19:24:48 +00001064 const char *semiPtr = strchr(startBuf, ';');
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00001065 // Replace the @class with typedefs corresponding to the classes.
Fangrui Song6907ce22018-07-30 19:24:48 +00001066 ReplaceText(startLoc, semiPtr-startBuf+1, typedefString);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001067}
1068
1069void RewriteModernObjC::RewriteForwardClassDecl(DeclGroupRef D) {
1070 std::string typedefString;
1071 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
Fariborz Jahanian0dded8a2013-09-24 17:03:07 +00001072 if (ObjCInterfaceDecl *ForwardDecl = dyn_cast<ObjCInterfaceDecl>(*I)) {
1073 if (I == D.begin()) {
1074 // Translate to typedef's that forward reference structs with the same name
1075 // as the class. As a convenience, we include the original declaration
1076 // as a comment.
1077 typedefString += "// @class ";
1078 typedefString += ForwardDecl->getNameAsString();
1079 typedefString += ";";
1080 }
1081 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001082 }
Fariborz Jahanian0dded8a2013-09-24 17:03:07 +00001083 else
1084 HandleTopLevelSingleDecl(*I);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001085 }
1086 DeclGroupRef::iterator I = D.begin();
1087 RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(*I), typedefString);
1088}
1089
1090void RewriteModernObjC::RewriteForwardClassDecl(
Craig Topper5603df42013-07-05 19:34:19 +00001091 const SmallVectorImpl<Decl *> &D) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00001092 std::string typedefString;
1093 for (unsigned i = 0; i < D.size(); i++) {
1094 ObjCInterfaceDecl *ForwardDecl = cast<ObjCInterfaceDecl>(D[i]);
1095 if (i == 0) {
1096 typedefString += "// @class ";
1097 typedefString += ForwardDecl->getNameAsString();
Fariborz Jahaniane8730a32013-02-08 17:15:07 +00001098 typedefString += ";";
Fariborz Jahanian11671902012-02-07 17:11:38 +00001099 }
1100 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
1101 }
1102 RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(D[0]), typedefString);
1103}
1104
1105void RewriteModernObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
1106 // When method is a synthesized one, such as a getter/setter there is
1107 // nothing to rewrite.
1108 if (Method->isImplicit())
1109 return;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001110 SourceLocation LocStart = Method->getBeginLoc();
Stephen Kelly1c301dc2018-08-09 21:09:38 +00001111 SourceLocation LocEnd = Method->getEndLoc();
Fariborz Jahanian11671902012-02-07 17:11:38 +00001112
1113 if (SM->getExpansionLineNumber(LocEnd) >
1114 SM->getExpansionLineNumber(LocStart)) {
1115 InsertText(LocStart, "#if 0\n");
1116 ReplaceText(LocEnd, 1, ";\n#endif\n");
1117 } else {
1118 InsertText(LocStart, "// ");
1119 }
1120}
1121
1122void RewriteModernObjC::RewriteProperty(ObjCPropertyDecl *prop) {
1123 SourceLocation Loc = prop->getAtLoc();
1124
1125 ReplaceText(Loc, 0, "// ");
1126 // FIXME: handle properties that are declared across multiple lines.
1127}
1128
1129void RewriteModernObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001130 SourceLocation LocStart = CatDecl->getBeginLoc();
Fariborz Jahanian11671902012-02-07 17:11:38 +00001131
1132 // FIXME: handle category headers that are declared across multiple lines.
Fariborz Jahanian144b7222012-05-01 17:46:45 +00001133 if (CatDecl->getIvarRBraceLoc().isValid()) {
1134 ReplaceText(LocStart, 1, "/** ");
1135 ReplaceText(CatDecl->getIvarRBraceLoc(), 1, "**/ ");
1136 }
1137 else {
Fariborz Jahanian2b383d212012-02-19 19:00:05 +00001138 ReplaceText(LocStart, 0, "// ");
Fariborz Jahanian144b7222012-05-01 17:46:45 +00001139 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001140
Manman Rena7a8b1f2016-01-26 18:05:23 +00001141 for (auto *I : CatDecl->instance_properties())
Aaron Ballmandc4bea42014-03-13 18:47:37 +00001142 RewriteProperty(I);
Fangrui Song6907ce22018-07-30 19:24:48 +00001143
Aaron Ballmanf26acce2014-03-13 19:50:17 +00001144 for (auto *I : CatDecl->instance_methods())
1145 RewriteMethodDeclaration(I);
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00001146 for (auto *I : CatDecl->class_methods())
1147 RewriteMethodDeclaration(I);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001148
1149 // Lastly, comment out the @end.
Fangrui Song6907ce22018-07-30 19:24:48 +00001150 ReplaceText(CatDecl->getAtEndRange().getBegin(),
Fariborz Jahanian3a65ce32013-04-03 19:11:21 +00001151 strlen("@end"), "/* @end */\n");
Fariborz Jahanian11671902012-02-07 17:11:38 +00001152}
1153
1154void RewriteModernObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001155 SourceLocation LocStart = PDecl->getBeginLoc();
Fariborz Jahanian11671902012-02-07 17:11:38 +00001156 assert(PDecl->isThisDeclarationADefinition());
Fangrui Song6907ce22018-07-30 19:24:48 +00001157
Fariborz Jahanian11671902012-02-07 17:11:38 +00001158 // FIXME: handle protocol headers that are declared across multiple lines.
1159 ReplaceText(LocStart, 0, "// ");
1160
Aaron Ballmanf26acce2014-03-13 19:50:17 +00001161 for (auto *I : PDecl->instance_methods())
1162 RewriteMethodDeclaration(I);
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00001163 for (auto *I : PDecl->class_methods())
1164 RewriteMethodDeclaration(I);
Manman Rena7a8b1f2016-01-26 18:05:23 +00001165 for (auto *I : PDecl->instance_properties())
Aaron Ballmandc4bea42014-03-13 18:47:37 +00001166 RewriteProperty(I);
Fangrui Song6907ce22018-07-30 19:24:48 +00001167
Fariborz Jahanian11671902012-02-07 17:11:38 +00001168 // Lastly, comment out the @end.
1169 SourceLocation LocEnd = PDecl->getAtEndRange().getBegin();
Fariborz Jahanian3a65ce32013-04-03 19:11:21 +00001170 ReplaceText(LocEnd, strlen("@end"), "/* @end */\n");
Fariborz Jahanian11671902012-02-07 17:11:38 +00001171
1172 // Must comment out @optional/@required
1173 const char *startBuf = SM->getCharacterData(LocStart);
1174 const char *endBuf = SM->getCharacterData(LocEnd);
1175 for (const char *p = startBuf; p < endBuf; p++) {
1176 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
1177 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
1178 ReplaceText(OptionalLoc, strlen("@optional"), "/* @optional */");
1179
1180 }
1181 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
1182 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
1183 ReplaceText(OptionalLoc, strlen("@required"), "/* @required */");
1184
1185 }
1186 }
1187}
1188
1189void RewriteModernObjC::RewriteForwardProtocolDecl(DeclGroupRef D) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001190 SourceLocation LocStart = (*D.begin())->getBeginLoc();
Fariborz Jahanian11671902012-02-07 17:11:38 +00001191 if (LocStart.isInvalid())
1192 llvm_unreachable("Invalid SourceLocation");
1193 // FIXME: handle forward protocol that are declared across multiple lines.
1194 ReplaceText(LocStart, 0, "// ");
1195}
1196
Fangrui Song6907ce22018-07-30 19:24:48 +00001197void
Craig Topper5603df42013-07-05 19:34:19 +00001198RewriteModernObjC::RewriteForwardProtocolDecl(const SmallVectorImpl<Decl *> &DG) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001199 SourceLocation LocStart = DG[0]->getBeginLoc();
Fariborz Jahanian11671902012-02-07 17:11:38 +00001200 if (LocStart.isInvalid())
1201 llvm_unreachable("Invalid SourceLocation");
1202 // FIXME: handle forward protocol that are declared across multiple lines.
1203 ReplaceText(LocStart, 0, "// ");
1204}
1205
1206void RewriteModernObjC::RewriteTypeIntoString(QualType T, std::string &ResultStr,
1207 const FunctionType *&FPRetType) {
1208 if (T->isObjCQualifiedIdType())
1209 ResultStr += "id";
1210 else if (T->isFunctionPointerType() ||
1211 T->isBlockPointerType()) {
1212 // needs special handling, since pointer-to-functions have special
1213 // syntax (where a decaration models use).
1214 QualType retType = T;
1215 QualType PointeeTy;
1216 if (const PointerType* PT = retType->getAs<PointerType>())
1217 PointeeTy = PT->getPointeeType();
1218 else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>())
1219 PointeeTy = BPT->getPointeeType();
1220 if ((FPRetType = PointeeTy->getAs<FunctionType>())) {
Alp Toker314cc812014-01-25 16:55:45 +00001221 ResultStr +=
1222 FPRetType->getReturnType().getAsString(Context->getPrintingPolicy());
Fariborz Jahanian11671902012-02-07 17:11:38 +00001223 ResultStr += "(*";
1224 }
1225 } else
1226 ResultStr += T.getAsString(Context->getPrintingPolicy());
1227}
1228
1229void RewriteModernObjC::RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
1230 ObjCMethodDecl *OMD,
1231 std::string &ResultStr) {
1232 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
Craig Topper8ae12032014-05-07 06:21:57 +00001233 const FunctionType *FPRetType = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00001234 ResultStr += "\nstatic ";
Alp Toker314cc812014-01-25 16:55:45 +00001235 RewriteTypeIntoString(OMD->getReturnType(), ResultStr, FPRetType);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001236 ResultStr += " ";
1237
1238 // Unique method name
1239 std::string NameStr;
1240
1241 if (OMD->isInstanceMethod())
1242 NameStr += "_I_";
1243 else
1244 NameStr += "_C_";
1245
1246 NameStr += IDecl->getNameAsString();
1247 NameStr += "_";
1248
1249 if (ObjCCategoryImplDecl *CID =
1250 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
1251 NameStr += CID->getNameAsString();
1252 NameStr += "_";
1253 }
1254 // Append selector names, replacing ':' with '_'
1255 {
1256 std::string selString = OMD->getSelector().getAsString();
1257 int len = selString.size();
1258 for (int i = 0; i < len; i++)
1259 if (selString[i] == ':')
1260 selString[i] = '_';
1261 NameStr += selString;
1262 }
1263 // Remember this name for metadata emission
1264 MethodInternalNames[OMD] = NameStr;
1265 ResultStr += NameStr;
1266
1267 // Rewrite arguments
1268 ResultStr += "(";
1269
1270 // invisible arguments
1271 if (OMD->isInstanceMethod()) {
1272 QualType selfTy = Context->getObjCInterfaceType(IDecl);
1273 selfTy = Context->getPointerType(selfTy);
1274 if (!LangOpts.MicrosoftExt) {
1275 if (ObjCSynthesizedStructs.count(const_cast<ObjCInterfaceDecl*>(IDecl)))
1276 ResultStr += "struct ";
1277 }
1278 // When rewriting for Microsoft, explicitly omit the structure name.
1279 ResultStr += IDecl->getNameAsString();
1280 ResultStr += " *";
1281 }
1282 else
1283 ResultStr += Context->getObjCClassType().getAsString(
1284 Context->getPrintingPolicy());
1285
1286 ResultStr += " self, ";
1287 ResultStr += Context->getObjCSelType().getAsString(Context->getPrintingPolicy());
1288 ResultStr += " _cmd";
1289
1290 // Method arguments.
David Majnemer59f77922016-06-24 04:05:48 +00001291 for (const auto *PDecl : OMD->parameters()) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00001292 ResultStr += ", ";
1293 if (PDecl->getType()->isObjCQualifiedIdType()) {
1294 ResultStr += "id ";
1295 ResultStr += PDecl->getNameAsString();
1296 } else {
1297 std::string Name = PDecl->getNameAsString();
1298 QualType QT = PDecl->getType();
1299 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian835cabe2012-03-27 16:42:20 +00001300 (void)convertBlockPointerToFunctionPointer(QT);
1301 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
Fariborz Jahanian11671902012-02-07 17:11:38 +00001302 ResultStr += Name;
1303 }
1304 }
1305 if (OMD->isVariadic())
1306 ResultStr += ", ...";
1307 ResultStr += ") ";
1308
1309 if (FPRetType) {
1310 ResultStr += ")"; // close the precedence "scope" for "*".
1311
1312 // Now, emit the argument types (if any).
1313 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
1314 ResultStr += "(";
Alp Toker9cacbab2014-01-20 20:26:09 +00001315 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00001316 if (i) ResultStr += ", ";
Alp Toker9cacbab2014-01-20 20:26:09 +00001317 std::string ParamStr =
1318 FT->getParamType(i).getAsString(Context->getPrintingPolicy());
Fariborz Jahanian11671902012-02-07 17:11:38 +00001319 ResultStr += ParamStr;
1320 }
1321 if (FT->isVariadic()) {
Alp Toker9cacbab2014-01-20 20:26:09 +00001322 if (FT->getNumParams())
1323 ResultStr += ", ";
Fariborz Jahanian11671902012-02-07 17:11:38 +00001324 ResultStr += "...";
1325 }
1326 ResultStr += ")";
1327 } else {
1328 ResultStr += "()";
1329 }
1330 }
1331}
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00001332
Fariborz Jahanian11671902012-02-07 17:11:38 +00001333void RewriteModernObjC::RewriteImplementationDecl(Decl *OID) {
1334 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
1335 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
1336
Fariborz Jahanian2b383d212012-02-19 19:00:05 +00001337 if (IMD) {
Fariborz Jahanian144b7222012-05-01 17:46:45 +00001338 if (IMD->getIvarRBraceLoc().isValid()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001339 ReplaceText(IMD->getBeginLoc(), 1, "/** ");
Fariborz Jahanian144b7222012-05-01 17:46:45 +00001340 ReplaceText(IMD->getIvarRBraceLoc(), 1, "**/ ");
Fariborz Jahanian2b383d212012-02-19 19:00:05 +00001341 }
Fariborz Jahanian144b7222012-05-01 17:46:45 +00001342 else {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001343 InsertText(IMD->getBeginLoc(), "// ");
Fariborz Jahanian144b7222012-05-01 17:46:45 +00001344 }
Fariborz Jahanian2b383d212012-02-19 19:00:05 +00001345 }
1346 else
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001347 InsertText(CID->getBeginLoc(), "// ");
Fariborz Jahanian11671902012-02-07 17:11:38 +00001348
Aaron Ballmanf26acce2014-03-13 19:50:17 +00001349 for (auto *OMD : IMD ? IMD->instance_methods() : CID->instance_methods()) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00001350 std::string ResultStr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00001351 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001352 SourceLocation LocStart = OMD->getBeginLoc();
1353 SourceLocation LocEnd = OMD->getCompoundBody()->getBeginLoc();
Fariborz Jahanian11671902012-02-07 17:11:38 +00001354
1355 const char *startBuf = SM->getCharacterData(LocStart);
1356 const char *endBuf = SM->getCharacterData(LocEnd);
1357 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
1358 }
1359
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00001360 for (auto *OMD : IMD ? IMD->class_methods() : CID->class_methods()) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00001361 std::string ResultStr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00001362 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001363 SourceLocation LocStart = OMD->getBeginLoc();
1364 SourceLocation LocEnd = OMD->getCompoundBody()->getBeginLoc();
Fariborz Jahanian11671902012-02-07 17:11:38 +00001365
1366 const char *startBuf = SM->getCharacterData(LocStart);
1367 const char *endBuf = SM->getCharacterData(LocEnd);
1368 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
1369 }
Aaron Ballmand85eff42014-03-14 15:02:45 +00001370 for (auto *I : IMD ? IMD->property_impls() : CID->property_impls())
1371 RewritePropertyImplDecl(I, IMD, CID);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001372
Stephen Kelly1c301dc2018-08-09 21:09:38 +00001373 InsertText(IMD ? IMD->getEndLoc() : CID->getEndLoc(), "// ");
Fariborz Jahanian11671902012-02-07 17:11:38 +00001374}
1375
1376void RewriteModernObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Fariborz Jahanian088959a2012-02-11 20:10:52 +00001377 // Do not synthesize more than once.
1378 if (ObjCSynthesizedStructs.count(ClassDecl))
1379 return;
1380 // Make sure super class's are written before current class is written.
1381 ObjCInterfaceDecl *SuperClass = ClassDecl->getSuperClass();
1382 while (SuperClass) {
1383 RewriteInterfaceDecl(SuperClass);
1384 SuperClass = SuperClass->getSuperClass();
1385 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00001386 std::string ResultStr;
Fariborz Jahaniand268b0c2012-02-17 22:20:12 +00001387 if (!ObjCWrittenInterfaces.count(ClassDecl->getCanonicalDecl())) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00001388 // we haven't seen a forward decl - generate a typedef.
Fariborz Jahanian2cc29af2012-03-12 23:58:28 +00001389 RewriteOneForwardClassDecl(ClassDecl, ResultStr);
Fariborz Jahanian5e49eb92012-02-22 18:13:25 +00001390 RewriteIvarOffsetSymbols(ClassDecl, ResultStr);
Fangrui Song6907ce22018-07-30 19:24:48 +00001391
Fariborz Jahanianff513382012-02-15 22:01:47 +00001392 RewriteObjCInternalStruct(ClassDecl, ResultStr);
Fariborz Jahaniand268b0c2012-02-17 22:20:12 +00001393 // Mark this typedef as having been written into its c++ equivalent.
1394 ObjCWrittenInterfaces.insert(ClassDecl->getCanonicalDecl());
Fangrui Song6907ce22018-07-30 19:24:48 +00001395
Manman Rena7a8b1f2016-01-26 18:05:23 +00001396 for (auto *I : ClassDecl->instance_properties())
Aaron Ballmandc4bea42014-03-13 18:47:37 +00001397 RewriteProperty(I);
Aaron Ballmanf26acce2014-03-13 19:50:17 +00001398 for (auto *I : ClassDecl->instance_methods())
1399 RewriteMethodDeclaration(I);
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00001400 for (auto *I : ClassDecl->class_methods())
1401 RewriteMethodDeclaration(I);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001402
Fariborz Jahanianff513382012-02-15 22:01:47 +00001403 // Lastly, comment out the @end.
Fangrui Song6907ce22018-07-30 19:24:48 +00001404 ReplaceText(ClassDecl->getAtEndRange().getBegin(), strlen("@end"),
Fariborz Jahanian3a65ce32013-04-03 19:11:21 +00001405 "/* @end */\n");
Fariborz Jahanianff513382012-02-15 22:01:47 +00001406 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00001407}
1408
1409Stmt *RewriteModernObjC::RewritePropertyOrImplicitSetter(PseudoObjectExpr *PseudoOp) {
1410 SourceRange OldRange = PseudoOp->getSourceRange();
1411
1412 // We just magically know some things about the structure of this
1413 // expression.
1414 ObjCMessageExpr *OldMsg =
1415 cast<ObjCMessageExpr>(PseudoOp->getSemanticExpr(
1416 PseudoOp->getNumSemanticExprs() - 1));
1417
1418 // Because the rewriter doesn't allow us to rewrite rewritten code,
1419 // we need to suppress rewriting the sub-statements.
Fariborz Jahanian31176b12012-04-10 22:06:54 +00001420 Expr *Base;
1421 SmallVector<Expr*, 2> Args;
Fariborz Jahanian11671902012-02-07 17:11:38 +00001422 {
1423 DisableReplaceStmtScope S(*this);
1424
1425 // Rebuild the base expression if we have one.
Craig Topper8ae12032014-05-07 06:21:57 +00001426 Base = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00001427 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1428 Base = OldMsg->getInstanceReceiver();
1429 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1430 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1431 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001432
Fariborz Jahanian31176b12012-04-10 22:06:54 +00001433 unsigned numArgs = OldMsg->getNumArgs();
1434 for (unsigned i = 0; i < numArgs; i++) {
1435 Expr *Arg = OldMsg->getArg(i);
1436 if (isa<OpaqueValueExpr>(Arg))
1437 Arg = cast<OpaqueValueExpr>(Arg)->getSourceExpr();
1438 Arg = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Arg));
1439 Args.push_back(Arg);
1440 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00001441 }
1442
1443 // TODO: avoid this copy.
1444 SmallVector<SourceLocation, 1> SelLocs;
1445 OldMsg->getSelectorLocs(SelLocs);
1446
Craig Topper8ae12032014-05-07 06:21:57 +00001447 ObjCMessageExpr *NewMsg = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00001448 switch (OldMsg->getReceiverKind()) {
1449 case ObjCMessageExpr::Class:
1450 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1451 OldMsg->getValueKind(),
1452 OldMsg->getLeftLoc(),
1453 OldMsg->getClassReceiverTypeInfo(),
1454 OldMsg->getSelector(),
1455 SelLocs,
1456 OldMsg->getMethodDecl(),
Fariborz Jahanian31176b12012-04-10 22:06:54 +00001457 Args,
Fariborz Jahanian11671902012-02-07 17:11:38 +00001458 OldMsg->getRightLoc(),
1459 OldMsg->isImplicit());
1460 break;
1461
1462 case ObjCMessageExpr::Instance:
1463 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1464 OldMsg->getValueKind(),
1465 OldMsg->getLeftLoc(),
1466 Base,
1467 OldMsg->getSelector(),
1468 SelLocs,
1469 OldMsg->getMethodDecl(),
Fariborz Jahanian31176b12012-04-10 22:06:54 +00001470 Args,
Fariborz Jahanian11671902012-02-07 17:11:38 +00001471 OldMsg->getRightLoc(),
1472 OldMsg->isImplicit());
1473 break;
1474
1475 case ObjCMessageExpr::SuperClass:
1476 case ObjCMessageExpr::SuperInstance:
1477 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1478 OldMsg->getValueKind(),
1479 OldMsg->getLeftLoc(),
1480 OldMsg->getSuperLoc(),
1481 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1482 OldMsg->getSuperType(),
1483 OldMsg->getSelector(),
1484 SelLocs,
1485 OldMsg->getMethodDecl(),
Fariborz Jahanian31176b12012-04-10 22:06:54 +00001486 Args,
Fariborz Jahanian11671902012-02-07 17:11:38 +00001487 OldMsg->getRightLoc(),
1488 OldMsg->isImplicit());
1489 break;
1490 }
1491
1492 Stmt *Replacement = SynthMessageExpr(NewMsg);
1493 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1494 return Replacement;
1495}
1496
1497Stmt *RewriteModernObjC::RewritePropertyOrImplicitGetter(PseudoObjectExpr *PseudoOp) {
1498 SourceRange OldRange = PseudoOp->getSourceRange();
1499
1500 // We just magically know some things about the structure of this
1501 // expression.
1502 ObjCMessageExpr *OldMsg =
1503 cast<ObjCMessageExpr>(PseudoOp->getResultExpr()->IgnoreImplicit());
1504
1505 // Because the rewriter doesn't allow us to rewrite rewritten code,
1506 // we need to suppress rewriting the sub-statements.
Craig Topper8ae12032014-05-07 06:21:57 +00001507 Expr *Base = nullptr;
Fariborz Jahanian31176b12012-04-10 22:06:54 +00001508 SmallVector<Expr*, 1> Args;
Fariborz Jahanian11671902012-02-07 17:11:38 +00001509 {
1510 DisableReplaceStmtScope S(*this);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001511 // Rebuild the base expression if we have one.
1512 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1513 Base = OldMsg->getInstanceReceiver();
1514 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1515 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1516 }
Fariborz Jahanian31176b12012-04-10 22:06:54 +00001517 unsigned numArgs = OldMsg->getNumArgs();
1518 for (unsigned i = 0; i < numArgs; i++) {
1519 Expr *Arg = OldMsg->getArg(i);
1520 if (isa<OpaqueValueExpr>(Arg))
1521 Arg = cast<OpaqueValueExpr>(Arg)->getSourceExpr();
1522 Arg = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Arg));
1523 Args.push_back(Arg);
1524 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00001525 }
1526
1527 // Intentionally empty.
1528 SmallVector<SourceLocation, 1> SelLocs;
Fariborz Jahanian11671902012-02-07 17:11:38 +00001529
Craig Topper8ae12032014-05-07 06:21:57 +00001530 ObjCMessageExpr *NewMsg = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00001531 switch (OldMsg->getReceiverKind()) {
1532 case ObjCMessageExpr::Class:
1533 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1534 OldMsg->getValueKind(),
1535 OldMsg->getLeftLoc(),
1536 OldMsg->getClassReceiverTypeInfo(),
1537 OldMsg->getSelector(),
1538 SelLocs,
1539 OldMsg->getMethodDecl(),
1540 Args,
1541 OldMsg->getRightLoc(),
1542 OldMsg->isImplicit());
1543 break;
1544
1545 case ObjCMessageExpr::Instance:
1546 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1547 OldMsg->getValueKind(),
1548 OldMsg->getLeftLoc(),
1549 Base,
1550 OldMsg->getSelector(),
1551 SelLocs,
1552 OldMsg->getMethodDecl(),
1553 Args,
1554 OldMsg->getRightLoc(),
1555 OldMsg->isImplicit());
1556 break;
1557
1558 case ObjCMessageExpr::SuperClass:
1559 case ObjCMessageExpr::SuperInstance:
1560 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1561 OldMsg->getValueKind(),
1562 OldMsg->getLeftLoc(),
1563 OldMsg->getSuperLoc(),
1564 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1565 OldMsg->getSuperType(),
1566 OldMsg->getSelector(),
1567 SelLocs,
1568 OldMsg->getMethodDecl(),
1569 Args,
1570 OldMsg->getRightLoc(),
1571 OldMsg->isImplicit());
1572 break;
1573 }
1574
1575 Stmt *Replacement = SynthMessageExpr(NewMsg);
1576 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1577 return Replacement;
1578}
1579
1580/// SynthCountByEnumWithState - To print:
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001581/// ((NSUInteger (*)
1582/// (id, SEL, struct __objcFastEnumerationState *, id *, NSUInteger))
Fariborz Jahanian11671902012-02-07 17:11:38 +00001583/// (void *)objc_msgSend)((id)l_collection,
1584/// sel_registerName(
1585/// "countByEnumeratingWithState:objects:count:"),
1586/// &enumState,
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001587/// (id *)__rw_items, (NSUInteger)16)
Fariborz Jahanian11671902012-02-07 17:11:38 +00001588///
1589void RewriteModernObjC::SynthCountByEnumWithState(std::string &buf) {
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001590 buf += "((_WIN_NSUInteger (*) (id, SEL, struct __objcFastEnumerationState *, "
1591 "id *, _WIN_NSUInteger))(void *)objc_msgSend)";
Fariborz Jahanian11671902012-02-07 17:11:38 +00001592 buf += "\n\t\t";
1593 buf += "((id)l_collection,\n\t\t";
1594 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1595 buf += "\n\t\t";
1596 buf += "&enumState, "
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001597 "(id *)__rw_items, (_WIN_NSUInteger)16)";
Fariborz Jahanian11671902012-02-07 17:11:38 +00001598}
1599
1600/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1601/// statement to exit to its outer synthesized loop.
1602///
1603Stmt *RewriteModernObjC::RewriteBreakStmt(BreakStmt *S) {
1604 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1605 return S;
1606 // replace break with goto __break_label
1607 std::string buf;
1608
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001609 SourceLocation startLoc = S->getBeginLoc();
Fariborz Jahanian11671902012-02-07 17:11:38 +00001610 buf = "goto __break_label_";
1611 buf += utostr(ObjCBcLabelNo.back());
1612 ReplaceText(startLoc, strlen("break"), buf);
1613
Craig Topper8ae12032014-05-07 06:21:57 +00001614 return nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00001615}
1616
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00001617void RewriteModernObjC::ConvertSourceLocationToLineDirective(
1618 SourceLocation Loc,
1619 std::string &LineString) {
Fariborz Jahaniane4c7e852013-02-08 00:27:34 +00001620 if (Loc.isFileID() && GenerateLineInfo) {
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00001621 LineString += "\n#line ";
1622 PresumedLoc PLoc = SM->getPresumedLoc(Loc);
1623 LineString += utostr(PLoc.getLine());
1624 LineString += " \"";
1625 LineString += Lexer::Stringify(PLoc.getFilename());
1626 LineString += "\"\n";
1627 }
1628}
1629
Fariborz Jahanian11671902012-02-07 17:11:38 +00001630/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1631/// statement to continue with its inner synthesized loop.
1632///
1633Stmt *RewriteModernObjC::RewriteContinueStmt(ContinueStmt *S) {
1634 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1635 return S;
1636 // replace continue with goto __continue_label
1637 std::string buf;
1638
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001639 SourceLocation startLoc = S->getBeginLoc();
Fariborz Jahanian11671902012-02-07 17:11:38 +00001640 buf = "goto __continue_label_";
1641 buf += utostr(ObjCBcLabelNo.back());
1642 ReplaceText(startLoc, strlen("continue"), buf);
1643
Craig Topper8ae12032014-05-07 06:21:57 +00001644 return nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00001645}
1646
1647/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
1648/// It rewrites:
1649/// for ( type elem in collection) { stmts; }
1650
1651/// Into:
1652/// {
1653/// type elem;
1654/// struct __objcFastEnumerationState enumState = { 0 };
1655/// id __rw_items[16];
1656/// id l_collection = (id)collection;
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001657/// NSUInteger limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian11671902012-02-07 17:11:38 +00001658/// objects:__rw_items count:16];
1659/// if (limit) {
1660/// unsigned long startMutations = *enumState.mutationsPtr;
1661/// do {
1662/// unsigned long counter = 0;
1663/// do {
1664/// if (startMutations != *enumState.mutationsPtr)
1665/// objc_enumerationMutation(l_collection);
1666/// elem = (type)enumState.itemsPtr[counter++];
1667/// stmts;
1668/// __continue_label: ;
1669/// } while (counter < limit);
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001670/// } while ((limit = [l_collection countByEnumeratingWithState:&enumState
1671/// objects:__rw_items count:16]));
Fariborz Jahanian11671902012-02-07 17:11:38 +00001672/// elem = nil;
1673/// __break_label: ;
1674/// }
1675/// else
1676/// elem = nil;
1677/// }
1678///
1679Stmt *RewriteModernObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
1680 SourceLocation OrigEnd) {
1681 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
1682 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
1683 "ObjCForCollectionStmt Statement stack mismatch");
1684 assert(!ObjCBcLabelNo.empty() &&
1685 "ObjCForCollectionStmt - Label No stack empty");
1686
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001687 SourceLocation startLoc = S->getBeginLoc();
Fariborz Jahanian11671902012-02-07 17:11:38 +00001688 const char *startBuf = SM->getCharacterData(startLoc);
1689 StringRef elementName;
1690 std::string elementTypeAsString;
1691 std::string buf;
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00001692 // line directive first.
1693 SourceLocation ForEachLoc = S->getForLoc();
1694 ConvertSourceLocationToLineDirective(ForEachLoc, buf);
1695 buf += "{\n\t";
Fariborz Jahanian11671902012-02-07 17:11:38 +00001696 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1697 // type elem;
1698 NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
1699 QualType ElementType = cast<ValueDecl>(D)->getType();
1700 if (ElementType->isObjCQualifiedIdType() ||
1701 ElementType->isObjCQualifiedInterfaceType())
1702 // Simply use 'id' for all qualified types.
1703 elementTypeAsString = "id";
1704 else
1705 elementTypeAsString = ElementType.getAsString(Context->getPrintingPolicy());
1706 buf += elementTypeAsString;
1707 buf += " ";
1708 elementName = D->getName();
1709 buf += elementName;
1710 buf += ";\n\t";
1711 }
1712 else {
1713 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
1714 elementName = DR->getDecl()->getName();
George Burgess IV00f70bd2018-03-01 05:43:23 +00001715 ValueDecl *VD = DR->getDecl();
Fariborz Jahanian11671902012-02-07 17:11:38 +00001716 if (VD->getType()->isObjCQualifiedIdType() ||
1717 VD->getType()->isObjCQualifiedInterfaceType())
1718 // Simply use 'id' for all qualified types.
1719 elementTypeAsString = "id";
1720 else
1721 elementTypeAsString = VD->getType().getAsString(Context->getPrintingPolicy());
1722 }
1723
1724 // struct __objcFastEnumerationState enumState = { 0 };
1725 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1726 // id __rw_items[16];
1727 buf += "id __rw_items[16];\n\t";
1728 // id l_collection = (id)
1729 buf += "id l_collection = (id)";
1730 // Find start location of 'collection' the hard way!
1731 const char *startCollectionBuf = startBuf;
1732 startCollectionBuf += 3; // skip 'for'
1733 startCollectionBuf = strchr(startCollectionBuf, '(');
1734 startCollectionBuf++; // skip '('
1735 // find 'in' and skip it.
1736 while (*startCollectionBuf != ' ' ||
1737 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1738 (*(startCollectionBuf+3) != ' ' &&
1739 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1740 startCollectionBuf++;
1741 startCollectionBuf += 3;
1742
1743 // Replace: "for (type element in" with string constructed thus far.
1744 ReplaceText(startLoc, startCollectionBuf - startBuf, buf);
1745 // Replace ')' in for '(' type elem in collection ')' with ';'
1746 SourceLocation rightParenLoc = S->getRParenLoc();
1747 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1748 SourceLocation lparenLoc = startLoc.getLocWithOffset(rparenBuf-startBuf);
1749 buf = ";\n\t";
1750
1751 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1752 // objects:__rw_items count:16];
1753 // which is synthesized into:
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001754 // NSUInteger limit =
1755 // ((NSUInteger (*)
1756 // (id, SEL, struct __objcFastEnumerationState *, id *, NSUInteger))
Fariborz Jahanian11671902012-02-07 17:11:38 +00001757 // (void *)objc_msgSend)((id)l_collection,
1758 // sel_registerName(
1759 // "countByEnumeratingWithState:objects:count:"),
1760 // (struct __objcFastEnumerationState *)&state,
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001761 // (id *)__rw_items, (NSUInteger)16);
1762 buf += "_WIN_NSUInteger limit =\n\t\t";
Fariborz Jahanian11671902012-02-07 17:11:38 +00001763 SynthCountByEnumWithState(buf);
1764 buf += ";\n\t";
1765 /// if (limit) {
1766 /// unsigned long startMutations = *enumState.mutationsPtr;
1767 /// do {
1768 /// unsigned long counter = 0;
1769 /// do {
1770 /// if (startMutations != *enumState.mutationsPtr)
1771 /// objc_enumerationMutation(l_collection);
1772 /// elem = (type)enumState.itemsPtr[counter++];
1773 buf += "if (limit) {\n\t";
1774 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1775 buf += "do {\n\t\t";
1776 buf += "unsigned long counter = 0;\n\t\t";
1777 buf += "do {\n\t\t\t";
1778 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1779 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1780 buf += elementName;
1781 buf += " = (";
1782 buf += elementTypeAsString;
1783 buf += ")enumState.itemsPtr[counter++];";
1784 // Replace ')' in for '(' type elem in collection ')' with all of these.
1785 ReplaceText(lparenLoc, 1, buf);
1786
1787 /// __continue_label: ;
1788 /// } while (counter < limit);
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001789 /// } while ((limit = [l_collection countByEnumeratingWithState:&enumState
1790 /// objects:__rw_items count:16]));
Fariborz Jahanian11671902012-02-07 17:11:38 +00001791 /// elem = nil;
1792 /// __break_label: ;
1793 /// }
1794 /// else
1795 /// elem = nil;
1796 /// }
1797 ///
1798 buf = ";\n\t";
1799 buf += "__continue_label_";
1800 buf += utostr(ObjCBcLabelNo.back());
1801 buf += ": ;";
1802 buf += "\n\t\t";
1803 buf += "} while (counter < limit);\n\t";
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001804 buf += "} while ((limit = ";
Fariborz Jahanian11671902012-02-07 17:11:38 +00001805 SynthCountByEnumWithState(buf);
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001806 buf += "));\n\t";
Fariborz Jahanian11671902012-02-07 17:11:38 +00001807 buf += elementName;
1808 buf += " = ((";
1809 buf += elementTypeAsString;
1810 buf += ")0);\n\t";
1811 buf += "__break_label_";
1812 buf += utostr(ObjCBcLabelNo.back());
1813 buf += ": ;\n\t";
1814 buf += "}\n\t";
1815 buf += "else\n\t\t";
1816 buf += elementName;
1817 buf += " = ((";
1818 buf += elementTypeAsString;
1819 buf += ")0);\n\t";
1820 buf += "}\n";
1821
1822 // Insert all these *after* the statement body.
1823 // FIXME: If this should support Obj-C++, support CXXTryStmt
1824 if (isa<CompoundStmt>(S->getBody())) {
1825 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(1);
1826 InsertText(endBodyLoc, buf);
1827 } else {
1828 /* Need to treat single statements specially. For example:
1829 *
1830 * for (A *a in b) if (stuff()) break;
1831 * for (A *a in b) xxxyy;
1832 *
1833 * The following code simply scans ahead to the semi to find the actual end.
1834 */
1835 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1836 const char *semiBuf = strchr(stmtBuf, ';');
1837 assert(semiBuf && "Can't find ';'");
1838 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(semiBuf-stmtBuf+1);
1839 InsertText(endBodyLoc, buf);
1840 }
1841 Stmts.pop_back();
1842 ObjCBcLabelNo.pop_back();
Craig Topper8ae12032014-05-07 06:21:57 +00001843 return nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00001844}
1845
Fariborz Jahanianfe6268e2012-03-16 21:33:16 +00001846static void Write_RethrowObject(std::string &buf) {
1847 buf += "{ struct _FIN { _FIN(id reth) : rethrow(reth) {}\n";
1848 buf += "\t~_FIN() { if (rethrow) objc_exception_throw(rethrow); }\n";
1849 buf += "\tid rethrow;\n";
1850 buf += "\t} _fin_force_rethow(_rethrow);";
1851}
1852
Fariborz Jahanian11671902012-02-07 17:11:38 +00001853/// RewriteObjCSynchronizedStmt -
1854/// This routine rewrites @synchronized(expr) stmt;
1855/// into:
1856/// objc_sync_enter(expr);
1857/// @try stmt @finally { objc_sync_exit(expr); }
1858///
1859Stmt *RewriteModernObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
1860 // Get the start location and compute the semi location.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001861 SourceLocation startLoc = S->getBeginLoc();
Fariborz Jahanian11671902012-02-07 17:11:38 +00001862 const char *startBuf = SM->getCharacterData(startLoc);
1863
1864 assert((*startBuf == '@') && "bogus @synchronized location");
1865
1866 std::string buf;
Fariborz Jahaniane030a632012-11-07 00:43:05 +00001867 SourceLocation SynchLoc = S->getAtSynchronizedLoc();
1868 ConvertSourceLocationToLineDirective(SynchLoc, buf);
Fariborz Jahanianff0c4602013-09-17 17:51:48 +00001869 buf += "{ id _rethrow = 0; id _sync_obj = (id)";
Fangrui Song6907ce22018-07-30 19:24:48 +00001870
Fariborz Jahanian11671902012-02-07 17:11:38 +00001871 const char *lparenBuf = startBuf;
1872 while (*lparenBuf != '(') lparenBuf++;
1873 ReplaceText(startLoc, lparenBuf-startBuf+1, buf);
Fangrui Song6907ce22018-07-30 19:24:48 +00001874
Fariborz Jahaniane8810762012-03-17 17:46:02 +00001875 buf = "; objc_sync_enter(_sync_obj);\n";
1876 buf += "try {\n\tstruct _SYNC_EXIT { _SYNC_EXIT(id arg) : sync_exit(arg) {}";
1877 buf += "\n\t~_SYNC_EXIT() {objc_sync_exit(sync_exit);}";
1878 buf += "\n\tid sync_exit;";
1879 buf += "\n\t} _sync_exit(_sync_obj);\n";
1880
Stephen Kelly1c301dc2018-08-09 21:09:38 +00001881 // We can't use S->getSynchExpr()->getEndLoc() to find the end location, since
Fariborz Jahaniane8810762012-03-17 17:46:02 +00001882 // the sync expression is typically a message expression that's already
1883 // been rewritten! (which implies the SourceLocation's are invalid).
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001884 SourceLocation RParenExprLoc = S->getSynchBody()->getBeginLoc();
Fariborz Jahaniane8810762012-03-17 17:46:02 +00001885 const char *RParenExprLocBuf = SM->getCharacterData(RParenExprLoc);
1886 while (*RParenExprLocBuf != ')') RParenExprLocBuf--;
1887 RParenExprLoc = startLoc.getLocWithOffset(RParenExprLocBuf-startBuf);
Fangrui Song6907ce22018-07-30 19:24:48 +00001888
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001889 SourceLocation LBranceLoc = S->getSynchBody()->getBeginLoc();
Fariborz Jahaniane8810762012-03-17 17:46:02 +00001890 const char *LBraceLocBuf = SM->getCharacterData(LBranceLoc);
1891 assert (*LBraceLocBuf == '{');
1892 ReplaceText(RParenExprLoc, (LBraceLocBuf - SM->getCharacterData(RParenExprLoc) + 1), buf);
Fangrui Song6907ce22018-07-30 19:24:48 +00001893
Stephen Kelly1c301dc2018-08-09 21:09:38 +00001894 SourceLocation startRBraceLoc = S->getSynchBody()->getEndLoc();
Matt Beaumont-Gay6e177d32012-03-16 22:20:39 +00001895 assert((*SM->getCharacterData(startRBraceLoc) == '}') &&
1896 "bogus @synchronized block");
Fangrui Song6907ce22018-07-30 19:24:48 +00001897
Fariborz Jahanianfe6268e2012-03-16 21:33:16 +00001898 buf = "} catch (id e) {_rethrow = e;}\n";
1899 Write_RethrowObject(buf);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001900 buf += "}\n";
Fariborz Jahanianfe6268e2012-03-16 21:33:16 +00001901 buf += "}\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00001902
Fariborz Jahanian1d24a0252012-03-16 21:43:45 +00001903 ReplaceText(startRBraceLoc, 1, buf);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001904
Craig Topper8ae12032014-05-07 06:21:57 +00001905 return nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00001906}
1907
1908void RewriteModernObjC::WarnAboutReturnGotoStmts(Stmt *S)
1909{
1910 // Perform a bottom up traversal of all children.
Benjamin Kramer642f1732015-07-02 21:03:14 +00001911 for (Stmt *SubStmt : S->children())
1912 if (SubStmt)
1913 WarnAboutReturnGotoStmts(SubStmt);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001914
1915 if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001916 Diags.Report(Context->getFullLoc(S->getBeginLoc()),
Fariborz Jahanian11671902012-02-07 17:11:38 +00001917 TryFinallyContainsReturnDiag);
1918 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00001919}
1920
Fariborz Jahanian9b43c3f2012-05-23 23:47:20 +00001921Stmt *RewriteModernObjC::RewriteObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S) {
1922 SourceLocation startLoc = S->getAtLoc();
1923 ReplaceText(startLoc, strlen("@autoreleasepool"), "/* @autoreleasepool */");
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001924 ReplaceText(S->getSubStmt()->getBeginLoc(), 1,
Fariborz Jahanianc37a1d62012-05-24 22:59:56 +00001925 "{ __AtAutoreleasePool __autoreleasepool; ");
Craig Topper8ae12032014-05-07 06:21:57 +00001926
1927 return nullptr;
Fariborz Jahanian9b43c3f2012-05-23 23:47:20 +00001928}
1929
Fariborz Jahanian11671902012-02-07 17:11:38 +00001930Stmt *RewriteModernObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Fariborz Jahanian3b71b172012-03-15 22:42:15 +00001931 ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt();
Fariborz Jahanianb960db42012-03-15 23:50:33 +00001932 bool noCatch = S->getNumCatchStmts() == 0;
Fariborz Jahanian3b71b172012-03-15 22:42:15 +00001933 std::string buf;
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00001934 SourceLocation TryLocation = S->getAtTryLoc();
1935 ConvertSourceLocationToLineDirective(TryLocation, buf);
Fangrui Song6907ce22018-07-30 19:24:48 +00001936
Fariborz Jahanian3b71b172012-03-15 22:42:15 +00001937 if (finalStmt) {
Fariborz Jahanianb960db42012-03-15 23:50:33 +00001938 if (noCatch)
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00001939 buf += "{ id volatile _rethrow = 0;\n";
Fariborz Jahanianb960db42012-03-15 23:50:33 +00001940 else {
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00001941 buf += "{ id volatile _rethrow = 0;\ntry {\n";
Fariborz Jahanianb960db42012-03-15 23:50:33 +00001942 }
Fariborz Jahanian3b71b172012-03-15 22:42:15 +00001943 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00001944 // Get the start location and compute the semi location.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001945 SourceLocation startLoc = S->getBeginLoc();
Fariborz Jahanian11671902012-02-07 17:11:38 +00001946 const char *startBuf = SM->getCharacterData(startLoc);
1947
1948 assert((*startBuf == '@') && "bogus @try location");
Fariborz Jahanian3b71b172012-03-15 22:42:15 +00001949 if (finalStmt)
1950 ReplaceText(startLoc, 1, buf);
1951 else
1952 // @try -> try
1953 ReplaceText(startLoc, 1, "");
Fangrui Song6907ce22018-07-30 19:24:48 +00001954
Fariborz Jahanian11671902012-02-07 17:11:38 +00001955 for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I) {
1956 ObjCAtCatchStmt *Catch = S->getCatchStmt(I);
Fariborz Jahanianf232bb42012-03-15 20:11:10 +00001957 VarDecl *catchDecl = Catch->getCatchParamDecl();
Fangrui Song6907ce22018-07-30 19:24:48 +00001958
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001959 startLoc = Catch->getBeginLoc();
Fariborz Jahanianf232bb42012-03-15 20:11:10 +00001960 bool AtRemoved = false;
1961 if (catchDecl) {
1962 QualType t = catchDecl->getType();
1963 if (const ObjCObjectPointerType *Ptr = t->getAs<ObjCObjectPointerType>()) {
1964 // Should be a pointer to a class.
1965 ObjCInterfaceDecl *IDecl = Ptr->getObjectType()->getInterface();
1966 if (IDecl) {
1967 std::string Result;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001968 ConvertSourceLocationToLineDirective(Catch->getBeginLoc(), Result);
Fangrui Song6907ce22018-07-30 19:24:48 +00001969
Fariborz Jahanianf232bb42012-03-15 20:11:10 +00001970 startBuf = SM->getCharacterData(startLoc);
1971 assert((*startBuf == '@') && "bogus @catch location");
1972 SourceLocation rParenLoc = Catch->getRParenLoc();
1973 const char *rParenBuf = SM->getCharacterData(rParenLoc);
Fangrui Song6907ce22018-07-30 19:24:48 +00001974
Fariborz Jahanianf232bb42012-03-15 20:11:10 +00001975 // _objc_exc_Foo *_e as argument to catch.
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00001976 Result += "catch (_objc_exc_"; Result += IDecl->getNameAsString();
Fariborz Jahanianf232bb42012-03-15 20:11:10 +00001977 Result += " *_"; Result += catchDecl->getNameAsString();
1978 Result += ")";
1979 ReplaceText(startLoc, rParenBuf-startBuf+1, Result);
1980 // Foo *e = (Foo *)_e;
1981 Result.clear();
1982 Result = "{ ";
1983 Result += IDecl->getNameAsString();
1984 Result += " *"; Result += catchDecl->getNameAsString();
1985 Result += " = ("; Result += IDecl->getNameAsString(); Result += "*)";
1986 Result += "_"; Result += catchDecl->getNameAsString();
Fangrui Song6907ce22018-07-30 19:24:48 +00001987
Fariborz Jahanianf232bb42012-03-15 20:11:10 +00001988 Result += "; ";
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001989 SourceLocation lBraceLoc = Catch->getCatchBody()->getBeginLoc();
Fariborz Jahanianf232bb42012-03-15 20:11:10 +00001990 ReplaceText(lBraceLoc, 1, Result);
1991 AtRemoved = true;
1992 }
1993 }
1994 }
1995 if (!AtRemoved)
1996 // @catch -> catch
1997 ReplaceText(startLoc, 1, "");
Fangrui Song6907ce22018-07-30 19:24:48 +00001998
Fariborz Jahanian11671902012-02-07 17:11:38 +00001999 }
Fariborz Jahanianb960db42012-03-15 23:50:33 +00002000 if (finalStmt) {
2001 buf.clear();
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002002 SourceLocation FinallyLoc = finalStmt->getBeginLoc();
Fangrui Song6907ce22018-07-30 19:24:48 +00002003
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00002004 if (noCatch) {
2005 ConvertSourceLocationToLineDirective(FinallyLoc, buf);
2006 buf += "catch (id e) {_rethrow = e;}\n";
2007 }
2008 else {
2009 buf += "}\n";
2010 ConvertSourceLocationToLineDirective(FinallyLoc, buf);
2011 buf += "catch (id e) {_rethrow = e;}\n";
2012 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002013
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002014 SourceLocation startFinalLoc = finalStmt->getBeginLoc();
Fariborz Jahanianb960db42012-03-15 23:50:33 +00002015 ReplaceText(startFinalLoc, 8, buf);
2016 Stmt *body = finalStmt->getFinallyBody();
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002017 SourceLocation startFinalBodyLoc = body->getBeginLoc();
Fariborz Jahanianb960db42012-03-15 23:50:33 +00002018 buf.clear();
Fariborz Jahanianfe6268e2012-03-16 21:33:16 +00002019 Write_RethrowObject(buf);
Fariborz Jahanianb960db42012-03-15 23:50:33 +00002020 ReplaceText(startFinalBodyLoc, 1, buf);
Fangrui Song6907ce22018-07-30 19:24:48 +00002021
Stephen Kelly1c301dc2018-08-09 21:09:38 +00002022 SourceLocation endFinalBodyLoc = body->getEndLoc();
Fariborz Jahanianb960db42012-03-15 23:50:33 +00002023 ReplaceText(endFinalBodyLoc, 1, "}\n}");
Fariborz Jahaniane8810762012-03-17 17:46:02 +00002024 // Now check for any return/continue/go statements within the @try.
2025 WarnAboutReturnGotoStmts(S->getTryBody());
Fariborz Jahanianb960db42012-03-15 23:50:33 +00002026 }
2027
Craig Topper8ae12032014-05-07 06:21:57 +00002028 return nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00002029}
2030
2031// This can't be done with ReplaceStmt(S, ThrowExpr), since
2032// the throw expression is typically a message expression that's already
2033// been rewritten! (which implies the SourceLocation's are invalid).
2034Stmt *RewriteModernObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
2035 // Get the start location and compute the semi location.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002036 SourceLocation startLoc = S->getBeginLoc();
Fariborz Jahanian11671902012-02-07 17:11:38 +00002037 const char *startBuf = SM->getCharacterData(startLoc);
2038
2039 assert((*startBuf == '@') && "bogus @throw location");
2040
2041 std::string buf;
2042 /* void objc_exception_throw(id) __attribute__((noreturn)); */
2043 if (S->getThrowExpr())
2044 buf = "objc_exception_throw(";
Fariborz Jahanian52fe6a02012-03-16 16:52:06 +00002045 else
2046 buf = "throw";
Fariborz Jahanian11671902012-02-07 17:11:38 +00002047
2048 // handle "@ throw" correctly.
2049 const char *wBuf = strchr(startBuf, 'w');
2050 assert((*wBuf == 'w') && "@throw: can't find 'w'");
2051 ReplaceText(startLoc, wBuf-startBuf+1, buf);
2052
Stephen Kelly1c301dc2018-08-09 21:09:38 +00002053 SourceLocation endLoc = S->getEndLoc();
Fariborz Jahanianb0fdab22013-02-11 19:30:33 +00002054 const char *endBuf = SM->getCharacterData(endLoc);
2055 const char *semiBuf = strchr(endBuf, ';');
Fariborz Jahanian11671902012-02-07 17:11:38 +00002056 assert((*semiBuf == ';') && "@throw: can't find ';'");
2057 SourceLocation semiLoc = startLoc.getLocWithOffset(semiBuf-startBuf);
Fariborz Jahanian52fe6a02012-03-16 16:52:06 +00002058 if (S->getThrowExpr())
2059 ReplaceText(semiLoc, 1, ");");
Craig Topper8ae12032014-05-07 06:21:57 +00002060 return nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00002061}
2062
2063Stmt *RewriteModernObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
2064 // Create a new string expression.
Fariborz Jahanian11671902012-02-07 17:11:38 +00002065 std::string StrEncoding;
2066 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
Benjamin Kramerfc188422014-02-25 12:26:11 +00002067 Expr *Replacement = getStringLiteral(StrEncoding);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002068 ReplaceStmt(Exp, Replacement);
2069
2070 // Replace this subexpr in the parent.
2071 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2072 return Replacement;
2073}
2074
2075Stmt *RewriteModernObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
2076 if (!SelGetUidFunctionDecl)
2077 SynthSelGetUidFunctionDecl();
2078 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
2079 // Create a call to sel_registerName("selName").
2080 SmallVector<Expr*, 8> SelExprs;
Benjamin Kramerfc188422014-02-25 12:26:11 +00002081 SelExprs.push_back(getStringLiteral(Exp->getSelector().getAsString()));
Fariborz Jahanian11671902012-02-07 17:11:38 +00002082 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
Craig Toppercf2126e2015-10-22 03:13:07 +00002083 SelExprs);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002084 ReplaceStmt(Exp, SelExp);
2085 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2086 return SelExp;
2087}
2088
Craig Toppercf2126e2015-10-22 03:13:07 +00002089CallExpr *
2090RewriteModernObjC::SynthesizeCallToFunctionDecl(FunctionDecl *FD,
2091 ArrayRef<Expr *> Args,
2092 SourceLocation StartLoc,
2093 SourceLocation EndLoc) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00002094 // Get the type, we will need to reference it in a couple spots.
2095 QualType msgSendType = FD->getType();
2096
2097 // Create a reference to the objc_msgSend() declaration.
Bruno Ricci5fc4db72018-12-21 14:10:18 +00002098 DeclRefExpr *DRE = new (Context) DeclRefExpr(*Context, FD, false, msgSendType,
2099 VK_LValue, SourceLocation());
Fariborz Jahanian11671902012-02-07 17:11:38 +00002100
2101 // Now, we cast the reference to a pointer to the objc_msgSend type.
2102 QualType pToFunc = Context->getPointerType(msgSendType);
Fangrui Song6907ce22018-07-30 19:24:48 +00002103 ImplicitCastExpr *ICE =
Fariborz Jahanian11671902012-02-07 17:11:38 +00002104 ImplicitCastExpr::Create(*Context, pToFunc, CK_FunctionToPointerDecay,
Craig Topper8ae12032014-05-07 06:21:57 +00002105 DRE, nullptr, VK_RValue);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002106
2107 const FunctionType *FT = msgSendType->getAs<FunctionType>();
2108
Bruno Riccic5885cf2018-12-21 15:20:32 +00002109 CallExpr *Exp = CallExpr::Create(
2110 *Context, ICE, Args, FT->getCallResultType(*Context), VK_RValue, EndLoc);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002111 return Exp;
2112}
2113
2114static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
2115 const char *&startRef, const char *&endRef) {
2116 while (startBuf < endBuf) {
2117 if (*startBuf == '<')
2118 startRef = startBuf; // mark the start.
2119 if (*startBuf == '>') {
2120 if (startRef && *startRef == '<') {
2121 endRef = startBuf; // mark the end.
2122 return true;
2123 }
2124 return false;
2125 }
2126 startBuf++;
2127 }
2128 return false;
2129}
2130
2131static void scanToNextArgument(const char *&argRef) {
2132 int angle = 0;
2133 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
2134 if (*argRef == '<')
2135 angle++;
2136 else if (*argRef == '>')
2137 angle--;
2138 argRef++;
2139 }
2140 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
2141}
2142
2143bool RewriteModernObjC::needToScanForQualifiers(QualType T) {
2144 if (T->isObjCQualifiedIdType())
2145 return true;
2146 if (const PointerType *PT = T->getAs<PointerType>()) {
2147 if (PT->getPointeeType()->isObjCQualifiedIdType())
2148 return true;
2149 }
2150 if (T->isObjCObjectPointerType()) {
2151 T = T->getPointeeType();
2152 return T->isObjCQualifiedInterfaceType();
2153 }
2154 if (T->isArrayType()) {
2155 QualType ElemTy = Context->getBaseElementType(T);
2156 return needToScanForQualifiers(ElemTy);
2157 }
2158 return false;
2159}
2160
2161void RewriteModernObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
2162 QualType Type = E->getType();
2163 if (needToScanForQualifiers(Type)) {
2164 SourceLocation Loc, EndLoc;
2165
2166 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
2167 Loc = ECE->getLParenLoc();
2168 EndLoc = ECE->getRParenLoc();
2169 } else {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002170 Loc = E->getBeginLoc();
Stephen Kelly1c301dc2018-08-09 21:09:38 +00002171 EndLoc = E->getEndLoc();
Fariborz Jahanian11671902012-02-07 17:11:38 +00002172 }
2173 // This will defend against trying to rewrite synthesized expressions.
2174 if (Loc.isInvalid() || EndLoc.isInvalid())
2175 return;
2176
2177 const char *startBuf = SM->getCharacterData(Loc);
2178 const char *endBuf = SM->getCharacterData(EndLoc);
Craig Topper8ae12032014-05-07 06:21:57 +00002179 const char *startRef = nullptr, *endRef = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00002180 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2181 // Get the locations of the startRef, endRef.
2182 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-startBuf);
2183 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-startBuf+1);
2184 // Comment out the protocol references.
2185 InsertText(LessLoc, "/*");
2186 InsertText(GreaterLoc, "*/");
2187 }
2188 }
2189}
2190
2191void RewriteModernObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
2192 SourceLocation Loc;
2193 QualType Type;
Craig Topper8ae12032014-05-07 06:21:57 +00002194 const FunctionProtoType *proto = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00002195 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
2196 Loc = VD->getLocation();
2197 Type = VD->getType();
2198 }
2199 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
2200 Loc = FD->getLocation();
2201 // Check for ObjC 'id' and class types that have been adorned with protocol
2202 // information (id<p>, C<p>*). The protocol references need to be rewritten!
2203 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2204 assert(funcType && "missing function type");
2205 proto = dyn_cast<FunctionProtoType>(funcType);
2206 if (!proto)
2207 return;
Alp Toker314cc812014-01-25 16:55:45 +00002208 Type = proto->getReturnType();
Fariborz Jahanian11671902012-02-07 17:11:38 +00002209 }
2210 else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
2211 Loc = FD->getLocation();
2212 Type = FD->getType();
2213 }
Fariborz Jahanian3a65ce32013-04-03 19:11:21 +00002214 else if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(Dcl)) {
2215 Loc = TD->getLocation();
2216 Type = TD->getUnderlyingType();
2217 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00002218 else
2219 return;
2220
2221 if (needToScanForQualifiers(Type)) {
2222 // Since types are unique, we need to scan the buffer.
2223
2224 const char *endBuf = SM->getCharacterData(Loc);
2225 const char *startBuf = endBuf;
2226 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
2227 startBuf--; // scan backward (from the decl location) for return type.
Craig Topper8ae12032014-05-07 06:21:57 +00002228 const char *startRef = nullptr, *endRef = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00002229 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2230 // Get the locations of the startRef, endRef.
2231 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-endBuf);
2232 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-endBuf+1);
2233 // Comment out the protocol references.
2234 InsertText(LessLoc, "/*");
2235 InsertText(GreaterLoc, "*/");
2236 }
2237 }
2238 if (!proto)
2239 return; // most likely, was a variable
2240 // Now check arguments.
2241 const char *startBuf = SM->getCharacterData(Loc);
2242 const char *startFuncBuf = startBuf;
Alp Toker9cacbab2014-01-20 20:26:09 +00002243 for (unsigned i = 0; i < proto->getNumParams(); i++) {
2244 if (needToScanForQualifiers(proto->getParamType(i))) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00002245 // Since types are unique, we need to scan the buffer.
2246
2247 const char *endBuf = startBuf;
2248 // scan forward (from the decl location) for argument types.
2249 scanToNextArgument(endBuf);
Craig Topper8ae12032014-05-07 06:21:57 +00002250 const char *startRef = nullptr, *endRef = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00002251 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2252 // Get the locations of the startRef, endRef.
2253 SourceLocation LessLoc =
2254 Loc.getLocWithOffset(startRef-startFuncBuf);
2255 SourceLocation GreaterLoc =
2256 Loc.getLocWithOffset(endRef-startFuncBuf+1);
2257 // Comment out the protocol references.
2258 InsertText(LessLoc, "/*");
2259 InsertText(GreaterLoc, "*/");
2260 }
2261 startBuf = ++endBuf;
2262 }
2263 else {
2264 // If the function name is derived from a macro expansion, then the
2265 // argument buffer will not follow the name. Need to speak with Chris.
2266 while (*startBuf && *startBuf != ')' && *startBuf != ',')
2267 startBuf++; // scan forward (from the decl location) for argument types.
2268 startBuf++;
2269 }
2270 }
2271}
2272
2273void RewriteModernObjC::RewriteTypeOfDecl(VarDecl *ND) {
2274 QualType QT = ND->getType();
2275 const Type* TypePtr = QT->getAs<Type>();
2276 if (!isa<TypeOfExprType>(TypePtr))
2277 return;
2278 while (isa<TypeOfExprType>(TypePtr)) {
2279 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
2280 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
2281 TypePtr = QT->getAs<Type>();
2282 }
2283 // FIXME. This will not work for multiple declarators; as in:
2284 // __typeof__(a) b,c,d;
2285 std::string TypeAsString(QT.getAsString(Context->getPrintingPolicy()));
2286 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
2287 const char *startBuf = SM->getCharacterData(DeclLoc);
2288 if (ND->getInit()) {
2289 std::string Name(ND->getNameAsString());
2290 TypeAsString += " " + Name + " = ";
2291 Expr *E = ND->getInit();
2292 SourceLocation startLoc;
2293 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
2294 startLoc = ECE->getLParenLoc();
2295 else
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002296 startLoc = E->getBeginLoc();
Fariborz Jahanian11671902012-02-07 17:11:38 +00002297 startLoc = SM->getExpansionLoc(startLoc);
2298 const char *endBuf = SM->getCharacterData(startLoc);
2299 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
2300 }
2301 else {
Stephen Kelly1c301dc2018-08-09 21:09:38 +00002302 SourceLocation X = ND->getEndLoc();
Fariborz Jahanian11671902012-02-07 17:11:38 +00002303 X = SM->getExpansionLoc(X);
2304 const char *endBuf = SM->getCharacterData(X);
2305 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
2306 }
2307}
2308
2309// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
2310void RewriteModernObjC::SynthSelGetUidFunctionDecl() {
2311 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
2312 SmallVector<QualType, 16> ArgTys;
2313 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2314 QualType getFuncType =
Jordan Rose5c382722013-03-08 21:51:21 +00002315 getSimpleFunctionType(Context->getObjCSelType(), ArgTys);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002316 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002317 SourceLocation(),
2318 SourceLocation(),
Craig Topper8ae12032014-05-07 06:21:57 +00002319 SelGetUidIdent, getFuncType,
2320 nullptr, SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002321}
2322
2323void RewriteModernObjC::RewriteFunctionDecl(FunctionDecl *FD) {
2324 // declared in <objc/objc.h>
2325 if (FD->getIdentifier() &&
2326 FD->getName() == "sel_registerName") {
2327 SelGetUidFunctionDecl = FD;
2328 return;
2329 }
2330 RewriteObjCQualifiedInterfaceTypes(FD);
2331}
2332
2333void RewriteModernObjC::RewriteBlockPointerType(std::string& Str, QualType Type) {
2334 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
2335 const char *argPtr = TypeString.c_str();
2336 if (!strchr(argPtr, '^')) {
2337 Str += TypeString;
2338 return;
2339 }
2340 while (*argPtr) {
2341 Str += (*argPtr == '^' ? '*' : *argPtr);
2342 argPtr++;
2343 }
2344}
2345
2346// FIXME. Consolidate this routine with RewriteBlockPointerType.
2347void RewriteModernObjC::RewriteBlockPointerTypeVariable(std::string& Str,
2348 ValueDecl *VD) {
2349 QualType Type = VD->getType();
2350 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
2351 const char *argPtr = TypeString.c_str();
2352 int paren = 0;
2353 while (*argPtr) {
2354 switch (*argPtr) {
2355 case '(':
2356 Str += *argPtr;
2357 paren++;
2358 break;
2359 case ')':
2360 Str += *argPtr;
2361 paren--;
2362 break;
2363 case '^':
2364 Str += '*';
2365 if (paren == 1)
2366 Str += VD->getNameAsString();
2367 break;
2368 default:
2369 Str += *argPtr;
2370 break;
2371 }
2372 argPtr++;
2373 }
2374}
2375
Fariborz Jahanianca357d92012-04-19 00:50:01 +00002376void RewriteModernObjC::RewriteBlockLiteralFunctionDecl(FunctionDecl *FD) {
2377 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
2378 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2379 const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(funcType);
2380 if (!proto)
2381 return;
Alp Toker314cc812014-01-25 16:55:45 +00002382 QualType Type = proto->getReturnType();
Fariborz Jahanianca357d92012-04-19 00:50:01 +00002383 std::string FdStr = Type.getAsString(Context->getPrintingPolicy());
2384 FdStr += " ";
2385 FdStr += FD->getName();
2386 FdStr += "(";
Alp Toker9cacbab2014-01-20 20:26:09 +00002387 unsigned numArgs = proto->getNumParams();
Fariborz Jahanianca357d92012-04-19 00:50:01 +00002388 for (unsigned i = 0; i < numArgs; i++) {
Alp Toker9cacbab2014-01-20 20:26:09 +00002389 QualType ArgType = proto->getParamType(i);
Fariborz Jahanianca357d92012-04-19 00:50:01 +00002390 RewriteBlockPointerType(FdStr, ArgType);
2391 if (i+1 < numArgs)
2392 FdStr += ", ";
2393 }
Fariborz Jahaniandf0577d2012-04-19 16:30:28 +00002394 if (FD->isVariadic()) {
2395 FdStr += (numArgs > 0) ? ", ...);\n" : "...);\n";
2396 }
2397 else
2398 FdStr += ");\n";
Fariborz Jahanianca357d92012-04-19 00:50:01 +00002399 InsertText(FunLocStart, FdStr);
2400}
2401
Benjamin Kramer60509af2013-09-09 14:48:42 +00002402// SynthSuperConstructorFunctionDecl - id __rw_objc_super(id obj, id super);
2403void RewriteModernObjC::SynthSuperConstructorFunctionDecl() {
2404 if (SuperConstructorFunctionDecl)
Fariborz Jahanian11671902012-02-07 17:11:38 +00002405 return;
2406 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
2407 SmallVector<QualType, 16> ArgTys;
2408 QualType argT = Context->getObjCIdType();
2409 assert(!argT.isNull() && "Can't find 'id' type");
2410 ArgTys.push_back(argT);
2411 ArgTys.push_back(argT);
2412 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002413 ArgTys);
Benjamin Kramer60509af2013-09-09 14:48:42 +00002414 SuperConstructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002415 SourceLocation(),
2416 SourceLocation(),
2417 msgSendIdent, msgSendType,
Craig Topper8ae12032014-05-07 06:21:57 +00002418 nullptr, SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002419}
2420
2421// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
2422void RewriteModernObjC::SynthMsgSendFunctionDecl() {
2423 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
2424 SmallVector<QualType, 16> ArgTys;
2425 QualType argT = Context->getObjCIdType();
2426 assert(!argT.isNull() && "Can't find 'id' type");
2427 ArgTys.push_back(argT);
2428 argT = Context->getObjCSelType();
2429 assert(!argT.isNull() && "Can't find 'SEL' type");
2430 ArgTys.push_back(argT);
2431 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002432 ArgTys, /*isVariadic=*/true);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002433 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002434 SourceLocation(),
2435 SourceLocation(),
Craig Topper8ae12032014-05-07 06:21:57 +00002436 msgSendIdent, msgSendType, nullptr,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002437 SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002438}
2439
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00002440// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(void);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002441void RewriteModernObjC::SynthMsgSendSuperFunctionDecl() {
2442 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00002443 SmallVector<QualType, 2> ArgTys;
2444 ArgTys.push_back(Context->VoidTy);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002445 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002446 ArgTys, /*isVariadic=*/true);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002447 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002448 SourceLocation(),
2449 SourceLocation(),
Craig Topper8ae12032014-05-07 06:21:57 +00002450 msgSendIdent, msgSendType,
2451 nullptr, SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002452}
2453
2454// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
2455void RewriteModernObjC::SynthMsgSendStretFunctionDecl() {
2456 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
2457 SmallVector<QualType, 16> ArgTys;
2458 QualType argT = Context->getObjCIdType();
2459 assert(!argT.isNull() && "Can't find 'id' type");
2460 ArgTys.push_back(argT);
2461 argT = Context->getObjCSelType();
2462 assert(!argT.isNull() && "Can't find 'SEL' type");
2463 ArgTys.push_back(argT);
2464 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002465 ArgTys, /*isVariadic=*/true);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002466 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002467 SourceLocation(),
2468 SourceLocation(),
Craig Topper8ae12032014-05-07 06:21:57 +00002469 msgSendIdent, msgSendType,
2470 nullptr, SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002471}
2472
2473// SynthMsgSendSuperStretFunctionDecl -
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00002474// id objc_msgSendSuper_stret(void);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002475void RewriteModernObjC::SynthMsgSendSuperStretFunctionDecl() {
2476 IdentifierInfo *msgSendIdent =
2477 &Context->Idents.get("objc_msgSendSuper_stret");
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00002478 SmallVector<QualType, 2> ArgTys;
2479 ArgTys.push_back(Context->VoidTy);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002480 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002481 ArgTys, /*isVariadic=*/true);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002482 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2483 SourceLocation(),
2484 SourceLocation(),
Chad Rosierac00fbc2013-01-04 22:40:33 +00002485 msgSendIdent,
Craig Topper8ae12032014-05-07 06:21:57 +00002486 msgSendType, nullptr,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002487 SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002488}
2489
2490// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
2491void RewriteModernObjC::SynthMsgSendFpretFunctionDecl() {
2492 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
2493 SmallVector<QualType, 16> ArgTys;
2494 QualType argT = Context->getObjCIdType();
2495 assert(!argT.isNull() && "Can't find 'id' type");
2496 ArgTys.push_back(argT);
2497 argT = Context->getObjCSelType();
2498 assert(!argT.isNull() && "Can't find 'SEL' type");
2499 ArgTys.push_back(argT);
2500 QualType msgSendType = getSimpleFunctionType(Context->DoubleTy,
Jordan Rose5c382722013-03-08 21:51:21 +00002501 ArgTys, /*isVariadic=*/true);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002502 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002503 SourceLocation(),
2504 SourceLocation(),
Craig Topper8ae12032014-05-07 06:21:57 +00002505 msgSendIdent, msgSendType,
2506 nullptr, SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002507}
2508
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00002509// SynthGetClassFunctionDecl - Class objc_getClass(const char *name);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002510void RewriteModernObjC::SynthGetClassFunctionDecl() {
2511 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
2512 SmallVector<QualType, 16> ArgTys;
2513 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00002514 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002515 ArgTys);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002516 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002517 SourceLocation(),
2518 SourceLocation(),
Craig Topper8ae12032014-05-07 06:21:57 +00002519 getClassIdent, getClassType,
2520 nullptr, SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002521}
2522
2523// SynthGetSuperClassFunctionDecl - Class class_getSuperclass(Class cls);
2524void RewriteModernObjC::SynthGetSuperClassFunctionDecl() {
Fangrui Song6907ce22018-07-30 19:24:48 +00002525 IdentifierInfo *getSuperClassIdent =
Fariborz Jahanian11671902012-02-07 17:11:38 +00002526 &Context->Idents.get("class_getSuperclass");
2527 SmallVector<QualType, 16> ArgTys;
2528 ArgTys.push_back(Context->getObjCClassType());
2529 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002530 ArgTys);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002531 GetSuperClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2532 SourceLocation(),
2533 SourceLocation(),
2534 getSuperClassIdent,
Craig Topper8ae12032014-05-07 06:21:57 +00002535 getClassType, nullptr,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002536 SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002537}
2538
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00002539// SynthGetMetaClassFunctionDecl - Class objc_getMetaClass(const char *name);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002540void RewriteModernObjC::SynthGetMetaClassFunctionDecl() {
2541 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
2542 SmallVector<QualType, 16> ArgTys;
2543 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00002544 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002545 ArgTys);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002546 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002547 SourceLocation(),
2548 SourceLocation(),
2549 getClassIdent, getClassType,
Craig Topper8ae12032014-05-07 06:21:57 +00002550 nullptr, SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002551}
2552
2553Stmt *RewriteModernObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Richard Trieuddd01ce2014-06-09 22:53:25 +00002554 assert (Exp != nullptr && "Expected non-null ObjCStringLiteral");
Fariborz Jahanian11671902012-02-07 17:11:38 +00002555 QualType strType = getConstantStringStructType();
2556
2557 std::string S = "__NSConstantStringImpl_";
2558
2559 std::string tmpName = InFileName;
2560 unsigned i;
2561 for (i=0; i < tmpName.length(); i++) {
2562 char c = tmpName.at(i);
Alp Tokerd4733632013-12-05 04:47:09 +00002563 // replace any non-alphanumeric characters with '_'.
Jordan Rosea7d03842013-02-08 22:30:41 +00002564 if (!isAlphanumeric(c))
Fariborz Jahanian11671902012-02-07 17:11:38 +00002565 tmpName[i] = '_';
2566 }
2567 S += tmpName;
2568 S += "_";
2569 S += utostr(NumObjCStringLiterals++);
2570
2571 Preamble += "static __NSConstantStringImpl " + S;
2572 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2573 Preamble += "0x000007c8,"; // utf8_str
2574 // The pretty printer for StringLiteral handles escape characters properly.
2575 std::string prettyBufS;
2576 llvm::raw_string_ostream prettyBuf(prettyBufS);
Craig Topper8ae12032014-05-07 06:21:57 +00002577 Exp->getString()->printPretty(prettyBuf, nullptr, PrintingPolicy(LangOpts));
Fariborz Jahanian11671902012-02-07 17:11:38 +00002578 Preamble += prettyBuf.str();
2579 Preamble += ",";
2580 Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
2581
2582 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
2583 SourceLocation(), &Context->Idents.get(S),
Craig Topper8ae12032014-05-07 06:21:57 +00002584 strType, nullptr, SC_Static);
Bruno Ricci5fc4db72018-12-21 14:10:18 +00002585 DeclRefExpr *DRE = new (Context)
2586 DeclRefExpr(*Context, NewVD, false, strType, VK_LValue, SourceLocation());
2587 Expr *Unop = new (Context)
2588 UnaryOperator(DRE, UO_AddrOf, Context->getPointerType(DRE->getType()),
2589 VK_RValue, OK_Ordinary, SourceLocation(), false);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002590 // cast to NSConstantString *
2591 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Exp->getType(),
2592 CK_CPointerToObjCPointerCast, Unop);
2593 ReplaceStmt(Exp, cast);
2594 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2595 return cast;
2596}
2597
Fariborz Jahanian307b7ad2012-03-27 20:17:30 +00002598Stmt *RewriteModernObjC::RewriteObjCBoolLiteralExpr(ObjCBoolLiteralExpr *Exp) {
2599 unsigned IntSize =
2600 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Fangrui Song6907ce22018-07-30 19:24:48 +00002601
2602 Expr *FlagExp = IntegerLiteral::Create(*Context,
2603 llvm::APInt(IntSize, Exp->getValue()),
Fariborz Jahanian307b7ad2012-03-27 20:17:30 +00002604 Context->IntTy, Exp->getLocation());
2605 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Context->ObjCBuiltinBoolTy,
2606 CK_BitCast, FlagExp);
Fangrui Song6907ce22018-07-30 19:24:48 +00002607 ParenExpr *PE = new (Context) ParenExpr(Exp->getLocation(), Exp->getExprLoc(),
Fariborz Jahanian307b7ad2012-03-27 20:17:30 +00002608 cast);
2609 ReplaceStmt(Exp, PE);
2610 return PE;
2611}
2612
Patrick Beard0caa3942012-04-19 00:25:12 +00002613Stmt *RewriteModernObjC::RewriteObjCBoxedExpr(ObjCBoxedExpr *Exp) {
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002614 // synthesize declaration of helper functions needed in this routine.
2615 if (!SelGetUidFunctionDecl)
2616 SynthSelGetUidFunctionDecl();
2617 // use objc_msgSend() for all.
2618 if (!MsgSendFunctionDecl)
2619 SynthMsgSendFunctionDecl();
2620 if (!GetClassFunctionDecl)
2621 SynthGetClassFunctionDecl();
Fangrui Song6907ce22018-07-30 19:24:48 +00002622
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002623 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002624 SourceLocation StartLoc = Exp->getBeginLoc();
Stephen Kelly1c301dc2018-08-09 21:09:38 +00002625 SourceLocation EndLoc = Exp->getEndLoc();
Fangrui Song6907ce22018-07-30 19:24:48 +00002626
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002627 // Synthesize a call to objc_msgSend().
2628 SmallVector<Expr*, 4> MsgExprs;
2629 SmallVector<Expr*, 4> ClsExprs;
Fangrui Song6907ce22018-07-30 19:24:48 +00002630
Patrick Beard0caa3942012-04-19 00:25:12 +00002631 // Create a call to objc_getClass("<BoxingClass>"). It will be the 1st argument.
2632 ObjCMethodDecl *BoxingMethod = Exp->getBoxingMethod();
2633 ObjCInterfaceDecl *BoxingClass = BoxingMethod->getClassInterface();
Fangrui Song6907ce22018-07-30 19:24:48 +00002634
Patrick Beard0caa3942012-04-19 00:25:12 +00002635 IdentifierInfo *clsName = BoxingClass->getIdentifier();
Benjamin Kramerfc188422014-02-25 12:26:11 +00002636 ClsExprs.push_back(getStringLiteral(clsName->getName()));
Craig Toppercf2126e2015-10-22 03:13:07 +00002637 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl, ClsExprs,
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002638 StartLoc, EndLoc);
2639 MsgExprs.push_back(Cls);
Fangrui Song6907ce22018-07-30 19:24:48 +00002640
Patrick Beard0caa3942012-04-19 00:25:12 +00002641 // Create a call to sel_registerName("<BoxingMethod>:"), etc.
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002642 // it will be the 2nd argument.
2643 SmallVector<Expr*, 4> SelExprs;
Benjamin Kramerfc188422014-02-25 12:26:11 +00002644 SelExprs.push_back(
2645 getStringLiteral(BoxingMethod->getSelector().getAsString()));
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002646 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
Craig Toppercf2126e2015-10-22 03:13:07 +00002647 SelExprs, StartLoc, EndLoc);
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002648 MsgExprs.push_back(SelExp);
Fangrui Song6907ce22018-07-30 19:24:48 +00002649
Patrick Beard0caa3942012-04-19 00:25:12 +00002650 // User provided sub-expression is the 3rd, and last, argument.
2651 Expr *subExpr = Exp->getSubExpr();
2652 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(subExpr)) {
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002653 QualType type = ICE->getType();
2654 const Expr *SubExpr = ICE->IgnoreParenImpCasts();
2655 CastKind CK = CK_BitCast;
2656 if (SubExpr->getType()->isIntegralType(*Context) && type->isBooleanType())
2657 CK = CK_IntegralToBoolean;
Patrick Beard0caa3942012-04-19 00:25:12 +00002658 subExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, subExpr);
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002659 }
Patrick Beard0caa3942012-04-19 00:25:12 +00002660 MsgExprs.push_back(subExpr);
Fangrui Song6907ce22018-07-30 19:24:48 +00002661
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002662 SmallVector<QualType, 4> ArgTypes;
Fariborz Jahanianf8e68e22015-04-09 18:36:50 +00002663 ArgTypes.push_back(Context->getObjCClassType());
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002664 ArgTypes.push_back(Context->getObjCSelType());
Aaron Ballman43b68be2014-03-07 17:50:17 +00002665 for (const auto PI : BoxingMethod->parameters())
2666 ArgTypes.push_back(PI->getType());
Fangrui Song6907ce22018-07-30 19:24:48 +00002667
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002668 QualType returnType = Exp->getType();
2669 // Get the type, we will need to reference it in a couple spots.
2670 QualType msgSendType = MsgSendFlavor->getType();
Fangrui Song6907ce22018-07-30 19:24:48 +00002671
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002672 // Create a reference to the objc_msgSend() declaration.
Bruno Ricci5fc4db72018-12-21 14:10:18 +00002673 DeclRefExpr *DRE = new (Context) DeclRefExpr(
2674 *Context, MsgSendFlavor, false, msgSendType, VK_LValue, SourceLocation());
Fangrui Song6907ce22018-07-30 19:24:48 +00002675
Bruno Ricci5fc4db72018-12-21 14:10:18 +00002676 CastExpr *cast = NoTypeInfoCStyleCastExpr(
2677 Context, Context->getPointerType(Context->VoidTy), CK_BitCast, DRE);
Fangrui Song6907ce22018-07-30 19:24:48 +00002678
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002679 // Now do the "normal" pointer to function cast.
2680 QualType castType =
Jordan Rose5c382722013-03-08 21:51:21 +00002681 getSimpleFunctionType(returnType, ArgTypes, BoxingMethod->isVariadic());
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002682 castType = Context->getPointerType(castType);
2683 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2684 cast);
Fangrui Song6907ce22018-07-30 19:24:48 +00002685
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002686 // Don't forget the parens to enforce the proper binding.
2687 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
Fangrui Song6907ce22018-07-30 19:24:48 +00002688
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002689 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Bruno Riccic5885cf2018-12-21 15:20:32 +00002690 CallExpr *CE = CallExpr::Create(*Context, PE, MsgExprs, FT->getReturnType(),
2691 VK_RValue, EndLoc);
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002692 ReplaceStmt(Exp, CE);
2693 return CE;
2694}
2695
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002696Stmt *RewriteModernObjC::RewriteObjCArrayLiteralExpr(ObjCArrayLiteral *Exp) {
2697 // synthesize declaration of helper functions needed in this routine.
2698 if (!SelGetUidFunctionDecl)
2699 SynthSelGetUidFunctionDecl();
2700 // use objc_msgSend() for all.
2701 if (!MsgSendFunctionDecl)
2702 SynthMsgSendFunctionDecl();
2703 if (!GetClassFunctionDecl)
2704 SynthGetClassFunctionDecl();
Fangrui Song6907ce22018-07-30 19:24:48 +00002705
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002706 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002707 SourceLocation StartLoc = Exp->getBeginLoc();
Stephen Kelly1c301dc2018-08-09 21:09:38 +00002708 SourceLocation EndLoc = Exp->getEndLoc();
Fangrui Song6907ce22018-07-30 19:24:48 +00002709
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002710 // Build the expression: __NSContainer_literal(int, ...).arr
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00002711 QualType IntQT = Context->IntTy;
2712 QualType NSArrayFType =
Jordan Rose5c382722013-03-08 21:51:21 +00002713 getSimpleFunctionType(Context->VoidTy, IntQT, true);
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002714 std::string NSArrayFName("__NSContainer_literal");
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00002715 FunctionDecl *NSArrayFD = SynthBlockInitFunctionDecl(NSArrayFName);
Bruno Ricci5fc4db72018-12-21 14:10:18 +00002716 DeclRefExpr *NSArrayDRE = new (Context) DeclRefExpr(
2717 *Context, NSArrayFD, false, NSArrayFType, VK_RValue, SourceLocation());
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00002718
2719 SmallVector<Expr*, 16> InitExprs;
2720 unsigned NumElements = Exp->getNumElements();
Fangrui Song6907ce22018-07-30 19:24:48 +00002721 unsigned UnsignedIntSize =
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00002722 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
2723 Expr *count = IntegerLiteral::Create(*Context,
2724 llvm::APInt(UnsignedIntSize, NumElements),
2725 Context->UnsignedIntTy, SourceLocation());
2726 InitExprs.push_back(count);
2727 for (unsigned i = 0; i < NumElements; i++)
2728 InitExprs.push_back(Exp->getElement(i));
Fangrui Song6907ce22018-07-30 19:24:48 +00002729 Expr *NSArrayCallExpr =
Bruno Riccic5885cf2018-12-21 15:20:32 +00002730 CallExpr::Create(*Context, NSArrayDRE, InitExprs, NSArrayFType, VK_LValue,
2731 SourceLocation());
Craig Topper8ae12032014-05-07 06:21:57 +00002732
2733 FieldDecl *ARRFD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00002734 SourceLocation(),
2735 &Context->Idents.get("arr"),
Fariborz Jahanianf8e68e22015-04-09 18:36:50 +00002736 Context->getPointerType(Context->VoidPtrTy),
2737 nullptr, /*BitWidth=*/nullptr,
2738 /*Mutable=*/true, ICIS_NoInit);
2739 MemberExpr *ArrayLiteralME = new (Context)
2740 MemberExpr(NSArrayCallExpr, false, SourceLocation(), ARRFD,
2741 SourceLocation(), ARRFD->getType(), VK_LValue, OK_Ordinary);
2742 QualType ConstIdT = Context->getObjCIdType().withConst();
Fangrui Song6907ce22018-07-30 19:24:48 +00002743 CStyleCastExpr * ArrayLiteralObjects =
2744 NoTypeInfoCStyleCastExpr(Context,
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00002745 Context->getPointerType(ConstIdT),
2746 CK_BitCast,
2747 ArrayLiteralME);
Fangrui Song6907ce22018-07-30 19:24:48 +00002748
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002749 // Synthesize a call to objc_msgSend().
2750 SmallVector<Expr*, 32> MsgExprs;
2751 SmallVector<Expr*, 4> ClsExprs;
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002752 QualType expType = Exp->getType();
Fangrui Song6907ce22018-07-30 19:24:48 +00002753
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002754 // Create a call to objc_getClass("NSArray"). It will be th 1st argument.
Fangrui Song6907ce22018-07-30 19:24:48 +00002755 ObjCInterfaceDecl *Class =
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002756 expType->getPointeeType()->getAs<ObjCObjectType>()->getInterface();
Fangrui Song6907ce22018-07-30 19:24:48 +00002757
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002758 IdentifierInfo *clsName = Class->getIdentifier();
Benjamin Kramerfc188422014-02-25 12:26:11 +00002759 ClsExprs.push_back(getStringLiteral(clsName->getName()));
Craig Toppercf2126e2015-10-22 03:13:07 +00002760 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl, ClsExprs,
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002761 StartLoc, EndLoc);
2762 MsgExprs.push_back(Cls);
Fangrui Song6907ce22018-07-30 19:24:48 +00002763
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002764 // Create a call to sel_registerName("arrayWithObjects:count:").
2765 // it will be the 2nd argument.
2766 SmallVector<Expr*, 4> SelExprs;
2767 ObjCMethodDecl *ArrayMethod = Exp->getArrayWithObjectsMethod();
Benjamin Kramerfc188422014-02-25 12:26:11 +00002768 SelExprs.push_back(
2769 getStringLiteral(ArrayMethod->getSelector().getAsString()));
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002770 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
Craig Toppercf2126e2015-10-22 03:13:07 +00002771 SelExprs, StartLoc, EndLoc);
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002772 MsgExprs.push_back(SelExp);
Fangrui Song6907ce22018-07-30 19:24:48 +00002773
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00002774 // (const id [])objects
2775 MsgExprs.push_back(ArrayLiteralObjects);
Fangrui Song6907ce22018-07-30 19:24:48 +00002776
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00002777 // (NSUInteger)cnt
2778 Expr *cnt = IntegerLiteral::Create(*Context,
2779 llvm::APInt(UnsignedIntSize, NumElements),
2780 Context->UnsignedIntTy, SourceLocation());
2781 MsgExprs.push_back(cnt);
Fangrui Song6907ce22018-07-30 19:24:48 +00002782
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002783 SmallVector<QualType, 4> ArgTypes;
Fariborz Jahanianf8e68e22015-04-09 18:36:50 +00002784 ArgTypes.push_back(Context->getObjCClassType());
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002785 ArgTypes.push_back(Context->getObjCSelType());
David Majnemer59f77922016-06-24 04:05:48 +00002786 for (const auto *PI : ArrayMethod->parameters())
Aaron Ballman43b68be2014-03-07 17:50:17 +00002787 ArgTypes.push_back(PI->getType());
Fangrui Song6907ce22018-07-30 19:24:48 +00002788
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002789 QualType returnType = Exp->getType();
2790 // Get the type, we will need to reference it in a couple spots.
2791 QualType msgSendType = MsgSendFlavor->getType();
Fangrui Song6907ce22018-07-30 19:24:48 +00002792
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002793 // Create a reference to the objc_msgSend() declaration.
Bruno Ricci5fc4db72018-12-21 14:10:18 +00002794 DeclRefExpr *DRE = new (Context) DeclRefExpr(
2795 *Context, MsgSendFlavor, false, msgSendType, VK_LValue, SourceLocation());
Fangrui Song6907ce22018-07-30 19:24:48 +00002796
Bruno Ricci5fc4db72018-12-21 14:10:18 +00002797 CastExpr *cast = NoTypeInfoCStyleCastExpr(
2798 Context, Context->getPointerType(Context->VoidTy), CK_BitCast, DRE);
Fangrui Song6907ce22018-07-30 19:24:48 +00002799
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002800 // Now do the "normal" pointer to function cast.
2801 QualType castType =
Jordan Rose5c382722013-03-08 21:51:21 +00002802 getSimpleFunctionType(returnType, ArgTypes, ArrayMethod->isVariadic());
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002803 castType = Context->getPointerType(castType);
2804 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2805 cast);
Fangrui Song6907ce22018-07-30 19:24:48 +00002806
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002807 // Don't forget the parens to enforce the proper binding.
2808 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
Fangrui Song6907ce22018-07-30 19:24:48 +00002809
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002810 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Bruno Riccic5885cf2018-12-21 15:20:32 +00002811 CallExpr *CE = CallExpr::Create(*Context, PE, MsgExprs, FT->getReturnType(),
2812 VK_RValue, EndLoc);
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002813 ReplaceStmt(Exp, CE);
2814 return CE;
2815}
2816
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002817Stmt *RewriteModernObjC::RewriteObjCDictionaryLiteralExpr(ObjCDictionaryLiteral *Exp) {
2818 // synthesize declaration of helper functions needed in this routine.
2819 if (!SelGetUidFunctionDecl)
2820 SynthSelGetUidFunctionDecl();
2821 // use objc_msgSend() for all.
2822 if (!MsgSendFunctionDecl)
2823 SynthMsgSendFunctionDecl();
2824 if (!GetClassFunctionDecl)
2825 SynthGetClassFunctionDecl();
Fangrui Song6907ce22018-07-30 19:24:48 +00002826
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002827 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002828 SourceLocation StartLoc = Exp->getBeginLoc();
Stephen Kelly1c301dc2018-08-09 21:09:38 +00002829 SourceLocation EndLoc = Exp->getEndLoc();
Fangrui Song6907ce22018-07-30 19:24:48 +00002830
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002831 // Build the expression: __NSContainer_literal(int, ...).arr
2832 QualType IntQT = Context->IntTy;
2833 QualType NSDictFType =
Jordan Rose5c382722013-03-08 21:51:21 +00002834 getSimpleFunctionType(Context->VoidTy, IntQT, true);
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002835 std::string NSDictFName("__NSContainer_literal");
2836 FunctionDecl *NSDictFD = SynthBlockInitFunctionDecl(NSDictFName);
Bruno Ricci5fc4db72018-12-21 14:10:18 +00002837 DeclRefExpr *NSDictDRE = new (Context) DeclRefExpr(
2838 *Context, NSDictFD, false, NSDictFType, VK_RValue, SourceLocation());
Fangrui Song6907ce22018-07-30 19:24:48 +00002839
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002840 SmallVector<Expr*, 16> KeyExprs;
2841 SmallVector<Expr*, 16> ValueExprs;
Fangrui Song6907ce22018-07-30 19:24:48 +00002842
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002843 unsigned NumElements = Exp->getNumElements();
Fangrui Song6907ce22018-07-30 19:24:48 +00002844 unsigned UnsignedIntSize =
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002845 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
2846 Expr *count = IntegerLiteral::Create(*Context,
2847 llvm::APInt(UnsignedIntSize, NumElements),
2848 Context->UnsignedIntTy, SourceLocation());
2849 KeyExprs.push_back(count);
2850 ValueExprs.push_back(count);
2851 for (unsigned i = 0; i < NumElements; i++) {
2852 ObjCDictionaryElement Element = Exp->getKeyValueElement(i);
2853 KeyExprs.push_back(Element.Key);
2854 ValueExprs.push_back(Element.Value);
2855 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002856
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002857 // (const id [])objects
Fangrui Song6907ce22018-07-30 19:24:48 +00002858 Expr *NSValueCallExpr =
Bruno Riccic5885cf2018-12-21 15:20:32 +00002859 CallExpr::Create(*Context, NSDictDRE, ValueExprs, NSDictFType, VK_LValue,
2860 SourceLocation());
Craig Topper8ae12032014-05-07 06:21:57 +00002861
2862 FieldDecl *ARRFD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002863 SourceLocation(),
2864 &Context->Idents.get("arr"),
Fariborz Jahanianf8e68e22015-04-09 18:36:50 +00002865 Context->getPointerType(Context->VoidPtrTy),
2866 nullptr, /*BitWidth=*/nullptr,
2867 /*Mutable=*/true, ICIS_NoInit);
2868 MemberExpr *DictLiteralValueME = new (Context)
2869 MemberExpr(NSValueCallExpr, false, SourceLocation(), ARRFD,
2870 SourceLocation(), ARRFD->getType(), VK_LValue, OK_Ordinary);
2871 QualType ConstIdT = Context->getObjCIdType().withConst();
Fangrui Song6907ce22018-07-30 19:24:48 +00002872 CStyleCastExpr * DictValueObjects =
2873 NoTypeInfoCStyleCastExpr(Context,
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002874 Context->getPointerType(ConstIdT),
2875 CK_BitCast,
2876 DictLiteralValueME);
2877 // (const id <NSCopying> [])keys
Bruno Riccic5885cf2018-12-21 15:20:32 +00002878 Expr *NSKeyCallExpr = CallExpr::Create(
2879 *Context, NSDictDRE, KeyExprs, NSDictFType, VK_LValue, SourceLocation());
Fariborz Jahanianf8e68e22015-04-09 18:36:50 +00002880
2881 MemberExpr *DictLiteralKeyME = new (Context)
2882 MemberExpr(NSKeyCallExpr, false, SourceLocation(), ARRFD,
2883 SourceLocation(), ARRFD->getType(), VK_LValue, OK_Ordinary);
2884
Fangrui Song6907ce22018-07-30 19:24:48 +00002885 CStyleCastExpr * DictKeyObjects =
2886 NoTypeInfoCStyleCastExpr(Context,
Fariborz Jahanianf8e68e22015-04-09 18:36:50 +00002887 Context->getPointerType(ConstIdT),
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002888 CK_BitCast,
2889 DictLiteralKeyME);
Fangrui Song6907ce22018-07-30 19:24:48 +00002890
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002891 // Synthesize a call to objc_msgSend().
2892 SmallVector<Expr*, 32> MsgExprs;
2893 SmallVector<Expr*, 4> ClsExprs;
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002894 QualType expType = Exp->getType();
Fangrui Song6907ce22018-07-30 19:24:48 +00002895
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002896 // Create a call to objc_getClass("NSArray"). It will be th 1st argument.
Fangrui Song6907ce22018-07-30 19:24:48 +00002897 ObjCInterfaceDecl *Class =
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002898 expType->getPointeeType()->getAs<ObjCObjectType>()->getInterface();
Fangrui Song6907ce22018-07-30 19:24:48 +00002899
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002900 IdentifierInfo *clsName = Class->getIdentifier();
Benjamin Kramerfc188422014-02-25 12:26:11 +00002901 ClsExprs.push_back(getStringLiteral(clsName->getName()));
Craig Toppercf2126e2015-10-22 03:13:07 +00002902 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl, ClsExprs,
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002903 StartLoc, EndLoc);
2904 MsgExprs.push_back(Cls);
Fangrui Song6907ce22018-07-30 19:24:48 +00002905
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002906 // Create a call to sel_registerName("arrayWithObjects:count:").
2907 // it will be the 2nd argument.
2908 SmallVector<Expr*, 4> SelExprs;
2909 ObjCMethodDecl *DictMethod = Exp->getDictWithObjectsMethod();
Benjamin Kramerfc188422014-02-25 12:26:11 +00002910 SelExprs.push_back(getStringLiteral(DictMethod->getSelector().getAsString()));
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002911 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
Craig Toppercf2126e2015-10-22 03:13:07 +00002912 SelExprs, StartLoc, EndLoc);
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002913 MsgExprs.push_back(SelExp);
Fangrui Song6907ce22018-07-30 19:24:48 +00002914
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002915 // (const id [])objects
2916 MsgExprs.push_back(DictValueObjects);
Fangrui Song6907ce22018-07-30 19:24:48 +00002917
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002918 // (const id <NSCopying> [])keys
2919 MsgExprs.push_back(DictKeyObjects);
Fangrui Song6907ce22018-07-30 19:24:48 +00002920
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002921 // (NSUInteger)cnt
2922 Expr *cnt = IntegerLiteral::Create(*Context,
2923 llvm::APInt(UnsignedIntSize, NumElements),
2924 Context->UnsignedIntTy, SourceLocation());
2925 MsgExprs.push_back(cnt);
Fangrui Song6907ce22018-07-30 19:24:48 +00002926
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002927 SmallVector<QualType, 8> ArgTypes;
Fariborz Jahanianf8e68e22015-04-09 18:36:50 +00002928 ArgTypes.push_back(Context->getObjCClassType());
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002929 ArgTypes.push_back(Context->getObjCSelType());
David Majnemer59f77922016-06-24 04:05:48 +00002930 for (const auto *PI : DictMethod->parameters()) {
Aaron Ballman43b68be2014-03-07 17:50:17 +00002931 QualType T = PI->getType();
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002932 if (const PointerType* PT = T->getAs<PointerType>()) {
2933 QualType PointeeTy = PT->getPointeeType();
2934 convertToUnqualifiedObjCType(PointeeTy);
2935 T = Context->getPointerType(PointeeTy);
2936 }
2937 ArgTypes.push_back(T);
2938 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002939
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002940 QualType returnType = Exp->getType();
2941 // Get the type, we will need to reference it in a couple spots.
2942 QualType msgSendType = MsgSendFlavor->getType();
Fangrui Song6907ce22018-07-30 19:24:48 +00002943
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002944 // Create a reference to the objc_msgSend() declaration.
Bruno Ricci5fc4db72018-12-21 14:10:18 +00002945 DeclRefExpr *DRE = new (Context) DeclRefExpr(
2946 *Context, MsgSendFlavor, false, msgSendType, VK_LValue, SourceLocation());
Fangrui Song6907ce22018-07-30 19:24:48 +00002947
Bruno Ricci5fc4db72018-12-21 14:10:18 +00002948 CastExpr *cast = NoTypeInfoCStyleCastExpr(
2949 Context, Context->getPointerType(Context->VoidTy), CK_BitCast, DRE);
Fangrui Song6907ce22018-07-30 19:24:48 +00002950
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002951 // Now do the "normal" pointer to function cast.
2952 QualType castType =
Jordan Rose5c382722013-03-08 21:51:21 +00002953 getSimpleFunctionType(returnType, ArgTypes, DictMethod->isVariadic());
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002954 castType = Context->getPointerType(castType);
2955 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2956 cast);
Fangrui Song6907ce22018-07-30 19:24:48 +00002957
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002958 // Don't forget the parens to enforce the proper binding.
2959 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
Fangrui Song6907ce22018-07-30 19:24:48 +00002960
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002961 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Bruno Riccic5885cf2018-12-21 15:20:32 +00002962 CallExpr *CE = CallExpr::Create(*Context, PE, MsgExprs, FT->getReturnType(),
2963 VK_RValue, EndLoc);
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002964 ReplaceStmt(Exp, CE);
2965 return CE;
2966}
2967
Fangrui Song6907ce22018-07-30 19:24:48 +00002968// struct __rw_objc_super {
2969// struct objc_object *object; struct objc_object *superClass;
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00002970// };
Fariborz Jahanian11671902012-02-07 17:11:38 +00002971QualType RewriteModernObjC::getSuperStructType() {
2972 if (!SuperStructDecl) {
2973 SuperStructDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
2974 SourceLocation(), SourceLocation(),
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00002975 &Context->Idents.get("__rw_objc_super"));
Fariborz Jahanian11671902012-02-07 17:11:38 +00002976 QualType FieldTypes[2];
2977
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00002978 // struct objc_object *object;
Fariborz Jahanian11671902012-02-07 17:11:38 +00002979 FieldTypes[0] = Context->getObjCIdType();
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00002980 // struct objc_object *superClass;
2981 FieldTypes[1] = Context->getObjCIdType();
Fariborz Jahanian11671902012-02-07 17:11:38 +00002982
2983 // Create fields
2984 for (unsigned i = 0; i < 2; ++i) {
2985 SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
2986 SourceLocation(),
Craig Topper8ae12032014-05-07 06:21:57 +00002987 SourceLocation(), nullptr,
2988 FieldTypes[i], nullptr,
2989 /*BitWidth=*/nullptr,
Fariborz Jahanian11671902012-02-07 17:11:38 +00002990 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00002991 ICIS_NoInit));
Fariborz Jahanian11671902012-02-07 17:11:38 +00002992 }
2993
2994 SuperStructDecl->completeDefinition();
2995 }
2996 return Context->getTagDeclType(SuperStructDecl);
2997}
2998
2999QualType RewriteModernObjC::getConstantStringStructType() {
3000 if (!ConstantStringDecl) {
3001 ConstantStringDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
3002 SourceLocation(), SourceLocation(),
3003 &Context->Idents.get("__NSConstantStringImpl"));
3004 QualType FieldTypes[4];
3005
3006 // struct objc_object *receiver;
3007 FieldTypes[0] = Context->getObjCIdType();
3008 // int flags;
3009 FieldTypes[1] = Context->IntTy;
3010 // char *str;
3011 FieldTypes[2] = Context->getPointerType(Context->CharTy);
3012 // long length;
3013 FieldTypes[3] = Context->LongTy;
3014
3015 // Create fields
3016 for (unsigned i = 0; i < 4; ++i) {
3017 ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
3018 ConstantStringDecl,
3019 SourceLocation(),
Craig Topper8ae12032014-05-07 06:21:57 +00003020 SourceLocation(), nullptr,
3021 FieldTypes[i], nullptr,
3022 /*BitWidth=*/nullptr,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003023 /*Mutable=*/true,
Richard Smith2b013182012-06-10 03:12:00 +00003024 ICIS_NoInit));
Fariborz Jahanian11671902012-02-07 17:11:38 +00003025 }
3026
3027 ConstantStringDecl->completeDefinition();
3028 }
3029 return Context->getTagDeclType(ConstantStringDecl);
3030}
3031
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003032/// getFunctionSourceLocation - returns start location of a function
3033/// definition. Complication arises when function has declared as
3034/// extern "C" or extern "C" {...}
3035static SourceLocation getFunctionSourceLocation (RewriteModernObjC &R,
3036 FunctionDecl *FD) {
3037 if (FD->isExternC() && !FD->isMain()) {
3038 const DeclContext *DC = FD->getDeclContext();
3039 if (const LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(DC))
3040 // if it is extern "C" {...}, return function decl's own location.
3041 if (!LSD->getRBraceLoc().isValid())
3042 return LSD->getExternLoc();
3043 }
Rafael Espindola6ae7e502013-04-03 19:27:57 +00003044 if (FD->getStorageClass() != SC_None)
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003045 R.RewriteBlockLiteralFunctionDecl(FD);
3046 return FD->getTypeSpecStartLoc();
3047}
3048
Fariborz Jahanianaa4a2422012-11-06 17:30:23 +00003049void RewriteModernObjC::RewriteLineDirective(const Decl *D) {
Fangrui Song6907ce22018-07-30 19:24:48 +00003050
Fariborz Jahanianaa4a2422012-11-06 17:30:23 +00003051 SourceLocation Location = D->getLocation();
Fangrui Song6907ce22018-07-30 19:24:48 +00003052
Fariborz Jahaniane4c7e852013-02-08 00:27:34 +00003053 if (Location.isFileID() && GenerateLineInfo) {
Fariborz Jahanian83dadc72012-11-07 18:15:53 +00003054 std::string LineString("\n#line ");
Fariborz Jahanianaa4a2422012-11-06 17:30:23 +00003055 PresumedLoc PLoc = SM->getPresumedLoc(Location);
3056 LineString += utostr(PLoc.getLine());
3057 LineString += " \"";
NAKAMURA Takumib46a05c2012-11-06 22:45:31 +00003058 LineString += Lexer::Stringify(PLoc.getFilename());
Fariborz Jahanianaa4a2422012-11-06 17:30:23 +00003059 if (isa<ObjCMethodDecl>(D))
3060 LineString += "\"";
3061 else LineString += "\"\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00003062
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003063 Location = D->getBeginLoc();
Fariborz Jahanianaa4a2422012-11-06 17:30:23 +00003064 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
3065 if (FD->isExternC() && !FD->isMain()) {
3066 const DeclContext *DC = FD->getDeclContext();
3067 if (const LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(DC))
3068 // if it is extern "C" {...}, return function decl's own location.
3069 if (!LSD->getRBraceLoc().isValid())
3070 Location = LSD->getExternLoc();
3071 }
3072 }
3073 InsertText(Location, LineString);
3074 }
3075}
3076
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003077/// SynthMsgSendStretCallExpr - This routine translates message expression
3078/// into a call to objc_msgSend_stret() entry point. Tricky part is that
3079/// nil check on receiver must be performed before calling objc_msgSend_stret.
3080/// MsgSendStretFlavor - function declaration objc_msgSend_stret(...)
3081/// msgSendType - function type of objc_msgSend_stret(...)
3082/// returnType - Result type of the method being synthesized.
3083/// ArgTypes - type of the arguments passed to objc_msgSend_stret, starting with receiver type.
Fangrui Song6907ce22018-07-30 19:24:48 +00003084/// MsgExprs - list of argument expressions being passed to objc_msgSend_stret,
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003085/// starting with receiver.
3086/// Method - Method being rewritten.
3087Expr *RewriteModernObjC::SynthMsgSendStretCallExpr(FunctionDecl *MsgSendStretFlavor,
Fangrui Song6907ce22018-07-30 19:24:48 +00003088 QualType returnType,
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003089 SmallVectorImpl<QualType> &ArgTypes,
3090 SmallVectorImpl<Expr*> &MsgExprs,
3091 ObjCMethodDecl *Method) {
3092 // Now do the "normal" pointer to function cast.
Jonas Devlieghere64a26302018-11-11 00:56:15 +00003093 QualType FuncType = getSimpleFunctionType(
3094 returnType, ArgTypes, Method ? Method->isVariadic() : false);
3095 QualType castType = Context->getPointerType(FuncType);
Fangrui Song6907ce22018-07-30 19:24:48 +00003096
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003097 // build type for containing the objc_msgSend_stret object.
3098 static unsigned stretCount=0;
3099 std::string name = "__Stret"; name += utostr(stretCount);
Fangrui Song6907ce22018-07-30 19:24:48 +00003100 std::string str =
Fariborz Jahanian1a112522012-07-25 21:48:36 +00003101 "extern \"C\" void * __cdecl memset(void *_Dst, int _Val, size_t _Size);\n";
Fariborz Jahanianb1a21242013-09-09 19:59:59 +00003102 str += "namespace {\n";
Fariborz Jahanian1a112522012-07-25 21:48:36 +00003103 str += "struct "; str += name;
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003104 str += " {\n\t";
3105 str += name;
3106 str += "(id receiver, SEL sel";
3107 for (unsigned i = 2; i < ArgTypes.size(); i++) {
Fariborz Jahanian2794ad52012-06-29 19:55:46 +00003108 std::string ArgName = "arg"; ArgName += utostr(i);
3109 ArgTypes[i].getAsStringInternal(ArgName, Context->getPrintingPolicy());
3110 str += ", "; str += ArgName;
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003111 }
3112 // could be vararg.
3113 for (unsigned i = ArgTypes.size(); i < MsgExprs.size(); i++) {
Fariborz Jahanian2794ad52012-06-29 19:55:46 +00003114 std::string ArgName = "arg"; ArgName += utostr(i);
3115 MsgExprs[i]->getType().getAsStringInternal(ArgName,
3116 Context->getPrintingPolicy());
3117 str += ", "; str += ArgName;
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003118 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003119
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003120 str += ") {\n";
Fariborz Jahanianb1a21242013-09-09 19:59:59 +00003121 str += "\t unsigned size = sizeof(";
3122 str += returnType.getAsString(Context->getPrintingPolicy()); str += ");\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00003123
Fariborz Jahanianb1a21242013-09-09 19:59:59 +00003124 str += "\t if (size == 1 || size == 2 || size == 4 || size == 8)\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00003125
Fariborz Jahanianb1a21242013-09-09 19:59:59 +00003126 str += "\t s = (("; str += castType.getAsString(Context->getPrintingPolicy());
3127 str += ")(void *)objc_msgSend)(receiver, sel";
3128 for (unsigned i = 2; i < ArgTypes.size(); i++) {
3129 str += ", arg"; str += utostr(i);
3130 }
3131 // could be vararg.
3132 for (unsigned i = ArgTypes.size(); i < MsgExprs.size(); i++) {
3133 str += ", arg"; str += utostr(i);
3134 }
3135 str+= ");\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00003136
Fariborz Jahanianb1a21242013-09-09 19:59:59 +00003137 str += "\t else if (receiver == 0)\n";
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003138 str += "\t memset((void*)&s, 0, sizeof(s));\n";
3139 str += "\t else\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00003140
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003141 str += "\t s = (("; str += castType.getAsString(Context->getPrintingPolicy());
3142 str += ")(void *)objc_msgSend_stret)(receiver, sel";
3143 for (unsigned i = 2; i < ArgTypes.size(); i++) {
3144 str += ", arg"; str += utostr(i);
3145 }
3146 // could be vararg.
3147 for (unsigned i = ArgTypes.size(); i < MsgExprs.size(); i++) {
3148 str += ", arg"; str += utostr(i);
3149 }
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003150 str += ");\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00003151
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003152 str += "\t}\n";
3153 str += "\t"; str += returnType.getAsString(Context->getPrintingPolicy());
3154 str += " s;\n";
Fariborz Jahanianb1a21242013-09-09 19:59:59 +00003155 str += "};\n};\n\n";
Fariborz Jahanianf1f36c62012-08-21 18:56:50 +00003156 SourceLocation FunLocStart;
3157 if (CurFunctionDef)
3158 FunLocStart = getFunctionSourceLocation(*this, CurFunctionDef);
3159 else {
3160 assert(CurMethodDef && "SynthMsgSendStretCallExpr - CurMethodDef is null");
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003161 FunLocStart = CurMethodDef->getBeginLoc();
Fariborz Jahanianf1f36c62012-08-21 18:56:50 +00003162 }
3163
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003164 InsertText(FunLocStart, str);
3165 ++stretCount;
Fangrui Song6907ce22018-07-30 19:24:48 +00003166
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003167 // AST for __Stretn(receiver, args).s;
3168 IdentifierInfo *ID = &Context->Idents.get(name);
Jonas Devlieghere64a26302018-11-11 00:56:15 +00003169 FunctionDecl *FD =
3170 FunctionDecl::Create(*Context, TUDecl, SourceLocation(), SourceLocation(),
3171 ID, FuncType, nullptr, SC_Extern, false, false);
Bruno Riccic5885cf2018-12-21 15:20:32 +00003172 DeclRefExpr *DRE = new (Context)
3173 DeclRefExpr(*Context, FD, false, castType, VK_RValue, SourceLocation());
3174 CallExpr *STCE = CallExpr::Create(*Context, DRE, MsgExprs, castType,
3175 VK_LValue, SourceLocation());
Craig Topper8ae12032014-05-07 06:21:57 +00003176
3177 FieldDecl *FieldD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003178 SourceLocation(),
3179 &Context->Idents.get("s"),
Fariborz Jahanianf8e68e22015-04-09 18:36:50 +00003180 returnType, nullptr,
3181 /*BitWidth=*/nullptr,
3182 /*Mutable=*/true, ICIS_NoInit);
3183 MemberExpr *ME = new (Context)
3184 MemberExpr(STCE, false, SourceLocation(), FieldD, SourceLocation(),
3185 FieldD->getType(), VK_LValue, OK_Ordinary);
3186
3187 return ME;
3188}
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003189
Fariborz Jahanian11671902012-02-07 17:11:38 +00003190Stmt *RewriteModernObjC::SynthMessageExpr(ObjCMessageExpr *Exp,
3191 SourceLocation StartLoc,
3192 SourceLocation EndLoc) {
3193 if (!SelGetUidFunctionDecl)
3194 SynthSelGetUidFunctionDecl();
3195 if (!MsgSendFunctionDecl)
3196 SynthMsgSendFunctionDecl();
3197 if (!MsgSendSuperFunctionDecl)
3198 SynthMsgSendSuperFunctionDecl();
3199 if (!MsgSendStretFunctionDecl)
3200 SynthMsgSendStretFunctionDecl();
3201 if (!MsgSendSuperStretFunctionDecl)
3202 SynthMsgSendSuperStretFunctionDecl();
3203 if (!MsgSendFpretFunctionDecl)
3204 SynthMsgSendFpretFunctionDecl();
3205 if (!GetClassFunctionDecl)
3206 SynthGetClassFunctionDecl();
3207 if (!GetSuperClassFunctionDecl)
3208 SynthGetSuperClassFunctionDecl();
3209 if (!GetMetaClassFunctionDecl)
3210 SynthGetMetaClassFunctionDecl();
3211
3212 // default to objc_msgSend().
3213 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
3214 // May need to use objc_msgSend_stret() as well.
Craig Topper8ae12032014-05-07 06:21:57 +00003215 FunctionDecl *MsgSendStretFlavor = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00003216 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
Alp Toker314cc812014-01-25 16:55:45 +00003217 QualType resultType = mDecl->getReturnType();
Fariborz Jahanian11671902012-02-07 17:11:38 +00003218 if (resultType->isRecordType())
3219 MsgSendStretFlavor = MsgSendStretFunctionDecl;
3220 else if (resultType->isRealFloatingType())
3221 MsgSendFlavor = MsgSendFpretFunctionDecl;
3222 }
3223
3224 // Synthesize a call to objc_msgSend().
3225 SmallVector<Expr*, 8> MsgExprs;
3226 switch (Exp->getReceiverKind()) {
3227 case ObjCMessageExpr::SuperClass: {
3228 MsgSendFlavor = MsgSendSuperFunctionDecl;
3229 if (MsgSendStretFlavor)
3230 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
3231 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
3232
3233 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
3234
3235 SmallVector<Expr*, 4> InitExprs;
3236
3237 // set the receiver to self, the first argument to all methods.
3238 InitExprs.push_back(
3239 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3240 CK_BitCast,
Bruno Ricci5fc4db72018-12-21 14:10:18 +00003241 new (Context) DeclRefExpr(*Context,
3242 CurMethodDef->getSelfDecl(),
John McCall113bee02012-03-10 09:33:50 +00003243 false,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003244 Context->getObjCIdType(),
3245 VK_RValue,
3246 SourceLocation()))
3247 ); // set the 'receiver'.
3248
3249 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3250 SmallVector<Expr*, 8> ClsExprs;
Benjamin Kramerfc188422014-02-25 12:26:11 +00003251 ClsExprs.push_back(getStringLiteral(ClassDecl->getIdentifier()->getName()));
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00003252 // (Class)objc_getClass("CurrentClass")
Fariborz Jahanian11671902012-02-07 17:11:38 +00003253 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
Craig Toppercf2126e2015-10-22 03:13:07 +00003254 ClsExprs, StartLoc, EndLoc);
Fariborz Jahanian11671902012-02-07 17:11:38 +00003255 ClsExprs.clear();
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00003256 ClsExprs.push_back(Cls);
Craig Toppercf2126e2015-10-22 03:13:07 +00003257 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl, ClsExprs,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003258 StartLoc, EndLoc);
Fangrui Song6907ce22018-07-30 19:24:48 +00003259
Fariborz Jahanian11671902012-02-07 17:11:38 +00003260 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3261 // To turn off a warning, type-cast to 'id'
3262 InitExprs.push_back( // set 'super class', using class_getSuperclass().
3263 NoTypeInfoCStyleCastExpr(Context,
3264 Context->getObjCIdType(),
3265 CK_BitCast, Cls));
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003266 // struct __rw_objc_super
Fariborz Jahanian11671902012-02-07 17:11:38 +00003267 QualType superType = getSuperStructType();
3268 Expr *SuperRep;
3269
3270 if (LangOpts.MicrosoftExt) {
Benjamin Kramer60509af2013-09-09 14:48:42 +00003271 SynthSuperConstructorFunctionDecl();
3272 // Simulate a constructor call...
Bruno Ricci5fc4db72018-12-21 14:10:18 +00003273 DeclRefExpr *DRE = new (Context)
3274 DeclRefExpr(*Context, SuperConstructorFunctionDecl, false, superType,
3275 VK_LValue, SourceLocation());
Bruno Riccic5885cf2018-12-21 15:20:32 +00003276 SuperRep = CallExpr::Create(*Context, DRE, InitExprs, superType,
3277 VK_LValue, SourceLocation());
Fariborz Jahanian11671902012-02-07 17:11:38 +00003278 // The code for super is a little tricky to prevent collision with
3279 // the structure definition in the header. The rewriter has it's own
3280 // internal definition (__rw_objc_super) that is uses. This is why
3281 // we need the cast below. For example:
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003282 // (struct __rw_objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
Fariborz Jahanian11671902012-02-07 17:11:38 +00003283 //
3284 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
3285 Context->getPointerType(SuperRep->getType()),
3286 VK_RValue, OK_Ordinary,
Aaron Ballmana5038552018-01-09 13:07:03 +00003287 SourceLocation(), false);
Fariborz Jahanian11671902012-02-07 17:11:38 +00003288 SuperRep = NoTypeInfoCStyleCastExpr(Context,
3289 Context->getPointerType(superType),
3290 CK_BitCast, SuperRep);
3291 } else {
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003292 // (struct __rw_objc_super) { <exprs from above> }
Fariborz Jahanian11671902012-02-07 17:11:38 +00003293 InitListExpr *ILE =
Benjamin Kramerc215e762012-08-24 11:54:20 +00003294 new (Context) InitListExpr(*Context, SourceLocation(), InitExprs,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003295 SourceLocation());
3296 TypeSourceInfo *superTInfo
3297 = Context->getTrivialTypeSourceInfo(superType);
3298 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
3299 superType, VK_LValue,
3300 ILE, false);
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003301 // struct __rw_objc_super *
Fariborz Jahanian11671902012-02-07 17:11:38 +00003302 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
3303 Context->getPointerType(SuperRep->getType()),
3304 VK_RValue, OK_Ordinary,
Aaron Ballmana5038552018-01-09 13:07:03 +00003305 SourceLocation(), false);
Fariborz Jahanian11671902012-02-07 17:11:38 +00003306 }
3307 MsgExprs.push_back(SuperRep);
3308 break;
3309 }
3310
3311 case ObjCMessageExpr::Class: {
3312 SmallVector<Expr*, 8> ClsExprs;
Fariborz Jahanian11671902012-02-07 17:11:38 +00003313 ObjCInterfaceDecl *Class
3314 = Exp->getClassReceiver()->getAs<ObjCObjectType>()->getInterface();
3315 IdentifierInfo *clsName = Class->getIdentifier();
Benjamin Kramerfc188422014-02-25 12:26:11 +00003316 ClsExprs.push_back(getStringLiteral(clsName->getName()));
Craig Toppercf2126e2015-10-22 03:13:07 +00003317 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl, ClsExprs,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003318 StartLoc, EndLoc);
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00003319 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
3320 Context->getObjCIdType(),
3321 CK_BitCast, Cls);
3322 MsgExprs.push_back(ArgExpr);
Fariborz Jahanian11671902012-02-07 17:11:38 +00003323 break;
3324 }
3325
3326 case ObjCMessageExpr::SuperInstance:{
3327 MsgSendFlavor = MsgSendSuperFunctionDecl;
3328 if (MsgSendStretFlavor)
3329 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
3330 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
3331 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
3332 SmallVector<Expr*, 4> InitExprs;
3333
3334 InitExprs.push_back(
3335 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3336 CK_BitCast,
Bruno Ricci5fc4db72018-12-21 14:10:18 +00003337 new (Context) DeclRefExpr(*Context,
3338 CurMethodDef->getSelfDecl(),
John McCall113bee02012-03-10 09:33:50 +00003339 false,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003340 Context->getObjCIdType(),
3341 VK_RValue, SourceLocation()))
3342 ); // set the 'receiver'.
Fangrui Song6907ce22018-07-30 19:24:48 +00003343
Fariborz Jahanian11671902012-02-07 17:11:38 +00003344 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3345 SmallVector<Expr*, 8> ClsExprs;
Benjamin Kramerfc188422014-02-25 12:26:11 +00003346 ClsExprs.push_back(getStringLiteral(ClassDecl->getIdentifier()->getName()));
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00003347 // (Class)objc_getClass("CurrentClass")
Craig Toppercf2126e2015-10-22 03:13:07 +00003348 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl, ClsExprs,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003349 StartLoc, EndLoc);
Fariborz Jahanian11671902012-02-07 17:11:38 +00003350 ClsExprs.clear();
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00003351 ClsExprs.push_back(Cls);
Craig Toppercf2126e2015-10-22 03:13:07 +00003352 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl, ClsExprs,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003353 StartLoc, EndLoc);
Fangrui Song6907ce22018-07-30 19:24:48 +00003354
Fariborz Jahanian11671902012-02-07 17:11:38 +00003355 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3356 // To turn off a warning, type-cast to 'id'
3357 InitExprs.push_back(
3358 // set 'super class', using class_getSuperclass().
3359 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3360 CK_BitCast, Cls));
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003361 // struct __rw_objc_super
Fariborz Jahanian11671902012-02-07 17:11:38 +00003362 QualType superType = getSuperStructType();
3363 Expr *SuperRep;
3364
3365 if (LangOpts.MicrosoftExt) {
Benjamin Kramer60509af2013-09-09 14:48:42 +00003366 SynthSuperConstructorFunctionDecl();
3367 // Simulate a constructor call...
Bruno Riccic5885cf2018-12-21 15:20:32 +00003368 DeclRefExpr *DRE = new (Context)
3369 DeclRefExpr(*Context, SuperConstructorFunctionDecl, false, superType,
3370 VK_LValue, SourceLocation());
3371 SuperRep = CallExpr::Create(*Context, DRE, InitExprs, superType,
3372 VK_LValue, SourceLocation());
Fariborz Jahanian11671902012-02-07 17:11:38 +00003373 // The code for super is a little tricky to prevent collision with
3374 // the structure definition in the header. The rewriter has it's own
3375 // internal definition (__rw_objc_super) that is uses. This is why
3376 // we need the cast below. For example:
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003377 // (struct __rw_objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
Fariborz Jahanian11671902012-02-07 17:11:38 +00003378 //
3379 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
3380 Context->getPointerType(SuperRep->getType()),
3381 VK_RValue, OK_Ordinary,
Aaron Ballmana5038552018-01-09 13:07:03 +00003382 SourceLocation(), false);
Fariborz Jahanian11671902012-02-07 17:11:38 +00003383 SuperRep = NoTypeInfoCStyleCastExpr(Context,
3384 Context->getPointerType(superType),
3385 CK_BitCast, SuperRep);
3386 } else {
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003387 // (struct __rw_objc_super) { <exprs from above> }
Fariborz Jahanian11671902012-02-07 17:11:38 +00003388 InitListExpr *ILE =
Benjamin Kramerc215e762012-08-24 11:54:20 +00003389 new (Context) InitListExpr(*Context, SourceLocation(), InitExprs,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003390 SourceLocation());
3391 TypeSourceInfo *superTInfo
3392 = Context->getTrivialTypeSourceInfo(superType);
3393 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
3394 superType, VK_RValue, ILE,
3395 false);
3396 }
3397 MsgExprs.push_back(SuperRep);
3398 break;
3399 }
3400
3401 case ObjCMessageExpr::Instance: {
3402 // Remove all type-casts because it may contain objc-style types; e.g.
3403 // Foo<Proto> *.
3404 Expr *recExpr = Exp->getInstanceReceiver();
3405 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
3406 recExpr = CE->getSubExpr();
3407 CastKind CK = recExpr->getType()->isObjCObjectPointerType()
3408 ? CK_BitCast : recExpr->getType()->isBlockPointerType()
3409 ? CK_BlockPointerToObjCPointerCast
3410 : CK_CPointerToObjCPointerCast;
3411
3412 recExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3413 CK, recExpr);
3414 MsgExprs.push_back(recExpr);
3415 break;
3416 }
3417 }
3418
3419 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
3420 SmallVector<Expr*, 8> SelExprs;
Benjamin Kramerfc188422014-02-25 12:26:11 +00003421 SelExprs.push_back(getStringLiteral(Exp->getSelector().getAsString()));
Fariborz Jahanian11671902012-02-07 17:11:38 +00003422 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
Craig Toppercf2126e2015-10-22 03:13:07 +00003423 SelExprs, StartLoc, EndLoc);
Fariborz Jahanian11671902012-02-07 17:11:38 +00003424 MsgExprs.push_back(SelExp);
3425
3426 // Now push any user supplied arguments.
3427 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
3428 Expr *userExpr = Exp->getArg(i);
3429 // Make all implicit casts explicit...ICE comes in handy:-)
3430 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
3431 // Reuse the ICE type, it is exactly what the doctor ordered.
3432 QualType type = ICE->getType();
3433 if (needToScanForQualifiers(type))
3434 type = Context->getObjCIdType();
3435 // Make sure we convert "type (^)(...)" to "type (*)(...)".
3436 (void)convertBlockPointerToFunctionPointer(type);
3437 const Expr *SubExpr = ICE->IgnoreParenImpCasts();
3438 CastKind CK;
Fangrui Song6907ce22018-07-30 19:24:48 +00003439 if (SubExpr->getType()->isIntegralType(*Context) &&
Fariborz Jahanian11671902012-02-07 17:11:38 +00003440 type->isBooleanType()) {
3441 CK = CK_IntegralToBoolean;
3442 } else if (type->isObjCObjectPointerType()) {
3443 if (SubExpr->getType()->isBlockPointerType()) {
3444 CK = CK_BlockPointerToObjCPointerCast;
3445 } else if (SubExpr->getType()->isPointerType()) {
3446 CK = CK_CPointerToObjCPointerCast;
3447 } else {
3448 CK = CK_BitCast;
3449 }
3450 } else {
3451 CK = CK_BitCast;
3452 }
3453
3454 userExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, userExpr);
3455 }
3456 // Make id<P...> cast into an 'id' cast.
3457 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
3458 if (CE->getType()->isObjCQualifiedIdType()) {
3459 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
3460 userExpr = CE->getSubExpr();
3461 CastKind CK;
3462 if (userExpr->getType()->isIntegralType(*Context)) {
3463 CK = CK_IntegralToPointer;
3464 } else if (userExpr->getType()->isBlockPointerType()) {
3465 CK = CK_BlockPointerToObjCPointerCast;
3466 } else if (userExpr->getType()->isPointerType()) {
3467 CK = CK_CPointerToObjCPointerCast;
3468 } else {
3469 CK = CK_BitCast;
3470 }
3471 userExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3472 CK, userExpr);
3473 }
3474 }
3475 MsgExprs.push_back(userExpr);
3476 // We've transferred the ownership to MsgExprs. For now, we *don't* null
3477 // out the argument in the original expression (since we aren't deleting
3478 // the ObjCMessageExpr). See RewritePropertyOrImplicitSetter() usage for more info.
3479 //Exp->setArg(i, 0);
3480 }
3481 // Generate the funky cast.
3482 CastExpr *cast;
3483 SmallVector<QualType, 8> ArgTypes;
3484 QualType returnType;
3485
3486 // Push 'id' and 'SEL', the 2 implicit arguments.
3487 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
3488 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
3489 else
3490 ArgTypes.push_back(Context->getObjCIdType());
3491 ArgTypes.push_back(Context->getObjCSelType());
3492 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
3493 // Push any user argument types.
David Majnemer59f77922016-06-24 04:05:48 +00003494 for (const auto *PI : OMD->parameters()) {
Aaron Ballman43b68be2014-03-07 17:50:17 +00003495 QualType t = PI->getType()->isObjCQualifiedIdType()
Fariborz Jahanian11671902012-02-07 17:11:38 +00003496 ? Context->getObjCIdType()
Aaron Ballman43b68be2014-03-07 17:50:17 +00003497 : PI->getType();
Fariborz Jahanian11671902012-02-07 17:11:38 +00003498 // Make sure we convert "t (^)(...)" to "t (*)(...)".
3499 (void)convertBlockPointerToFunctionPointer(t);
3500 ArgTypes.push_back(t);
3501 }
3502 returnType = Exp->getType();
3503 convertToUnqualifiedObjCType(returnType);
3504 (void)convertBlockPointerToFunctionPointer(returnType);
3505 } else {
3506 returnType = Context->getObjCIdType();
3507 }
3508 // Get the type, we will need to reference it in a couple spots.
3509 QualType msgSendType = MsgSendFlavor->getType();
3510
3511 // Create a reference to the objc_msgSend() declaration.
Bruno Ricci5fc4db72018-12-21 14:10:18 +00003512 DeclRefExpr *DRE = new (Context) DeclRefExpr(
3513 *Context, MsgSendFlavor, false, msgSendType, VK_LValue, SourceLocation());
Fariborz Jahanian11671902012-02-07 17:11:38 +00003514
3515 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
3516 // If we don't do this cast, we get the following bizarre warning/note:
3517 // xx.m:13: warning: function called through a non-compatible type
3518 // xx.m:13: note: if this code is reached, the program will abort
3519 cast = NoTypeInfoCStyleCastExpr(Context,
3520 Context->getPointerType(Context->VoidTy),
3521 CK_BitCast, DRE);
3522
3523 // Now do the "normal" pointer to function cast.
Jordan Rose5c382722013-03-08 21:51:21 +00003524 // If we don't have a method decl, force a variadic cast.
3525 const ObjCMethodDecl *MD = Exp->getMethodDecl();
Fariborz Jahanian11671902012-02-07 17:11:38 +00003526 QualType castType =
Jordan Rose5c382722013-03-08 21:51:21 +00003527 getSimpleFunctionType(returnType, ArgTypes, MD ? MD->isVariadic() : true);
Fariborz Jahanian11671902012-02-07 17:11:38 +00003528 castType = Context->getPointerType(castType);
3529 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
3530 cast);
3531
3532 // Don't forget the parens to enforce the proper binding.
3533 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
3534
3535 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Bruno Riccic5885cf2018-12-21 15:20:32 +00003536 CallExpr *CE = CallExpr::Create(*Context, PE, MsgExprs, FT->getReturnType(),
3537 VK_RValue, EndLoc);
Fariborz Jahanian11671902012-02-07 17:11:38 +00003538 Stmt *ReplacingStmt = CE;
3539 if (MsgSendStretFlavor) {
3540 // We have the method which returns a struct/union. Must also generate
3541 // call to objc_msgSend_stret and hang both varieties on a conditional
3542 // expression which dictate which one to envoke depending on size of
3543 // method's return type.
3544
Fariborz Jahanianb1a21242013-09-09 19:59:59 +00003545 Expr *STCE = SynthMsgSendStretCallExpr(MsgSendStretFlavor,
3546 returnType,
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003547 ArgTypes, MsgExprs,
3548 Exp->getMethodDecl());
Fariborz Jahanianb1a21242013-09-09 19:59:59 +00003549 ReplacingStmt = STCE;
Fariborz Jahanian11671902012-02-07 17:11:38 +00003550 }
3551 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3552 return ReplacingStmt;
3553}
3554
3555Stmt *RewriteModernObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003556 Stmt *ReplacingStmt =
Stephen Kelly1c301dc2018-08-09 21:09:38 +00003557 SynthMessageExpr(Exp, Exp->getBeginLoc(), Exp->getEndLoc());
Fariborz Jahanian11671902012-02-07 17:11:38 +00003558
3559 // Now do the actual rewrite.
3560 ReplaceStmt(Exp, ReplacingStmt);
3561
3562 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3563 return ReplacingStmt;
3564}
3565
3566// typedef struct objc_object Protocol;
3567QualType RewriteModernObjC::getProtocolType() {
3568 if (!ProtocolTypeDecl) {
3569 TypeSourceInfo *TInfo
3570 = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
3571 ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
3572 SourceLocation(), SourceLocation(),
3573 &Context->Idents.get("Protocol"),
3574 TInfo);
3575 }
3576 return Context->getTypeDeclType(ProtocolTypeDecl);
3577}
3578
3579/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
3580/// a synthesized/forward data reference (to the protocol's metadata).
3581/// The forward references (and metadata) are generated in
3582/// RewriteModernObjC::HandleTranslationUnit().
3583Stmt *RewriteModernObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Fangrui Song6907ce22018-07-30 19:24:48 +00003584 std::string Name = "_OBJC_PROTOCOL_REFERENCE_$_" +
Fariborz Jahanianb31e3af2012-03-15 17:05:33 +00003585 Exp->getProtocol()->getNameAsString();
Fariborz Jahanian11671902012-02-07 17:11:38 +00003586 IdentifierInfo *ID = &Context->Idents.get(Name);
3587 VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Craig Topper8ae12032014-05-07 06:21:57 +00003588 SourceLocation(), ID, getProtocolType(),
3589 nullptr, SC_Extern);
Bruno Ricci5fc4db72018-12-21 14:10:18 +00003590 DeclRefExpr *DRE = new (Context) DeclRefExpr(
3591 *Context, VD, false, getProtocolType(), VK_LValue, SourceLocation());
3592 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(
Fariborz Jahaniand38951a2013-11-22 18:43:41 +00003593 Context, Context->getPointerType(DRE->getType()), CK_BitCast, DRE);
Fariborz Jahanian11671902012-02-07 17:11:38 +00003594 ReplaceStmt(Exp, castExpr);
3595 ProtocolExprDecls.insert(Exp->getProtocol()->getCanonicalDecl());
3596 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3597 return castExpr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00003598}
3599
Fangrui Song6907ce22018-07-30 19:24:48 +00003600/// IsTagDefinedInsideClass - This routine checks that a named tagged type
3601/// is defined inside an objective-c class. If so, it returns true.
3602bool RewriteModernObjC::IsTagDefinedInsideClass(ObjCContainerDecl *IDecl,
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003603 TagDecl *Tag,
3604 bool &IsNamedDefinition) {
Fariborz Jahanian5979c312012-04-30 19:46:53 +00003605 if (!IDecl)
3606 return false;
3607 SourceLocation TagLocation;
3608 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) {
3609 RD = RD->getDefinition();
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003610 if (!RD || !RD->getDeclName().getAsIdentifierInfo())
Fariborz Jahanian5979c312012-04-30 19:46:53 +00003611 return false;
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003612 IsNamedDefinition = true;
Fariborz Jahanian5979c312012-04-30 19:46:53 +00003613 TagLocation = RD->getLocation();
3614 return Context->getSourceManager().isBeforeInTranslationUnit(
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003615 IDecl->getLocation(), TagLocation);
3616 }
3617 if (EnumDecl *ED = dyn_cast<EnumDecl>(Tag)) {
3618 if (!ED || !ED->getDeclName().getAsIdentifierInfo())
3619 return false;
3620 IsNamedDefinition = true;
3621 TagLocation = ED->getLocation();
3622 return Context->getSourceManager().isBeforeInTranslationUnit(
3623 IDecl->getLocation(), TagLocation);
Fariborz Jahanian5979c312012-04-30 19:46:53 +00003624 }
3625 return false;
3626}
3627
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003628/// RewriteObjCFieldDeclType - This routine rewrites a type into the buffer.
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003629/// It handles elaborated types, as well as enum types in the process.
Fangrui Song6907ce22018-07-30 19:24:48 +00003630bool RewriteModernObjC::RewriteObjCFieldDeclType(QualType &Type,
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003631 std::string &Result) {
Fariborz Jahaniand7c67772012-05-02 17:34:59 +00003632 if (isa<TypedefType>(Type)) {
3633 Result += "\t";
3634 return false;
3635 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003636
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003637 if (Type->isArrayType()) {
3638 QualType ElemTy = Context->getBaseElementType(Type);
3639 return RewriteObjCFieldDeclType(ElemTy, Result);
3640 }
3641 else if (Type->isRecordType()) {
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003642 RecordDecl *RD = Type->getAs<RecordType>()->getDecl();
3643 if (RD->isCompleteDefinition()) {
3644 if (RD->isStruct())
3645 Result += "\n\tstruct ";
3646 else if (RD->isUnion())
3647 Result += "\n\tunion ";
3648 else
3649 assert(false && "class not allowed as an ivar type");
Fangrui Song6907ce22018-07-30 19:24:48 +00003650
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003651 Result += RD->getName();
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003652 if (GlobalDefinedTags.count(RD)) {
3653 // struct/union is defined globally, use it.
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003654 Result += " ";
3655 return true;
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003656 }
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003657 Result += " {\n";
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00003658 for (auto *FD : RD->fields())
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003659 RewriteObjCFieldDecl(FD, Result);
Fangrui Song6907ce22018-07-30 19:24:48 +00003660 Result += "\t} ";
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003661 return true;
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003662 }
3663 }
3664 else if (Type->isEnumeralType()) {
3665 EnumDecl *ED = Type->getAs<EnumType>()->getDecl();
3666 if (ED->isCompleteDefinition()) {
3667 Result += "\n\tenum ";
3668 Result += ED->getName();
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003669 if (GlobalDefinedTags.count(ED)) {
3670 // Enum is globall defined, use it.
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003671 Result += " ";
3672 return true;
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003673 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003674
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003675 Result += " {\n";
Aaron Ballman23a6dcb2014-03-08 18:45:14 +00003676 for (const auto *EC : ED->enumerators()) {
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003677 Result += "\t"; Result += EC->getName(); Result += " = ";
3678 llvm::APSInt Val = EC->getInitVal();
3679 Result += Val.toString(10);
3680 Result += ",\n";
3681 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003682 Result += "\t} ";
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003683 return true;
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003684 }
3685 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003686
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003687 Result += "\t";
3688 convertObjCTypeToCStyleType(Type);
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003689 return false;
3690}
3691
3692
3693/// RewriteObjCFieldDecl - This routine rewrites a field into the buffer.
3694/// It handles elaborated types, as well as enum types in the process.
Fangrui Song6907ce22018-07-30 19:24:48 +00003695void RewriteModernObjC::RewriteObjCFieldDecl(FieldDecl *fieldDecl,
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003696 std::string &Result) {
3697 QualType Type = fieldDecl->getType();
3698 std::string Name = fieldDecl->getNameAsString();
Fangrui Song6907ce22018-07-30 19:24:48 +00003699
3700 bool EleboratedType = RewriteObjCFieldDeclType(Type, Result);
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003701 if (!EleboratedType)
3702 Type.getAsStringInternal(Name, Context->getPrintingPolicy());
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003703 Result += Name;
3704 if (fieldDecl->isBitField()) {
3705 Result += " : "; Result += utostr(fieldDecl->getBitWidthValue(*Context));
3706 }
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003707 else if (EleboratedType && Type->isArrayType()) {
Eli Friedman07bab732012-12-13 01:43:21 +00003708 const ArrayType *AT = Context->getAsArrayType(Type);
3709 do {
3710 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003711 Result += "[";
3712 llvm::APInt Dim = CAT->getSize();
3713 Result += utostr(Dim.getZExtValue());
3714 Result += "]";
3715 }
Eli Friedman07bab732012-12-13 01:43:21 +00003716 AT = Context->getAsArrayType(AT->getElementType());
3717 } while (AT);
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003718 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003719
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003720 Result += ";\n";
3721}
3722
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003723/// RewriteLocallyDefinedNamedAggregates - This routine rewrites locally defined
3724/// named aggregate types into the input buffer.
Fangrui Song6907ce22018-07-30 19:24:48 +00003725void RewriteModernObjC::RewriteLocallyDefinedNamedAggregates(FieldDecl *fieldDecl,
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003726 std::string &Result) {
3727 QualType Type = fieldDecl->getType();
Fariborz Jahaniand7c67772012-05-02 17:34:59 +00003728 if (isa<TypedefType>(Type))
3729 return;
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003730 if (Type->isArrayType())
3731 Type = Context->getBaseElementType(Type);
Fangrui Song6907ce22018-07-30 19:24:48 +00003732 ObjCContainerDecl *IDecl =
Fariborz Jahanian144b7222012-05-01 17:46:45 +00003733 dyn_cast<ObjCContainerDecl>(fieldDecl->getDeclContext());
Craig Topper8ae12032014-05-07 06:21:57 +00003734
3735 TagDecl *TD = nullptr;
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003736 if (Type->isRecordType()) {
3737 TD = Type->getAs<RecordType>()->getDecl();
3738 }
3739 else if (Type->isEnumeralType()) {
3740 TD = Type->getAs<EnumType>()->getDecl();
3741 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003742
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003743 if (TD) {
3744 if (GlobalDefinedTags.count(TD))
3745 return;
Fangrui Song6907ce22018-07-30 19:24:48 +00003746
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003747 bool IsNamedDefinition = false;
3748 if (IsTagDefinedInsideClass(IDecl, TD, IsNamedDefinition)) {
3749 RewriteObjCFieldDeclType(Type, Result);
3750 Result += ";";
3751 }
3752 if (IsNamedDefinition)
3753 GlobalDefinedTags.insert(TD);
3754 }
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003755}
3756
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00003757unsigned RewriteModernObjC::ObjCIvarBitfieldGroupNo(ObjCIvarDecl *IV) {
3758 const ObjCInterfaceDecl *CDecl = IV->getContainingInterface();
3759 if (ObjCInterefaceHasBitfieldGroups.count(CDecl)) {
3760 return IvarGroupNumber[IV];
3761 }
3762 unsigned GroupNo = 0;
3763 SmallVector<const ObjCIvarDecl *, 8> IVars;
3764 for (const ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
3765 IVD; IVD = IVD->getNextIvar())
3766 IVars.push_back(IVD);
Fangrui Song6907ce22018-07-30 19:24:48 +00003767
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00003768 for (unsigned i = 0, e = IVars.size(); i < e; i++)
3769 if (IVars[i]->isBitField()) {
3770 IvarGroupNumber[IVars[i++]] = ++GroupNo;
3771 while (i < e && IVars[i]->isBitField())
3772 IvarGroupNumber[IVars[i++]] = GroupNo;
3773 if (i < e)
3774 --i;
3775 }
3776
3777 ObjCInterefaceHasBitfieldGroups.insert(CDecl);
3778 return IvarGroupNumber[IV];
3779}
3780
3781QualType RewriteModernObjC::SynthesizeBitfieldGroupStructType(
3782 ObjCIvarDecl *IV,
3783 SmallVectorImpl<ObjCIvarDecl *> &IVars) {
3784 std::string StructTagName;
3785 ObjCIvarBitfieldGroupType(IV, StructTagName);
3786 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct,
3787 Context->getTranslationUnitDecl(),
3788 SourceLocation(), SourceLocation(),
3789 &Context->Idents.get(StructTagName));
3790 for (unsigned i=0, e = IVars.size(); i < e; i++) {
3791 ObjCIvarDecl *Ivar = IVars[i];
3792 RD->addDecl(FieldDecl::Create(*Context, RD, SourceLocation(), SourceLocation(),
3793 &Context->Idents.get(Ivar->getName()),
3794 Ivar->getType(),
Craig Topper8ae12032014-05-07 06:21:57 +00003795 nullptr, /*Expr *BW */Ivar->getBitWidth(),
3796 false, ICIS_NoInit));
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00003797 }
3798 RD->completeDefinition();
3799 return Context->getTagDeclType(RD);
3800}
3801
3802QualType RewriteModernObjC::GetGroupRecordTypeForObjCIvarBitfield(ObjCIvarDecl *IV) {
3803 const ObjCInterfaceDecl *CDecl = IV->getContainingInterface();
3804 unsigned GroupNo = ObjCIvarBitfieldGroupNo(IV);
3805 std::pair<const ObjCInterfaceDecl*, unsigned> tuple = std::make_pair(CDecl, GroupNo);
3806 if (GroupRecordType.count(tuple))
3807 return GroupRecordType[tuple];
Fangrui Song6907ce22018-07-30 19:24:48 +00003808
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00003809 SmallVector<ObjCIvarDecl *, 8> IVars;
3810 for (const ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
3811 IVD; IVD = IVD->getNextIvar()) {
3812 if (IVD->isBitField())
3813 IVars.push_back(const_cast<ObjCIvarDecl *>(IVD));
3814 else {
3815 if (!IVars.empty()) {
3816 unsigned GroupNo = ObjCIvarBitfieldGroupNo(IVars[0]);
3817 // Generate the struct type for this group of bitfield ivars.
3818 GroupRecordType[std::make_pair(CDecl, GroupNo)] =
3819 SynthesizeBitfieldGroupStructType(IVars[0], IVars);
3820 IVars.clear();
3821 }
3822 }
3823 }
3824 if (!IVars.empty()) {
3825 // Do the last one.
3826 unsigned GroupNo = ObjCIvarBitfieldGroupNo(IVars[0]);
3827 GroupRecordType[std::make_pair(CDecl, GroupNo)] =
3828 SynthesizeBitfieldGroupStructType(IVars[0], IVars);
3829 }
3830 QualType RetQT = GroupRecordType[tuple];
3831 assert(!RetQT.isNull() && "GetGroupRecordTypeForObjCIvarBitfield struct type is NULL");
Fangrui Song6907ce22018-07-30 19:24:48 +00003832
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00003833 return RetQT;
3834}
3835
3836/// ObjCIvarBitfieldGroupDecl - Names field decl. for ivar bitfield group.
3837/// Name would be: classname__GRBF_n where n is the group number for this ivar.
3838void RewriteModernObjC::ObjCIvarBitfieldGroupDecl(ObjCIvarDecl *IV,
3839 std::string &Result) {
3840 const ObjCInterfaceDecl *CDecl = IV->getContainingInterface();
3841 Result += CDecl->getName();
3842 Result += "__GRBF_";
3843 unsigned GroupNo = ObjCIvarBitfieldGroupNo(IV);
3844 Result += utostr(GroupNo);
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00003845}
3846
3847/// ObjCIvarBitfieldGroupType - Names struct type for ivar bitfield group.
3848/// Name of the struct would be: classname__T_n where n is the group number for
3849/// this ivar.
3850void RewriteModernObjC::ObjCIvarBitfieldGroupType(ObjCIvarDecl *IV,
3851 std::string &Result) {
3852 const ObjCInterfaceDecl *CDecl = IV->getContainingInterface();
3853 Result += CDecl->getName();
3854 Result += "__T_";
3855 unsigned GroupNo = ObjCIvarBitfieldGroupNo(IV);
3856 Result += utostr(GroupNo);
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00003857}
3858
3859/// ObjCIvarBitfieldGroupOffset - Names symbol for ivar bitfield group field offset.
3860/// Name would be: OBJC_IVAR_$_classname__GRBF_n where n is the group number for
3861/// this ivar.
3862void RewriteModernObjC::ObjCIvarBitfieldGroupOffset(ObjCIvarDecl *IV,
3863 std::string &Result) {
3864 Result += "OBJC_IVAR_$_";
3865 ObjCIvarBitfieldGroupDecl(IV, Result);
3866}
3867
3868#define SKIP_BITFIELDS(IX, ENDIX, VEC) { \
3869 while ((IX < ENDIX) && VEC[IX]->isBitField()) \
3870 ++IX; \
3871 if (IX < ENDIX) \
3872 --IX; \
3873}
3874
Fariborz Jahanian11671902012-02-07 17:11:38 +00003875/// RewriteObjCInternalStruct - Rewrite one internal struct corresponding to
3876/// an objective-c class with ivars.
3877void RewriteModernObjC::RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
3878 std::string &Result) {
3879 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
3880 assert(CDecl->getName() != "" &&
3881 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanian11671902012-02-07 17:11:38 +00003882 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Fariborz Jahaniancb1d9f32012-02-10 23:18:24 +00003883 SmallVector<ObjCIvarDecl *, 8> IVars;
3884 for (ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
Fariborz Jahaniand7a32612012-03-06 17:16:27 +00003885 IVD; IVD = IVD->getNextIvar())
Fariborz Jahaniancb1d9f32012-02-10 23:18:24 +00003886 IVars.push_back(IVD);
Fangrui Song6907ce22018-07-30 19:24:48 +00003887
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003888 SourceLocation LocStart = CDecl->getBeginLoc();
Fariborz Jahanian11671902012-02-07 17:11:38 +00003889 SourceLocation LocEnd = CDecl->getEndOfDefinitionLoc();
Fangrui Song6907ce22018-07-30 19:24:48 +00003890
Fariborz Jahanian11671902012-02-07 17:11:38 +00003891 const char *startBuf = SM->getCharacterData(LocStart);
3892 const char *endBuf = SM->getCharacterData(LocEnd);
Fangrui Song6907ce22018-07-30 19:24:48 +00003893
Fariborz Jahanian11671902012-02-07 17:11:38 +00003894 // If no ivars and no root or if its root, directly or indirectly,
3895 // have no ivars (thus not synthesized) then no need to synthesize this class.
Fariborz Jahaniancb1d9f32012-02-10 23:18:24 +00003896 if ((!CDecl->isThisDeclarationADefinition() || IVars.size() == 0) &&
Fariborz Jahanian11671902012-02-07 17:11:38 +00003897 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
3898 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
3899 ReplaceText(LocStart, endBuf-startBuf, Result);
3900 return;
3901 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003902
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003903 // Insert named struct/union definitions inside class to
3904 // outer scope. This follows semantics of locally defined
3905 // struct/unions in objective-c classes.
3906 for (unsigned i = 0, e = IVars.size(); i < e; i++)
3907 RewriteLocallyDefinedNamedAggregates(IVars[i], Result);
Fangrui Song6907ce22018-07-30 19:24:48 +00003908
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00003909 // Insert named structs which are syntheized to group ivar bitfields
3910 // to outer scope as well.
3911 for (unsigned i = 0, e = IVars.size(); i < e; i++)
3912 if (IVars[i]->isBitField()) {
3913 ObjCIvarDecl *IV = IVars[i];
3914 QualType QT = GetGroupRecordTypeForObjCIvarBitfield(IV);
3915 RewriteObjCFieldDeclType(QT, Result);
3916 Result += ";";
3917 // skip over ivar bitfields in this group.
3918 SKIP_BITFIELDS(i , e, IVars);
3919 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003920
Fariborz Jahanian11671902012-02-07 17:11:38 +00003921 Result += "\nstruct ";
3922 Result += CDecl->getNameAsString();
Fariborz Jahaniancb1d9f32012-02-10 23:18:24 +00003923 Result += "_IMPL {\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00003924
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00003925 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Fariborz Jahaniancb1d9f32012-02-10 23:18:24 +00003926 Result += "\tstruct "; Result += RCDecl->getNameAsString();
3927 Result += "_IMPL "; Result += RCDecl->getNameAsString();
3928 Result += "_IVARS;\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00003929 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003930
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00003931 for (unsigned i = 0, e = IVars.size(); i < e; i++) {
3932 if (IVars[i]->isBitField()) {
3933 ObjCIvarDecl *IV = IVars[i];
3934 Result += "\tstruct ";
3935 ObjCIvarBitfieldGroupType(IV, Result); Result += " ";
3936 ObjCIvarBitfieldGroupDecl(IV, Result); Result += ";\n";
3937 // skip over ivar bitfields in this group.
3938 SKIP_BITFIELDS(i , e, IVars);
3939 }
3940 else
3941 RewriteObjCFieldDecl(IVars[i], Result);
3942 }
Fariborz Jahanian245534d2012-02-12 21:36:23 +00003943
Fariborz Jahaniancb1d9f32012-02-10 23:18:24 +00003944 Result += "};\n";
3945 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
3946 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00003947 // Mark this struct as having been generated.
David Blaikie82e95a32014-11-19 07:49:47 +00003948 if (!ObjCSynthesizedStructs.insert(CDecl).second)
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00003949 llvm_unreachable("struct already synthesize- RewriteObjCInternalStruct");
Fariborz Jahanian11671902012-02-07 17:11:38 +00003950}
3951
Fariborz Jahanian5e49eb92012-02-22 18:13:25 +00003952/// RewriteIvarOffsetSymbols - Rewrite ivar offset symbols of those ivars which
3953/// have been referenced in an ivar access expression.
3954void RewriteModernObjC::RewriteIvarOffsetSymbols(ObjCInterfaceDecl *CDecl,
3955 std::string &Result) {
3956 // write out ivar offset symbols which have been referenced in an ivar
3957 // access expression.
Mandeep Singh Granga2baff02017-07-06 18:49:57 +00003958 llvm::SmallSetVector<ObjCIvarDecl *, 8> Ivars = ReferencedIvars[CDecl];
3959
Fariborz Jahanian5e49eb92012-02-22 18:13:25 +00003960 if (Ivars.empty())
3961 return;
Mandeep Singh Granga2baff02017-07-06 18:49:57 +00003962
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00003963 llvm::DenseSet<std::pair<const ObjCInterfaceDecl*, unsigned> > GroupSymbolOutput;
Craig Topperc6914d02014-08-25 04:15:02 +00003964 for (ObjCIvarDecl *IvarDecl : Ivars) {
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00003965 const ObjCInterfaceDecl *IDecl = IvarDecl->getContainingInterface();
3966 unsigned GroupNo = 0;
3967 if (IvarDecl->isBitField()) {
3968 GroupNo = ObjCIvarBitfieldGroupNo(IvarDecl);
3969 if (GroupSymbolOutput.count(std::make_pair(IDecl, GroupNo)))
3970 continue;
3971 }
Fariborz Jahaniane47bf2b2012-03-12 16:46:58 +00003972 Result += "\n";
3973 if (LangOpts.MicrosoftExt)
3974 Result += "__declspec(allocate(\".objc_ivar$B\")) ";
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00003975 Result += "extern \"C\" ";
Fangrui Song6907ce22018-07-30 19:24:48 +00003976 if (LangOpts.MicrosoftExt &&
Fariborz Jahaniane47bf2b2012-03-12 16:46:58 +00003977 IvarDecl->getAccessControl() != ObjCIvarDecl::Private &&
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00003978 IvarDecl->getAccessControl() != ObjCIvarDecl::Package)
3979 Result += "__declspec(dllimport) ";
3980
Fariborz Jahanian38c59102012-03-27 16:21:30 +00003981 Result += "unsigned long ";
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00003982 if (IvarDecl->isBitField()) {
3983 ObjCIvarBitfieldGroupOffset(IvarDecl, Result);
3984 GroupSymbolOutput.insert(std::make_pair(IDecl, GroupNo));
3985 }
3986 else
3987 WriteInternalIvarName(CDecl, IvarDecl, Result);
Fariborz Jahaniana854174a2012-03-20 17:13:39 +00003988 Result += ";";
Fariborz Jahanian5e49eb92012-02-22 18:13:25 +00003989 }
3990}
3991
Fariborz Jahanian11671902012-02-07 17:11:38 +00003992//===----------------------------------------------------------------------===//
3993// Meta Data Emission
3994//===----------------------------------------------------------------------===//
3995
Fariborz Jahanian11671902012-02-07 17:11:38 +00003996/// RewriteImplementations - This routine rewrites all method implementations
3997/// and emits meta-data.
3998
3999void RewriteModernObjC::RewriteImplementations() {
4000 int ClsDefCount = ClassImplementation.size();
4001 int CatDefCount = CategoryImplementation.size();
4002
4003 // Rewrite implemented methods
Fariborz Jahanian088959a2012-02-11 20:10:52 +00004004 for (int i = 0; i < ClsDefCount; i++) {
4005 ObjCImplementationDecl *OIMP = ClassImplementation[i];
4006 ObjCInterfaceDecl *CDecl = OIMP->getClassInterface();
4007 if (CDecl->isImplicitInterfaceDecl())
Fariborz Jahaniand268b0c2012-02-17 22:20:12 +00004008 assert(false &&
4009 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian088959a2012-02-11 20:10:52 +00004010 RewriteImplementationDecl(OIMP);
4011 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00004012
Fariborz Jahanian320c88a2012-02-17 20:33:00 +00004013 for (int i = 0; i < CatDefCount; i++) {
4014 ObjCCategoryImplDecl *CIMP = CategoryImplementation[i];
4015 ObjCInterfaceDecl *CDecl = CIMP->getClassInterface();
4016 if (CDecl->isImplicitInterfaceDecl())
4017 assert(false &&
4018 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian320c88a2012-02-17 20:33:00 +00004019 RewriteImplementationDecl(CIMP);
4020 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00004021}
4022
Fangrui Song6907ce22018-07-30 19:24:48 +00004023void RewriteModernObjC::RewriteByRefString(std::string &ResultStr,
Fariborz Jahanian11671902012-02-07 17:11:38 +00004024 const std::string &Name,
4025 ValueDecl *VD, bool def) {
Fangrui Song6907ce22018-07-30 19:24:48 +00004026 assert(BlockByRefDeclNo.count(VD) &&
Fariborz Jahanian11671902012-02-07 17:11:38 +00004027 "RewriteByRefString: ByRef decl missing");
4028 if (def)
4029 ResultStr += "struct ";
Fangrui Song6907ce22018-07-30 19:24:48 +00004030 ResultStr += "__Block_byref_" + Name +
Fariborz Jahanian11671902012-02-07 17:11:38 +00004031 "_" + utostr(BlockByRefDeclNo[VD]) ;
4032}
4033
4034static bool HasLocalVariableExternalStorage(ValueDecl *VD) {
4035 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4036 return (Var->isFunctionOrMethodVarDecl() && !Var->hasLocalStorage());
4037 return false;
4038}
4039
4040std::string RewriteModernObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
4041 StringRef funcName,
4042 std::string Tag) {
4043 const FunctionType *AFT = CE->getFunctionType();
Alp Toker314cc812014-01-25 16:55:45 +00004044 QualType RT = AFT->getReturnType();
Fariborz Jahanian11671902012-02-07 17:11:38 +00004045 std::string StructRef = "struct " + Tag;
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00004046 SourceLocation BlockLoc = CE->getExprLoc();
4047 std::string S;
4048 ConvertSourceLocationToLineDirective(BlockLoc, S);
Fangrui Song6907ce22018-07-30 19:24:48 +00004049
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00004050 S += "static " + RT.getAsString(Context->getPrintingPolicy()) + " __" +
4051 funcName.str() + "_block_func_" + utostr(i);
Fariborz Jahanian11671902012-02-07 17:11:38 +00004052
4053 BlockDecl *BD = CE->getBlockDecl();
4054
4055 if (isa<FunctionNoProtoType>(AFT)) {
4056 // No user-supplied arguments. Still need to pass in a pointer to the
4057 // block (to reference imported block decl refs).
4058 S += "(" + StructRef + " *__cself)";
4059 } else if (BD->param_empty()) {
4060 S += "(" + StructRef + " *__cself)";
4061 } else {
4062 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
4063 assert(FT && "SynthesizeBlockFunc: No function proto");
4064 S += '(';
4065 // first add the implicit argument.
4066 S += StructRef + " *__cself, ";
4067 std::string ParamStr;
4068 for (BlockDecl::param_iterator AI = BD->param_begin(),
4069 E = BD->param_end(); AI != E; ++AI) {
4070 if (AI != BD->param_begin()) S += ", ";
4071 ParamStr = (*AI)->getNameAsString();
4072 QualType QT = (*AI)->getType();
Fariborz Jahanian835cabe2012-03-27 16:42:20 +00004073 (void)convertBlockPointerToFunctionPointer(QT);
4074 QT.getAsStringInternal(ParamStr, Context->getPrintingPolicy());
Fariborz Jahanian11671902012-02-07 17:11:38 +00004075 S += ParamStr;
4076 }
4077 if (FT->isVariadic()) {
4078 if (!BD->param_empty()) S += ", ";
4079 S += "...";
4080 }
4081 S += ')';
4082 }
4083 S += " {\n";
4084
4085 // Create local declarations to avoid rewriting all closure decl ref exprs.
4086 // First, emit a declaration for all "by ref" decls.
Craig Topper2341c0d2013-07-04 03:08:24 +00004087 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00004088 E = BlockByRefDecls.end(); I != E; ++I) {
4089 S += " ";
4090 std::string Name = (*I)->getNameAsString();
4091 std::string TypeString;
4092 RewriteByRefString(TypeString, Name, (*I));
4093 TypeString += " *";
4094 Name = TypeString + Name;
4095 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
4096 }
4097 // Next, emit a declaration for all "by copy" declarations.
Craig Topper2341c0d2013-07-04 03:08:24 +00004098 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00004099 E = BlockByCopyDecls.end(); I != E; ++I) {
4100 S += " ";
4101 // Handle nested closure invocation. For example:
4102 //
4103 // void (^myImportedClosure)(void);
4104 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
4105 //
4106 // void (^anotherClosure)(void);
4107 // anotherClosure = ^(void) {
4108 // myImportedClosure(); // import and invoke the closure
4109 // };
4110 //
4111 if (isTopLevelBlockPointerType((*I)->getType())) {
4112 RewriteBlockPointerTypeVariable(S, (*I));
4113 S += " = (";
4114 RewriteBlockPointerType(S, (*I)->getType());
4115 S += ")";
4116 S += "__cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
4117 }
4118 else {
4119 std::string Name = (*I)->getNameAsString();
4120 QualType QT = (*I)->getType();
4121 if (HasLocalVariableExternalStorage(*I))
4122 QT = Context->getPointerType(QT);
4123 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
Fangrui Song6907ce22018-07-30 19:24:48 +00004124 S += Name + " = __cself->" +
Fariborz Jahanian11671902012-02-07 17:11:38 +00004125 (*I)->getNameAsString() + "; // bound by copy\n";
4126 }
4127 }
4128 std::string RewrittenStr = RewrittenBlockExprs[CE];
4129 const char *cstr = RewrittenStr.c_str();
4130 while (*cstr++ != '{') ;
4131 S += cstr;
4132 S += "\n";
4133 return S;
4134}
4135
4136std::string RewriteModernObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
4137 StringRef funcName,
4138 std::string Tag) {
4139 std::string StructRef = "struct " + Tag;
4140 std::string S = "static void __";
4141
4142 S += funcName;
4143 S += "_block_copy_" + utostr(i);
4144 S += "(" + StructRef;
4145 S += "*dst, " + StructRef;
4146 S += "*src) {";
Craig Topperc6914d02014-08-25 04:15:02 +00004147 for (ValueDecl *VD : ImportedBlockDecls) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00004148 S += "_Block_object_assign((void*)&dst->";
Craig Topperc6914d02014-08-25 04:15:02 +00004149 S += VD->getNameAsString();
Fariborz Jahanian11671902012-02-07 17:11:38 +00004150 S += ", (void*)src->";
Craig Topperc6914d02014-08-25 04:15:02 +00004151 S += VD->getNameAsString();
4152 if (BlockByRefDeclsPtrSet.count(VD))
Fariborz Jahanian11671902012-02-07 17:11:38 +00004153 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
4154 else if (VD->getType()->isBlockPointerType())
4155 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
4156 else
4157 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
4158 }
4159 S += "}\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00004160
Fariborz Jahanian11671902012-02-07 17:11:38 +00004161 S += "\nstatic void __";
4162 S += funcName;
4163 S += "_block_dispose_" + utostr(i);
4164 S += "(" + StructRef;
4165 S += "*src) {";
Craig Topperc6914d02014-08-25 04:15:02 +00004166 for (ValueDecl *VD : ImportedBlockDecls) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00004167 S += "_Block_object_dispose((void*)src->";
Craig Topperc6914d02014-08-25 04:15:02 +00004168 S += VD->getNameAsString();
4169 if (BlockByRefDeclsPtrSet.count(VD))
Fariborz Jahanian11671902012-02-07 17:11:38 +00004170 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
4171 else if (VD->getType()->isBlockPointerType())
4172 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
4173 else
4174 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
4175 }
4176 S += "}\n";
4177 return S;
4178}
4179
Fangrui Song6907ce22018-07-30 19:24:48 +00004180std::string RewriteModernObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
Fariborz Jahanian11671902012-02-07 17:11:38 +00004181 std::string Desc) {
4182 std::string S = "\nstruct " + Tag;
4183 std::string Constructor = " " + Tag;
4184
4185 S += " {\n struct __block_impl impl;\n";
4186 S += " struct " + Desc;
4187 S += "* Desc;\n";
4188
4189 Constructor += "(void *fp, "; // Invoke function pointer.
4190 Constructor += "struct " + Desc; // Descriptor pointer.
4191 Constructor += " *desc";
4192
4193 if (BlockDeclRefs.size()) {
4194 // Output all "by copy" declarations.
Craig Topper2341c0d2013-07-04 03:08:24 +00004195 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00004196 E = BlockByCopyDecls.end(); I != E; ++I) {
4197 S += " ";
4198 std::string FieldName = (*I)->getNameAsString();
4199 std::string ArgName = "_" + FieldName;
4200 // Handle nested closure invocation. For example:
4201 //
4202 // void (^myImportedBlock)(void);
4203 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
4204 //
4205 // void (^anotherBlock)(void);
4206 // anotherBlock = ^(void) {
4207 // myImportedBlock(); // import and invoke the closure
4208 // };
4209 //
4210 if (isTopLevelBlockPointerType((*I)->getType())) {
4211 S += "struct __block_impl *";
4212 Constructor += ", void *" + ArgName;
4213 } else {
4214 QualType QT = (*I)->getType();
4215 if (HasLocalVariableExternalStorage(*I))
4216 QT = Context->getPointerType(QT);
4217 QT.getAsStringInternal(FieldName, Context->getPrintingPolicy());
4218 QT.getAsStringInternal(ArgName, Context->getPrintingPolicy());
4219 Constructor += ", " + ArgName;
4220 }
4221 S += FieldName + ";\n";
4222 }
4223 // Output all "by ref" declarations.
Craig Topper2341c0d2013-07-04 03:08:24 +00004224 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00004225 E = BlockByRefDecls.end(); I != E; ++I) {
4226 S += " ";
4227 std::string FieldName = (*I)->getNameAsString();
4228 std::string ArgName = "_" + FieldName;
4229 {
4230 std::string TypeString;
4231 RewriteByRefString(TypeString, FieldName, (*I));
4232 TypeString += " *";
4233 FieldName = TypeString + FieldName;
4234 ArgName = TypeString + ArgName;
4235 Constructor += ", " + ArgName;
4236 }
4237 S += FieldName + "; // by ref\n";
4238 }
4239 // Finish writing the constructor.
4240 Constructor += ", int flags=0)";
4241 // Initialize all "by copy" arguments.
4242 bool firsTime = true;
Craig Topper2341c0d2013-07-04 03:08:24 +00004243 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00004244 E = BlockByCopyDecls.end(); I != E; ++I) {
4245 std::string Name = (*I)->getNameAsString();
4246 if (firsTime) {
4247 Constructor += " : ";
4248 firsTime = false;
4249 }
4250 else
4251 Constructor += ", ";
4252 if (isTopLevelBlockPointerType((*I)->getType()))
4253 Constructor += Name + "((struct __block_impl *)_" + Name + ")";
4254 else
4255 Constructor += Name + "(_" + Name + ")";
4256 }
4257 // Initialize all "by ref" arguments.
Craig Topper2341c0d2013-07-04 03:08:24 +00004258 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00004259 E = BlockByRefDecls.end(); I != E; ++I) {
4260 std::string Name = (*I)->getNameAsString();
4261 if (firsTime) {
4262 Constructor += " : ";
4263 firsTime = false;
4264 }
4265 else
4266 Constructor += ", ";
4267 Constructor += Name + "(_" + Name + "->__forwarding)";
4268 }
Fangrui Song6907ce22018-07-30 19:24:48 +00004269
Fariborz Jahanian11671902012-02-07 17:11:38 +00004270 Constructor += " {\n";
4271 if (GlobalVarDecl)
4272 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4273 else
4274 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
4275 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
4276
4277 Constructor += " Desc = desc;\n";
4278 } else {
4279 // Finish writing the constructor.
4280 Constructor += ", int flags=0) {\n";
4281 if (GlobalVarDecl)
4282 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4283 else
4284 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
4285 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
4286 Constructor += " Desc = desc;\n";
4287 }
4288 Constructor += " ";
4289 Constructor += "}\n";
4290 S += Constructor;
4291 S += "};\n";
4292 return S;
4293}
4294
Fangrui Song6907ce22018-07-30 19:24:48 +00004295std::string RewriteModernObjC::SynthesizeBlockDescriptor(std::string DescTag,
Fariborz Jahanian11671902012-02-07 17:11:38 +00004296 std::string ImplTag, int i,
4297 StringRef FunName,
4298 unsigned hasCopy) {
4299 std::string S = "\nstatic struct " + DescTag;
Fangrui Song6907ce22018-07-30 19:24:48 +00004300
Fariborz Jahanian2e7f6382012-05-03 21:44:12 +00004301 S += " {\n size_t reserved;\n";
4302 S += " size_t Block_size;\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00004303 if (hasCopy) {
4304 S += " void (*copy)(struct ";
4305 S += ImplTag; S += "*, struct ";
4306 S += ImplTag; S += "*);\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00004307
Fariborz Jahanian11671902012-02-07 17:11:38 +00004308 S += " void (*dispose)(struct ";
4309 S += ImplTag; S += "*);\n";
4310 }
4311 S += "} ";
4312
4313 S += DescTag + "_DATA = { 0, sizeof(struct ";
4314 S += ImplTag + ")";
4315 if (hasCopy) {
4316 S += ", __" + FunName.str() + "_block_copy_" + utostr(i);
4317 S += ", __" + FunName.str() + "_block_dispose_" + utostr(i);
4318 }
4319 S += "};\n";
4320 return S;
4321}
4322
4323void RewriteModernObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
4324 StringRef FunName) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00004325 bool RewriteSC = (GlobalVarDecl &&
4326 !Blocks.empty() &&
4327 GlobalVarDecl->getStorageClass() == SC_Static &&
4328 GlobalVarDecl->getType().getCVRQualifiers());
4329 if (RewriteSC) {
4330 std::string SC(" void __");
4331 SC += GlobalVarDecl->getNameAsString();
4332 SC += "() {}";
4333 InsertText(FunLocStart, SC);
4334 }
Fangrui Song6907ce22018-07-30 19:24:48 +00004335
Fariborz Jahanian11671902012-02-07 17:11:38 +00004336 // Insert closures that were part of the function.
4337 for (unsigned i = 0, count=0; i < Blocks.size(); i++) {
4338 CollectBlockDeclRefInfo(Blocks[i]);
4339 // Need to copy-in the inner copied-in variables not actually used in this
4340 // block.
4341 for (int j = 0; j < InnerDeclRefsCount[i]; j++) {
John McCall113bee02012-03-10 09:33:50 +00004342 DeclRefExpr *Exp = InnerDeclRefs[count++];
Fariborz Jahanian11671902012-02-07 17:11:38 +00004343 ValueDecl *VD = Exp->getDecl();
4344 BlockDeclRefs.push_back(Exp);
John McCall113bee02012-03-10 09:33:50 +00004345 if (!VD->hasAttr<BlocksAttr>()) {
4346 if (!BlockByCopyDeclsPtrSet.count(VD)) {
4347 BlockByCopyDeclsPtrSet.insert(VD);
4348 BlockByCopyDecls.push_back(VD);
4349 }
4350 continue;
Fariborz Jahanian11671902012-02-07 17:11:38 +00004351 }
John McCall113bee02012-03-10 09:33:50 +00004352
4353 if (!BlockByRefDeclsPtrSet.count(VD)) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00004354 BlockByRefDeclsPtrSet.insert(VD);
4355 BlockByRefDecls.push_back(VD);
4356 }
John McCall113bee02012-03-10 09:33:50 +00004357
Fariborz Jahanian11671902012-02-07 17:11:38 +00004358 // imported objects in the inner blocks not used in the outer
4359 // blocks must be copied/disposed in the outer block as well.
Fangrui Song6907ce22018-07-30 19:24:48 +00004360 if (VD->getType()->isObjCObjectPointerType() ||
Fariborz Jahanian11671902012-02-07 17:11:38 +00004361 VD->getType()->isBlockPointerType())
4362 ImportedBlockDecls.insert(VD);
4363 }
4364
4365 std::string ImplTag = "__" + FunName.str() + "_block_impl_" + utostr(i);
4366 std::string DescTag = "__" + FunName.str() + "_block_desc_" + utostr(i);
4367
4368 std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
4369
4370 InsertText(FunLocStart, CI);
4371
4372 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
4373
4374 InsertText(FunLocStart, CF);
4375
4376 if (ImportedBlockDecls.size()) {
4377 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
4378 InsertText(FunLocStart, HF);
4379 }
4380 std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
4381 ImportedBlockDecls.size() > 0);
4382 InsertText(FunLocStart, BD);
4383
4384 BlockDeclRefs.clear();
4385 BlockByRefDecls.clear();
4386 BlockByRefDeclsPtrSet.clear();
4387 BlockByCopyDecls.clear();
4388 BlockByCopyDeclsPtrSet.clear();
4389 ImportedBlockDecls.clear();
4390 }
4391 if (RewriteSC) {
4392 // Must insert any 'const/volatile/static here. Since it has been
4393 // removed as result of rewriting of block literals.
4394 std::string SC;
4395 if (GlobalVarDecl->getStorageClass() == SC_Static)
4396 SC = "static ";
4397 if (GlobalVarDecl->getType().isConstQualified())
4398 SC += "const ";
4399 if (GlobalVarDecl->getType().isVolatileQualified())
4400 SC += "volatile ";
4401 if (GlobalVarDecl->getType().isRestrictQualified())
4402 SC += "restrict ";
4403 InsertText(FunLocStart, SC);
4404 }
Fariborz Jahaniane0050702012-03-23 00:00:49 +00004405 if (GlobalConstructionExp) {
4406 // extra fancy dance for global literal expression.
Fangrui Song6907ce22018-07-30 19:24:48 +00004407
Fariborz Jahaniane0050702012-03-23 00:00:49 +00004408 // Always the latest block expression on the block stack.
4409 std::string Tag = "__";
4410 Tag += FunName;
4411 Tag += "_block_impl_";
4412 Tag += utostr(Blocks.size()-1);
4413 std::string globalBuf = "static ";
4414 globalBuf += Tag; globalBuf += " ";
4415 std::string SStr;
Fangrui Song6907ce22018-07-30 19:24:48 +00004416
Fariborz Jahaniane0050702012-03-23 00:00:49 +00004417 llvm::raw_string_ostream constructorExprBuf(SStr);
Craig Topper8ae12032014-05-07 06:21:57 +00004418 GlobalConstructionExp->printPretty(constructorExprBuf, nullptr,
4419 PrintingPolicy(LangOpts));
Fariborz Jahaniane0050702012-03-23 00:00:49 +00004420 globalBuf += constructorExprBuf.str();
4421 globalBuf += ";\n";
4422 InsertText(FunLocStart, globalBuf);
Craig Topper8ae12032014-05-07 06:21:57 +00004423 GlobalConstructionExp = nullptr;
Fariborz Jahaniane0050702012-03-23 00:00:49 +00004424 }
4425
Fariborz Jahanian11671902012-02-07 17:11:38 +00004426 Blocks.clear();
4427 InnerDeclRefsCount.clear();
4428 InnerDeclRefs.clear();
4429 RewrittenBlockExprs.clear();
4430}
4431
4432void RewriteModernObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
Fangrui Song6907ce22018-07-30 19:24:48 +00004433 SourceLocation FunLocStart =
Fariborz Jahaniane49a42c2012-04-25 17:56:48 +00004434 (!Blocks.empty()) ? getFunctionSourceLocation(*this, FD)
4435 : FD->getTypeSpecStartLoc();
Fariborz Jahanian11671902012-02-07 17:11:38 +00004436 StringRef FuncName = FD->getName();
4437
4438 SynthesizeBlockLiterals(FunLocStart, FuncName);
4439}
4440
4441static void BuildUniqueMethodName(std::string &Name,
4442 ObjCMethodDecl *MD) {
4443 ObjCInterfaceDecl *IFace = MD->getClassInterface();
4444 Name = IFace->getName();
4445 Name += "__" + MD->getSelector().getAsString();
4446 // Convert colons to underscores.
4447 std::string::size_type loc = 0;
Sylvestre Ledrud8650cd2017-01-28 13:36:34 +00004448 while ((loc = Name.find(':', loc)) != std::string::npos)
Fariborz Jahanian11671902012-02-07 17:11:38 +00004449 Name.replace(loc, 1, "_");
4450}
4451
4452void RewriteModernObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004453 // fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
4454 // SourceLocation FunLocStart = MD->getBeginLoc();
4455 SourceLocation FunLocStart = MD->getBeginLoc();
Fariborz Jahanian11671902012-02-07 17:11:38 +00004456 std::string FuncName;
4457 BuildUniqueMethodName(FuncName, MD);
4458 SynthesizeBlockLiterals(FunLocStart, FuncName);
4459}
4460
4461void RewriteModernObjC::GetBlockDeclRefExprs(Stmt *S) {
Benjamin Kramer642f1732015-07-02 21:03:14 +00004462 for (Stmt *SubStmt : S->children())
4463 if (SubStmt) {
4464 if (BlockExpr *CBE = dyn_cast<BlockExpr>(SubStmt))
Fariborz Jahanian11671902012-02-07 17:11:38 +00004465 GetBlockDeclRefExprs(CBE->getBody());
4466 else
Benjamin Kramer642f1732015-07-02 21:03:14 +00004467 GetBlockDeclRefExprs(SubStmt);
Fariborz Jahanian11671902012-02-07 17:11:38 +00004468 }
4469 // Handle specific things.
Alexey Bataevf841bd92014-12-16 07:00:22 +00004470 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S))
Alexey Bataev19acc3d2015-01-12 10:17:46 +00004471 if (DRE->refersToEnclosingVariableOrCapture() ||
Alexey Bataevf841bd92014-12-16 07:00:22 +00004472 HasLocalVariableExternalStorage(DRE->getDecl()))
Fariborz Jahanian35f6e122012-04-16 23:00:57 +00004473 // FIXME: Handle enums.
Alexey Bataevf841bd92014-12-16 07:00:22 +00004474 BlockDeclRefs.push_back(DRE);
Fariborz Jahanian11671902012-02-07 17:11:38 +00004475}
4476
Craig Topper5603df42013-07-05 19:34:19 +00004477void RewriteModernObjC::GetInnerBlockDeclRefExprs(Stmt *S,
4478 SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs,
Craig Topper4dd9b432014-08-17 23:49:53 +00004479 llvm::SmallPtrSetImpl<const DeclContext *> &InnerContexts) {
Benjamin Kramer642f1732015-07-02 21:03:14 +00004480 for (Stmt *SubStmt : S->children())
4481 if (SubStmt) {
4482 if (BlockExpr *CBE = dyn_cast<BlockExpr>(SubStmt)) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00004483 InnerContexts.insert(cast<DeclContext>(CBE->getBlockDecl()));
4484 GetInnerBlockDeclRefExprs(CBE->getBody(),
4485 InnerBlockDeclRefs,
4486 InnerContexts);
4487 }
4488 else
Benjamin Kramer642f1732015-07-02 21:03:14 +00004489 GetInnerBlockDeclRefExprs(SubStmt, InnerBlockDeclRefs, InnerContexts);
Fariborz Jahanian11671902012-02-07 17:11:38 +00004490 }
4491 // Handle specific things.
John McCall113bee02012-03-10 09:33:50 +00004492 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
Alexey Bataev19acc3d2015-01-12 10:17:46 +00004493 if (DRE->refersToEnclosingVariableOrCapture() ||
Alexey Bataevf841bd92014-12-16 07:00:22 +00004494 HasLocalVariableExternalStorage(DRE->getDecl())) {
4495 if (!InnerContexts.count(DRE->getDecl()->getDeclContext()))
John McCall113bee02012-03-10 09:33:50 +00004496 InnerBlockDeclRefs.push_back(DRE);
Alexey Bataevf841bd92014-12-16 07:00:22 +00004497 if (VarDecl *Var = cast<VarDecl>(DRE->getDecl()))
John McCall113bee02012-03-10 09:33:50 +00004498 if (Var->isFunctionOrMethodVarDecl())
4499 ImportedLocalExternalDecls.insert(Var);
4500 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00004501 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00004502}
4503
Fariborz Jahanianc3cdc412012-02-13 18:57:49 +00004504/// convertObjCTypeToCStyleType - This routine converts such objc types
4505/// as qualified objects, and blocks to their closest c/c++ types that
4506/// it can. It returns true if input type was modified.
4507bool RewriteModernObjC::convertObjCTypeToCStyleType(QualType &T) {
4508 QualType oldT = T;
4509 convertBlockPointerToFunctionPointer(T);
4510 if (T->isFunctionPointerType()) {
4511 QualType PointeeTy;
4512 if (const PointerType* PT = T->getAs<PointerType>()) {
4513 PointeeTy = PT->getPointeeType();
4514 if (const FunctionType *FT = PointeeTy->getAs<FunctionType>()) {
4515 T = convertFunctionTypeOfBlocks(FT);
4516 T = Context->getPointerType(T);
4517 }
4518 }
4519 }
Fangrui Song6907ce22018-07-30 19:24:48 +00004520
Fariborz Jahanianc3cdc412012-02-13 18:57:49 +00004521 convertToUnqualifiedObjCType(T);
4522 return T != oldT;
4523}
4524
Fariborz Jahanian11671902012-02-07 17:11:38 +00004525/// convertFunctionTypeOfBlocks - This routine converts a function type
4526/// whose result type may be a block pointer or whose argument type(s)
4527/// might be block pointers to an equivalent function type replacing
4528/// all block pointers to function pointers.
4529QualType RewriteModernObjC::convertFunctionTypeOfBlocks(const FunctionType *FT) {
4530 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
4531 // FTP will be null for closures that don't take arguments.
4532 // Generate a funky cast.
4533 SmallVector<QualType, 8> ArgTypes;
Alp Toker314cc812014-01-25 16:55:45 +00004534 QualType Res = FT->getReturnType();
Fariborz Jahanianc3cdc412012-02-13 18:57:49 +00004535 bool modified = convertObjCTypeToCStyleType(Res);
Fangrui Song6907ce22018-07-30 19:24:48 +00004536
Fariborz Jahanian11671902012-02-07 17:11:38 +00004537 if (FTP) {
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00004538 for (auto &I : FTP->param_types()) {
4539 QualType t = I;
Fariborz Jahanian11671902012-02-07 17:11:38 +00004540 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanianc3cdc412012-02-13 18:57:49 +00004541 if (convertObjCTypeToCStyleType(t))
4542 modified = true;
Fariborz Jahanian11671902012-02-07 17:11:38 +00004543 ArgTypes.push_back(t);
4544 }
4545 }
4546 QualType FuncType;
Fariborz Jahanianc3cdc412012-02-13 18:57:49 +00004547 if (modified)
Jordan Rose5c382722013-03-08 21:51:21 +00004548 FuncType = getSimpleFunctionType(Res, ArgTypes);
Fariborz Jahanian11671902012-02-07 17:11:38 +00004549 else FuncType = QualType(FT, 0);
4550 return FuncType;
4551}
4552
4553Stmt *RewriteModernObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
4554 // Navigate to relevant type information.
Craig Topper8ae12032014-05-07 06:21:57 +00004555 const BlockPointerType *CPT = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00004556
4557 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
4558 CPT = DRE->getType()->getAs<BlockPointerType>();
Fariborz Jahanian11671902012-02-07 17:11:38 +00004559 } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
4560 CPT = MExpr->getType()->getAs<BlockPointerType>();
Fangrui Song6907ce22018-07-30 19:24:48 +00004561 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00004562 else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
4563 return SynthesizeBlockCall(Exp, PRE->getSubExpr());
4564 }
Fangrui Song6907ce22018-07-30 19:24:48 +00004565 else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
Fariborz Jahanian11671902012-02-07 17:11:38 +00004566 CPT = IEXPR->getType()->getAs<BlockPointerType>();
Fangrui Song6907ce22018-07-30 19:24:48 +00004567 else if (const ConditionalOperator *CEXPR =
Fariborz Jahanian11671902012-02-07 17:11:38 +00004568 dyn_cast<ConditionalOperator>(BlockExp)) {
4569 Expr *LHSExp = CEXPR->getLHS();
4570 Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
4571 Expr *RHSExp = CEXPR->getRHS();
4572 Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
4573 Expr *CONDExp = CEXPR->getCond();
4574 ConditionalOperator *CondExpr =
4575 new (Context) ConditionalOperator(CONDExp,
4576 SourceLocation(), cast<Expr>(LHSStmt),
4577 SourceLocation(), cast<Expr>(RHSStmt),
4578 Exp->getType(), VK_RValue, OK_Ordinary);
4579 return CondExpr;
4580 } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
4581 CPT = IRE->getType()->getAs<BlockPointerType>();
4582 } else if (const PseudoObjectExpr *POE
4583 = dyn_cast<PseudoObjectExpr>(BlockExp)) {
4584 CPT = POE->getType()->castAs<BlockPointerType>();
4585 } else {
Craig Topper0da20762016-04-24 02:08:22 +00004586 assert(false && "RewriteBlockClass: Bad type");
Fariborz Jahanian11671902012-02-07 17:11:38 +00004587 }
4588 assert(CPT && "RewriteBlockClass: Bad type");
4589 const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
4590 assert(FT && "RewriteBlockClass: Bad type");
4591 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
4592 // FTP will be null for closures that don't take arguments.
4593
4594 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
4595 SourceLocation(), SourceLocation(),
4596 &Context->Idents.get("__block_impl"));
4597 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
4598
4599 // Generate a funky cast.
4600 SmallVector<QualType, 8> ArgTypes;
4601
4602 // Push the block argument type.
4603 ArgTypes.push_back(PtrBlock);
4604 if (FTP) {
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00004605 for (auto &I : FTP->param_types()) {
4606 QualType t = I;
Fariborz Jahanian11671902012-02-07 17:11:38 +00004607 // Make sure we convert "t (^)(...)" to "t (*)(...)".
4608 if (!convertBlockPointerToFunctionPointer(t))
4609 convertToUnqualifiedObjCType(t);
4610 ArgTypes.push_back(t);
4611 }
4612 }
4613 // Now do the pointer to function cast.
Jordan Rose5c382722013-03-08 21:51:21 +00004614 QualType PtrToFuncCastType = getSimpleFunctionType(Exp->getType(), ArgTypes);
Fariborz Jahanian11671902012-02-07 17:11:38 +00004615
4616 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
4617
4618 CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock,
4619 CK_BitCast,
4620 const_cast<Expr*>(BlockExp));
4621 // Don't forget the parens to enforce the proper binding.
4622 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4623 BlkCast);
4624 //PE->dump();
4625
Craig Topper8ae12032014-05-07 06:21:57 +00004626 FieldDecl *FD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00004627 SourceLocation(),
4628 &Context->Idents.get("FuncPtr"),
Fariborz Jahanianf8e68e22015-04-09 18:36:50 +00004629 Context->VoidPtrTy, nullptr,
4630 /*BitWidth=*/nullptr, /*Mutable=*/true,
4631 ICIS_NoInit);
4632 MemberExpr *ME =
4633 new (Context) MemberExpr(PE, true, SourceLocation(), FD, SourceLocation(),
4634 FD->getType(), VK_LValue, OK_Ordinary);
4635
4636 CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType,
4637 CK_BitCast, ME);
4638 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
Fariborz Jahanian11671902012-02-07 17:11:38 +00004639
4640 SmallVector<Expr*, 8> BlkExprs;
4641 // Add the implicit argument.
4642 BlkExprs.push_back(BlkCast);
4643 // Add the user arguments.
4644 for (CallExpr::arg_iterator I = Exp->arg_begin(),
4645 E = Exp->arg_end(); I != E; ++I) {
4646 BlkExprs.push_back(*I);
4647 }
Bruno Riccic5885cf2018-12-21 15:20:32 +00004648 CallExpr *CE = CallExpr::Create(*Context, PE, BlkExprs, Exp->getType(),
4649 VK_RValue, SourceLocation());
Fariborz Jahanian11671902012-02-07 17:11:38 +00004650 return CE;
4651}
4652
4653// We need to return the rewritten expression to handle cases where the
John McCall113bee02012-03-10 09:33:50 +00004654// DeclRefExpr is embedded in another expression being rewritten.
Fariborz Jahanian11671902012-02-07 17:11:38 +00004655// For example:
4656//
4657// int main() {
4658// __block Foo *f;
4659// __block int i;
4660//
4661// void (^myblock)() = ^() {
John McCall113bee02012-03-10 09:33:50 +00004662// [f test]; // f is a DeclRefExpr embedded in a message (which is being rewritten).
Fariborz Jahanian11671902012-02-07 17:11:38 +00004663// i = 77;
4664// };
4665//}
John McCall113bee02012-03-10 09:33:50 +00004666Stmt *RewriteModernObjC::RewriteBlockDeclRefExpr(DeclRefExpr *DeclRefExp) {
Fangrui Song6907ce22018-07-30 19:24:48 +00004667 // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
Fariborz Jahanian11671902012-02-07 17:11:38 +00004668 // for each DeclRefExp where BYREFVAR is name of the variable.
John McCall113bee02012-03-10 09:33:50 +00004669 ValueDecl *VD = DeclRefExp->getDecl();
Alexey Bataev19acc3d2015-01-12 10:17:46 +00004670 bool isArrow = DeclRefExp->refersToEnclosingVariableOrCapture() ||
Alexey Bataevf841bd92014-12-16 07:00:22 +00004671 HasLocalVariableExternalStorage(DeclRefExp->getDecl());
Craig Topper8ae12032014-05-07 06:21:57 +00004672
4673 FieldDecl *FD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00004674 SourceLocation(),
Fangrui Song6907ce22018-07-30 19:24:48 +00004675 &Context->Idents.get("__forwarding"),
Fariborz Jahanianf8e68e22015-04-09 18:36:50 +00004676 Context->VoidPtrTy, nullptr,
4677 /*BitWidth=*/nullptr, /*Mutable=*/true,
4678 ICIS_NoInit);
4679 MemberExpr *ME = new (Context)
4680 MemberExpr(DeclRefExp, isArrow, SourceLocation(), FD, SourceLocation(),
4681 FD->getType(), VK_LValue, OK_Ordinary);
4682
4683 StringRef Name = VD->getName();
4684 FD = FieldDecl::Create(*Context, nullptr, SourceLocation(), SourceLocation(),
Fangrui Song6907ce22018-07-30 19:24:48 +00004685 &Context->Idents.get(Name),
Fariborz Jahanianf8e68e22015-04-09 18:36:50 +00004686 Context->VoidPtrTy, nullptr,
4687 /*BitWidth=*/nullptr, /*Mutable=*/true,
4688 ICIS_NoInit);
4689 ME =
4690 new (Context) MemberExpr(ME, true, SourceLocation(), FD, SourceLocation(),
4691 DeclRefExp->getType(), VK_LValue, OK_Ordinary);
4692
4693 // Need parens to enforce precedence.
Fangrui Song6907ce22018-07-30 19:24:48 +00004694 ParenExpr *PE = new (Context) ParenExpr(DeclRefExp->getExprLoc(),
4695 DeclRefExp->getExprLoc(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00004696 ME);
4697 ReplaceStmt(DeclRefExp, PE);
4698 return PE;
4699}
4700
Fangrui Song6907ce22018-07-30 19:24:48 +00004701// Rewrites the imported local variable V with external storage
Fariborz Jahanian11671902012-02-07 17:11:38 +00004702// (static, extern, etc.) as *V
4703//
4704Stmt *RewriteModernObjC::RewriteLocalVariableExternalStorage(DeclRefExpr *DRE) {
4705 ValueDecl *VD = DRE->getDecl();
4706 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4707 if (!ImportedLocalExternalDecls.count(Var))
4708 return DRE;
4709 Expr *Exp = new (Context) UnaryOperator(DRE, UO_Deref, DRE->getType(),
4710 VK_LValue, OK_Ordinary,
Aaron Ballmana5038552018-01-09 13:07:03 +00004711 DRE->getLocation(), false);
Fariborz Jahanian11671902012-02-07 17:11:38 +00004712 // Need parens to enforce precedence.
Fangrui Song6907ce22018-07-30 19:24:48 +00004713 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00004714 Exp);
4715 ReplaceStmt(DRE, PE);
4716 return PE;
4717}
4718
4719void RewriteModernObjC::RewriteCastExpr(CStyleCastExpr *CE) {
4720 SourceLocation LocStart = CE->getLParenLoc();
4721 SourceLocation LocEnd = CE->getRParenLoc();
4722
4723 // Need to avoid trying to rewrite synthesized casts.
4724 if (LocStart.isInvalid())
4725 return;
4726 // Need to avoid trying to rewrite casts contained in macros.
4727 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
4728 return;
4729
4730 const char *startBuf = SM->getCharacterData(LocStart);
4731 const char *endBuf = SM->getCharacterData(LocEnd);
4732 QualType QT = CE->getType();
4733 const Type* TypePtr = QT->getAs<Type>();
4734 if (isa<TypeOfExprType>(TypePtr)) {
4735 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
4736 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
4737 std::string TypeAsString = "(";
4738 RewriteBlockPointerType(TypeAsString, QT);
4739 TypeAsString += ")";
4740 ReplaceText(LocStart, endBuf-startBuf+1, TypeAsString);
4741 return;
4742 }
4743 // advance the location to startArgList.
4744 const char *argPtr = startBuf;
4745
4746 while (*argPtr++ && (argPtr < endBuf)) {
4747 switch (*argPtr) {
4748 case '^':
4749 // Replace the '^' with '*'.
4750 LocStart = LocStart.getLocWithOffset(argPtr-startBuf);
4751 ReplaceText(LocStart, 1, "*");
4752 break;
4753 }
4754 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00004755}
4756
Fariborz Jahanian2c00acd2012-04-10 00:08:18 +00004757void RewriteModernObjC::RewriteImplicitCastObjCExpr(CastExpr *IC) {
4758 CastKind CastKind = IC->getCastKind();
Fariborz Jahaniancc172282012-04-16 22:14:01 +00004759 if (CastKind != CK_BlockPointerToObjCPointerCast &&
4760 CastKind != CK_AnyPointerToBlockPointerCast)
4761 return;
Fangrui Song6907ce22018-07-30 19:24:48 +00004762
Fariborz Jahaniancc172282012-04-16 22:14:01 +00004763 QualType QT = IC->getType();
4764 (void)convertBlockPointerToFunctionPointer(QT);
4765 std::string TypeString(QT.getAsString(Context->getPrintingPolicy()));
4766 std::string Str = "(";
4767 Str += TypeString;
4768 Str += ")";
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004769 InsertText(IC->getSubExpr()->getBeginLoc(), Str);
Fariborz Jahanian2c00acd2012-04-10 00:08:18 +00004770}
4771
Fariborz Jahanian11671902012-02-07 17:11:38 +00004772void RewriteModernObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
4773 SourceLocation DeclLoc = FD->getLocation();
4774 unsigned parenCount = 0;
4775
4776 // We have 1 or more arguments that have closure pointers.
4777 const char *startBuf = SM->getCharacterData(DeclLoc);
4778 const char *startArgList = strchr(startBuf, '(');
4779
4780 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
4781
4782 parenCount++;
4783 // advance the location to startArgList.
4784 DeclLoc = DeclLoc.getLocWithOffset(startArgList-startBuf);
4785 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
4786
4787 const char *argPtr = startArgList;
4788
4789 while (*argPtr++ && parenCount) {
4790 switch (*argPtr) {
4791 case '^':
4792 // Replace the '^' with '*'.
4793 DeclLoc = DeclLoc.getLocWithOffset(argPtr-startArgList);
4794 ReplaceText(DeclLoc, 1, "*");
4795 break;
4796 case '(':
4797 parenCount++;
4798 break;
4799 case ')':
4800 parenCount--;
4801 break;
4802 }
4803 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00004804}
4805
4806bool RewriteModernObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
4807 const FunctionProtoType *FTP;
4808 const PointerType *PT = QT->getAs<PointerType>();
4809 if (PT) {
4810 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4811 } else {
4812 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4813 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4814 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4815 }
4816 if (FTP) {
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00004817 for (const auto &I : FTP->param_types())
4818 if (isTopLevelBlockPointerType(I))
Fariborz Jahanian11671902012-02-07 17:11:38 +00004819 return true;
4820 }
4821 return false;
4822}
4823
4824bool RewriteModernObjC::PointerTypeTakesAnyObjCQualifiedType(QualType QT) {
4825 const FunctionProtoType *FTP;
4826 const PointerType *PT = QT->getAs<PointerType>();
4827 if (PT) {
4828 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4829 } else {
4830 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4831 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4832 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4833 }
4834 if (FTP) {
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00004835 for (const auto &I : FTP->param_types()) {
4836 if (I->isObjCQualifiedIdType())
Fariborz Jahanian11671902012-02-07 17:11:38 +00004837 return true;
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00004838 if (I->isObjCObjectPointerType() &&
4839 I->getPointeeType()->isObjCQualifiedInterfaceType())
Fariborz Jahanian11671902012-02-07 17:11:38 +00004840 return true;
4841 }
Fangrui Song6907ce22018-07-30 19:24:48 +00004842
Fariborz Jahanian11671902012-02-07 17:11:38 +00004843 }
4844 return false;
4845}
4846
4847void RewriteModernObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
4848 const char *&RParen) {
4849 const char *argPtr = strchr(Name, '(');
4850 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
4851
4852 LParen = argPtr; // output the start.
4853 argPtr++; // skip past the left paren.
4854 unsigned parenCount = 1;
4855
4856 while (*argPtr && parenCount) {
4857 switch (*argPtr) {
4858 case '(': parenCount++; break;
4859 case ')': parenCount--; break;
4860 default: break;
4861 }
4862 if (parenCount) argPtr++;
4863 }
4864 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
4865 RParen = argPtr; // output the end
4866}
4867
4868void RewriteModernObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
4869 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4870 RewriteBlockPointerFunctionArgs(FD);
4871 return;
4872 }
4873 // Handle Variables and Typedefs.
4874 SourceLocation DeclLoc = ND->getLocation();
4875 QualType DeclT;
4876 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
4877 DeclT = VD->getType();
4878 else if (TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(ND))
4879 DeclT = TDD->getUnderlyingType();
4880 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
4881 DeclT = FD->getType();
4882 else
4883 llvm_unreachable("RewriteBlockPointerDecl(): Decl type not yet handled");
4884
4885 const char *startBuf = SM->getCharacterData(DeclLoc);
4886 const char *endBuf = startBuf;
4887 // scan backward (from the decl location) for the end of the previous decl.
4888 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
4889 startBuf--;
4890 SourceLocation Start = DeclLoc.getLocWithOffset(startBuf-endBuf);
4891 std::string buf;
4892 unsigned OrigLength=0;
4893 // *startBuf != '^' if we are dealing with a pointer to function that
4894 // may take block argument types (which will be handled below).
4895 if (*startBuf == '^') {
4896 // Replace the '^' with '*', computing a negative offset.
4897 buf = '*';
4898 startBuf++;
4899 OrigLength++;
4900 }
4901 while (*startBuf != ')') {
4902 buf += *startBuf;
4903 startBuf++;
4904 OrigLength++;
4905 }
4906 buf += ')';
4907 OrigLength++;
Fangrui Song6907ce22018-07-30 19:24:48 +00004908
Fariborz Jahanian11671902012-02-07 17:11:38 +00004909 if (PointerTypeTakesAnyBlockArguments(DeclT) ||
4910 PointerTypeTakesAnyObjCQualifiedType(DeclT)) {
4911 // Replace the '^' with '*' for arguments.
4912 // Replace id<P> with id/*<>*/
4913 DeclLoc = ND->getLocation();
4914 startBuf = SM->getCharacterData(DeclLoc);
4915 const char *argListBegin, *argListEnd;
4916 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
4917 while (argListBegin < argListEnd) {
4918 if (*argListBegin == '^')
4919 buf += '*';
4920 else if (*argListBegin == '<') {
Fangrui Song6907ce22018-07-30 19:24:48 +00004921 buf += "/*";
Fariborz Jahanian11671902012-02-07 17:11:38 +00004922 buf += *argListBegin++;
Dmitri Gribenko76bb5cabfa2012-09-10 21:20:09 +00004923 OrigLength++;
Fariborz Jahanian11671902012-02-07 17:11:38 +00004924 while (*argListBegin != '>') {
4925 buf += *argListBegin++;
4926 OrigLength++;
4927 }
4928 buf += *argListBegin;
4929 buf += "*/";
4930 }
4931 else
4932 buf += *argListBegin;
4933 argListBegin++;
4934 OrigLength++;
4935 }
4936 buf += ')';
4937 OrigLength++;
4938 }
4939 ReplaceText(Start, OrigLength, buf);
Fariborz Jahanian11671902012-02-07 17:11:38 +00004940}
4941
Fariborz Jahanian11671902012-02-07 17:11:38 +00004942/// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
4943/// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
4944/// struct Block_byref_id_object *src) {
Fangrui Song6907ce22018-07-30 19:24:48 +00004945/// _Block_object_assign (&_dest->object, _src->object,
Fariborz Jahanian11671902012-02-07 17:11:38 +00004946/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4947/// [|BLOCK_FIELD_IS_WEAK]) // object
Fangrui Song6907ce22018-07-30 19:24:48 +00004948/// _Block_object_assign(&_dest->object, _src->object,
Fariborz Jahanian11671902012-02-07 17:11:38 +00004949/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4950/// [|BLOCK_FIELD_IS_WEAK]) // block
4951/// }
4952/// And:
4953/// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
Fangrui Song6907ce22018-07-30 19:24:48 +00004954/// _Block_object_dispose(_src->object,
Fariborz Jahanian11671902012-02-07 17:11:38 +00004955/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4956/// [|BLOCK_FIELD_IS_WEAK]) // object
Fangrui Song6907ce22018-07-30 19:24:48 +00004957/// _Block_object_dispose(_src->object,
Fariborz Jahanian11671902012-02-07 17:11:38 +00004958/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4959/// [|BLOCK_FIELD_IS_WEAK]) // block
4960/// }
4961
4962std::string RewriteModernObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
4963 int flag) {
4964 std::string S;
4965 if (CopyDestroyCache.count(flag))
4966 return S;
4967 CopyDestroyCache.insert(flag);
4968 S = "static void __Block_byref_id_object_copy_";
4969 S += utostr(flag);
4970 S += "(void *dst, void *src) {\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00004971
Fariborz Jahanian11671902012-02-07 17:11:38 +00004972 // offset into the object pointer is computed as:
4973 // void * + void* + int + int + void* + void *
Fangrui Song6907ce22018-07-30 19:24:48 +00004974 unsigned IntSize =
Fariborz Jahanian11671902012-02-07 17:11:38 +00004975 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Fangrui Song6907ce22018-07-30 19:24:48 +00004976 unsigned VoidPtrSize =
Fariborz Jahanian11671902012-02-07 17:11:38 +00004977 static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
Fangrui Song6907ce22018-07-30 19:24:48 +00004978
Fariborz Jahanian11671902012-02-07 17:11:38 +00004979 unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/Context->getCharWidth();
4980 S += " _Block_object_assign((char*)dst + ";
4981 S += utostr(offset);
4982 S += ", *(void * *) ((char*)src + ";
4983 S += utostr(offset);
4984 S += "), ";
4985 S += utostr(flag);
4986 S += ");\n}\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00004987
Fariborz Jahanian11671902012-02-07 17:11:38 +00004988 S += "static void __Block_byref_id_object_dispose_";
4989 S += utostr(flag);
4990 S += "(void *src) {\n";
4991 S += " _Block_object_dispose(*(void * *) ((char*)src + ";
4992 S += utostr(offset);
4993 S += "), ";
4994 S += utostr(flag);
4995 S += ");\n}\n";
4996 return S;
4997}
4998
4999/// RewriteByRefVar - For each __block typex ND variable this routine transforms
5000/// the declaration into:
5001/// struct __Block_byref_ND {
5002/// void *__isa; // NULL for everything except __weak pointers
5003/// struct __Block_byref_ND *__forwarding;
5004/// int32_t __flags;
5005/// int32_t __size;
5006/// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
5007/// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
5008/// typex ND;
5009/// };
5010///
5011/// It then replaces declaration of ND variable with:
Fangrui Song6907ce22018-07-30 19:24:48 +00005012/// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
5013/// __size=sizeof(struct __Block_byref_ND),
Fariborz Jahanian11671902012-02-07 17:11:38 +00005014/// ND=initializer-if-any};
5015///
5016///
Fariborz Jahanian847713a2012-04-24 19:38:45 +00005017void RewriteModernObjC::RewriteByRefVar(VarDecl *ND, bool firstDecl,
5018 bool lastDecl) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00005019 int flag = 0;
5020 int isa = 0;
5021 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
5022 if (DeclLoc.isInvalid())
5023 // If type location is missing, it is because of missing type (a warning).
5024 // Use variable's location which is good for this case.
5025 DeclLoc = ND->getLocation();
5026 const char *startBuf = SM->getCharacterData(DeclLoc);
Stephen Kelly1c301dc2018-08-09 21:09:38 +00005027 SourceLocation X = ND->getEndLoc();
Fariborz Jahanian11671902012-02-07 17:11:38 +00005028 X = SM->getExpansionLoc(X);
5029 const char *endBuf = SM->getCharacterData(X);
5030 std::string Name(ND->getNameAsString());
5031 std::string ByrefType;
5032 RewriteByRefString(ByrefType, Name, ND, true);
5033 ByrefType += " {\n";
5034 ByrefType += " void *__isa;\n";
5035 RewriteByRefString(ByrefType, Name, ND);
5036 ByrefType += " *__forwarding;\n";
5037 ByrefType += " int __flags;\n";
5038 ByrefType += " int __size;\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00005039 // Add void *__Block_byref_id_object_copy;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005040 // void *__Block_byref_id_object_dispose; if needed.
5041 QualType Ty = ND->getType();
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00005042 bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty, ND);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005043 if (HasCopyAndDispose) {
5044 ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
5045 ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
5046 }
5047
5048 QualType T = Ty;
5049 (void)convertBlockPointerToFunctionPointer(T);
5050 T.getAsStringInternal(Name, Context->getPrintingPolicy());
Fangrui Song6907ce22018-07-30 19:24:48 +00005051
Fariborz Jahanian11671902012-02-07 17:11:38 +00005052 ByrefType += " " + Name + ";\n";
5053 ByrefType += "};\n";
5054 // Insert this type in global scope. It is needed by helper function.
5055 SourceLocation FunLocStart;
5056 if (CurFunctionDef)
Fariborz Jahanianca357d92012-04-19 00:50:01 +00005057 FunLocStart = getFunctionSourceLocation(*this, CurFunctionDef);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005058 else {
5059 assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null");
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005060 FunLocStart = CurMethodDef->getBeginLoc();
Fariborz Jahanian11671902012-02-07 17:11:38 +00005061 }
5062 InsertText(FunLocStart, ByrefType);
Fangrui Song6907ce22018-07-30 19:24:48 +00005063
Fariborz Jahanian11671902012-02-07 17:11:38 +00005064 if (Ty.isObjCGCWeak()) {
5065 flag |= BLOCK_FIELD_IS_WEAK;
5066 isa = 1;
5067 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00005068 if (HasCopyAndDispose) {
5069 flag = BLOCK_BYREF_CALLER;
5070 QualType Ty = ND->getType();
5071 // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
5072 if (Ty->isBlockPointerType())
5073 flag |= BLOCK_FIELD_IS_BLOCK;
5074 else
5075 flag |= BLOCK_FIELD_IS_OBJECT;
5076 std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
5077 if (!HF.empty())
Fariborz Jahaniane4996132013-02-07 22:50:40 +00005078 Preamble += HF;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005079 }
Fangrui Song6907ce22018-07-30 19:24:48 +00005080
5081 // struct __Block_byref_ND ND =
5082 // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
Fariborz Jahanian11671902012-02-07 17:11:38 +00005083 // initializer-if-any};
Craig Topper8ae12032014-05-07 06:21:57 +00005084 bool hasInit = (ND->getInit() != nullptr);
Fariborz Jahanian5811fd62012-04-11 23:57:12 +00005085 // FIXME. rewriter does not support __block c++ objects which
5086 // require construction.
Fariborz Jahanian16d0d6c2012-04-26 23:20:25 +00005087 if (hasInit)
5088 if (CXXConstructExpr *CExp = dyn_cast<CXXConstructExpr>(ND->getInit())) {
5089 CXXConstructorDecl *CXXDecl = CExp->getConstructor();
5090 if (CXXDecl && CXXDecl->isDefaultConstructor())
5091 hasInit = false;
5092 }
Fangrui Song6907ce22018-07-30 19:24:48 +00005093
Fariborz Jahanian11671902012-02-07 17:11:38 +00005094 unsigned flags = 0;
5095 if (HasCopyAndDispose)
5096 flags |= BLOCK_HAS_COPY_DISPOSE;
5097 Name = ND->getNameAsString();
5098 ByrefType.clear();
5099 RewriteByRefString(ByrefType, Name, ND);
5100 std::string ForwardingCastType("(");
5101 ForwardingCastType += ByrefType + " *)";
Fariborz Jahanian3fd9bbd2012-04-24 16:45:27 +00005102 ByrefType += " " + Name + " = {(void*)";
5103 ByrefType += utostr(isa);
5104 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
5105 ByrefType += utostr(flags);
5106 ByrefType += ", ";
5107 ByrefType += "sizeof(";
5108 RewriteByRefString(ByrefType, Name, ND);
5109 ByrefType += ")";
5110 if (HasCopyAndDispose) {
5111 ByrefType += ", __Block_byref_id_object_copy_";
5112 ByrefType += utostr(flag);
5113 ByrefType += ", __Block_byref_id_object_dispose_";
5114 ByrefType += utostr(flag);
5115 }
Fangrui Song6907ce22018-07-30 19:24:48 +00005116
Fariborz Jahanian847713a2012-04-24 19:38:45 +00005117 if (!firstDecl) {
5118 // In multiple __block declarations, and for all but 1st declaration,
5119 // find location of the separating comma. This would be start location
5120 // where new text is to be inserted.
5121 DeclLoc = ND->getLocation();
5122 const char *startDeclBuf = SM->getCharacterData(DeclLoc);
5123 const char *commaBuf = startDeclBuf;
5124 while (*commaBuf != ',')
5125 commaBuf--;
5126 assert((*commaBuf == ',') && "RewriteByRefVar: can't find ','");
5127 DeclLoc = DeclLoc.getLocWithOffset(commaBuf - startDeclBuf);
5128 startBuf = commaBuf;
5129 }
Fangrui Song6907ce22018-07-30 19:24:48 +00005130
Fariborz Jahanian11671902012-02-07 17:11:38 +00005131 if (!hasInit) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00005132 ByrefType += "};\n";
5133 unsigned nameSize = Name.size();
Simon Pilgrim2c518802017-03-30 14:13:19 +00005134 // for block or function pointer declaration. Name is already
Fariborz Jahanian11671902012-02-07 17:11:38 +00005135 // part of the declaration.
5136 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType())
5137 nameSize = 1;
5138 ReplaceText(DeclLoc, endBuf-startBuf+nameSize, ByrefType);
5139 }
5140 else {
Fariborz Jahanian3fd9bbd2012-04-24 16:45:27 +00005141 ByrefType += ", ";
Fariborz Jahanian11671902012-02-07 17:11:38 +00005142 SourceLocation startLoc;
5143 Expr *E = ND->getInit();
5144 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
5145 startLoc = ECE->getLParenLoc();
5146 else
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005147 startLoc = E->getBeginLoc();
Fariborz Jahanian11671902012-02-07 17:11:38 +00005148 startLoc = SM->getExpansionLoc(startLoc);
5149 endBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005150 ReplaceText(DeclLoc, endBuf-startBuf, ByrefType);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005151
Fariborz Jahanian847713a2012-04-24 19:38:45 +00005152 const char separator = lastDecl ? ';' : ',';
5153 const char *startInitializerBuf = SM->getCharacterData(startLoc);
5154 const char *separatorBuf = strchr(startInitializerBuf, separator);
Fangrui Song6907ce22018-07-30 19:24:48 +00005155 assert((*separatorBuf == separator) &&
Fariborz Jahanian847713a2012-04-24 19:38:45 +00005156 "RewriteByRefVar: can't find ';' or ','");
5157 SourceLocation separatorLoc =
5158 startLoc.getLocWithOffset(separatorBuf-startInitializerBuf);
Fangrui Song6907ce22018-07-30 19:24:48 +00005159
Fariborz Jahanian847713a2012-04-24 19:38:45 +00005160 InsertText(separatorLoc, lastDecl ? "}" : "};\n");
Fariborz Jahanian11671902012-02-07 17:11:38 +00005161 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00005162}
5163
5164void RewriteModernObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
5165 // Add initializers for any closure decl refs.
5166 GetBlockDeclRefExprs(Exp->getBody());
5167 if (BlockDeclRefs.size()) {
5168 // Unique all "by copy" declarations.
5169 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCall113bee02012-03-10 09:33:50 +00005170 if (!BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00005171 if (!BlockByCopyDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
5172 BlockByCopyDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
5173 BlockByCopyDecls.push_back(BlockDeclRefs[i]->getDecl());
5174 }
5175 }
5176 // Unique all "by ref" declarations.
5177 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCall113bee02012-03-10 09:33:50 +00005178 if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00005179 if (!BlockByRefDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
5180 BlockByRefDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
5181 BlockByRefDecls.push_back(BlockDeclRefs[i]->getDecl());
5182 }
5183 }
5184 // Find any imported blocks...they will need special attention.
5185 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCall113bee02012-03-10 09:33:50 +00005186 if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
Fangrui Song6907ce22018-07-30 19:24:48 +00005187 BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
Fariborz Jahanian11671902012-02-07 17:11:38 +00005188 BlockDeclRefs[i]->getType()->isBlockPointerType())
5189 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
5190 }
5191}
5192
5193FunctionDecl *RewriteModernObjC::SynthBlockInitFunctionDecl(StringRef name) {
5194 IdentifierInfo *ID = &Context->Idents.get(name);
5195 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
5196 return FunctionDecl::Create(*Context, TUDecl, SourceLocation(),
Craig Topper8ae12032014-05-07 06:21:57 +00005197 SourceLocation(), ID, FType, nullptr, SC_Extern,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00005198 false, false);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005199}
5200
5201Stmt *RewriteModernObjC::SynthBlockInitExpr(BlockExpr *Exp,
Craig Topper5603df42013-07-05 19:34:19 +00005202 const SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00005203 const BlockDecl *block = Exp->getBlockDecl();
Fangrui Song6907ce22018-07-30 19:24:48 +00005204
Fariborz Jahanian11671902012-02-07 17:11:38 +00005205 Blocks.push_back(Exp);
5206
5207 CollectBlockDeclRefInfo(Exp);
Fangrui Song6907ce22018-07-30 19:24:48 +00005208
Fariborz Jahanian11671902012-02-07 17:11:38 +00005209 // Add inner imported variables now used in current block.
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00005210 int countOfInnerDecls = 0;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005211 if (!InnerBlockDeclRefs.empty()) {
5212 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++) {
John McCall113bee02012-03-10 09:33:50 +00005213 DeclRefExpr *Exp = InnerBlockDeclRefs[i];
Fariborz Jahanian11671902012-02-07 17:11:38 +00005214 ValueDecl *VD = Exp->getDecl();
John McCall113bee02012-03-10 09:33:50 +00005215 if (!VD->hasAttr<BlocksAttr>() && !BlockByCopyDeclsPtrSet.count(VD)) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00005216 // We need to save the copied-in variables in nested
5217 // blocks because it is needed at the end for some of the API generations.
5218 // See SynthesizeBlockLiterals routine.
5219 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5220 BlockDeclRefs.push_back(Exp);
5221 BlockByCopyDeclsPtrSet.insert(VD);
5222 BlockByCopyDecls.push_back(VD);
5223 }
John McCall113bee02012-03-10 09:33:50 +00005224 if (VD->hasAttr<BlocksAttr>() && !BlockByRefDeclsPtrSet.count(VD)) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00005225 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5226 BlockDeclRefs.push_back(Exp);
5227 BlockByRefDeclsPtrSet.insert(VD);
5228 BlockByRefDecls.push_back(VD);
5229 }
5230 }
5231 // Find any imported blocks...they will need special attention.
5232 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++)
John McCall113bee02012-03-10 09:33:50 +00005233 if (InnerBlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
Fangrui Song6907ce22018-07-30 19:24:48 +00005234 InnerBlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
Fariborz Jahanian11671902012-02-07 17:11:38 +00005235 InnerBlockDeclRefs[i]->getType()->isBlockPointerType())
5236 ImportedBlockDecls.insert(InnerBlockDeclRefs[i]->getDecl());
5237 }
5238 InnerDeclRefsCount.push_back(countOfInnerDecls);
Fangrui Song6907ce22018-07-30 19:24:48 +00005239
Fariborz Jahanian11671902012-02-07 17:11:38 +00005240 std::string FuncName;
5241
5242 if (CurFunctionDef)
5243 FuncName = CurFunctionDef->getNameAsString();
5244 else if (CurMethodDef)
5245 BuildUniqueMethodName(FuncName, CurMethodDef);
5246 else if (GlobalVarDecl)
5247 FuncName = std::string(GlobalVarDecl->getNameAsString());
5248
Fangrui Song6907ce22018-07-30 19:24:48 +00005249 bool GlobalBlockExpr =
Fariborz Jahaniane0050702012-03-23 00:00:49 +00005250 block->getDeclContext()->getRedeclContext()->isFileContext();
Fangrui Song6907ce22018-07-30 19:24:48 +00005251
Fariborz Jahaniane0050702012-03-23 00:00:49 +00005252 if (GlobalBlockExpr && !GlobalVarDecl) {
5253 Diags.Report(block->getLocation(), GlobalBlockRewriteFailedDiag);
5254 GlobalBlockExpr = false;
5255 }
Fangrui Song6907ce22018-07-30 19:24:48 +00005256
Fariborz Jahanian11671902012-02-07 17:11:38 +00005257 std::string BlockNumber = utostr(Blocks.size()-1);
5258
Fariborz Jahanian11671902012-02-07 17:11:38 +00005259 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
5260
5261 // Get a pointer to the function type so we can cast appropriately.
5262 QualType BFT = convertFunctionTypeOfBlocks(Exp->getFunctionType());
5263 QualType FType = Context->getPointerType(BFT);
5264
5265 FunctionDecl *FD;
5266 Expr *NewRep;
5267
Benjamin Kramer60509af2013-09-09 14:48:42 +00005268 // Simulate a constructor call...
Fariborz Jahaniane0050702012-03-23 00:00:49 +00005269 std::string Tag;
Fangrui Song6907ce22018-07-30 19:24:48 +00005270
Fariborz Jahaniane0050702012-03-23 00:00:49 +00005271 if (GlobalBlockExpr)
5272 Tag = "__global_";
5273 else
5274 Tag = "__";
5275 Tag += FuncName + "_block_impl_" + BlockNumber;
Fangrui Song6907ce22018-07-30 19:24:48 +00005276
Fariborz Jahanian11671902012-02-07 17:11:38 +00005277 FD = SynthBlockInitFunctionDecl(Tag);
Bruno Ricci5fc4db72018-12-21 14:10:18 +00005278 DeclRefExpr *DRE = new (Context)
5279 DeclRefExpr(*Context, FD, false, FType, VK_RValue, SourceLocation());
Fariborz Jahanian11671902012-02-07 17:11:38 +00005280
5281 SmallVector<Expr*, 4> InitExprs;
5282
5283 // Initialize the block function.
5284 FD = SynthBlockInitFunctionDecl(Func);
Bruno Ricci5fc4db72018-12-21 14:10:18 +00005285 DeclRefExpr *Arg = new (Context) DeclRefExpr(
5286 *Context, FD, false, FD->getType(), VK_LValue, SourceLocation());
Fariborz Jahanian11671902012-02-07 17:11:38 +00005287 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
5288 CK_BitCast, Arg);
5289 InitExprs.push_back(castExpr);
5290
5291 // Initialize the block descriptor.
5292 std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
5293
Malcolm Parsonsf76f6502016-11-02 10:39:27 +00005294 VarDecl *NewVD = VarDecl::Create(
5295 *Context, TUDecl, SourceLocation(), SourceLocation(),
5296 &Context->Idents.get(DescData), Context->VoidPtrTy, nullptr, SC_Static);
Bruno Ricci5fc4db72018-12-21 14:10:18 +00005297 UnaryOperator *DescRefExpr = new (Context) UnaryOperator(
5298 new (Context) DeclRefExpr(*Context, NewVD, false, Context->VoidPtrTy,
5299 VK_LValue, SourceLocation()),
5300 UO_AddrOf, Context->getPointerType(Context->VoidPtrTy), VK_RValue,
5301 OK_Ordinary, SourceLocation(), false);
Fangrui Song6907ce22018-07-30 19:24:48 +00005302 InitExprs.push_back(DescRefExpr);
5303
Fariborz Jahanian11671902012-02-07 17:11:38 +00005304 // Add initializers for any closure decl refs.
5305 if (BlockDeclRefs.size()) {
5306 Expr *Exp;
5307 // Output all "by copy" declarations.
Craig Topper2341c0d2013-07-04 03:08:24 +00005308 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00005309 E = BlockByCopyDecls.end(); I != E; ++I) {
5310 if (isObjCType((*I)->getType())) {
5311 // FIXME: Conform to ABI ([[obj retain] autorelease]).
5312 FD = SynthBlockInitFunctionDecl((*I)->getName());
Bruno Ricci5fc4db72018-12-21 14:10:18 +00005313 Exp = new (Context) DeclRefExpr(*Context, FD, false, FD->getType(),
John McCall113bee02012-03-10 09:33:50 +00005314 VK_LValue, SourceLocation());
Fariborz Jahanian11671902012-02-07 17:11:38 +00005315 if (HasLocalVariableExternalStorage(*I)) {
5316 QualType QT = (*I)->getType();
5317 QT = Context->getPointerType(QT);
5318 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
Aaron Ballmana5038552018-01-09 13:07:03 +00005319 OK_Ordinary, SourceLocation(),
5320 false);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005321 }
5322 } else if (isTopLevelBlockPointerType((*I)->getType())) {
5323 FD = SynthBlockInitFunctionDecl((*I)->getName());
Bruno Ricci5fc4db72018-12-21 14:10:18 +00005324 Arg = new (Context) DeclRefExpr(*Context, FD, false, FD->getType(),
John McCall113bee02012-03-10 09:33:50 +00005325 VK_LValue, SourceLocation());
Fariborz Jahanian11671902012-02-07 17:11:38 +00005326 Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
5327 CK_BitCast, Arg);
5328 } else {
5329 FD = SynthBlockInitFunctionDecl((*I)->getName());
Bruno Ricci5fc4db72018-12-21 14:10:18 +00005330 Exp = new (Context) DeclRefExpr(*Context, FD, false, FD->getType(),
John McCall113bee02012-03-10 09:33:50 +00005331 VK_LValue, SourceLocation());
Fariborz Jahanian11671902012-02-07 17:11:38 +00005332 if (HasLocalVariableExternalStorage(*I)) {
5333 QualType QT = (*I)->getType();
5334 QT = Context->getPointerType(QT);
5335 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
Aaron Ballmana5038552018-01-09 13:07:03 +00005336 OK_Ordinary, SourceLocation(),
5337 false);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005338 }
Fangrui Song6907ce22018-07-30 19:24:48 +00005339
Fariborz Jahanian11671902012-02-07 17:11:38 +00005340 }
5341 InitExprs.push_back(Exp);
5342 }
5343 // Output all "by ref" declarations.
Craig Topper2341c0d2013-07-04 03:08:24 +00005344 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00005345 E = BlockByRefDecls.end(); I != E; ++I) {
5346 ValueDecl *ND = (*I);
5347 std::string Name(ND->getNameAsString());
5348 std::string RecName;
5349 RewriteByRefString(RecName, Name, ND, true);
Fangrui Song6907ce22018-07-30 19:24:48 +00005350 IdentifierInfo *II = &Context->Idents.get(RecName.c_str()
Fariborz Jahanian11671902012-02-07 17:11:38 +00005351 + sizeof("struct"));
5352 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
5353 SourceLocation(), SourceLocation(),
5354 II);
5355 assert(RD && "SynthBlockInitExpr(): Can't find RecordDecl");
5356 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
Fangrui Song6907ce22018-07-30 19:24:48 +00005357
Fariborz Jahanian11671902012-02-07 17:11:38 +00005358 FD = SynthBlockInitFunctionDecl((*I)->getName());
Bruno Ricci5fc4db72018-12-21 14:10:18 +00005359 Exp = new (Context) DeclRefExpr(*Context, FD, false, FD->getType(),
5360 VK_LValue, SourceLocation());
Fariborz Jahanian11671902012-02-07 17:11:38 +00005361 bool isNestedCapturedVar = false;
5362 if (block)
Aaron Ballman9371dd22014-03-14 18:34:04 +00005363 for (const auto &CI : block->captures()) {
5364 const VarDecl *variable = CI.getVariable();
5365 if (variable == ND && CI.isNested()) {
Fangrui Song6907ce22018-07-30 19:24:48 +00005366 assert (CI.isByRef() &&
Fariborz Jahanian11671902012-02-07 17:11:38 +00005367 "SynthBlockInitExpr - captured block variable is not byref");
5368 isNestedCapturedVar = true;
5369 break;
5370 }
5371 }
5372 // captured nested byref variable has its address passed. Do not take
5373 // its address again.
5374 if (!isNestedCapturedVar)
5375 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf,
5376 Context->getPointerType(Exp->getType()),
Aaron Ballmana5038552018-01-09 13:07:03 +00005377 VK_RValue, OK_Ordinary, SourceLocation(),
5378 false);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005379 Exp = NoTypeInfoCStyleCastExpr(Context, castT, CK_BitCast, Exp);
5380 InitExprs.push_back(Exp);
5381 }
5382 }
5383 if (ImportedBlockDecls.size()) {
5384 // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
5385 int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
Fangrui Song6907ce22018-07-30 19:24:48 +00005386 unsigned IntSize =
Fariborz Jahanian11671902012-02-07 17:11:38 +00005387 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Fangrui Song6907ce22018-07-30 19:24:48 +00005388 Expr *FlagExp = IntegerLiteral::Create(*Context, llvm::APInt(IntSize, flag),
Fariborz Jahanian11671902012-02-07 17:11:38 +00005389 Context->IntTy, SourceLocation());
5390 InitExprs.push_back(FlagExp);
5391 }
Bruno Riccic5885cf2018-12-21 15:20:32 +00005392 NewRep = CallExpr::Create(*Context, DRE, InitExprs, FType, VK_LValue,
5393 SourceLocation());
Fangrui Song6907ce22018-07-30 19:24:48 +00005394
Fariborz Jahaniane0050702012-03-23 00:00:49 +00005395 if (GlobalBlockExpr) {
Craig Topper8ae12032014-05-07 06:21:57 +00005396 assert (!GlobalConstructionExp &&
Fariborz Jahaniane0050702012-03-23 00:00:49 +00005397 "SynthBlockInitExpr - GlobalConstructionExp must be null");
5398 GlobalConstructionExp = NewRep;
5399 NewRep = DRE;
5400 }
Fangrui Song6907ce22018-07-30 19:24:48 +00005401
Fariborz Jahanian11671902012-02-07 17:11:38 +00005402 NewRep = new (Context) UnaryOperator(NewRep, UO_AddrOf,
5403 Context->getPointerType(NewRep->getType()),
Aaron Ballmana5038552018-01-09 13:07:03 +00005404 VK_RValue, OK_Ordinary, SourceLocation(), false);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005405 NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CK_BitCast,
5406 NewRep);
Fariborz Jahanian937224772014-10-28 23:46:58 +00005407 // Put Paren around the call.
5408 NewRep = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
5409 NewRep);
Fangrui Song6907ce22018-07-30 19:24:48 +00005410
Fariborz Jahanian11671902012-02-07 17:11:38 +00005411 BlockDeclRefs.clear();
5412 BlockByRefDecls.clear();
5413 BlockByRefDeclsPtrSet.clear();
5414 BlockByCopyDecls.clear();
5415 BlockByCopyDeclsPtrSet.clear();
5416 ImportedBlockDecls.clear();
5417 return NewRep;
5418}
5419
5420bool RewriteModernObjC::IsDeclStmtInForeachHeader(DeclStmt *DS) {
Fangrui Song6907ce22018-07-30 19:24:48 +00005421 if (const ObjCForCollectionStmt * CS =
Fariborz Jahanian11671902012-02-07 17:11:38 +00005422 dyn_cast<ObjCForCollectionStmt>(Stmts.back()))
5423 return CS->getElement() == DS;
5424 return false;
5425}
5426
5427//===----------------------------------------------------------------------===//
5428// Function Body / Expression rewriting
5429//===----------------------------------------------------------------------===//
5430
5431Stmt *RewriteModernObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
5432 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
5433 isa<DoStmt>(S) || isa<ForStmt>(S))
5434 Stmts.push_back(S);
5435 else if (isa<ObjCForCollectionStmt>(S)) {
5436 Stmts.push_back(S);
5437 ObjCBcLabelNo.push_back(++BcLabelCount);
5438 }
5439
5440 // Pseudo-object operations and ivar references need special
5441 // treatment because we're going to recursively rewrite them.
5442 if (PseudoObjectExpr *PseudoOp = dyn_cast<PseudoObjectExpr>(S)) {
5443 if (isa<BinaryOperator>(PseudoOp->getSyntacticForm())) {
5444 return RewritePropertyOrImplicitSetter(PseudoOp);
5445 } else {
5446 return RewritePropertyOrImplicitGetter(PseudoOp);
5447 }
5448 } else if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
5449 return RewriteObjCIvarRefExpr(IvarRefExpr);
5450 }
Fariborz Jahanian4254cdb2013-02-08 18:57:50 +00005451 else if (isa<OpaqueValueExpr>(S))
5452 S = cast<OpaqueValueExpr>(S)->getSourceExpr();
Fariborz Jahanian11671902012-02-07 17:11:38 +00005453
5454 SourceRange OrigStmtRange = S->getSourceRange();
5455
5456 // Perform a bottom up rewrite of all children.
Benjamin Kramer642f1732015-07-02 21:03:14 +00005457 for (Stmt *&childStmt : S->children())
5458 if (childStmt) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00005459 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(childStmt);
5460 if (newStmt) {
Benjamin Kramer642f1732015-07-02 21:03:14 +00005461 childStmt = newStmt;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005462 }
5463 }
5464
5465 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
John McCall113bee02012-03-10 09:33:50 +00005466 SmallVector<DeclRefExpr *, 8> InnerBlockDeclRefs;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005467 llvm::SmallPtrSet<const DeclContext *, 8> InnerContexts;
5468 InnerContexts.insert(BE->getBlockDecl());
5469 ImportedLocalExternalDecls.clear();
5470 GetInnerBlockDeclRefExprs(BE->getBody(),
5471 InnerBlockDeclRefs, InnerContexts);
5472 // Rewrite the block body in place.
5473 Stmt *SaveCurrentBody = CurrentBody;
5474 CurrentBody = BE->getBody();
Craig Topper8ae12032014-05-07 06:21:57 +00005475 PropParentMap = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005476 // block literal on rhs of a property-dot-sytax assignment
5477 // must be replaced by its synthesize ast so getRewrittenText
5478 // works as expected. In this case, what actually ends up on RHS
5479 // is the blockTranscribed which is the helper function for the
5480 // block literal; as in: self.c = ^() {[ace ARR];};
5481 bool saveDisableReplaceStmt = DisableReplaceStmt;
5482 DisableReplaceStmt = false;
5483 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
5484 DisableReplaceStmt = saveDisableReplaceStmt;
5485 CurrentBody = SaveCurrentBody;
Craig Topper8ae12032014-05-07 06:21:57 +00005486 PropParentMap = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005487 ImportedLocalExternalDecls.clear();
5488 // Now we snarf the rewritten text and stash it away for later use.
5489 std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
5490 RewrittenBlockExprs[BE] = Str;
5491
5492 Stmt *blockTranscribed = SynthBlockInitExpr(BE, InnerBlockDeclRefs);
Fangrui Song6907ce22018-07-30 19:24:48 +00005493
Fariborz Jahanian11671902012-02-07 17:11:38 +00005494 //blockTranscribed->dump();
5495 ReplaceStmt(S, blockTranscribed);
5496 return blockTranscribed;
5497 }
5498 // Handle specific things.
5499 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
5500 return RewriteAtEncode(AtEncode);
5501
5502 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
5503 return RewriteAtSelector(AtSelector);
5504
5505 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
5506 return RewriteObjCStringLiteral(AtString);
Fangrui Song6907ce22018-07-30 19:24:48 +00005507
Fariborz Jahanian307b7ad2012-03-27 20:17:30 +00005508 if (ObjCBoolLiteralExpr *BoolLitExpr = dyn_cast<ObjCBoolLiteralExpr>(S))
5509 return RewriteObjCBoolLiteralExpr(BoolLitExpr);
Fangrui Song6907ce22018-07-30 19:24:48 +00005510
Patrick Beard0caa3942012-04-19 00:25:12 +00005511 if (ObjCBoxedExpr *BoxedExpr = dyn_cast<ObjCBoxedExpr>(S))
5512 return RewriteObjCBoxedExpr(BoxedExpr);
Fangrui Song6907ce22018-07-30 19:24:48 +00005513
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00005514 if (ObjCArrayLiteral *ArrayLitExpr = dyn_cast<ObjCArrayLiteral>(S))
5515 return RewriteObjCArrayLiteralExpr(ArrayLitExpr);
Fangrui Song6907ce22018-07-30 19:24:48 +00005516
5517 if (ObjCDictionaryLiteral *DictionaryLitExpr =
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00005518 dyn_cast<ObjCDictionaryLiteral>(S))
5519 return RewriteObjCDictionaryLiteralExpr(DictionaryLitExpr);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005520
5521 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
5522#if 0
5523 // Before we rewrite it, put the original message expression in a comment.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005524 SourceLocation startLoc = MessExpr->getBeginLoc();
Stephen Kelly1c301dc2018-08-09 21:09:38 +00005525 SourceLocation endLoc = MessExpr->getEndLoc();
Fariborz Jahanian11671902012-02-07 17:11:38 +00005526
5527 const char *startBuf = SM->getCharacterData(startLoc);
5528 const char *endBuf = SM->getCharacterData(endLoc);
5529
5530 std::string messString;
5531 messString += "// ";
5532 messString.append(startBuf, endBuf-startBuf+1);
5533 messString += "\n";
5534
5535 // FIXME: Missing definition of
5536 // InsertText(clang::SourceLocation, char const*, unsigned int).
Craig Toppera2a8d9c2015-10-22 03:13:10 +00005537 // InsertText(startLoc, messString);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005538 // Tried this, but it didn't work either...
5539 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
5540#endif
5541 return RewriteMessageExpr(MessExpr);
5542 }
5543
Fangrui Song6907ce22018-07-30 19:24:48 +00005544 if (ObjCAutoreleasePoolStmt *StmtAutoRelease =
Fariborz Jahanian9b43c3f2012-05-23 23:47:20 +00005545 dyn_cast<ObjCAutoreleasePoolStmt>(S)) {
5546 return RewriteObjCAutoreleasePoolStmt(StmtAutoRelease);
5547 }
Fangrui Song6907ce22018-07-30 19:24:48 +00005548
Fariborz Jahanian11671902012-02-07 17:11:38 +00005549 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
5550 return RewriteObjCTryStmt(StmtTry);
5551
5552 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
5553 return RewriteObjCSynchronizedStmt(StmtTry);
5554
5555 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
5556 return RewriteObjCThrowStmt(StmtThrow);
5557
5558 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
5559 return RewriteObjCProtocolExpr(ProtocolExp);
5560
5561 if (ObjCForCollectionStmt *StmtForCollection =
5562 dyn_cast<ObjCForCollectionStmt>(S))
5563 return RewriteObjCForCollectionStmt(StmtForCollection,
5564 OrigStmtRange.getEnd());
5565 if (BreakStmt *StmtBreakStmt =
5566 dyn_cast<BreakStmt>(S))
5567 return RewriteBreakStmt(StmtBreakStmt);
5568 if (ContinueStmt *StmtContinueStmt =
5569 dyn_cast<ContinueStmt>(S))
5570 return RewriteContinueStmt(StmtContinueStmt);
5571
5572 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
5573 // and cast exprs.
5574 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
5575 // FIXME: What we're doing here is modifying the type-specifier that
5576 // precedes the first Decl. In the future the DeclGroup should have
5577 // a separate type-specifier that we can rewrite.
5578 // NOTE: We need to avoid rewriting the DeclStmt if it is within
5579 // the context of an ObjCForCollectionStmt. For example:
5580 // NSArray *someArray;
5581 // for (id <FooProtocol> index in someArray) ;
Fangrui Song6907ce22018-07-30 19:24:48 +00005582 // This is because RewriteObjCForCollectionStmt() does textual rewriting
Fariborz Jahanian11671902012-02-07 17:11:38 +00005583 // and it depends on the original text locations/positions.
5584 if (Stmts.empty() || !IsDeclStmtInForeachHeader(DS))
5585 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
5586
5587 // Blocks rewrite rules.
5588 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
5589 DI != DE; ++DI) {
5590 Decl *SD = *DI;
5591 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
5592 if (isTopLevelBlockPointerType(ND->getType()))
5593 RewriteBlockPointerDecl(ND);
5594 else if (ND->getType()->isFunctionPointerType())
5595 CheckFunctionPointerDecl(ND->getType(), ND);
5596 if (VarDecl *VD = dyn_cast<VarDecl>(SD)) {
5597 if (VD->hasAttr<BlocksAttr>()) {
5598 static unsigned uniqueByrefDeclCount = 0;
5599 assert(!BlockByRefDeclNo.count(ND) &&
5600 "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl");
5601 BlockByRefDeclNo[ND] = uniqueByrefDeclCount++;
Fariborz Jahanian847713a2012-04-24 19:38:45 +00005602 RewriteByRefVar(VD, (DI == DS->decl_begin()), ((DI+1) == DE));
Fariborz Jahanian11671902012-02-07 17:11:38 +00005603 }
Fangrui Song6907ce22018-07-30 19:24:48 +00005604 else
Fariborz Jahanian11671902012-02-07 17:11:38 +00005605 RewriteTypeOfDecl(VD);
5606 }
5607 }
5608 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(SD)) {
5609 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
5610 RewriteBlockPointerDecl(TD);
5611 else if (TD->getUnderlyingType()->isFunctionPointerType())
5612 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5613 }
5614 }
5615 }
5616
5617 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
5618 RewriteObjCQualifiedInterfaceTypes(CE);
5619
5620 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
5621 isa<DoStmt>(S) || isa<ForStmt>(S)) {
5622 assert(!Stmts.empty() && "Statement stack is empty");
5623 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
5624 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
5625 && "Statement stack mismatch");
5626 Stmts.pop_back();
5627 }
5628 // Handle blocks rewriting.
Fariborz Jahanian11671902012-02-07 17:11:38 +00005629 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
Fangrui Song6907ce22018-07-30 19:24:48 +00005630 ValueDecl *VD = DRE->getDecl();
Fariborz Jahanian11671902012-02-07 17:11:38 +00005631 if (VD->hasAttr<BlocksAttr>())
5632 return RewriteBlockDeclRefExpr(DRE);
5633 if (HasLocalVariableExternalStorage(VD))
5634 return RewriteLocalVariableExternalStorage(DRE);
5635 }
Fangrui Song6907ce22018-07-30 19:24:48 +00005636
Fariborz Jahanian11671902012-02-07 17:11:38 +00005637 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
5638 if (CE->getCallee()->getType()->isBlockPointerType()) {
5639 Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
5640 ReplaceStmt(S, BlockCall);
5641 return BlockCall;
5642 }
5643 }
5644 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
5645 RewriteCastExpr(CE);
5646 }
Fariborz Jahanian2c00acd2012-04-10 00:08:18 +00005647 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
5648 RewriteImplicitCastObjCExpr(ICE);
5649 }
Fariborz Jahaniancc172282012-04-16 22:14:01 +00005650#if 0
Fariborz Jahanian3a5d5522012-04-13 18:00:54 +00005651
Fariborz Jahanian11671902012-02-07 17:11:38 +00005652 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
5653 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(),
5654 ICE->getSubExpr(),
5655 SourceLocation());
5656 // Get the new text.
5657 std::string SStr;
5658 llvm::raw_string_ostream Buf(SStr);
Richard Smith235341b2012-08-16 03:56:14 +00005659 Replacement->printPretty(Buf);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005660 const std::string &Str = Buf.str();
5661
5662 printf("CAST = %s\n", &Str[0]);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005663 InsertText(ICE->getSubExpr()->getBeginLoc(), Str);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005664 delete S;
5665 return Replacement;
5666 }
5667#endif
5668 // Return this stmt unmodified.
5669 return S;
5670}
5671
5672void RewriteModernObjC::RewriteRecordBody(RecordDecl *RD) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005673 for (auto *FD : RD->fields()) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00005674 if (isTopLevelBlockPointerType(FD->getType()))
5675 RewriteBlockPointerDecl(FD);
5676 if (FD->getType()->isObjCQualifiedIdType() ||
5677 FD->getType()->isObjCQualifiedInterfaceType())
5678 RewriteObjCQualifiedInterfaceTypes(FD);
5679 }
5680}
5681
5682/// HandleDeclInMainFile - This is called for each top-level decl defined in the
5683/// main file of the input.
5684void RewriteModernObjC::HandleDeclInMainFile(Decl *D) {
5685 switch (D->getKind()) {
5686 case Decl::Function: {
5687 FunctionDecl *FD = cast<FunctionDecl>(D);
5688 if (FD->isOverloadedOperator())
5689 return;
5690
5691 // Since function prototypes don't have ParmDecl's, we check the function
5692 // prototype. This enables us to rewrite function declarations and
5693 // definitions using the same code.
5694 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
5695
Argyrios Kyrtzidis75627ad2012-02-12 04:48:45 +00005696 if (!FD->isThisDeclarationADefinition())
5697 break;
5698
Fariborz Jahanian11671902012-02-07 17:11:38 +00005699 // FIXME: If this should support Obj-C++, support CXXTryStmt
5700 if (CompoundStmt *Body = dyn_cast_or_null<CompoundStmt>(FD->getBody())) {
5701 CurFunctionDef = FD;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005702 CurrentBody = Body;
5703 Body =
5704 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5705 FD->setBody(Body);
Craig Topper8ae12032014-05-07 06:21:57 +00005706 CurrentBody = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005707 if (PropParentMap) {
5708 delete PropParentMap;
Craig Topper8ae12032014-05-07 06:21:57 +00005709 PropParentMap = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005710 }
5711 // This synthesizes and inserts the block "impl" struct, invoke function,
5712 // and any copy/dispose helper functions.
5713 InsertBlockLiteralsWithinFunction(FD);
Fariborz Jahanianaa4a2422012-11-06 17:30:23 +00005714 RewriteLineDirective(D);
Craig Topper8ae12032014-05-07 06:21:57 +00005715 CurFunctionDef = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005716 }
5717 break;
5718 }
5719 case Decl::ObjCMethod: {
5720 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(D);
5721 if (CompoundStmt *Body = MD->getCompoundBody()) {
5722 CurMethodDef = MD;
5723 CurrentBody = Body;
5724 Body =
5725 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5726 MD->setBody(Body);
Craig Topper8ae12032014-05-07 06:21:57 +00005727 CurrentBody = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005728 if (PropParentMap) {
5729 delete PropParentMap;
Craig Topper8ae12032014-05-07 06:21:57 +00005730 PropParentMap = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005731 }
5732 InsertBlockLiteralsWithinMethod(MD);
Fariborz Jahanianaa4a2422012-11-06 17:30:23 +00005733 RewriteLineDirective(D);
Craig Topper8ae12032014-05-07 06:21:57 +00005734 CurMethodDef = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005735 }
5736 break;
5737 }
5738 case Decl::ObjCImplementation: {
5739 ObjCImplementationDecl *CI = cast<ObjCImplementationDecl>(D);
5740 ClassImplementation.push_back(CI);
5741 break;
5742 }
5743 case Decl::ObjCCategoryImpl: {
5744 ObjCCategoryImplDecl *CI = cast<ObjCCategoryImplDecl>(D);
5745 CategoryImplementation.push_back(CI);
5746 break;
5747 }
5748 case Decl::Var: {
5749 VarDecl *VD = cast<VarDecl>(D);
5750 RewriteObjCQualifiedInterfaceTypes(VD);
5751 if (isTopLevelBlockPointerType(VD->getType()))
5752 RewriteBlockPointerDecl(VD);
5753 else if (VD->getType()->isFunctionPointerType()) {
5754 CheckFunctionPointerDecl(VD->getType(), VD);
5755 if (VD->getInit()) {
5756 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
5757 RewriteCastExpr(CE);
5758 }
5759 }
5760 } else if (VD->getType()->isRecordType()) {
5761 RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
5762 if (RD->isCompleteDefinition())
5763 RewriteRecordBody(RD);
5764 }
5765 if (VD->getInit()) {
5766 GlobalVarDecl = VD;
5767 CurrentBody = VD->getInit();
5768 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
Craig Topper8ae12032014-05-07 06:21:57 +00005769 CurrentBody = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005770 if (PropParentMap) {
5771 delete PropParentMap;
Craig Topper8ae12032014-05-07 06:21:57 +00005772 PropParentMap = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005773 }
5774 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(), VD->getName());
Craig Topper8ae12032014-05-07 06:21:57 +00005775 GlobalVarDecl = nullptr;
5776
Fariborz Jahanian11671902012-02-07 17:11:38 +00005777 // This is needed for blocks.
5778 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
5779 RewriteCastExpr(CE);
5780 }
5781 }
5782 break;
5783 }
5784 case Decl::TypeAlias:
5785 case Decl::Typedef: {
5786 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
5787 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
5788 RewriteBlockPointerDecl(TD);
5789 else if (TD->getUnderlyingType()->isFunctionPointerType())
5790 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
Fariborz Jahanian3a65ce32013-04-03 19:11:21 +00005791 else
5792 RewriteObjCQualifiedInterfaceTypes(TD);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005793 }
5794 break;
5795 }
5796 case Decl::CXXRecord:
5797 case Decl::Record: {
5798 RecordDecl *RD = cast<RecordDecl>(D);
Fangrui Song6907ce22018-07-30 19:24:48 +00005799 if (RD->isCompleteDefinition())
Fariborz Jahanian11671902012-02-07 17:11:38 +00005800 RewriteRecordBody(RD);
5801 break;
5802 }
5803 default:
5804 break;
5805 }
5806 // Nothing yet.
5807}
5808
Fariborz Jahanianb31e3af2012-03-15 17:05:33 +00005809/// Write_ProtocolExprReferencedMetadata - This routine writer out the
5810/// protocol reference symbols in the for of:
5811/// struct _protocol_t *PROTOCOL_REF = &PROTOCOL_METADATA.
Fangrui Song6907ce22018-07-30 19:24:48 +00005812static void Write_ProtocolExprReferencedMetadata(ASTContext *Context,
Fariborz Jahanianb31e3af2012-03-15 17:05:33 +00005813 ObjCProtocolDecl *PDecl,
5814 std::string &Result) {
5815 // Also output .objc_protorefs$B section and its meta-data.
5816 if (Context->getLangOpts().MicrosoftExt)
Fariborz Jahanian75f2e3c2012-04-27 21:39:49 +00005817 Result += "static ";
Fariborz Jahanianb31e3af2012-03-15 17:05:33 +00005818 Result += "struct _protocol_t *";
5819 Result += "_OBJC_PROTOCOL_REFERENCE_$_";
5820 Result += PDecl->getNameAsString();
5821 Result += " = &";
5822 Result += "_OBJC_PROTOCOL_"; Result += PDecl->getNameAsString();
5823 Result += ";\n";
5824}
5825
Fariborz Jahanian11671902012-02-07 17:11:38 +00005826void RewriteModernObjC::HandleTranslationUnit(ASTContext &C) {
5827 if (Diags.hasErrorOccurred())
5828 return;
5829
5830 RewriteInclude();
5831
Fariborz Jahaniane4996132013-02-07 22:50:40 +00005832 for (unsigned i = 0, e = FunctionDefinitionsSeen.size(); i < e; i++) {
Alp Tokerf6a24ce2013-12-05 16:25:25 +00005833 // translation of function bodies were postponed until all class and
Fariborz Jahaniane4996132013-02-07 22:50:40 +00005834 // their extensions and implementations are seen. This is because, we
Alp Tokerf6a24ce2013-12-05 16:25:25 +00005835 // cannot build grouping structs for bitfields until they are all seen.
Fariborz Jahaniane4996132013-02-07 22:50:40 +00005836 FunctionDecl *FDecl = FunctionDefinitionsSeen[i];
5837 HandleTopLevelSingleDecl(FDecl);
5838 }
5839
Fariborz Jahanian11671902012-02-07 17:11:38 +00005840 // Here's a great place to add any extra declarations that may be needed.
5841 // Write out meta data for each @protocol(<expr>).
Craig Topperc6914d02014-08-25 04:15:02 +00005842 for (ObjCProtocolDecl *ProtDecl : ProtocolExprDecls) {
5843 RewriteObjCProtocolMetaData(ProtDecl, Preamble);
5844 Write_ProtocolExprReferencedMetadata(Context, ProtDecl, Preamble);
Fariborz Jahanianb31e3af2012-03-15 17:05:33 +00005845 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00005846
5847 InsertText(SM->getLocForStartOfFile(MainFileID), Preamble, false);
Fangrui Song6907ce22018-07-30 19:24:48 +00005848
Fariborz Jahanian89919cc2012-05-08 23:54:35 +00005849 if (ClassImplementation.size() || CategoryImplementation.size())
5850 RewriteImplementations();
Fangrui Song6907ce22018-07-30 19:24:48 +00005851
Fariborz Jahanian8e1118cbd2012-02-21 23:58:41 +00005852 for (unsigned i = 0, e = ObjCInterfacesSeen.size(); i < e; i++) {
5853 ObjCInterfaceDecl *CDecl = ObjCInterfacesSeen[i];
5854 // Write struct declaration for the class matching its ivar declarations.
5855 // Note that for modern abi, this is postponed until the end of TU
5856 // because class extensions and the implementation might declare their own
5857 // private ivars.
5858 RewriteInterfaceDecl(CDecl);
5859 }
Fangrui Song6907ce22018-07-30 19:24:48 +00005860
Fariborz Jahanian11671902012-02-07 17:11:38 +00005861 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
5862 // we are done.
5863 if (const RewriteBuffer *RewriteBuf =
5864 Rewrite.getRewriteBufferFor(MainFileID)) {
5865 //printf("Changed:\n");
5866 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
5867 } else {
5868 llvm::errs() << "No changes\n";
5869 }
5870
5871 if (ClassImplementation.size() || CategoryImplementation.size() ||
5872 ProtocolExprDecls.size()) {
5873 // Rewrite Objective-c meta data*
5874 std::string ResultStr;
5875 RewriteMetaDataIntoBuffer(ResultStr);
5876 // Emit metadata.
5877 *OutFile << ResultStr;
5878 }
Fariborz Jahanianddddca32012-03-14 21:44:09 +00005879 // Emit ImageInfo;
5880 {
5881 std::string ResultStr;
5882 WriteImageInfo(ResultStr);
5883 *OutFile << ResultStr;
5884 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00005885 OutFile->flush();
5886}
5887
5888void RewriteModernObjC::Initialize(ASTContext &context) {
5889 InitializeCommon(context);
Fangrui Song6907ce22018-07-30 19:24:48 +00005890
Fariborz Jahanianb52221e2012-03-10 17:45:38 +00005891 Preamble += "#ifndef __OBJC2__\n";
5892 Preamble += "#define __OBJC2__\n";
5893 Preamble += "#endif\n";
5894
Fariborz Jahanian11671902012-02-07 17:11:38 +00005895 // declaring objc_selector outside the parameter list removes a silly
5896 // scope related warning...
5897 if (IsHeader)
5898 Preamble = "#pragma once\n";
5899 Preamble += "struct objc_selector; struct objc_class;\n";
Fariborz Jahanian27db0b32012-04-12 23:52:52 +00005900 Preamble += "struct __rw_objc_super { \n\tstruct objc_object *object; ";
5901 Preamble += "\n\tstruct objc_object *superClass; ";
5902 // Add a constructor for creating temporary objects.
5903 Preamble += "\n\t__rw_objc_super(struct objc_object *o, struct objc_object *s) ";
5904 Preamble += ": object(o), superClass(s) {} ";
5905 Preamble += "\n};\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00005906
Fariborz Jahanian11671902012-02-07 17:11:38 +00005907 if (LangOpts.MicrosoftExt) {
Fariborz Jahanian008dfe22012-03-11 19:41:56 +00005908 // Define all sections using syntax that makes sense.
Fariborz Jahanianddddca32012-03-14 21:44:09 +00005909 // These are currently generated.
5910 Preamble += "\n#pragma section(\".objc_classlist$B\", long, read, write)\n";
Fariborz Jahanian008dfe22012-03-11 19:41:56 +00005911 Preamble += "#pragma section(\".objc_catlist$B\", long, read, write)\n";
Fariborz Jahanianddddca32012-03-14 21:44:09 +00005912 Preamble += "#pragma section(\".objc_imageinfo$B\", long, read, write)\n";
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00005913 Preamble += "#pragma section(\".objc_nlclslist$B\", long, read, write)\n";
5914 Preamble += "#pragma section(\".objc_nlcatlist$B\", long, read, write)\n";
Fariborz Jahanianddddca32012-03-14 21:44:09 +00005915 // These are generated but not necessary for functionality.
Fariborz Jahanianddddca32012-03-14 21:44:09 +00005916 Preamble += "#pragma section(\".cat_cls_meth$B\", long, read, write)\n";
Fariborz Jahanian008dfe22012-03-11 19:41:56 +00005917 Preamble += "#pragma section(\".inst_meth$B\", long, read, write)\n";
5918 Preamble += "#pragma section(\".cls_meth$B\", long, read, write)\n";
Fariborz Jahaniane47bf2b2012-03-12 16:46:58 +00005919 Preamble += "#pragma section(\".objc_ivar$B\", long, read, write)\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00005920
Fariborz Jahanianb31e3af2012-03-15 17:05:33 +00005921 // These need be generated for performance. Currently they are not,
5922 // using API calls instead.
5923 Preamble += "#pragma section(\".objc_selrefs$B\", long, read, write)\n";
5924 Preamble += "#pragma section(\".objc_classrefs$B\", long, read, write)\n";
5925 Preamble += "#pragma section(\".objc_superrefs$B\", long, read, write)\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00005926
Fariborz Jahanian11671902012-02-07 17:11:38 +00005927 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00005928 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
5929 Preamble += "typedef struct objc_object Protocol;\n";
5930 Preamble += "#define _REWRITER_typedef_Protocol\n";
5931 Preamble += "#endif\n";
5932 if (LangOpts.MicrosoftExt) {
5933 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
5934 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00005935 }
Fariborz Jahanian167384d2012-03-21 23:41:04 +00005936 else
Fariborz Jahanian11671902012-02-07 17:11:38 +00005937 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00005938
Fariborz Jahanian167384d2012-03-21 23:41:04 +00005939 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend(void);\n";
5940 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSendSuper(void);\n";
5941 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend_stret(void);\n";
5942 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSendSuper_stret(void);\n";
5943 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend_fpret(void);\n";
5944
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00005945 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *objc_getClass";
Fariborz Jahanian11671902012-02-07 17:11:38 +00005946 Preamble += "(const char *);\n";
5947 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *class_getSuperclass";
5948 Preamble += "(struct objc_class *);\n";
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00005949 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *objc_getMetaClass";
Fariborz Jahanian11671902012-02-07 17:11:38 +00005950 Preamble += "(const char *);\n";
Fariborz Jahanian34660592012-03-19 18:11:32 +00005951 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw( struct objc_object *);\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00005952 // @synchronized hooks.
Aaron Ballman9c004462012-09-06 16:44:16 +00005953 Preamble += "__OBJC_RW_DLLIMPORT int objc_sync_enter( struct objc_object *);\n";
5954 Preamble += "__OBJC_RW_DLLIMPORT int objc_sync_exit( struct objc_object *);\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00005955 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00005956 Preamble += "#ifdef _WIN64\n";
5957 Preamble += "typedef unsigned long long _WIN_NSUInteger;\n";
5958 Preamble += "#else\n";
5959 Preamble += "typedef unsigned int _WIN_NSUInteger;\n";
5960 Preamble += "#endif\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00005961 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
5962 Preamble += "struct __objcFastEnumerationState {\n\t";
5963 Preamble += "unsigned long state;\n\t";
5964 Preamble += "void **itemsPtr;\n\t";
5965 Preamble += "unsigned long *mutationsPtr;\n\t";
5966 Preamble += "unsigned long extra[5];\n};\n";
5967 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
5968 Preamble += "#define __FASTENUMERATIONSTATE\n";
5969 Preamble += "#endif\n";
5970 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
5971 Preamble += "struct __NSConstantStringImpl {\n";
5972 Preamble += " int *isa;\n";
5973 Preamble += " int flags;\n";
5974 Preamble += " char *str;\n";
Fariborz Jahaniandb3a5dc2014-04-16 17:03:06 +00005975 Preamble += "#if _WIN64\n";
Fariborz Jahanian287e79a2014-04-01 19:32:35 +00005976 Preamble += " long long length;\n";
5977 Preamble += "#else\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00005978 Preamble += " long length;\n";
Fariborz Jahanian287e79a2014-04-01 19:32:35 +00005979 Preamble += "#endif\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00005980 Preamble += "};\n";
5981 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
5982 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
5983 Preamble += "#else\n";
5984 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
5985 Preamble += "#endif\n";
5986 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
5987 Preamble += "#endif\n";
5988 // Blocks preamble.
5989 Preamble += "#ifndef BLOCK_IMPL\n";
5990 Preamble += "#define BLOCK_IMPL\n";
5991 Preamble += "struct __block_impl {\n";
5992 Preamble += " void *isa;\n";
5993 Preamble += " int Flags;\n";
5994 Preamble += " int Reserved;\n";
5995 Preamble += " void *FuncPtr;\n";
5996 Preamble += "};\n";
5997 Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
5998 Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n";
5999 Preamble += "extern \"C\" __declspec(dllexport) "
6000 "void _Block_object_assign(void *, const void *, const int);\n";
6001 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
6002 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
6003 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
6004 Preamble += "#else\n";
6005 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n";
6006 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n";
6007 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
6008 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
6009 Preamble += "#endif\n";
6010 Preamble += "#endif\n";
6011 if (LangOpts.MicrosoftExt) {
6012 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
6013 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
6014 Preamble += "#ifndef KEEP_ATTRIBUTES\n"; // We use this for clang tests.
6015 Preamble += "#define __attribute__(X)\n";
6016 Preamble += "#endif\n";
Fariborz Jahaniane1240fe2012-04-12 16:33:31 +00006017 Preamble += "#ifndef __weak\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006018 Preamble += "#define __weak\n";
Fariborz Jahaniane1240fe2012-04-12 16:33:31 +00006019 Preamble += "#endif\n";
6020 Preamble += "#ifndef __block\n";
6021 Preamble += "#define __block\n";
6022 Preamble += "#endif\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006023 }
6024 else {
6025 Preamble += "#define __block\n";
6026 Preamble += "#define __weak\n";
6027 }
Fangrui Song6907ce22018-07-30 19:24:48 +00006028
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00006029 // Declarations required for modern objective-c array and dictionary literals.
6030 Preamble += "\n#include <stdarg.h>\n";
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00006031 Preamble += "struct __NSContainer_literal {\n";
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00006032 Preamble += " void * *arr;\n";
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00006033 Preamble += " __NSContainer_literal (unsigned int count, ...) {\n";
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00006034 Preamble += "\tva_list marker;\n";
6035 Preamble += "\tva_start(marker, count);\n";
6036 Preamble += "\tarr = new void *[count];\n";
6037 Preamble += "\tfor (unsigned i = 0; i < count; i++)\n";
6038 Preamble += "\t arr[i] = va_arg(marker, void *);\n";
6039 Preamble += "\tva_end( marker );\n";
6040 Preamble += " };\n";
Fariborz Jahanian70ef9292012-05-02 23:53:46 +00006041 Preamble += " ~__NSContainer_literal() {\n";
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00006042 Preamble += "\tdelete[] arr;\n";
6043 Preamble += " }\n";
6044 Preamble += "};\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00006045
Fariborz Jahanian9b43c3f2012-05-23 23:47:20 +00006046 // Declaration required for implementation of @autoreleasepool statement.
6047 Preamble += "extern \"C\" __declspec(dllimport) void * objc_autoreleasePoolPush(void);\n";
6048 Preamble += "extern \"C\" __declspec(dllimport) void objc_autoreleasePoolPop(void *);\n\n";
6049 Preamble += "struct __AtAutoreleasePool {\n";
6050 Preamble += " __AtAutoreleasePool() {atautoreleasepoolobj = objc_autoreleasePoolPush();}\n";
6051 Preamble += " ~__AtAutoreleasePool() {objc_autoreleasePoolPop(atautoreleasepoolobj);}\n";
6052 Preamble += " void * atautoreleasepoolobj;\n";
6053 Preamble += "};\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00006054
Fariborz Jahanian11671902012-02-07 17:11:38 +00006055 // NOTE! Windows uses LLP64 for 64bit mode. So, cast pointer to long long
6056 // as this avoids warning in any 64bit/32bit compilation model.
6057 Preamble += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long long) &((TYPE *)0)->MEMBER)\n";
6058}
6059
Hiroshi Inouec5e54dd2017-07-03 08:49:44 +00006060/// RewriteIvarOffsetComputation - This routine synthesizes computation of
Fariborz Jahanian11671902012-02-07 17:11:38 +00006061/// ivar offset.
6062void RewriteModernObjC::RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
6063 std::string &Result) {
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006064 Result += "__OFFSETOFIVAR__(struct ";
6065 Result += ivar->getContainingInterface()->getNameAsString();
6066 if (LangOpts.MicrosoftExt)
6067 Result += "_IMPL";
6068 Result += ", ";
6069 if (ivar->isBitField())
6070 ObjCIvarBitfieldGroupDecl(ivar, Result);
6071 else
Fariborz Jahanian11671902012-02-07 17:11:38 +00006072 Result += ivar->getNameAsString();
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006073 Result += ")";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006074}
6075
6076/// WriteModernMetadataDeclarations - Writes out metadata declarations for modern ABI.
6077/// struct _prop_t {
Fariborz Jahanian67f7c552012-02-07 23:31:52 +00006078/// const char *name;
Fariborz Jahanian11671902012-02-07 17:11:38 +00006079/// char *attributes;
6080/// }
6081
6082/// struct _prop_list_t {
6083/// uint32_t entsize; // sizeof(struct _prop_t)
6084/// uint32_t count_of_properties;
6085/// struct _prop_t prop_list[count_of_properties];
6086/// }
6087
6088/// struct _protocol_t;
6089
6090/// struct _protocol_list_t {
6091/// long protocol_count; // Note, this is 32/64 bit
6092/// struct _protocol_t * protocol_list[protocol_count];
6093/// }
6094
6095/// struct _objc_method {
6096/// SEL _cmd;
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006097/// const char *method_type;
Fariborz Jahanian11671902012-02-07 17:11:38 +00006098/// char *_imp;
6099/// }
6100
6101/// struct _method_list_t {
6102/// uint32_t entsize; // sizeof(struct _objc_method)
6103/// uint32_t method_count;
6104/// struct _objc_method method_list[method_count];
6105/// }
6106
6107/// struct _protocol_t {
6108/// id isa; // NULL
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006109/// const char *protocol_name;
Fariborz Jahanian11671902012-02-07 17:11:38 +00006110/// const struct _protocol_list_t * protocol_list; // super protocols
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006111/// const struct method_list_t *instance_methods;
6112/// const struct method_list_t *class_methods;
Fariborz Jahanian11671902012-02-07 17:11:38 +00006113/// const struct method_list_t *optionalInstanceMethods;
6114/// const struct method_list_t *optionalClassMethods;
6115/// const struct _prop_list_t * properties;
6116/// const uint32_t size; // sizeof(struct _protocol_t)
6117/// const uint32_t flags; // = 0
6118/// const char ** extendedMethodTypes;
6119/// }
6120
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006121/// struct _ivar_t {
6122/// unsigned long int *offset; // pointer to ivar offset location
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006123/// const char *name;
6124/// const char *type;
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006125/// uint32_t alignment;
6126/// uint32_t size;
6127/// }
6128
6129/// struct _ivar_list_t {
6130/// uint32 entsize; // sizeof(struct _ivar_t)
6131/// uint32 count;
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006132/// struct _ivar_t list[count];
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006133/// }
6134
6135/// struct _class_ro_t {
Fariborz Jahanian34134812012-03-24 16:53:16 +00006136/// uint32_t flags;
6137/// uint32_t instanceStart;
6138/// uint32_t instanceSize;
6139/// uint32_t reserved; // only when building for 64bit targets
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006140/// const uint8_t *ivarLayout;
6141/// const char *name;
6142/// const struct _method_list_t *baseMethods;
6143/// const struct _protocol_list_t *baseProtocols;
6144/// const struct _ivar_list_t *ivars;
6145/// const uint8_t *weakIvarLayout;
6146/// const struct _prop_list_t *properties;
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006147/// }
6148
6149/// struct _class_t {
6150/// struct _class_t *isa;
Fariborz Jahanian6e60c132012-03-20 17:34:50 +00006151/// struct _class_t *superclass;
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006152/// void *cache;
6153/// IMP *vtable;
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006154/// struct _class_ro_t *ro;
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006155/// }
6156
6157/// struct _category_t {
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006158/// const char *name;
Fariborz Jahaniancd79a492012-03-20 21:41:28 +00006159/// struct _class_t *cls;
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006160/// const struct _method_list_t *instance_methods;
6161/// const struct _method_list_t *class_methods;
6162/// const struct _protocol_list_t *protocols;
6163/// const struct _prop_list_t *properties;
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006164/// }
6165
6166/// MessageRefTy - LLVM for:
6167/// struct _message_ref_t {
6168/// IMP messenger;
6169/// SEL name;
6170/// };
6171
6172/// SuperMessageRefTy - LLVM for:
6173/// struct _super_message_ref_t {
6174/// SUPER_IMP messenger;
6175/// SEL name;
6176/// };
6177
Fariborz Jahanian45489622012-03-14 18:09:23 +00006178static void WriteModernMetadataDeclarations(ASTContext *Context, std::string &Result) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00006179 static bool meta_data_declared = false;
6180 if (meta_data_declared)
6181 return;
Fangrui Song6907ce22018-07-30 19:24:48 +00006182
Fariborz Jahanian11671902012-02-07 17:11:38 +00006183 Result += "\nstruct _prop_t {\n";
Fariborz Jahanian67f7c552012-02-07 23:31:52 +00006184 Result += "\tconst char *name;\n";
6185 Result += "\tconst char *attributes;\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006186 Result += "};\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00006187
Fariborz Jahanian11671902012-02-07 17:11:38 +00006188 Result += "\nstruct _protocol_t;\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00006189
Fariborz Jahanian11671902012-02-07 17:11:38 +00006190 Result += "\nstruct _objc_method {\n";
6191 Result += "\tstruct objc_selector * _cmd;\n";
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006192 Result += "\tconst char *method_type;\n";
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006193 Result += "\tvoid *_imp;\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006194 Result += "};\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00006195
Fariborz Jahanian11671902012-02-07 17:11:38 +00006196 Result += "\nstruct _protocol_t {\n";
6197 Result += "\tvoid * isa; // NULL\n";
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006198 Result += "\tconst char *protocol_name;\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006199 Result += "\tconst struct _protocol_list_t * protocol_list; // super protocols\n";
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006200 Result += "\tconst struct method_list_t *instance_methods;\n";
6201 Result += "\tconst struct method_list_t *class_methods;\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006202 Result += "\tconst struct method_list_t *optionalInstanceMethods;\n";
6203 Result += "\tconst struct method_list_t *optionalClassMethods;\n";
6204 Result += "\tconst struct _prop_list_t * properties;\n";
6205 Result += "\tconst unsigned int size; // sizeof(struct _protocol_t)\n";
6206 Result += "\tconst unsigned int flags; // = 0\n";
6207 Result += "\tconst char ** extendedMethodTypes;\n";
6208 Result += "};\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00006209
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006210 Result += "\nstruct _ivar_t {\n";
6211 Result += "\tunsigned long int *offset; // pointer to ivar offset location\n";
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006212 Result += "\tconst char *name;\n";
6213 Result += "\tconst char *type;\n";
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006214 Result += "\tunsigned int alignment;\n";
6215 Result += "\tunsigned int size;\n";
6216 Result += "};\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00006217
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006218 Result += "\nstruct _class_ro_t {\n";
Fariborz Jahanian34134812012-03-24 16:53:16 +00006219 Result += "\tunsigned int flags;\n";
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006220 Result += "\tunsigned int instanceStart;\n";
Fariborz Jahanian34134812012-03-24 16:53:16 +00006221 Result += "\tunsigned int instanceSize;\n";
Fariborz Jahanian45489622012-03-14 18:09:23 +00006222 const llvm::Triple &Triple(Context->getTargetInfo().getTriple());
6223 if (Triple.getArch() == llvm::Triple::x86_64)
Fariborz Jahanian34134812012-03-24 16:53:16 +00006224 Result += "\tunsigned int reserved;\n";
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006225 Result += "\tconst unsigned char *ivarLayout;\n";
6226 Result += "\tconst char *name;\n";
6227 Result += "\tconst struct _method_list_t *baseMethods;\n";
6228 Result += "\tconst struct _objc_protocol_list *baseProtocols;\n";
6229 Result += "\tconst struct _ivar_list_t *ivars;\n";
6230 Result += "\tconst unsigned char *weakIvarLayout;\n";
6231 Result += "\tconst struct _prop_list_t *properties;\n";
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006232 Result += "};\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00006233
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006234 Result += "\nstruct _class_t {\n";
6235 Result += "\tstruct _class_t *isa;\n";
Fariborz Jahanian6e60c132012-03-20 17:34:50 +00006236 Result += "\tstruct _class_t *superclass;\n";
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006237 Result += "\tvoid *cache;\n";
6238 Result += "\tvoid *vtable;\n";
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006239 Result += "\tstruct _class_ro_t *ro;\n";
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006240 Result += "};\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00006241
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006242 Result += "\nstruct _category_t {\n";
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006243 Result += "\tconst char *name;\n";
Fariborz Jahaniancd79a492012-03-20 21:41:28 +00006244 Result += "\tstruct _class_t *cls;\n";
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006245 Result += "\tconst struct _method_list_t *instance_methods;\n";
6246 Result += "\tconst struct _method_list_t *class_methods;\n";
6247 Result += "\tconst struct _protocol_list_t *protocols;\n";
6248 Result += "\tconst struct _prop_list_t *properties;\n";
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006249 Result += "};\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00006250
Fariborz Jahanian38c59102012-03-27 16:21:30 +00006251 Result += "extern \"C\" __declspec(dllimport) struct objc_cache _objc_empty_cache;\n";
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00006252 Result += "#pragma warning(disable:4273)\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006253 meta_data_declared = true;
6254}
6255
Fariborz Jahaniane18961b2012-02-08 19:53:58 +00006256static void Write_protocol_list_t_TypeDecl(std::string &Result,
6257 long super_protocol_count) {
6258 Result += "struct /*_protocol_list_t*/"; Result += " {\n";
6259 Result += "\tlong protocol_count; // Note, this is 32/64 bit\n";
6260 Result += "\tstruct _protocol_t *super_protocols[";
6261 Result += utostr(super_protocol_count); Result += "];\n";
6262 Result += "}";
6263}
6264
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006265static void Write_method_list_t_TypeDecl(std::string &Result,
6266 unsigned int method_count) {
6267 Result += "struct /*_method_list_t*/"; Result += " {\n";
6268 Result += "\tunsigned int entsize; // sizeof(struct _objc_method)\n";
6269 Result += "\tunsigned int method_count;\n";
6270 Result += "\tstruct _objc_method method_list[";
6271 Result += utostr(method_count); Result += "];\n";
6272 Result += "}";
6273}
6274
Fariborz Jahanian67f7c552012-02-07 23:31:52 +00006275static void Write__prop_list_t_TypeDecl(std::string &Result,
6276 unsigned int property_count) {
6277 Result += "struct /*_prop_list_t*/"; Result += " {\n";
6278 Result += "\tunsigned int entsize; // sizeof(struct _prop_t)\n";
6279 Result += "\tunsigned int count_of_properties;\n";
6280 Result += "\tstruct _prop_t prop_list[";
6281 Result += utostr(property_count); Result += "];\n";
6282 Result += "}";
6283}
6284
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006285static void Write__ivar_list_t_TypeDecl(std::string &Result,
6286 unsigned int ivar_count) {
6287 Result += "struct /*_ivar_list_t*/"; Result += " {\n";
6288 Result += "\tunsigned int entsize; // sizeof(struct _prop_t)\n";
6289 Result += "\tunsigned int count;\n";
6290 Result += "\tstruct _ivar_t ivar_list[";
6291 Result += utostr(ivar_count); Result += "];\n";
6292 Result += "}";
6293}
6294
Fariborz Jahaniane18961b2012-02-08 19:53:58 +00006295static void Write_protocol_list_initializer(ASTContext *Context, std::string &Result,
6296 ArrayRef<ObjCProtocolDecl *> SuperProtocols,
6297 StringRef VarName,
6298 StringRef ProtocolName) {
6299 if (SuperProtocols.size() > 0) {
6300 Result += "\nstatic ";
6301 Write_protocol_list_t_TypeDecl(Result, SuperProtocols.size());
6302 Result += " "; Result += VarName;
Fangrui Song6907ce22018-07-30 19:24:48 +00006303 Result += ProtocolName;
Fariborz Jahaniane18961b2012-02-08 19:53:58 +00006304 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6305 Result += "\t"; Result += utostr(SuperProtocols.size()); Result += ",\n";
6306 for (unsigned i = 0, e = SuperProtocols.size(); i < e; i++) {
6307 ObjCProtocolDecl *SuperPD = SuperProtocols[i];
Fangrui Song6907ce22018-07-30 19:24:48 +00006308 Result += "\t&"; Result += "_OBJC_PROTOCOL_";
Fariborz Jahaniane18961b2012-02-08 19:53:58 +00006309 Result += SuperPD->getNameAsString();
6310 if (i == e-1)
6311 Result += "\n};\n";
6312 else
6313 Result += ",\n";
6314 }
6315 }
6316}
6317
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006318static void Write_method_list_t_initializer(RewriteModernObjC &RewriteObj,
6319 ASTContext *Context, std::string &Result,
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006320 ArrayRef<ObjCMethodDecl *> Methods,
6321 StringRef VarName,
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006322 StringRef TopLevelDeclName,
6323 bool MethodImpl) {
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006324 if (Methods.size() > 0) {
6325 Result += "\nstatic ";
6326 Write_method_list_t_TypeDecl(Result, Methods.size());
6327 Result += " "; Result += VarName;
Fangrui Song6907ce22018-07-30 19:24:48 +00006328 Result += TopLevelDeclName;
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006329 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6330 Result += "\t"; Result += "sizeof(_objc_method)"; Result += ",\n";
6331 Result += "\t"; Result += utostr(Methods.size()); Result += ",\n";
6332 for (unsigned i = 0, e = Methods.size(); i < e; i++) {
6333 ObjCMethodDecl *MD = Methods[i];
6334 if (i == 0)
6335 Result += "\t{{(struct objc_selector *)\"";
6336 else
6337 Result += "\t{(struct objc_selector *)\"";
6338 Result += (MD)->getSelector().getAsString(); Result += "\"";
6339 Result += ", ";
John McCall843dfcc2016-11-29 21:57:00 +00006340 std::string MethodTypeString = Context->getObjCEncodingForMethodDecl(MD);
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006341 Result += "\""; Result += MethodTypeString; Result += "\"";
6342 Result += ", ";
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006343 if (!MethodImpl)
6344 Result += "0";
6345 else {
6346 Result += "(void *)";
6347 Result += RewriteObj.MethodInternalNames[MD];
6348 }
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006349 if (i == e-1)
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006350 Result += "}}\n";
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006351 else
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006352 Result += "},\n";
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006353 }
6354 Result += "};\n";
6355 }
6356}
6357
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006358static void Write_prop_list_t_initializer(RewriteModernObjC &RewriteObj,
Fariborz Jahanian67f7c552012-02-07 23:31:52 +00006359 ASTContext *Context, std::string &Result,
6360 ArrayRef<ObjCPropertyDecl *> Properties,
6361 const Decl *Container,
6362 StringRef VarName,
6363 StringRef ProtocolName) {
6364 if (Properties.size() > 0) {
6365 Result += "\nstatic ";
6366 Write__prop_list_t_TypeDecl(Result, Properties.size());
6367 Result += " "; Result += VarName;
Fangrui Song6907ce22018-07-30 19:24:48 +00006368 Result += ProtocolName;
Fariborz Jahanian67f7c552012-02-07 23:31:52 +00006369 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6370 Result += "\t"; Result += "sizeof(_prop_t)"; Result += ",\n";
6371 Result += "\t"; Result += utostr(Properties.size()); Result += ",\n";
6372 for (unsigned i = 0, e = Properties.size(); i < e; i++) {
6373 ObjCPropertyDecl *PropDecl = Properties[i];
6374 if (i == 0)
6375 Result += "\t{{\"";
6376 else
6377 Result += "\t{\"";
6378 Result += PropDecl->getName(); Result += "\",";
John McCall843dfcc2016-11-29 21:57:00 +00006379 std::string PropertyTypeString =
6380 Context->getObjCEncodingForPropertyDecl(PropDecl, Container);
6381 std::string QuotePropertyTypeString;
Fariborz Jahanian67f7c552012-02-07 23:31:52 +00006382 RewriteObj.QuoteDoublequotes(PropertyTypeString, QuotePropertyTypeString);
6383 Result += "\""; Result += QuotePropertyTypeString; Result += "\"";
6384 if (i == e-1)
6385 Result += "}}\n";
6386 else
6387 Result += "},\n";
6388 }
6389 Result += "};\n";
6390 }
6391}
6392
Fariborz Jahanian0a256882012-02-16 18:54:09 +00006393// Metadata flags
6394enum MetaDataDlags {
6395 CLS = 0x0,
6396 CLS_META = 0x1,
6397 CLS_ROOT = 0x2,
6398 OBJC2_CLS_HIDDEN = 0x10,
6399 CLS_EXCEPTION = 0x20,
Fangrui Song6907ce22018-07-30 19:24:48 +00006400
Fariborz Jahanian0a256882012-02-16 18:54:09 +00006401 /// (Obsolete) ARC-specific: this class has a .release_ivars method
6402 CLS_HAS_IVAR_RELEASER = 0x40,
6403 /// class was compiled with -fobjc-arr
6404 CLS_COMPILED_BY_ARC = 0x80 // (1<<7)
6405};
6406
Fangrui Song6907ce22018-07-30 19:24:48 +00006407static void Write__class_ro_t_initializer(ASTContext *Context, std::string &Result,
6408 unsigned int flags,
6409 const std::string &InstanceStart,
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006410 const std::string &InstanceSize,
6411 ArrayRef<ObjCMethodDecl *>baseMethods,
6412 ArrayRef<ObjCProtocolDecl *>baseProtocols,
6413 ArrayRef<ObjCIvarDecl *>ivars,
6414 ArrayRef<ObjCPropertyDecl *>Properties,
6415 StringRef VarName,
6416 StringRef ClassName) {
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006417 Result += "\nstatic struct _class_ro_t ";
6418 Result += VarName; Result += ClassName;
6419 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00006420 Result += "\t";
6421 Result += llvm::utostr(flags); Result += ", ";
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006422 Result += InstanceStart; Result += ", ";
6423 Result += InstanceSize; Result += ", \n";
6424 Result += "\t";
Fariborz Jahanian45489622012-03-14 18:09:23 +00006425 const llvm::Triple &Triple(Context->getTargetInfo().getTriple());
6426 if (Triple.getArch() == llvm::Triple::x86_64)
6427 // uint32_t const reserved; // only when building for 64bit targets
6428 Result += "(unsigned int)0, \n\t";
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006429 // const uint8_t * const ivarLayout;
6430 Result += "0, \n\t";
6431 Result += "\""; Result += ClassName; Result += "\",\n\t";
Fariborz Jahanian0a256882012-02-16 18:54:09 +00006432 bool metaclass = ((flags & CLS_META) != 0);
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006433 if (baseMethods.size() > 0) {
6434 Result += "(const struct _method_list_t *)&";
Fariborz Jahanian0a256882012-02-16 18:54:09 +00006435 if (metaclass)
6436 Result += "_OBJC_$_CLASS_METHODS_";
6437 else
6438 Result += "_OBJC_$_INSTANCE_METHODS_";
6439 Result += ClassName;
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006440 Result += ",\n\t";
6441 }
6442 else
6443 Result += "0, \n\t";
6444
Fariborz Jahanian0a256882012-02-16 18:54:09 +00006445 if (!metaclass && baseProtocols.size() > 0) {
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006446 Result += "(const struct _objc_protocol_list *)&";
6447 Result += "_OBJC_CLASS_PROTOCOLS_$_"; Result += ClassName;
6448 Result += ",\n\t";
6449 }
6450 else
6451 Result += "0, \n\t";
6452
Fariborz Jahanian0a256882012-02-16 18:54:09 +00006453 if (!metaclass && ivars.size() > 0) {
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006454 Result += "(const struct _ivar_list_t *)&";
6455 Result += "_OBJC_$_INSTANCE_VARIABLES_"; Result += ClassName;
6456 Result += ",\n\t";
6457 }
6458 else
6459 Result += "0, \n\t";
6460
6461 // weakIvarLayout
6462 Result += "0, \n\t";
Fariborz Jahanian0a256882012-02-16 18:54:09 +00006463 if (!metaclass && Properties.size() > 0) {
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006464 Result += "(const struct _prop_list_t *)&";
Fariborz Jahanianc41d8282012-02-16 21:57:59 +00006465 Result += "_OBJC_$_PROP_LIST_"; Result += ClassName;
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006466 Result += ",\n";
6467 }
6468 else
6469 Result += "0, \n";
6470
6471 Result += "};\n";
6472}
6473
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006474static void Write_class_t(ASTContext *Context, std::string &Result,
6475 StringRef VarName,
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006476 const ObjCInterfaceDecl *CDecl, bool metaclass) {
6477 bool rootClass = (!CDecl->getSuperClass());
6478 const ObjCInterfaceDecl *RootClass = CDecl;
Fangrui Song6907ce22018-07-30 19:24:48 +00006479
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006480 if (!rootClass) {
6481 // Find the Root class
6482 RootClass = CDecl->getSuperClass();
6483 while (RootClass->getSuperClass()) {
6484 RootClass = RootClass->getSuperClass();
6485 }
6486 }
6487
6488 if (metaclass && rootClass) {
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006489 // Need to handle a case of use of forward declaration.
Fariborz Jahanianfca65102012-03-10 18:25:06 +00006490 Result += "\n";
Fariborz Jahanian38c59102012-03-27 16:21:30 +00006491 Result += "extern \"C\" ";
Fariborz Jahanianfca65102012-03-10 18:25:06 +00006492 if (CDecl->getImplementation())
6493 Result += "__declspec(dllexport) ";
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00006494 else
6495 Result += "__declspec(dllimport) ";
Fangrui Song6907ce22018-07-30 19:24:48 +00006496
Fariborz Jahanian38c59102012-03-27 16:21:30 +00006497 Result += "struct _class_t OBJC_CLASS_$_";
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006498 Result += CDecl->getNameAsString();
6499 Result += ";\n";
6500 }
6501 // Also, for possibility of 'super' metadata class not having been defined yet.
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006502 if (!rootClass) {
Fariborz Jahanian064b5382012-03-29 19:04:10 +00006503 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahanianfca65102012-03-10 18:25:06 +00006504 Result += "\n";
Fariborz Jahanian38c59102012-03-27 16:21:30 +00006505 Result += "extern \"C\" ";
Fariborz Jahanian064b5382012-03-29 19:04:10 +00006506 if (SuperClass->getImplementation())
Fariborz Jahanianfca65102012-03-10 18:25:06 +00006507 Result += "__declspec(dllexport) ";
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00006508 else
6509 Result += "__declspec(dllimport) ";
6510
Fangrui Song6907ce22018-07-30 19:24:48 +00006511 Result += "struct _class_t ";
Fariborz Jahanianfca65102012-03-10 18:25:06 +00006512 Result += VarName;
Fariborz Jahanian064b5382012-03-29 19:04:10 +00006513 Result += SuperClass->getNameAsString();
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006514 Result += ";\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00006515
Fariborz Jahanian064b5382012-03-29 19:04:10 +00006516 if (metaclass && RootClass != SuperClass) {
Fariborz Jahanian38c59102012-03-27 16:21:30 +00006517 Result += "extern \"C\" ";
Fariborz Jahanian35465592012-03-20 21:09:58 +00006518 if (RootClass->getImplementation())
6519 Result += "__declspec(dllexport) ";
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00006520 else
6521 Result += "__declspec(dllimport) ";
6522
Fangrui Song6907ce22018-07-30 19:24:48 +00006523 Result += "struct _class_t ";
Fariborz Jahanian35465592012-03-20 21:09:58 +00006524 Result += VarName;
6525 Result += RootClass->getNameAsString();
6526 Result += ";\n";
6527 }
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006528 }
Fangrui Song6907ce22018-07-30 19:24:48 +00006529
6530 Result += "\nextern \"C\" __declspec(dllexport) struct _class_t ";
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00006531 Result += VarName; Result += CDecl->getNameAsString();
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006532 Result += " __attribute__ ((used, section (\"__DATA,__objc_data\"))) = {\n";
6533 Result += "\t";
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006534 if (metaclass) {
6535 if (!rootClass) {
6536 Result += "0, // &"; Result += VarName;
6537 Result += RootClass->getNameAsString();
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006538 Result += ",\n\t";
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006539 Result += "0, // &"; Result += VarName;
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006540 Result += CDecl->getSuperClass()->getNameAsString();
6541 Result += ",\n\t";
6542 }
6543 else {
Fangrui Song6907ce22018-07-30 19:24:48 +00006544 Result += "0, // &"; Result += VarName;
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006545 Result += CDecl->getNameAsString();
6546 Result += ",\n\t";
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006547 Result += "0, // &OBJC_CLASS_$_"; Result += CDecl->getNameAsString();
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006548 Result += ",\n\t";
6549 }
6550 }
6551 else {
Fangrui Song6907ce22018-07-30 19:24:48 +00006552 Result += "0, // &OBJC_METACLASS_$_";
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006553 Result += CDecl->getNameAsString();
6554 Result += ",\n\t";
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006555 if (!rootClass) {
6556 Result += "0, // &"; Result += VarName;
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006557 Result += CDecl->getSuperClass()->getNameAsString();
6558 Result += ",\n\t";
6559 }
Fangrui Song6907ce22018-07-30 19:24:48 +00006560 else
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006561 Result += "0,\n\t";
6562 }
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006563 Result += "0, // (void *)&_objc_empty_cache,\n\t";
6564 Result += "0, // unused, was (void *)&_objc_empty_vtable,\n\t";
6565 if (metaclass)
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006566 Result += "&_OBJC_METACLASS_RO_$_";
6567 else
6568 Result += "&_OBJC_CLASS_RO_$_";
6569 Result += CDecl->getNameAsString();
6570 Result += ",\n};\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00006571
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006572 // Add static function to initialize some of the meta-data fields.
6573 // avoid doing it twice.
6574 if (metaclass)
6575 return;
Fangrui Song6907ce22018-07-30 19:24:48 +00006576
6577 const ObjCInterfaceDecl *SuperClass =
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006578 rootClass ? CDecl : CDecl->getSuperClass();
Fangrui Song6907ce22018-07-30 19:24:48 +00006579
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006580 Result += "static void OBJC_CLASS_SETUP_$_";
6581 Result += CDecl->getNameAsString();
6582 Result += "(void ) {\n";
6583 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
6584 Result += ".isa = "; Result += "&OBJC_METACLASS_$_";
Fariborz Jahanian35465592012-03-20 21:09:58 +00006585 Result += RootClass->getNameAsString(); Result += ";\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00006586
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006587 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
Fariborz Jahanian35465592012-03-20 21:09:58 +00006588 Result += ".superclass = ";
6589 if (rootClass)
6590 Result += "&OBJC_CLASS_$_";
6591 else
6592 Result += "&OBJC_METACLASS_$_";
6593
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006594 Result += SuperClass->getNameAsString(); Result += ";\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00006595
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006596 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
6597 Result += ".cache = "; Result += "&_objc_empty_cache"; Result += ";\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00006598
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006599 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6600 Result += ".isa = "; Result += "&OBJC_METACLASS_$_";
6601 Result += CDecl->getNameAsString(); Result += ";\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00006602
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006603 if (!rootClass) {
6604 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6605 Result += ".superclass = "; Result += "&OBJC_CLASS_$_";
6606 Result += SuperClass->getNameAsString(); Result += ";\n";
6607 }
Fangrui Song6907ce22018-07-30 19:24:48 +00006608
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006609 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6610 Result += ".cache = "; Result += "&_objc_empty_cache"; Result += ";\n";
6611 Result += "}\n";
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006612}
6613
Fangrui Song6907ce22018-07-30 19:24:48 +00006614static void Write_category_t(RewriteModernObjC &RewriteObj, ASTContext *Context,
Fariborz Jahanianf2055052012-02-17 18:40:41 +00006615 std::string &Result,
Fariborz Jahanian5ed21c32012-03-27 18:41:05 +00006616 ObjCCategoryDecl *CatDecl,
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00006617 ObjCInterfaceDecl *ClassDecl,
Fariborz Jahanianf2055052012-02-17 18:40:41 +00006618 ArrayRef<ObjCMethodDecl *> InstanceMethods,
6619 ArrayRef<ObjCMethodDecl *> ClassMethods,
6620 ArrayRef<ObjCProtocolDecl *> RefedProtocols,
6621 ArrayRef<ObjCPropertyDecl *> ClassProperties) {
Fariborz Jahanian5ed21c32012-03-27 18:41:05 +00006622 StringRef CatName = CatDecl->getName();
NAKAMURA Takumi3eb0edd2012-03-21 03:21:46 +00006623 StringRef ClassName = ClassDecl->getName();
Fangrui Song6907ce22018-07-30 19:24:48 +00006624 // must declare an extern class object in case this class is not implemented
Fariborz Jahanian320c88a2012-02-17 20:33:00 +00006625 // in this TU.
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00006626 Result += "\n";
Fariborz Jahanian38c59102012-03-27 16:21:30 +00006627 Result += "extern \"C\" ";
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00006628 if (ClassDecl->getImplementation())
6629 Result += "__declspec(dllexport) ";
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00006630 else
6631 Result += "__declspec(dllimport) ";
Fangrui Song6907ce22018-07-30 19:24:48 +00006632
Fariborz Jahanian38c59102012-03-27 16:21:30 +00006633 Result += "struct _class_t ";
Fariborz Jahanian320c88a2012-02-17 20:33:00 +00006634 Result += "OBJC_CLASS_$_"; Result += ClassName;
6635 Result += ";\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00006636
Fariborz Jahanianf2055052012-02-17 18:40:41 +00006637 Result += "\nstatic struct _category_t ";
6638 Result += "_OBJC_$_CATEGORY_";
6639 Result += ClassName; Result += "_$_"; Result += CatName;
6640 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = \n";
6641 Result += "{\n";
6642 Result += "\t\""; Result += ClassName; Result += "\",\n";
Fariborz Jahaniancd79a492012-03-20 21:41:28 +00006643 Result += "\t0, // &"; Result += "OBJC_CLASS_$_"; Result += ClassName;
Fariborz Jahanianf2055052012-02-17 18:40:41 +00006644 Result += ",\n";
6645 if (InstanceMethods.size() > 0) {
Fangrui Song6907ce22018-07-30 19:24:48 +00006646 Result += "\t(const struct _method_list_t *)&";
Fariborz Jahanianf2055052012-02-17 18:40:41 +00006647 Result += "_OBJC_$_CATEGORY_INSTANCE_METHODS_";
6648 Result += ClassName; Result += "_$_"; Result += CatName;
6649 Result += ",\n";
6650 }
6651 else
6652 Result += "\t0,\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00006653
Fariborz Jahanianf2055052012-02-17 18:40:41 +00006654 if (ClassMethods.size() > 0) {
Fangrui Song6907ce22018-07-30 19:24:48 +00006655 Result += "\t(const struct _method_list_t *)&";
Fariborz Jahanianf2055052012-02-17 18:40:41 +00006656 Result += "_OBJC_$_CATEGORY_CLASS_METHODS_";
6657 Result += ClassName; Result += "_$_"; Result += CatName;
6658 Result += ",\n";
6659 }
6660 else
6661 Result += "\t0,\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00006662
Fariborz Jahanianf2055052012-02-17 18:40:41 +00006663 if (RefedProtocols.size() > 0) {
Fangrui Song6907ce22018-07-30 19:24:48 +00006664 Result += "\t(const struct _protocol_list_t *)&";
Fariborz Jahanianf2055052012-02-17 18:40:41 +00006665 Result += "_OBJC_CATEGORY_PROTOCOLS_$_";
6666 Result += ClassName; Result += "_$_"; Result += CatName;
6667 Result += ",\n";
6668 }
6669 else
6670 Result += "\t0,\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00006671
Fariborz Jahanianf2055052012-02-17 18:40:41 +00006672 if (ClassProperties.size() > 0) {
6673 Result += "\t(const struct _prop_list_t *)&"; Result += "_OBJC_$_PROP_LIST_";
6674 Result += ClassName; Result += "_$_"; Result += CatName;
6675 Result += ",\n";
6676 }
6677 else
6678 Result += "\t0,\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00006679
Fariborz Jahanianf2055052012-02-17 18:40:41 +00006680 Result += "};\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00006681
Fariborz Jahaniancd79a492012-03-20 21:41:28 +00006682 // Add static function to initialize the class pointer in the category structure.
6683 Result += "static void OBJC_CATEGORY_SETUP_$_";
6684 Result += ClassDecl->getNameAsString();
6685 Result += "_$_";
6686 Result += CatName;
6687 Result += "(void ) {\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00006688 Result += "\t_OBJC_$_CATEGORY_";
Fariborz Jahaniancd79a492012-03-20 21:41:28 +00006689 Result += ClassDecl->getNameAsString();
6690 Result += "_$_";
6691 Result += CatName;
6692 Result += ".cls = "; Result += "&OBJC_CLASS_$_"; Result += ClassName;
6693 Result += ";\n}\n";
Fariborz Jahanianf2055052012-02-17 18:40:41 +00006694}
6695
Fariborz Jahaniana8395a62012-02-08 22:23:26 +00006696static void Write__extendedMethodTypes_initializer(RewriteModernObjC &RewriteObj,
6697 ASTContext *Context, std::string &Result,
6698 ArrayRef<ObjCMethodDecl *> Methods,
6699 StringRef VarName,
6700 StringRef ProtocolName) {
6701 if (Methods.size() == 0)
6702 return;
Fangrui Song6907ce22018-07-30 19:24:48 +00006703
Fariborz Jahaniana8395a62012-02-08 22:23:26 +00006704 Result += "\nstatic const char *";
6705 Result += VarName; Result += ProtocolName;
6706 Result += " [] __attribute__ ((used, section (\"__DATA,__objc_const\"))) = \n";
6707 Result += "{\n";
6708 for (unsigned i = 0, e = Methods.size(); i < e; i++) {
6709 ObjCMethodDecl *MD = Methods[i];
John McCall843dfcc2016-11-29 21:57:00 +00006710 std::string MethodTypeString =
6711 Context->getObjCEncodingForMethodDecl(MD, true);
6712 std::string QuoteMethodTypeString;
Fariborz Jahaniana8395a62012-02-08 22:23:26 +00006713 RewriteObj.QuoteDoublequotes(MethodTypeString, QuoteMethodTypeString);
6714 Result += "\t\""; Result += QuoteMethodTypeString; Result += "\"";
6715 if (i == e-1)
6716 Result += "\n};\n";
6717 else {
6718 Result += ",\n";
6719 }
6720 }
6721}
6722
Fariborz Jahanianaaf4d692012-04-11 21:12:36 +00006723static void Write_IvarOffsetVar(RewriteModernObjC &RewriteObj,
6724 ASTContext *Context,
Fangrui Song6907ce22018-07-30 19:24:48 +00006725 std::string &Result,
6726 ArrayRef<ObjCIvarDecl *> Ivars,
Fariborz Jahaniana854174a2012-03-20 17:13:39 +00006727 ObjCInterfaceDecl *CDecl) {
Fariborz Jahanian75e71b92012-02-13 20:59:02 +00006728 // FIXME. visibilty of offset symbols may have to be set; for Darwin
6729 // this is what happens:
6730 /**
6731 if (Ivar->getAccessControl() == ObjCIvarDecl::Private ||
6732 Ivar->getAccessControl() == ObjCIvarDecl::Package ||
6733 Class->getVisibility() == HiddenVisibility)
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00006734 Visibility should be: HiddenVisibility;
Fariborz Jahanian75e71b92012-02-13 20:59:02 +00006735 else
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00006736 Visibility should be: DefaultVisibility;
Fariborz Jahanian75e71b92012-02-13 20:59:02 +00006737 */
Fangrui Song6907ce22018-07-30 19:24:48 +00006738
Fariborz Jahanian1c1da172012-02-13 21:34:45 +00006739 Result += "\n";
6740 for (unsigned i =0, e = Ivars.size(); i < e; i++) {
6741 ObjCIvarDecl *IvarDecl = Ivars[i];
Fariborz Jahaniane47bf2b2012-03-12 16:46:58 +00006742 if (Context->getLangOpts().MicrosoftExt)
6743 Result += "__declspec(allocate(\".objc_ivar$B\")) ";
Fangrui Song6907ce22018-07-30 19:24:48 +00006744
Fariborz Jahaniane47bf2b2012-03-12 16:46:58 +00006745 if (!Context->getLangOpts().MicrosoftExt ||
6746 IvarDecl->getAccessControl() == ObjCIvarDecl::Private ||
Fariborz Jahanianc9295ec2012-03-10 01:34:42 +00006747 IvarDecl->getAccessControl() == ObjCIvarDecl::Package)
Fangrui Song6907ce22018-07-30 19:24:48 +00006748 Result += "extern \"C\" unsigned long int ";
Fariborz Jahanian2677ded2012-03-10 00:53:02 +00006749 else
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00006750 Result += "extern \"C\" __declspec(dllexport) unsigned long int ";
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006751 if (Ivars[i]->isBitField())
6752 RewriteObj.ObjCIvarBitfieldGroupOffset(IvarDecl, Result);
6753 else
6754 WriteInternalIvarName(CDecl, IvarDecl, Result);
Fariborz Jahanian1c1da172012-02-13 21:34:45 +00006755 Result += " __attribute__ ((used, section (\"__DATA,__objc_ivar\")))";
6756 Result += " = ";
Fariborz Jahanianaaf4d692012-04-11 21:12:36 +00006757 RewriteObj.RewriteIvarOffsetComputation(IvarDecl, Result);
6758 Result += ";\n";
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006759 if (Ivars[i]->isBitField()) {
6760 // skip over rest of the ivar bitfields.
6761 SKIP_BITFIELDS(i , e, Ivars);
6762 }
Fariborz Jahanian75e71b92012-02-13 20:59:02 +00006763 }
6764}
6765
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006766static void Write__ivar_list_t_initializer(RewriteModernObjC &RewriteObj,
6767 ASTContext *Context, std::string &Result,
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006768 ArrayRef<ObjCIvarDecl *> OriginalIvars,
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006769 StringRef VarName,
Fariborz Jahaniana854174a2012-03-20 17:13:39 +00006770 ObjCInterfaceDecl *CDecl) {
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006771 if (OriginalIvars.size() > 0) {
6772 Write_IvarOffsetVar(RewriteObj, Context, Result, OriginalIvars, CDecl);
6773 SmallVector<ObjCIvarDecl *, 8> Ivars;
6774 // strip off all but the first ivar bitfield from each group of ivars.
6775 // Such ivars in the ivar list table will be replaced by their grouping struct
6776 // 'ivar'.
6777 for (unsigned i = 0, e = OriginalIvars.size(); i < e; i++) {
6778 if (OriginalIvars[i]->isBitField()) {
6779 Ivars.push_back(OriginalIvars[i]);
6780 // skip over rest of the ivar bitfields.
6781 SKIP_BITFIELDS(i , e, OriginalIvars);
6782 }
6783 else
6784 Ivars.push_back(OriginalIvars[i]);
6785 }
Fangrui Song6907ce22018-07-30 19:24:48 +00006786
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006787 Result += "\nstatic ";
6788 Write__ivar_list_t_TypeDecl(Result, Ivars.size());
6789 Result += " "; Result += VarName;
Fariborz Jahaniana854174a2012-03-20 17:13:39 +00006790 Result += CDecl->getNameAsString();
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006791 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6792 Result += "\t"; Result += "sizeof(_ivar_t)"; Result += ",\n";
6793 Result += "\t"; Result += utostr(Ivars.size()); Result += ",\n";
6794 for (unsigned i =0, e = Ivars.size(); i < e; i++) {
6795 ObjCIvarDecl *IvarDecl = Ivars[i];
6796 if (i == 0)
6797 Result += "\t{{";
6798 else
6799 Result += "\t {";
Fariborz Jahaniana854174a2012-03-20 17:13:39 +00006800 Result += "(unsigned long int *)&";
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006801 if (Ivars[i]->isBitField())
6802 RewriteObj.ObjCIvarBitfieldGroupOffset(IvarDecl, Result);
6803 else
6804 WriteInternalIvarName(CDecl, IvarDecl, Result);
Fariborz Jahanian75e71b92012-02-13 20:59:02 +00006805 Result += ", ";
Fangrui Song6907ce22018-07-30 19:24:48 +00006806
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006807 Result += "\"";
6808 if (Ivars[i]->isBitField())
6809 RewriteObj.ObjCIvarBitfieldGroupDecl(Ivars[i], Result);
6810 else
6811 Result += IvarDecl->getName();
6812 Result += "\", ";
Fangrui Song6907ce22018-07-30 19:24:48 +00006813
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006814 QualType IVQT = IvarDecl->getType();
6815 if (IvarDecl->isBitField())
6816 IVQT = RewriteObj.GetGroupRecordTypeForObjCIvarBitfield(IvarDecl);
Fangrui Song6907ce22018-07-30 19:24:48 +00006817
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006818 std::string IvarTypeString, QuoteIvarTypeString;
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006819 Context->getObjCEncodingForType(IVQT, IvarTypeString,
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006820 IvarDecl);
6821 RewriteObj.QuoteDoublequotes(IvarTypeString, QuoteIvarTypeString);
6822 Result += "\""; Result += QuoteIvarTypeString; Result += "\", ";
Fangrui Song6907ce22018-07-30 19:24:48 +00006823
Fariborz Jahanian088959a2012-02-11 20:10:52 +00006824 // FIXME. this alignment represents the host alignment and need be changed to
6825 // represent the target alignment.
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006826 unsigned Align = Context->getTypeAlign(IVQT)/8;
Fariborz Jahanian088959a2012-02-11 20:10:52 +00006827 Align = llvm::Log2_32(Align);
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006828 Result += llvm::utostr(Align); Result += ", ";
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006829 CharUnits Size = Context->getTypeSizeInChars(IVQT);
Fariborz Jahaniancb1d9f32012-02-10 23:18:24 +00006830 Result += llvm::utostr(Size.getQuantity());
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006831 if (i == e-1)
6832 Result += "}}\n";
6833 else
6834 Result += "},\n";
6835 }
6836 Result += "};\n";
6837 }
6838}
6839
Fariborz Jahanian11671902012-02-07 17:11:38 +00006840/// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
Fangrui Song6907ce22018-07-30 19:24:48 +00006841void RewriteModernObjC::RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl,
Fariborz Jahaniane18961b2012-02-08 19:53:58 +00006842 std::string &Result) {
Fangrui Song6907ce22018-07-30 19:24:48 +00006843
Fariborz Jahanian11671902012-02-07 17:11:38 +00006844 // Do not synthesize the protocol more than once.
6845 if (ObjCSynthesizedProtocols.count(PDecl->getCanonicalDecl()))
6846 return;
Fariborz Jahanian45489622012-03-14 18:09:23 +00006847 WriteModernMetadataDeclarations(Context, Result);
Fangrui Song6907ce22018-07-30 19:24:48 +00006848
Fariborz Jahanian11671902012-02-07 17:11:38 +00006849 if (ObjCProtocolDecl *Def = PDecl->getDefinition())
6850 PDecl = Def;
Fariborz Jahaniane18961b2012-02-08 19:53:58 +00006851 // Must write out all protocol definitions in current qualifier list,
6852 // and in their nested qualifiers before writing out current definition.
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00006853 for (auto *I : PDecl->protocols())
6854 RewriteObjCProtocolMetaData(I, Result);
Fangrui Song6907ce22018-07-30 19:24:48 +00006855
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006856 // Construct method lists.
6857 std::vector<ObjCMethodDecl *> InstanceMethods, ClassMethods;
6858 std::vector<ObjCMethodDecl *> OptInstanceMethods, OptClassMethods;
Aaron Ballmanf26acce2014-03-13 19:50:17 +00006859 for (auto *MD : PDecl->instance_methods()) {
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006860 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
6861 OptInstanceMethods.push_back(MD);
6862 } else {
6863 InstanceMethods.push_back(MD);
6864 }
6865 }
Fangrui Song6907ce22018-07-30 19:24:48 +00006866
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00006867 for (auto *MD : PDecl->class_methods()) {
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006868 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
6869 OptClassMethods.push_back(MD);
6870 } else {
6871 ClassMethods.push_back(MD);
6872 }
6873 }
Fariborz Jahaniana8395a62012-02-08 22:23:26 +00006874 std::vector<ObjCMethodDecl *> AllMethods;
6875 for (unsigned i = 0, e = InstanceMethods.size(); i < e; i++)
6876 AllMethods.push_back(InstanceMethods[i]);
6877 for (unsigned i = 0, e = ClassMethods.size(); i < e; i++)
6878 AllMethods.push_back(ClassMethods[i]);
6879 for (unsigned i = 0, e = OptInstanceMethods.size(); i < e; i++)
6880 AllMethods.push_back(OptInstanceMethods[i]);
6881 for (unsigned i = 0, e = OptClassMethods.size(); i < e; i++)
6882 AllMethods.push_back(OptClassMethods[i]);
6883
6884 Write__extendedMethodTypes_initializer(*this, Context, Result,
6885 AllMethods,
6886 "_OBJC_PROTOCOL_METHOD_TYPES_",
6887 PDecl->getNameAsString());
Fariborz Jahaniane18961b2012-02-08 19:53:58 +00006888 // Protocol's super protocol list
Fangrui Song6907ce22018-07-30 19:24:48 +00006889 SmallVector<ObjCProtocolDecl *, 8> SuperProtocols(PDecl->protocols());
Fariborz Jahaniane18961b2012-02-08 19:53:58 +00006890 Write_protocol_list_initializer(Context, Result, SuperProtocols,
6891 "_OBJC_PROTOCOL_REFS_",
6892 PDecl->getNameAsString());
Fangrui Song6907ce22018-07-30 19:24:48 +00006893
6894 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006895 "_OBJC_PROTOCOL_INSTANCE_METHODS_",
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006896 PDecl->getNameAsString(), false);
Fangrui Song6907ce22018-07-30 19:24:48 +00006897
6898 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006899 "_OBJC_PROTOCOL_CLASS_METHODS_",
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006900 PDecl->getNameAsString(), false);
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006901
Fangrui Song6907ce22018-07-30 19:24:48 +00006902 Write_method_list_t_initializer(*this, Context, Result, OptInstanceMethods,
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006903 "_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_",
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006904 PDecl->getNameAsString(), false);
Fangrui Song6907ce22018-07-30 19:24:48 +00006905
6906 Write_method_list_t_initializer(*this, Context, Result, OptClassMethods,
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006907 "_OBJC_PROTOCOL_OPT_CLASS_METHODS_",
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006908 PDecl->getNameAsString(), false);
Fangrui Song6907ce22018-07-30 19:24:48 +00006909
Fariborz Jahanian67f7c552012-02-07 23:31:52 +00006910 // Protocol's property metadata.
Manman Rena7a8b1f2016-01-26 18:05:23 +00006911 SmallVector<ObjCPropertyDecl *, 8> ProtocolProperties(
6912 PDecl->instance_properties());
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006913 Write_prop_list_t_initializer(*this, Context, Result, ProtocolProperties,
Craig Topper8ae12032014-05-07 06:21:57 +00006914 /* Container */nullptr,
Fariborz Jahanian67f7c552012-02-07 23:31:52 +00006915 "_OBJC_PROTOCOL_PROPERTIES_",
6916 PDecl->getNameAsString());
Craig Topper8ae12032014-05-07 06:21:57 +00006917
Fariborz Jahanian48985802012-02-08 00:50:52 +00006918 // Writer out root metadata for current protocol: struct _protocol_t
Fariborz Jahanian008dfe22012-03-11 19:41:56 +00006919 Result += "\n";
6920 if (LangOpts.MicrosoftExt)
Fariborz Jahanian1b085422012-04-14 17:13:08 +00006921 Result += "static ";
Fariborz Jahanianb31e3af2012-03-15 17:05:33 +00006922 Result += "struct _protocol_t _OBJC_PROTOCOL_";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006923 Result += PDecl->getNameAsString();
Akira Hatanaka7f550f32016-02-11 06:36:35 +00006924 Result += " __attribute__ ((used)) = {\n";
Fariborz Jahanian48985802012-02-08 00:50:52 +00006925 Result += "\t0,\n"; // id is; is null
6926 Result += "\t\""; Result += PDecl->getNameAsString(); Result += "\",\n";
Fariborz Jahaniane18961b2012-02-08 19:53:58 +00006927 if (SuperProtocols.size() > 0) {
6928 Result += "\t(const struct _protocol_list_t *)&"; Result += "_OBJC_PROTOCOL_REFS_";
6929 Result += PDecl->getNameAsString(); Result += ",\n";
6930 }
6931 else
6932 Result += "\t0,\n";
Fariborz Jahanian48985802012-02-08 00:50:52 +00006933 if (InstanceMethods.size() > 0) {
Fangrui Song6907ce22018-07-30 19:24:48 +00006934 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
Fariborz Jahanian48985802012-02-08 00:50:52 +00006935 Result += PDecl->getNameAsString(); Result += ",\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006936 }
6937 else
Fariborz Jahanian48985802012-02-08 00:50:52 +00006938 Result += "\t0,\n";
6939
6940 if (ClassMethods.size() > 0) {
Fangrui Song6907ce22018-07-30 19:24:48 +00006941 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_CLASS_METHODS_";
Fariborz Jahanian48985802012-02-08 00:50:52 +00006942 Result += PDecl->getNameAsString(); Result += ",\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006943 }
6944 else
Fariborz Jahanian48985802012-02-08 00:50:52 +00006945 Result += "\t0,\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00006946
Fariborz Jahanian48985802012-02-08 00:50:52 +00006947 if (OptInstanceMethods.size() > 0) {
Fangrui Song6907ce22018-07-30 19:24:48 +00006948 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_";
Fariborz Jahanian48985802012-02-08 00:50:52 +00006949 Result += PDecl->getNameAsString(); Result += ",\n";
6950 }
6951 else
6952 Result += "\t0,\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00006953
Fariborz Jahanian48985802012-02-08 00:50:52 +00006954 if (OptClassMethods.size() > 0) {
Fangrui Song6907ce22018-07-30 19:24:48 +00006955 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_CLASS_METHODS_";
Fariborz Jahanian48985802012-02-08 00:50:52 +00006956 Result += PDecl->getNameAsString(); Result += ",\n";
6957 }
6958 else
6959 Result += "\t0,\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00006960
Fariborz Jahanian48985802012-02-08 00:50:52 +00006961 if (ProtocolProperties.size() > 0) {
Fangrui Song6907ce22018-07-30 19:24:48 +00006962 Result += "\t(const struct _prop_list_t *)&_OBJC_PROTOCOL_PROPERTIES_";
Fariborz Jahanian48985802012-02-08 00:50:52 +00006963 Result += PDecl->getNameAsString(); Result += ",\n";
6964 }
6965 else
6966 Result += "\t0,\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00006967
Fariborz Jahanian48985802012-02-08 00:50:52 +00006968 Result += "\t"; Result += "sizeof(_protocol_t)"; Result += ",\n";
6969 Result += "\t0,\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00006970
Fariborz Jahaniana8395a62012-02-08 22:23:26 +00006971 if (AllMethods.size() > 0) {
6972 Result += "\t(const char **)&"; Result += "_OBJC_PROTOCOL_METHOD_TYPES_";
6973 Result += PDecl->getNameAsString();
6974 Result += "\n};\n";
6975 }
6976 else
6977 Result += "\t0\n};\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00006978
Fariborz Jahanianddddca32012-03-14 21:44:09 +00006979 if (LangOpts.MicrosoftExt)
Fariborz Jahanian1b085422012-04-14 17:13:08 +00006980 Result += "static ";
Fariborz Jahanianddddca32012-03-14 21:44:09 +00006981 Result += "struct _protocol_t *";
6982 Result += "_OBJC_LABEL_PROTOCOL_$_"; Result += PDecl->getNameAsString();
6983 Result += " = &_OBJC_PROTOCOL_"; Result += PDecl->getNameAsString();
6984 Result += ";\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00006985
Fariborz Jahanian11671902012-02-07 17:11:38 +00006986 // Mark this protocol as having been generated.
David Blaikie82e95a32014-11-19 07:49:47 +00006987 if (!ObjCSynthesizedProtocols.insert(PDecl->getCanonicalDecl()).second)
Fariborz Jahanian11671902012-02-07 17:11:38 +00006988 llvm_unreachable("protocol already synthesized");
Fariborz Jahanian11671902012-02-07 17:11:38 +00006989}
6990
Fariborz Jahanian0a256882012-02-16 18:54:09 +00006991/// hasObjCExceptionAttribute - Return true if this class or any super
6992/// class has the __objc_exception__ attribute.
6993/// FIXME. Move this to ASTContext.cpp as it is also used for IRGen.
6994static bool hasObjCExceptionAttribute(ASTContext &Context,
6995 const ObjCInterfaceDecl *OID) {
6996 if (OID->hasAttr<ObjCExceptionAttr>())
6997 return true;
6998 if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
6999 return hasObjCExceptionAttribute(Context, Super);
7000 return false;
7001}
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007002
Fariborz Jahanian11671902012-02-07 17:11:38 +00007003void RewriteModernObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
7004 std::string &Result) {
7005 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
Fangrui Song6907ce22018-07-30 19:24:48 +00007006
Fariborz Jahanian11671902012-02-07 17:11:38 +00007007 // Explicitly declared @interface's are already synthesized.
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00007008 if (CDecl->isImplicitInterfaceDecl())
Fangrui Song6907ce22018-07-30 19:24:48 +00007009 assert(false &&
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00007010 "Legacy implicit interface rewriting not supported in moder abi");
Fangrui Song6907ce22018-07-30 19:24:48 +00007011
Fariborz Jahanian45489622012-03-14 18:09:23 +00007012 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00007013 SmallVector<ObjCIvarDecl *, 8> IVars;
Fangrui Song6907ce22018-07-30 19:24:48 +00007014
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00007015 for (ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
7016 IVD; IVD = IVD->getNextIvar()) {
7017 // Ignore unnamed bit-fields.
7018 if (!IVD->getDeclName())
7019 continue;
7020 IVars.push_back(IVD);
Fariborz Jahanian11671902012-02-07 17:11:38 +00007021 }
Fangrui Song6907ce22018-07-30 19:24:48 +00007022
7023 Write__ivar_list_t_initializer(*this, Context, Result, IVars,
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007024 "_OBJC_$_INSTANCE_VARIABLES_",
Fariborz Jahaniana854174a2012-03-20 17:13:39 +00007025 CDecl);
Fangrui Song6907ce22018-07-30 19:24:48 +00007026
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007027 // Build _objc_method_list for class's instance methods if needed
Aaron Ballmanf26acce2014-03-13 19:50:17 +00007028 SmallVector<ObjCMethodDecl *, 32> InstanceMethods(IDecl->instance_methods());
Fangrui Song6907ce22018-07-30 19:24:48 +00007029
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007030 // If any of our property implementations have associated getters or
7031 // setters, produce metadata for them as well.
Aaron Ballmand85eff42014-03-14 15:02:45 +00007032 for (const auto *Prop : IDecl->property_impls()) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00007033 if (Prop->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007034 continue;
David Blaikie2d7c57e2012-04-30 02:36:29 +00007035 if (!Prop->getPropertyIvarDecl())
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007036 continue;
David Blaikie2d7c57e2012-04-30 02:36:29 +00007037 ObjCPropertyDecl *PD = Prop->getPropertyDecl();
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007038 if (!PD)
7039 continue;
7040 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
Fariborz Jahanianf687e7b2012-05-03 22:52:13 +00007041 if (mustSynthesizeSetterGetterMethod(IDecl, PD, true /*getter*/))
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007042 InstanceMethods.push_back(Getter);
7043 if (PD->isReadOnly())
7044 continue;
7045 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
Fariborz Jahanianf687e7b2012-05-03 22:52:13 +00007046 if (mustSynthesizeSetterGetterMethod(IDecl, PD, false /*setter*/))
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007047 InstanceMethods.push_back(Setter);
7048 }
Fangrui Song6907ce22018-07-30 19:24:48 +00007049
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007050 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
7051 "_OBJC_$_INSTANCE_METHODS_",
7052 IDecl->getNameAsString(), true);
Fangrui Song6907ce22018-07-30 19:24:48 +00007053
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00007054 SmallVector<ObjCMethodDecl *, 32> ClassMethods(IDecl->class_methods());
Fangrui Song6907ce22018-07-30 19:24:48 +00007055
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007056 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
7057 "_OBJC_$_CLASS_METHODS_",
7058 IDecl->getNameAsString(), true);
Fangrui Song6907ce22018-07-30 19:24:48 +00007059
Fariborz Jahanianbce367742012-02-14 19:31:35 +00007060 // Protocols referenced in class declaration?
7061 // Protocol's super protocol list
7062 std::vector<ObjCProtocolDecl *> RefedProtocols;
7063 const ObjCList<ObjCProtocolDecl> &Protocols = CDecl->getReferencedProtocols();
7064 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
7065 E = Protocols.end();
7066 I != E; ++I) {
7067 RefedProtocols.push_back(*I);
7068 // Must write out all protocol definitions in current qualifier list,
7069 // and in their nested qualifiers before writing out current definition.
7070 RewriteObjCProtocolMetaData(*I, Result);
7071 }
Fangrui Song6907ce22018-07-30 19:24:48 +00007072
7073 Write_protocol_list_initializer(Context, Result,
Fariborz Jahanianbce367742012-02-14 19:31:35 +00007074 RefedProtocols,
7075 "_OBJC_CLASS_PROTOCOLS_$_",
7076 IDecl->getNameAsString());
Fangrui Song6907ce22018-07-30 19:24:48 +00007077
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007078 // Protocol's property metadata.
Manman Rena7a8b1f2016-01-26 18:05:23 +00007079 SmallVector<ObjCPropertyDecl *, 8> ClassProperties(
7080 CDecl->instance_properties());
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007081 Write_prop_list_t_initializer(*this, Context, Result, ClassProperties,
Fariborz Jahanianee1db7a2012-03-22 17:39:35 +00007082 /* Container */IDecl,
Fariborz Jahanianc41d8282012-02-16 21:57:59 +00007083 "_OBJC_$_PROP_LIST_",
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007084 CDecl->getNameAsString());
Fangrui Song6907ce22018-07-30 19:24:48 +00007085
Fariborz Jahanian0a256882012-02-16 18:54:09 +00007086 // Data for initializing _class_ro_t metaclass meta-data
7087 uint32_t flags = CLS_META;
7088 std::string InstanceSize;
7089 std::string InstanceStart;
Fangrui Song6907ce22018-07-30 19:24:48 +00007090
Fariborz Jahanian0a256882012-02-16 18:54:09 +00007091 bool classIsHidden = CDecl->getVisibility() == HiddenVisibility;
7092 if (classIsHidden)
7093 flags |= OBJC2_CLS_HIDDEN;
Fangrui Song6907ce22018-07-30 19:24:48 +00007094
Fariborz Jahanian0a256882012-02-16 18:54:09 +00007095 if (!CDecl->getSuperClass())
7096 // class is root
7097 flags |= CLS_ROOT;
7098 InstanceSize = "sizeof(struct _class_t)";
7099 InstanceStart = InstanceSize;
Fangrui Song6907ce22018-07-30 19:24:48 +00007100 Write__class_ro_t_initializer(Context, Result, flags,
Fariborz Jahanian0a256882012-02-16 18:54:09 +00007101 InstanceStart, InstanceSize,
7102 ClassMethods,
Craig Topper8ae12032014-05-07 06:21:57 +00007103 nullptr,
7104 nullptr,
7105 nullptr,
Fariborz Jahanian0a256882012-02-16 18:54:09 +00007106 "_OBJC_METACLASS_RO_$_",
7107 CDecl->getNameAsString());
7108
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007109 // Data for initializing _class_ro_t meta-data
Fariborz Jahanian0a256882012-02-16 18:54:09 +00007110 flags = CLS;
7111 if (classIsHidden)
7112 flags |= OBJC2_CLS_HIDDEN;
Fangrui Song6907ce22018-07-30 19:24:48 +00007113
Fariborz Jahanian0a256882012-02-16 18:54:09 +00007114 if (hasObjCExceptionAttribute(*Context, CDecl))
7115 flags |= CLS_EXCEPTION;
7116
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007117 if (!CDecl->getSuperClass())
7118 // class is root
7119 flags |= CLS_ROOT;
Fangrui Song6907ce22018-07-30 19:24:48 +00007120
Fariborz Jahanian0a256882012-02-16 18:54:09 +00007121 InstanceSize.clear();
7122 InstanceStart.clear();
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007123 if (!ObjCSynthesizedStructs.count(CDecl)) {
7124 InstanceSize = "0";
7125 InstanceStart = "0";
7126 }
7127 else {
7128 InstanceSize = "sizeof(struct ";
7129 InstanceSize += CDecl->getNameAsString();
7130 InstanceSize += "_IMPL)";
Fangrui Song6907ce22018-07-30 19:24:48 +00007131
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007132 ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
7133 if (IVD) {
Fariborz Jahanianaaf4d692012-04-11 21:12:36 +00007134 RewriteIvarOffsetComputation(IVD, InstanceStart);
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007135 }
Fangrui Song6907ce22018-07-30 19:24:48 +00007136 else
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007137 InstanceStart = InstanceSize;
7138 }
Fangrui Song6907ce22018-07-30 19:24:48 +00007139 Write__class_ro_t_initializer(Context, Result, flags,
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007140 InstanceStart, InstanceSize,
7141 InstanceMethods,
7142 RefedProtocols,
7143 IVars,
7144 ClassProperties,
7145 "_OBJC_CLASS_RO_$_",
7146 CDecl->getNameAsString());
Fangrui Song6907ce22018-07-30 19:24:48 +00007147
Fariborz Jahanian638252f2012-02-16 21:37:05 +00007148 Write_class_t(Context, Result,
7149 "OBJC_METACLASS_$_",
7150 CDecl, /*metaclass*/true);
Fangrui Song6907ce22018-07-30 19:24:48 +00007151
Fariborz Jahanian638252f2012-02-16 21:37:05 +00007152 Write_class_t(Context, Result,
7153 "OBJC_CLASS_$_",
7154 CDecl, /*metaclass*/false);
Fangrui Song6907ce22018-07-30 19:24:48 +00007155
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00007156 if (ImplementationIsNonLazy(IDecl))
7157 DefinedNonLazyClasses.push_back(CDecl);
Fariborz Jahanian11671902012-02-07 17:11:38 +00007158}
7159
Fariborz Jahanian5ed21c32012-03-27 18:41:05 +00007160void RewriteModernObjC::RewriteClassSetupInitHook(std::string &Result) {
7161 int ClsDefCount = ClassImplementation.size();
7162 if (!ClsDefCount)
7163 return;
7164 Result += "#pragma section(\".objc_inithooks$B\", long, read, write)\n";
7165 Result += "__declspec(allocate(\".objc_inithooks$B\")) ";
7166 Result += "static void *OBJC_CLASS_SETUP[] = {\n";
7167 for (int i = 0; i < ClsDefCount; i++) {
7168 ObjCImplementationDecl *IDecl = ClassImplementation[i];
7169 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
7170 Result += "\t(void *)&OBJC_CLASS_SETUP_$_";
7171 Result += CDecl->getName(); Result += ",\n";
7172 }
7173 Result += "};\n";
7174}
7175
Fariborz Jahanian11671902012-02-07 17:11:38 +00007176void RewriteModernObjC::RewriteMetaDataIntoBuffer(std::string &Result) {
7177 int ClsDefCount = ClassImplementation.size();
7178 int CatDefCount = CategoryImplementation.size();
Fangrui Song6907ce22018-07-30 19:24:48 +00007179
Fariborz Jahanian11671902012-02-07 17:11:38 +00007180 // For each implemented class, write out all its meta data.
7181 for (int i = 0; i < ClsDefCount; i++)
7182 RewriteObjCClassMetaData(ClassImplementation[i], Result);
Fangrui Song6907ce22018-07-30 19:24:48 +00007183
Fariborz Jahanian5ed21c32012-03-27 18:41:05 +00007184 RewriteClassSetupInitHook(Result);
Fangrui Song6907ce22018-07-30 19:24:48 +00007185
Fariborz Jahanian11671902012-02-07 17:11:38 +00007186 // For each implemented category, write out all its meta data.
7187 for (int i = 0; i < CatDefCount; i++)
7188 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
Fangrui Song6907ce22018-07-30 19:24:48 +00007189
Fariborz Jahanian5ed21c32012-03-27 18:41:05 +00007190 RewriteCategorySetupInitHook(Result);
Fangrui Song6907ce22018-07-30 19:24:48 +00007191
Fariborz Jahaniane7a0c932012-02-17 00:06:14 +00007192 if (ClsDefCount > 0) {
Fariborz Jahanian008dfe22012-03-11 19:41:56 +00007193 if (LangOpts.MicrosoftExt)
7194 Result += "__declspec(allocate(\".objc_classlist$B\")) ";
Fariborz Jahaniane7a0c932012-02-17 00:06:14 +00007195 Result += "static struct _class_t *L_OBJC_LABEL_CLASS_$ [";
7196 Result += llvm::utostr(ClsDefCount); Result += "]";
Fangrui Song6907ce22018-07-30 19:24:48 +00007197 Result +=
Fariborz Jahaniane7a0c932012-02-17 00:06:14 +00007198 " __attribute__((used, section (\"__DATA, __objc_classlist,"
7199 "regular,no_dead_strip\")))= {\n";
7200 for (int i = 0; i < ClsDefCount; i++) {
7201 Result += "\t&OBJC_CLASS_$_";
7202 Result += ClassImplementation[i]->getNameAsString();
7203 Result += ",\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00007204 }
Fariborz Jahaniane7a0c932012-02-17 00:06:14 +00007205 Result += "};\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00007206
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00007207 if (!DefinedNonLazyClasses.empty()) {
7208 if (LangOpts.MicrosoftExt)
7209 Result += "__declspec(allocate(\".objc_nlclslist$B\")) \n";
7210 Result += "static struct _class_t *_OBJC_LABEL_NONLAZY_CLASS_$[] = {\n\t";
7211 for (unsigned i = 0, e = DefinedNonLazyClasses.size(); i < e; i++) {
7212 Result += "\t&OBJC_CLASS_$_"; Result += DefinedNonLazyClasses[i]->getNameAsString();
7213 Result += ",\n";
7214 }
7215 Result += "};\n";
7216 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00007217 }
Fangrui Song6907ce22018-07-30 19:24:48 +00007218
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007219 if (CatDefCount > 0) {
Fariborz Jahanian008dfe22012-03-11 19:41:56 +00007220 if (LangOpts.MicrosoftExt)
7221 Result += "__declspec(allocate(\".objc_catlist$B\")) ";
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007222 Result += "static struct _category_t *L_OBJC_LABEL_CATEGORY_$ [";
7223 Result += llvm::utostr(CatDefCount); Result += "]";
Fangrui Song6907ce22018-07-30 19:24:48 +00007224 Result +=
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007225 " __attribute__((used, section (\"__DATA, __objc_catlist,"
7226 "regular,no_dead_strip\")))= {\n";
7227 for (int i = 0; i < CatDefCount; i++) {
7228 Result += "\t&_OBJC_$_CATEGORY_";
Fangrui Song6907ce22018-07-30 19:24:48 +00007229 Result +=
7230 CategoryImplementation[i]->getClassInterface()->getNameAsString();
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007231 Result += "_$_";
7232 Result += CategoryImplementation[i]->getNameAsString();
7233 Result += ",\n";
7234 }
7235 Result += "};\n";
7236 }
Fangrui Song6907ce22018-07-30 19:24:48 +00007237
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00007238 if (!DefinedNonLazyCategories.empty()) {
7239 if (LangOpts.MicrosoftExt)
7240 Result += "__declspec(allocate(\".objc_nlcatlist$B\")) \n";
7241 Result += "static struct _category_t *_OBJC_LABEL_NONLAZY_CATEGORY_$[] = {\n\t";
7242 for (unsigned i = 0, e = DefinedNonLazyCategories.size(); i < e; i++) {
7243 Result += "\t&_OBJC_$_CATEGORY_";
Fangrui Song6907ce22018-07-30 19:24:48 +00007244 Result +=
7245 DefinedNonLazyCategories[i]->getClassInterface()->getNameAsString();
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00007246 Result += "_$_";
7247 Result += DefinedNonLazyCategories[i]->getNameAsString();
7248 Result += ",\n";
7249 }
7250 Result += "};\n";
7251 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00007252}
7253
Fariborz Jahanianddddca32012-03-14 21:44:09 +00007254void RewriteModernObjC::WriteImageInfo(std::string &Result) {
7255 if (LangOpts.MicrosoftExt)
7256 Result += "__declspec(allocate(\".objc_imageinfo$B\")) \n";
Fangrui Song6907ce22018-07-30 19:24:48 +00007257
Fariborz Jahanianddddca32012-03-14 21:44:09 +00007258 Result += "static struct IMAGE_INFO { unsigned version; unsigned flag; } ";
7259 // version 0, ObjCABI is 2
Fariborz Jahanianb31e3af2012-03-15 17:05:33 +00007260 Result += "_OBJC_IMAGE_INFO = { 0, 2 };\n";
Fariborz Jahanianddddca32012-03-14 21:44:09 +00007261}
7262
Fariborz Jahanian11671902012-02-07 17:11:38 +00007263/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
7264/// implementation.
7265void RewriteModernObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
7266 std::string &Result) {
Fariborz Jahanian45489622012-03-14 18:09:23 +00007267 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanian11671902012-02-07 17:11:38 +00007268 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
7269 // Find category declaration for this implementation.
Douglas Gregor048fbfa2013-01-16 23:00:23 +00007270 ObjCCategoryDecl *CDecl
7271 = ClassDecl->FindCategoryDeclaration(IDecl->getIdentifier());
Fangrui Song6907ce22018-07-30 19:24:48 +00007272
Fariborz Jahanian11671902012-02-07 17:11:38 +00007273 std::string FullCategoryName = ClassDecl->getNameAsString();
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007274 FullCategoryName += "_$_";
7275 FullCategoryName += CDecl->getNameAsString();
Fangrui Song6907ce22018-07-30 19:24:48 +00007276
Fariborz Jahanian11671902012-02-07 17:11:38 +00007277 // Build _objc_method_list for class's instance methods if needed
Aaron Ballmanf26acce2014-03-13 19:50:17 +00007278 SmallVector<ObjCMethodDecl *, 32> InstanceMethods(IDecl->instance_methods());
Fangrui Song6907ce22018-07-30 19:24:48 +00007279
Fariborz Jahanian11671902012-02-07 17:11:38 +00007280 // If any of our property implementations have associated getters or
7281 // setters, produce metadata for them as well.
Aaron Ballmand85eff42014-03-14 15:02:45 +00007282 for (const auto *Prop : IDecl->property_impls()) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00007283 if (Prop->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
Fariborz Jahanian11671902012-02-07 17:11:38 +00007284 continue;
David Blaikie2d7c57e2012-04-30 02:36:29 +00007285 if (!Prop->getPropertyIvarDecl())
Fariborz Jahanian11671902012-02-07 17:11:38 +00007286 continue;
David Blaikie2d7c57e2012-04-30 02:36:29 +00007287 ObjCPropertyDecl *PD = Prop->getPropertyDecl();
Fariborz Jahanian11671902012-02-07 17:11:38 +00007288 if (!PD)
7289 continue;
7290 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
7291 InstanceMethods.push_back(Getter);
7292 if (PD->isReadOnly())
7293 continue;
7294 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
7295 InstanceMethods.push_back(Setter);
7296 }
Fangrui Song6907ce22018-07-30 19:24:48 +00007297
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007298 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
7299 "_OBJC_$_CATEGORY_INSTANCE_METHODS_",
7300 FullCategoryName, true);
Fangrui Song6907ce22018-07-30 19:24:48 +00007301
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00007302 SmallVector<ObjCMethodDecl *, 32> ClassMethods(IDecl->class_methods());
Fangrui Song6907ce22018-07-30 19:24:48 +00007303
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007304 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
7305 "_OBJC_$_CATEGORY_CLASS_METHODS_",
7306 FullCategoryName, true);
Fangrui Song6907ce22018-07-30 19:24:48 +00007307
Fariborz Jahanian11671902012-02-07 17:11:38 +00007308 // Protocols referenced in class declaration?
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007309 // Protocol's super protocol list
Aaron Ballman19a41762014-03-14 12:55:57 +00007310 SmallVector<ObjCProtocolDecl *, 8> RefedProtocols(CDecl->protocols());
7311 for (auto *I : CDecl->protocols())
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007312 // Must write out all protocol definitions in current qualifier list,
7313 // and in their nested qualifiers before writing out current definition.
Aaron Ballman19a41762014-03-14 12:55:57 +00007314 RewriteObjCProtocolMetaData(I, Result);
Fangrui Song6907ce22018-07-30 19:24:48 +00007315
7316 Write_protocol_list_initializer(Context, Result,
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007317 RefedProtocols,
7318 "_OBJC_CATEGORY_PROTOCOLS_$_",
7319 FullCategoryName);
Fangrui Song6907ce22018-07-30 19:24:48 +00007320
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007321 // Protocol's property metadata.
Manman Rena7a8b1f2016-01-26 18:05:23 +00007322 SmallVector<ObjCPropertyDecl *, 8> ClassProperties(
7323 CDecl->instance_properties());
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007324 Write_prop_list_t_initializer(*this, Context, Result, ClassProperties,
Fariborz Jahaniane9863b52012-05-03 23:19:33 +00007325 /* Container */IDecl,
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007326 "_OBJC_$_PROP_LIST_",
7327 FullCategoryName);
Fangrui Song6907ce22018-07-30 19:24:48 +00007328
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007329 Write_category_t(*this, Context, Result,
Fariborz Jahanian5ed21c32012-03-27 18:41:05 +00007330 CDecl,
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00007331 ClassDecl,
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007332 InstanceMethods,
7333 ClassMethods,
7334 RefedProtocols,
7335 ClassProperties);
Fangrui Song6907ce22018-07-30 19:24:48 +00007336
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00007337 // Determine if this category is also "non-lazy".
7338 if (ImplementationIsNonLazy(IDecl))
7339 DefinedNonLazyCategories.push_back(CDecl);
Fariborz Jahanian5ed21c32012-03-27 18:41:05 +00007340}
7341
7342void RewriteModernObjC::RewriteCategorySetupInitHook(std::string &Result) {
7343 int CatDefCount = CategoryImplementation.size();
7344 if (!CatDefCount)
7345 return;
7346 Result += "#pragma section(\".objc_inithooks$B\", long, read, write)\n";
7347 Result += "__declspec(allocate(\".objc_inithooks$B\")) ";
7348 Result += "static void *OBJC_CATEGORY_SETUP[] = {\n";
7349 for (int i = 0; i < CatDefCount; i++) {
7350 ObjCCategoryImplDecl *IDecl = CategoryImplementation[i];
7351 ObjCCategoryDecl *CatDecl= IDecl->getCategoryDecl();
7352 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
7353 Result += "\t(void *)&OBJC_CATEGORY_SETUP_$_";
7354 Result += ClassDecl->getName();
7355 Result += "_$_";
7356 Result += CatDecl->getName();
7357 Result += ",\n";
7358 }
7359 Result += "};\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00007360}
7361
7362// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
7363/// class methods.
7364template<typename MethodIterator>
7365void RewriteModernObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
7366 MethodIterator MethodEnd,
7367 bool IsInstanceMethod,
7368 StringRef prefix,
7369 StringRef ClassName,
7370 std::string &Result) {
7371 if (MethodBegin == MethodEnd) return;
Fangrui Song6907ce22018-07-30 19:24:48 +00007372
Fariborz Jahanian11671902012-02-07 17:11:38 +00007373 if (!objc_impl_method) {
7374 /* struct _objc_method {
7375 SEL _cmd;
7376 char *method_types;
7377 void *_imp;
7378 }
7379 */
7380 Result += "\nstruct _objc_method {\n";
7381 Result += "\tSEL _cmd;\n";
7382 Result += "\tchar *method_types;\n";
7383 Result += "\tvoid *_imp;\n";
7384 Result += "};\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00007385
Fariborz Jahanian11671902012-02-07 17:11:38 +00007386 objc_impl_method = true;
7387 }
Fangrui Song6907ce22018-07-30 19:24:48 +00007388
Fariborz Jahanian11671902012-02-07 17:11:38 +00007389 // Build _objc_method_list for class's methods if needed
Fangrui Song6907ce22018-07-30 19:24:48 +00007390
Fariborz Jahanian11671902012-02-07 17:11:38 +00007391 /* struct {
7392 struct _objc_method_list *next_method;
7393 int method_count;
7394 struct _objc_method method_list[];
7395 }
7396 */
7397 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
Fariborz Jahanian008dfe22012-03-11 19:41:56 +00007398 Result += "\n";
7399 if (LangOpts.MicrosoftExt) {
7400 if (IsInstanceMethod)
7401 Result += "__declspec(allocate(\".inst_meth$B\")) ";
7402 else
7403 Result += "__declspec(allocate(\".cls_meth$B\")) ";
7404 }
7405 Result += "static struct {\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00007406 Result += "\tstruct _objc_method_list *next_method;\n";
7407 Result += "\tint method_count;\n";
7408 Result += "\tstruct _objc_method method_list[";
7409 Result += utostr(NumMethods);
7410 Result += "];\n} _OBJC_";
7411 Result += prefix;
7412 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
7413 Result += "_METHODS_";
7414 Result += ClassName;
7415 Result += " __attribute__ ((used, section (\"__OBJC, __";
7416 Result += IsInstanceMethod ? "inst" : "cls";
7417 Result += "_meth\")))= ";
7418 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00007419
Fariborz Jahanian11671902012-02-07 17:11:38 +00007420 Result += "\t,{{(SEL)\"";
7421 Result += (*MethodBegin)->getSelector().getAsString().c_str();
7422 std::string MethodTypeString;
7423 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
7424 Result += "\", \"";
7425 Result += MethodTypeString;
7426 Result += "\", (void *)";
7427 Result += MethodInternalNames[*MethodBegin];
7428 Result += "}\n";
7429 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
7430 Result += "\t ,{(SEL)\"";
7431 Result += (*MethodBegin)->getSelector().getAsString().c_str();
7432 std::string MethodTypeString;
7433 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
7434 Result += "\", \"";
7435 Result += MethodTypeString;
7436 Result += "\", (void *)";
7437 Result += MethodInternalNames[*MethodBegin];
7438 Result += "}\n";
7439 }
7440 Result += "\t }\n};\n";
7441}
7442
7443Stmt *RewriteModernObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) {
7444 SourceRange OldRange = IV->getSourceRange();
7445 Expr *BaseExpr = IV->getBase();
Fangrui Song6907ce22018-07-30 19:24:48 +00007446
Fariborz Jahanian11671902012-02-07 17:11:38 +00007447 // Rewrite the base, but without actually doing replaces.
7448 {
7449 DisableReplaceStmtScope S(*this);
7450 BaseExpr = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(BaseExpr));
7451 IV->setBase(BaseExpr);
7452 }
Fangrui Song6907ce22018-07-30 19:24:48 +00007453
Fariborz Jahanian11671902012-02-07 17:11:38 +00007454 ObjCIvarDecl *D = IV->getDecl();
Fangrui Song6907ce22018-07-30 19:24:48 +00007455
Fariborz Jahanian11671902012-02-07 17:11:38 +00007456 Expr *Replacement = IV;
Fangrui Song6907ce22018-07-30 19:24:48 +00007457
Fariborz Jahanian11671902012-02-07 17:11:38 +00007458 if (BaseExpr->getType()->isObjCObjectPointerType()) {
7459 const ObjCInterfaceType *iFaceDecl =
Fariborz Jahanian89919cc2012-05-08 23:54:35 +00007460 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
Fariborz Jahanian11671902012-02-07 17:11:38 +00007461 assert(iFaceDecl && "RewriteObjCIvarRefExpr - iFaceDecl is null");
7462 // lookup which class implements the instance variable.
Craig Topper8ae12032014-05-07 06:21:57 +00007463 ObjCInterfaceDecl *clsDeclared = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00007464 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
7465 clsDeclared);
7466 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
Fangrui Song6907ce22018-07-30 19:24:48 +00007467
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007468 // Build name of symbol holding ivar offset.
Fariborz Jahaniana854174a2012-03-20 17:13:39 +00007469 std::string IvarOffsetName;
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00007470 if (D->isBitField())
7471 ObjCIvarBitfieldGroupOffset(D, IvarOffsetName);
7472 else
7473 WriteInternalIvarName(clsDeclared, D, IvarOffsetName);
Fangrui Song6907ce22018-07-30 19:24:48 +00007474
Fariborz Jahanian5e49eb92012-02-22 18:13:25 +00007475 ReferencedIvars[clsDeclared].insert(D);
Fangrui Song6907ce22018-07-30 19:24:48 +00007476
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007477 // cast offset to "char *".
Fangrui Song6907ce22018-07-30 19:24:48 +00007478 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context,
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007479 Context->getPointerType(Context->CharTy),
Fariborz Jahanian11671902012-02-07 17:11:38 +00007480 CK_BitCast,
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007481 BaseExpr);
7482 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
7483 SourceLocation(), &Context->Idents.get(IvarOffsetName),
Craig Topper8ae12032014-05-07 06:21:57 +00007484 Context->UnsignedLongTy, nullptr,
7485 SC_Extern);
Bruno Ricci5fc4db72018-12-21 14:10:18 +00007486 DeclRefExpr *DRE = new (Context)
7487 DeclRefExpr(*Context, NewVD, false, Context->UnsignedLongTy,
7488 VK_LValue, SourceLocation());
Fangrui Song6907ce22018-07-30 19:24:48 +00007489 BinaryOperator *addExpr =
7490 new (Context) BinaryOperator(castExpr, DRE, BO_Add,
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007491 Context->getPointerType(Context->CharTy),
Adam Nemet484aa452017-03-27 19:17:25 +00007492 VK_RValue, OK_Ordinary, SourceLocation(), FPOptions());
Fariborz Jahanian11671902012-02-07 17:11:38 +00007493 // Don't forget the parens to enforce the proper binding.
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007494 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(),
7495 SourceLocation(),
7496 addExpr);
Fariborz Jahaniandd5a59b2012-02-24 17:35:35 +00007497 QualType IvarT = D->getType();
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00007498 if (D->isBitField())
7499 IvarT = GetGroupRecordTypeForObjCIvarBitfield(D);
Fariborz Jahanianbf217c82012-04-27 22:48:54 +00007500
Fariborz Jahaniand7c67772012-05-02 17:34:59 +00007501 if (!isa<TypedefType>(IvarT) && IvarT->isRecordType()) {
Fariborz Jahanianbf217c82012-04-27 22:48:54 +00007502 RecordDecl *RD = IvarT->getAs<RecordType>()->getDecl();
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00007503 RD = RD->getDefinition();
7504 if (RD && !RD->getDeclName().getAsIdentifierInfo()) {
Fariborz Jahanianbf217c82012-04-27 22:48:54 +00007505 // decltype(((Foo_IMPL*)0)->bar) *
Fangrui Song6907ce22018-07-30 19:24:48 +00007506 ObjCContainerDecl *CDecl =
Fariborz Jahaniand7c67772012-05-02 17:34:59 +00007507 dyn_cast<ObjCContainerDecl>(D->getDeclContext());
7508 // ivar in class extensions requires special treatment.
7509 if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(CDecl))
7510 CDecl = CatDecl->getClassInterface();
7511 std::string RecName = CDecl->getName();
Fariborz Jahanianbf217c82012-04-27 22:48:54 +00007512 RecName += "_IMPL";
Malcolm Parsonsf76f6502016-11-02 10:39:27 +00007513 RecordDecl *RD = RecordDecl::Create(
7514 *Context, TTK_Struct, TUDecl, SourceLocation(), SourceLocation(),
7515 &Context->Idents.get(RecName));
Fariborz Jahanianbf217c82012-04-27 22:48:54 +00007516 QualType PtrStructIMPL = Context->getPointerType(Context->getTagDeclType(RD));
Fangrui Song6907ce22018-07-30 19:24:48 +00007517 unsigned UnsignedIntSize =
Fariborz Jahanianbf217c82012-04-27 22:48:54 +00007518 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
7519 Expr *Zero = IntegerLiteral::Create(*Context,
7520 llvm::APInt(UnsignedIntSize, 0),
7521 Context->UnsignedIntTy, SourceLocation());
7522 Zero = NoTypeInfoCStyleCastExpr(Context, PtrStructIMPL, CK_BitCast, Zero);
7523 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
7524 Zero);
Craig Topper8ae12032014-05-07 06:21:57 +00007525 FieldDecl *FD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
Fariborz Jahanianbf217c82012-04-27 22:48:54 +00007526 SourceLocation(),
7527 &Context->Idents.get(D->getNameAsString()),
Fariborz Jahanianf8e68e22015-04-09 18:36:50 +00007528 IvarT, nullptr,
7529 /*BitWidth=*/nullptr,
7530 /*Mutable=*/true, ICIS_NoInit);
7531 MemberExpr *ME = new (Context)
7532 MemberExpr(PE, true, SourceLocation(), FD, SourceLocation(),
7533 FD->getType(), VK_LValue, OK_Ordinary);
7534 IvarT = Context->getDecltypeType(ME, ME->getType());
7535 }
7536 }
Fariborz Jahanian1dc712f2012-02-29 00:26:20 +00007537 convertObjCTypeToCStyleType(IvarT);
Fariborz Jahaniandd5a59b2012-02-24 17:35:35 +00007538 QualType castT = Context->getPointerType(IvarT);
Fangrui Song6907ce22018-07-30 19:24:48 +00007539
7540 castExpr = NoTypeInfoCStyleCastExpr(Context,
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007541 castT,
7542 CK_BitCast,
7543 PE);
Fangrui Song6907ce22018-07-30 19:24:48 +00007544
7545
Fariborz Jahanian1dc712f2012-02-29 00:26:20 +00007546 Expr *Exp = new (Context) UnaryOperator(castExpr, UO_Deref, IvarT,
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007547 VK_LValue, OK_Ordinary,
Aaron Ballmana5038552018-01-09 13:07:03 +00007548 SourceLocation(), false);
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007549 PE = new (Context) ParenExpr(OldRange.getBegin(),
7550 OldRange.getEnd(),
7551 Exp);
Fangrui Song6907ce22018-07-30 19:24:48 +00007552
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00007553 if (D->isBitField()) {
Craig Topper8ae12032014-05-07 06:21:57 +00007554 FieldDecl *FD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00007555 SourceLocation(),
7556 &Context->Idents.get(D->getNameAsString()),
Fariborz Jahanianf8e68e22015-04-09 18:36:50 +00007557 D->getType(), nullptr,
7558 /*BitWidth=*/D->getBitWidth(),
7559 /*Mutable=*/true, ICIS_NoInit);
7560 MemberExpr *ME = new (Context)
7561 MemberExpr(PE, /*isArrow*/ false, SourceLocation(), FD,
7562 SourceLocation(), FD->getType(), VK_LValue, OK_Ordinary);
7563 Replacement = ME;
7564
7565 }
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00007566 else
7567 Replacement = PE;
Fariborz Jahanian11671902012-02-07 17:11:38 +00007568 }
Fangrui Song6907ce22018-07-30 19:24:48 +00007569
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007570 ReplaceStmtWithRange(IV, Replacement, OldRange);
Fangrui Song6907ce22018-07-30 19:24:48 +00007571 return Replacement;
Fariborz Jahanian11671902012-02-07 17:11:38 +00007572}
Alp Toker0621cb22014-07-16 16:48:33 +00007573
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00007574#endif // CLANG_ENABLE_OBJC_REWRITER