blob: 1df73ef9cd69c6877cbaff03422e2836a2669b98 [file] [log] [blame]
Fariborz Jahanian11671902012-02-07 17:11:38 +00001//===--- RewriteObjC.cpp - Playground for the code rewriter ---------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// Hacks and fun related to the code rewriter.
11//
12//===----------------------------------------------------------------------===//
13
Ted Kremenekcdf81492012-09-01 05:09:24 +000014#include "clang/Rewrite/Frontend/ASTConsumers.h"
Fariborz Jahanian11671902012-02-07 17:11:38 +000015#include "clang/AST/AST.h"
16#include "clang/AST/ASTConsumer.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000017#include "clang/AST/Attr.h"
Fariborz Jahanian11671902012-02-07 17:11:38 +000018#include "clang/AST/ParentMap.h"
Jordan Rosea7d03842013-02-08 22:30:41 +000019#include "clang/Basic/CharInfo.h"
Fariborz Jahanian11671902012-02-07 17:11:38 +000020#include "clang/Basic/Diagnostic.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000021#include "clang/Basic/IdentifierTable.h"
22#include "clang/Basic/SourceManager.h"
Benjamin Kramerd7d2b1f2012-12-01 16:35:25 +000023#include "clang/Basic/TargetInfo.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
Alp Toker0621cb22014-07-16 16:48:33 +000033#ifdef CLANG_ENABLE_OBJC_REWRITER
34
Fariborz Jahanian11671902012-02-07 17:11:38 +000035using namespace clang;
36using llvm::utostr;
37
38namespace {
39 class RewriteModernObjC : public ASTConsumer {
40 protected:
41
42 enum {
43 BLOCK_FIELD_IS_OBJECT = 3, /* id, NSObject, __attribute__((NSObject)),
44 block, ... */
45 BLOCK_FIELD_IS_BLOCK = 7, /* a block variable */
46 BLOCK_FIELD_IS_BYREF = 8, /* the on stack structure holding the
47 __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 };
54
55 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 };
Fariborz Jahanian11671902012-02-07 17:11:38 +000063
64 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;
75 raw_ostream* OutFile;
76 std::string Preamble;
77
78 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;
90
91 unsigned TryFinallyContainsReturnDiag;
92 // Needed for super.
93 ObjCMethodDecl *CurMethodDef;
94 RecordDecl *SuperStructDecl;
95 RecordDecl *ConstantStringDecl;
96
97 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;
120
121 /// DefinedNonLazyCategories - List of defined "non-lazy" categories.
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000122 SmallVector<ObjCCategoryDecl *, 8> DefinedNonLazyCategories;
Fariborz Jahanian07a423d2012-03-14 23:18:19 +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;
128
129 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;
Fariborz Jahanian11671902012-02-07 17:11:38 +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;
146
147 llvm::DenseMap<BlockExpr *, std::string> RewrittenBlockExprs;
Fariborz Jahanian5e49eb92012-02-22 18:13:25 +0000148 llvm::DenseMap<ObjCInterfaceDecl *,
149 llvm::SmallPtrSet<ObjCIvarDecl *, 8> > ReferencedIvars;
150
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;
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +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;
169
170 bool DisableReplaceStmt;
171 class DisableReplaceStmtScope {
172 RewriteModernObjC &R;
173 bool SavedValue;
174
175 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 }
239
Fariborz Jahanian11671902012-02-07 17:11:38 +0000240 void HandleTopLevelSingleDecl(Decl *D);
241 void HandleDeclInMainFile(Decl *D);
242 RewriteModernObjC(std::string inFile, raw_ostream *OS,
243 DiagnosticsEngine &D, const LangOptions &LOpts,
Fariborz Jahaniane4c7e852013-02-08 00:27:34 +0000244 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) {
267 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
268 << Old->getSourceRange();
269 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;
284 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
285 << Old->getSourceRange();
286 }
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);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000316 void RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
317 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);
Fariborz Jahanian89919cc2012-05-08 23:54:35 +0000343
344 std::string getIvarAccessString(ObjCIvarDecl *D);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000345
346 // 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);
Fariborz Jahanian08ed8922012-04-03 17:35:38 +0000369 void RewriteLinkageSpec(LinkageSpecDecl *LSD);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000370
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +0000371 // Computes ivar bitfield group no.
372 unsigned ObjCIvarBitfieldGroupNo(ObjCIvarDecl *IV);
373 // Names field decl. for ivar bitfield group.
374 void ObjCIvarBitfieldGroupDecl(ObjCIvarDecl *IV, std::string &Result);
375 // Names struct type for ivar bitfield group.
376 void ObjCIvarBitfieldGroupType(ObjCIvarDecl *IV, std::string &Result);
377 // Names symbol for ivar bitfield group field offset.
378 void ObjCIvarBitfieldGroupOffset(ObjCIvarDecl *IV, std::string &Result);
379 // Given an ivar bitfield, it builds (or finds) its group record type.
380 QualType GetGroupRecordTypeForObjCIvarBitfield(ObjCIvarDecl *IV);
381 QualType SynthesizeBitfieldGroupStructType(
382 ObjCIvarDecl *IV,
383 SmallVectorImpl<ObjCIvarDecl *> &IVars);
384
Fariborz Jahanian11671902012-02-07 17:11:38 +0000385 // Block rewriting.
386 void RewriteBlocksInFunctionProtoType(QualType funcType, NamedDecl *D);
387
388 // Block specific rewrite rules.
389 void RewriteBlockPointerDecl(NamedDecl *VD);
Fariborz Jahanian847713a2012-04-24 19:38:45 +0000390 void RewriteByRefVar(VarDecl *VD, bool firstDecl, bool lastDecl);
John McCall113bee02012-03-10 09:33:50 +0000391 Stmt *RewriteBlockDeclRefExpr(DeclRefExpr *VD);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000392 Stmt *RewriteLocalVariableExternalStorage(DeclRefExpr *DRE);
393 void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
394
395 void RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
396 std::string &Result);
397
Fariborz Jahanian265a4212012-02-28 22:45:07 +0000398 void RewriteObjCFieldDecl(FieldDecl *fieldDecl, std::string &Result);
Fariborz Jahanian144b7222012-05-01 17:46:45 +0000399 bool IsTagDefinedInsideClass(ObjCContainerDecl *IDecl, TagDecl *Tag,
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +0000400 bool &IsNamedDefinition);
401 void RewriteLocallyDefinedNamedAggregates(FieldDecl *fieldDecl,
402 std::string &Result);
Fariborz Jahanian265a4212012-02-28 22:45:07 +0000403
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +0000404 bool RewriteObjCFieldDeclType(QualType &Type, std::string &Result);
405
Fariborz Jahanian5e49eb92012-02-22 18:13:25 +0000406 void RewriteIvarOffsetSymbols(ObjCInterfaceDecl *CDecl,
407 std::string &Result);
Craig Topperfb6b25b2014-03-15 04:29:04 +0000408
409 void Initialize(ASTContext &context) override;
410
Benjamin Kramer474261a2012-06-02 10:20:41 +0000411 // Misc. AST transformation routines. Sometimes they end up calling
Fariborz Jahanian11671902012-02-07 17:11:38 +0000412 // rewriting routines on the new ASTs.
413 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
Craig Toppercf2126e2015-10-22 03:13:07 +0000414 ArrayRef<Expr *> Args,
Fariborz Jahanian11671902012-02-07 17:11:38 +0000415 SourceLocation StartLoc=SourceLocation(),
416 SourceLocation EndLoc=SourceLocation());
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +0000417
418 Expr *SynthMsgSendStretCallExpr(FunctionDecl *MsgSendStretFlavor,
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +0000419 QualType returnType,
420 SmallVectorImpl<QualType> &ArgTypes,
421 SmallVectorImpl<Expr*> &MsgExprs,
422 ObjCMethodDecl *Method);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000423
424 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp,
425 SourceLocation StartLoc=SourceLocation(),
426 SourceLocation EndLoc=SourceLocation());
427
428 void SynthCountByEnumWithState(std::string &buf);
429 void SynthMsgSendFunctionDecl();
430 void SynthMsgSendSuperFunctionDecl();
431 void SynthMsgSendStretFunctionDecl();
432 void SynthMsgSendFpretFunctionDecl();
433 void SynthMsgSendSuperStretFunctionDecl();
434 void SynthGetClassFunctionDecl();
435 void SynthGetMetaClassFunctionDecl();
436 void SynthGetSuperClassFunctionDecl();
437 void SynthSelGetUidFunctionDecl();
Benjamin Kramer60509af2013-09-09 14:48:42 +0000438 void SynthSuperConstructorFunctionDecl();
Fariborz Jahanian11671902012-02-07 17:11:38 +0000439
440 // Rewriting metadata
441 template<typename MethodIterator>
442 void RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
443 MethodIterator MethodEnd,
444 bool IsInstanceMethod,
445 StringRef prefix,
446 StringRef ClassName,
447 std::string &Result);
Fariborz Jahaniane18961b2012-02-08 19:53:58 +0000448 void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
449 std::string &Result);
Fariborz Jahanian95badad2012-04-30 16:57:52 +0000450 void RewriteObjCProtocolListMetaData(
Fariborz Jahanian11671902012-02-07 17:11:38 +0000451 const ObjCList<ObjCProtocolDecl> &Prots,
452 StringRef prefix, StringRef ClassName, std::string &Result);
Fariborz Jahanian95badad2012-04-30 16:57:52 +0000453 void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanian11671902012-02-07 17:11:38 +0000454 std::string &Result);
Fariborz Jahanian95badad2012-04-30 16:57:52 +0000455 void RewriteClassSetupInitHook(std::string &Result);
Fariborz Jahanian5ed21c32012-03-27 18:41:05 +0000456
Fariborz Jahanian95badad2012-04-30 16:57:52 +0000457 void RewriteMetaDataIntoBuffer(std::string &Result);
458 void WriteImageInfo(std::string &Result);
459 void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
Fariborz Jahanian11671902012-02-07 17:11:38 +0000460 std::string &Result);
Fariborz Jahanian95badad2012-04-30 16:57:52 +0000461 void RewriteCategorySetupInitHook(std::string &Result);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000462
463 // Rewriting ivar
Fariborz Jahanian95badad2012-04-30 16:57:52 +0000464 void RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
Fariborz Jahanian11671902012-02-07 17:11:38 +0000465 std::string &Result);
Fariborz Jahanian95badad2012-04-30 16:57:52 +0000466 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000467
468
469 std::string SynthesizeByrefCopyDestroyHelper(VarDecl *VD, int flag);
470 std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
471 StringRef funcName, std::string Tag);
472 std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
473 StringRef funcName, std::string Tag);
474 std::string SynthesizeBlockImpl(BlockExpr *CE,
475 std::string Tag, std::string Desc);
476 std::string SynthesizeBlockDescriptor(std::string DescTag,
477 std::string ImplTag,
478 int i, StringRef funcName,
479 unsigned hasCopy);
480 Stmt *SynthesizeBlockCall(CallExpr *Exp, const Expr* BlockExp);
481 void SynthesizeBlockLiterals(SourceLocation FunLocStart,
482 StringRef FunName);
483 FunctionDecl *SynthBlockInitFunctionDecl(StringRef name);
484 Stmt *SynthBlockInitExpr(BlockExpr *Exp,
Craig Topper5603df42013-07-05 19:34:19 +0000485 const SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000486
487 // Misc. helper routines.
488 QualType getProtocolType();
489 void WarnAboutReturnGotoStmts(Stmt *S);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000490 void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
491 void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
492 void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
493
494 bool IsDeclStmtInForeachHeader(DeclStmt *DS);
495 void CollectBlockDeclRefInfo(BlockExpr *Exp);
496 void GetBlockDeclRefExprs(Stmt *S);
Craig Topper5603df42013-07-05 19:34:19 +0000497 void GetInnerBlockDeclRefExprs(Stmt *S,
498 SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs,
Craig Topper4dd9b432014-08-17 23:49:53 +0000499 llvm::SmallPtrSetImpl<const DeclContext *> &InnerContexts);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000500
501 // We avoid calling Type::isBlockPointerType(), since it operates on the
502 // canonical type. We only care if the top-level type is a closure pointer.
503 bool isTopLevelBlockPointerType(QualType T) {
504 return isa<BlockPointerType>(T);
505 }
506
507 /// convertBlockPointerToFunctionPointer - Converts a block-pointer type
508 /// to a function pointer type and upon success, returns true; false
509 /// otherwise.
510 bool convertBlockPointerToFunctionPointer(QualType &T) {
511 if (isTopLevelBlockPointerType(T)) {
512 const BlockPointerType *BPT = T->getAs<BlockPointerType>();
513 T = Context->getPointerType(BPT->getPointeeType());
514 return true;
515 }
516 return false;
517 }
518
Fariborz Jahanianc3cdc412012-02-13 18:57:49 +0000519 bool convertObjCTypeToCStyleType(QualType &T);
520
Fariborz Jahanian11671902012-02-07 17:11:38 +0000521 bool needToScanForQualifiers(QualType T);
522 QualType getSuperStructType();
523 QualType getConstantStringStructType();
524 QualType convertFunctionTypeOfBlocks(const FunctionType *FT);
525 bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf);
526
527 void convertToUnqualifiedObjCType(QualType &T) {
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +0000528 if (T->isObjCQualifiedIdType()) {
529 bool isConst = T.isConstQualified();
530 T = isConst ? Context->getObjCIdType().withConst()
531 : Context->getObjCIdType();
532 }
Fariborz Jahanian11671902012-02-07 17:11:38 +0000533 else if (T->isObjCQualifiedClassType())
534 T = Context->getObjCClassType();
535 else if (T->isObjCObjectPointerType() &&
536 T->getPointeeType()->isObjCQualifiedInterfaceType()) {
537 if (const ObjCObjectPointerType * OBJPT =
538 T->getAsObjCInterfacePointerType()) {
539 const ObjCInterfaceType *IFaceT = OBJPT->getInterfaceType();
540 T = QualType(IFaceT, 0);
541 T = Context->getPointerType(T);
542 }
543 }
544 }
545
546 // FIXME: This predicate seems like it would be useful to add to ASTContext.
547 bool isObjCType(QualType T) {
548 if (!LangOpts.ObjC1 && !LangOpts.ObjC2)
549 return false;
550
551 QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
552
553 if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
554 OCT == Context->getCanonicalType(Context->getObjCClassType()))
555 return true;
556
557 if (const PointerType *PT = OCT->getAs<PointerType>()) {
558 if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
559 PT->getPointeeType()->isObjCQualifiedIdType())
560 return true;
561 }
562 return false;
563 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000564
Fariborz Jahanian11671902012-02-07 17:11:38 +0000565 bool PointerTypeTakesAnyBlockArguments(QualType QT);
566 bool PointerTypeTakesAnyObjCQualifiedType(QualType QT);
567 void GetExtentOfArgList(const char *Name, const char *&LParen,
568 const char *&RParen);
569
570 void QuoteDoublequotes(std::string &From, std::string &To) {
571 for (unsigned i = 0; i < From.length(); i++) {
572 if (From[i] == '"')
573 To += "\\\"";
574 else
575 To += From[i];
576 }
577 }
578
579 QualType getSimpleFunctionType(QualType result,
Jordan Rose5c382722013-03-08 21:51:21 +0000580 ArrayRef<QualType> args,
Fariborz Jahanian11671902012-02-07 17:11:38 +0000581 bool variadic = false) {
582 if (result == Context->getObjCInstanceType())
583 result = Context->getObjCIdType();
584 FunctionProtoType::ExtProtoInfo fpi;
585 fpi.Variadic = variadic;
Jordan Rose5c382722013-03-08 21:51:21 +0000586 return Context->getFunctionType(result, args, fpi);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000587 }
588
589 // Helper function: create a CStyleCastExpr with trivial type source info.
590 CStyleCastExpr* NoTypeInfoCStyleCastExpr(ASTContext *Ctx, QualType Ty,
591 CastKind Kind, Expr *E) {
592 TypeSourceInfo *TInfo = Ctx->getTrivialTypeSourceInfo(Ty, SourceLocation());
Craig Topper8ae12032014-05-07 06:21:57 +0000593 return CStyleCastExpr::Create(*Ctx, Ty, VK_RValue, Kind, E, nullptr,
594 TInfo, SourceLocation(), SourceLocation());
Fariborz Jahanian11671902012-02-07 17:11:38 +0000595 }
Fariborz Jahanian07a423d2012-03-14 23:18:19 +0000596
597 bool ImplementationIsNonLazy(const ObjCImplDecl *OD) const {
598 IdentifierInfo* II = &Context->Idents.get("load");
599 Selector LoadSel = Context->Selectors.getSelector(0, &II);
Craig Topper8ae12032014-05-07 06:21:57 +0000600 return OD->getClassMethod(LoadSel) != nullptr;
Fariborz Jahanian07a423d2012-03-14 23:18:19 +0000601 }
Benjamin Kramerfc188422014-02-25 12:26:11 +0000602
603 StringLiteral *getStringLiteral(StringRef Str) {
604 QualType StrType = Context->getConstantArrayType(
605 Context->CharTy, llvm::APInt(32, Str.size() + 1), ArrayType::Normal,
606 0);
607 return StringLiteral::Create(*Context, Str, StringLiteral::Ascii,
608 /*Pascal=*/false, StrType, SourceLocation());
609 }
Fariborz Jahanian11671902012-02-07 17:11:38 +0000610 };
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000611} // end anonymous namespace
Fariborz Jahanian11671902012-02-07 17:11:38 +0000612
613void RewriteModernObjC::RewriteBlocksInFunctionProtoType(QualType funcType,
614 NamedDecl *D) {
615 if (const FunctionProtoType *fproto
616 = dyn_cast<FunctionProtoType>(funcType.IgnoreParens())) {
Aaron Ballman40bd0aa2014-03-17 15:23:01 +0000617 for (const auto &I : fproto->param_types())
618 if (isTopLevelBlockPointerType(I)) {
Fariborz Jahanian11671902012-02-07 17:11:38 +0000619 // All the args are checked/rewritten. Don't call twice!
620 RewriteBlockPointerDecl(D);
621 break;
622 }
623 }
624}
625
626void RewriteModernObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
627 const PointerType *PT = funcType->getAs<PointerType>();
628 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
629 RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND);
630}
631
632static bool IsHeaderFile(const std::string &Filename) {
633 std::string::size_type DotPos = Filename.rfind('.');
634
635 if (DotPos == std::string::npos) {
636 // no file extension
637 return false;
638 }
639
640 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
641 // C header: .h
642 // C++ header: .hh or .H;
643 return Ext == "h" || Ext == "hh" || Ext == "H";
644}
645
646RewriteModernObjC::RewriteModernObjC(std::string inFile, raw_ostream* OS,
647 DiagnosticsEngine &D, const LangOptions &LOpts,
Fariborz Jahaniane4c7e852013-02-08 00:27:34 +0000648 bool silenceMacroWarn,
649 bool LineInfo)
Fariborz Jahanian11671902012-02-07 17:11:38 +0000650 : Diags(D), LangOpts(LOpts), InFileName(inFile), OutFile(OS),
Fariborz Jahaniane4c7e852013-02-08 00:27:34 +0000651 SilenceRewriteMacroWarning(silenceMacroWarn), GenerateLineInfo(LineInfo) {
Fariborz Jahanian11671902012-02-07 17:11:38 +0000652 IsHeader = IsHeaderFile(inFile);
653 RewriteFailedDiag = Diags.getCustomDiagID(DiagnosticsEngine::Warning,
654 "rewriting sub-expression within a macro (may not be correct)");
Fariborz Jahanianbdf975e2012-03-22 19:54:39 +0000655 // FIXME. This should be an error. But if block is not called, it is OK. And it
656 // may break including some headers.
657 GlobalBlockRewriteFailedDiag = Diags.getCustomDiagID(DiagnosticsEngine::Warning,
658 "rewriting block literal declared in global scope is not implemented");
659
Fariborz Jahanian11671902012-02-07 17:11:38 +0000660 TryFinallyContainsReturnDiag = Diags.getCustomDiagID(
661 DiagnosticsEngine::Warning,
662 "rewriter doesn't support user-specified control flow semantics "
663 "for @try/@finally (code may not execute properly)");
664}
665
David Blaikie6beb6aa2014-08-10 19:56:51 +0000666std::unique_ptr<ASTConsumer> clang::CreateModernObjCRewriter(
667 const std::string &InFile, raw_ostream *OS, DiagnosticsEngine &Diags,
668 const LangOptions &LOpts, bool SilenceRewriteMacroWarning, bool LineInfo) {
669 return llvm::make_unique<RewriteModernObjC>(
670 InFile, OS, Diags, LOpts, SilenceRewriteMacroWarning, LineInfo);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000671}
672
673void RewriteModernObjC::InitializeCommon(ASTContext &context) {
674 Context = &context;
675 SM = &Context->getSourceManager();
676 TUDecl = Context->getTranslationUnitDecl();
Craig Topper8ae12032014-05-07 06:21:57 +0000677 MsgSendFunctionDecl = nullptr;
678 MsgSendSuperFunctionDecl = nullptr;
679 MsgSendStretFunctionDecl = nullptr;
680 MsgSendSuperStretFunctionDecl = nullptr;
681 MsgSendFpretFunctionDecl = nullptr;
682 GetClassFunctionDecl = nullptr;
683 GetMetaClassFunctionDecl = nullptr;
684 GetSuperClassFunctionDecl = nullptr;
685 SelGetUidFunctionDecl = nullptr;
686 CFStringFunctionDecl = nullptr;
687 ConstantStringClassReference = nullptr;
688 NSStringRecord = nullptr;
689 CurMethodDef = nullptr;
690 CurFunctionDef = nullptr;
691 GlobalVarDecl = nullptr;
692 GlobalConstructionExp = nullptr;
693 SuperStructDecl = nullptr;
694 ProtocolTypeDecl = nullptr;
695 ConstantStringDecl = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +0000696 BcLabelCount = 0;
Craig Topper8ae12032014-05-07 06:21:57 +0000697 SuperConstructorFunctionDecl = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +0000698 NumObjCStringLiterals = 0;
Craig Topper8ae12032014-05-07 06:21:57 +0000699 PropParentMap = nullptr;
700 CurrentBody = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +0000701 DisableReplaceStmt = false;
702 objc_impl_method = false;
703
704 // Get the ID and start/end of the main file.
705 MainFileID = SM->getMainFileID();
706 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
707 MainFileStart = MainBuf->getBufferStart();
708 MainFileEnd = MainBuf->getBufferEnd();
709
David Blaikiebbafb8a2012-03-11 07:00:24 +0000710 Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOpts());
Fariborz Jahanian11671902012-02-07 17:11:38 +0000711}
712
713//===----------------------------------------------------------------------===//
714// Top Level Driver Code
715//===----------------------------------------------------------------------===//
716
717void RewriteModernObjC::HandleTopLevelSingleDecl(Decl *D) {
718 if (Diags.hasErrorOccurred())
719 return;
720
721 // Two cases: either the decl could be in the main file, or it could be in a
722 // #included file. If the former, rewrite it now. If the later, check to see
723 // if we rewrote the #include/#import.
724 SourceLocation Loc = D->getLocation();
725 Loc = SM->getExpansionLoc(Loc);
726
727 // If this is for a builtin, ignore it.
728 if (Loc.isInvalid()) return;
729
730 // Look for built-in declarations that we need to refer during the rewrite.
731 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
732 RewriteFunctionDecl(FD);
733 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
734 // declared in <Foundation/NSString.h>
735 if (FVD->getName() == "_NSConstantStringClassReference") {
736 ConstantStringClassReference = FVD;
737 return;
738 }
Fariborz Jahanian11671902012-02-07 17:11:38 +0000739 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
740 RewriteCategoryDecl(CD);
741 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
742 if (PD->isThisDeclarationADefinition())
743 RewriteProtocolDecl(PD);
744 } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) {
Fariborz Jahanianf264d5d2012-04-04 17:16:15 +0000745 // FIXME. This will not work in all situations and leaving it out
746 // is harmless.
747 // RewriteLinkageSpec(LSD);
748
Fariborz Jahanian11671902012-02-07 17:11:38 +0000749 // Recurse into linkage specifications
750 for (DeclContext::decl_iterator DI = LSD->decls_begin(),
751 DIEnd = LSD->decls_end();
752 DI != DIEnd; ) {
753 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>((*DI))) {
754 if (!IFace->isThisDeclarationADefinition()) {
755 SmallVector<Decl *, 8> DG;
756 SourceLocation StartLoc = IFace->getLocStart();
757 do {
758 if (isa<ObjCInterfaceDecl>(*DI) &&
759 !cast<ObjCInterfaceDecl>(*DI)->isThisDeclarationADefinition() &&
760 StartLoc == (*DI)->getLocStart())
761 DG.push_back(*DI);
762 else
763 break;
764
765 ++DI;
766 } while (DI != DIEnd);
767 RewriteForwardClassDecl(DG);
768 continue;
769 }
Fariborz Jahanian08ed8922012-04-03 17:35:38 +0000770 else {
771 // Keep track of all interface declarations seen.
772 ObjCInterfacesSeen.push_back(IFace);
773 ++DI;
774 continue;
775 }
Fariborz Jahanian11671902012-02-07 17:11:38 +0000776 }
777
778 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>((*DI))) {
779 if (!Proto->isThisDeclarationADefinition()) {
780 SmallVector<Decl *, 8> DG;
781 SourceLocation StartLoc = Proto->getLocStart();
782 do {
783 if (isa<ObjCProtocolDecl>(*DI) &&
784 !cast<ObjCProtocolDecl>(*DI)->isThisDeclarationADefinition() &&
785 StartLoc == (*DI)->getLocStart())
786 DG.push_back(*DI);
787 else
788 break;
789
790 ++DI;
791 } while (DI != DIEnd);
792 RewriteForwardProtocolDecl(DG);
793 continue;
794 }
795 }
796
797 HandleTopLevelSingleDecl(*DI);
798 ++DI;
799 }
800 }
801 // If we have a decl in the main file, see if we should rewrite it.
Eli Friedman5ba37d52013-08-22 00:27:10 +0000802 if (SM->isWrittenInMainFile(Loc))
Fariborz Jahanian11671902012-02-07 17:11:38 +0000803 return HandleDeclInMainFile(D);
804}
805
806//===----------------------------------------------------------------------===//
807// Syntactic (non-AST) Rewriting Code
808//===----------------------------------------------------------------------===//
809
810void RewriteModernObjC::RewriteInclude() {
811 SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID);
812 StringRef MainBuf = SM->getBufferData(MainFileID);
813 const char *MainBufStart = MainBuf.begin();
814 const char *MainBufEnd = MainBuf.end();
815 size_t ImportLen = strlen("import");
816
817 // Loop over the whole file, looking for includes.
818 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
819 if (*BufPtr == '#') {
820 if (++BufPtr == MainBufEnd)
821 return;
822 while (*BufPtr == ' ' || *BufPtr == '\t')
823 if (++BufPtr == MainBufEnd)
824 return;
825 if (!strncmp(BufPtr, "import", ImportLen)) {
826 // replace import with include
827 SourceLocation ImportLoc =
828 LocStart.getLocWithOffset(BufPtr-MainBufStart);
829 ReplaceText(ImportLoc, ImportLen, "include");
830 BufPtr += ImportLen;
831 }
832 }
833 }
834}
835
Fariborz Jahanian89919cc2012-05-08 23:54:35 +0000836static void WriteInternalIvarName(const ObjCInterfaceDecl *IDecl,
837 ObjCIvarDecl *IvarDecl, std::string &Result) {
838 Result += "OBJC_IVAR_$_";
839 Result += IDecl->getName();
840 Result += "$";
841 Result += IvarDecl->getName();
842}
843
844std::string
845RewriteModernObjC::getIvarAccessString(ObjCIvarDecl *D) {
846 const ObjCInterfaceDecl *ClassDecl = D->getContainingInterface();
847
848 // Build name of symbol holding ivar offset.
849 std::string IvarOffsetName;
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +0000850 if (D->isBitField())
851 ObjCIvarBitfieldGroupOffset(D, IvarOffsetName);
852 else
853 WriteInternalIvarName(ClassDecl, D, IvarOffsetName);
Fariborz Jahanian89919cc2012-05-08 23:54:35 +0000854
Fariborz Jahanian89919cc2012-05-08 23:54:35 +0000855 std::string S = "(*(";
856 QualType IvarT = D->getType();
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +0000857 if (D->isBitField())
858 IvarT = GetGroupRecordTypeForObjCIvarBitfield(D);
Fariborz Jahanian89919cc2012-05-08 23:54:35 +0000859
860 if (!isa<TypedefType>(IvarT) && IvarT->isRecordType()) {
861 RecordDecl *RD = IvarT->getAs<RecordType>()->getDecl();
862 RD = RD->getDefinition();
863 if (RD && !RD->getDeclName().getAsIdentifierInfo()) {
864 // decltype(((Foo_IMPL*)0)->bar) *
865 ObjCContainerDecl *CDecl =
866 dyn_cast<ObjCContainerDecl>(D->getDeclContext());
867 // ivar in class extensions requires special treatment.
868 if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(CDecl))
869 CDecl = CatDecl->getClassInterface();
870 std::string RecName = CDecl->getName();
871 RecName += "_IMPL";
872 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
873 SourceLocation(), SourceLocation(),
874 &Context->Idents.get(RecName.c_str()));
875 QualType PtrStructIMPL = Context->getPointerType(Context->getTagDeclType(RD));
876 unsigned UnsignedIntSize =
877 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
878 Expr *Zero = IntegerLiteral::Create(*Context,
879 llvm::APInt(UnsignedIntSize, 0),
880 Context->UnsignedIntTy, SourceLocation());
881 Zero = NoTypeInfoCStyleCastExpr(Context, PtrStructIMPL, CK_BitCast, Zero);
882 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
883 Zero);
Craig Topper8ae12032014-05-07 06:21:57 +0000884 FieldDecl *FD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
Fariborz Jahanian89919cc2012-05-08 23:54:35 +0000885 SourceLocation(),
886 &Context->Idents.get(D->getNameAsString()),
Fariborz Jahanianf8e68e22015-04-09 18:36:50 +0000887 IvarT, nullptr,
888 /*BitWidth=*/nullptr, /*Mutable=*/true,
889 ICIS_NoInit);
890 MemberExpr *ME = new (Context)
891 MemberExpr(PE, true, SourceLocation(), FD, SourceLocation(),
892 FD->getType(), VK_LValue, OK_Ordinary);
893 IvarT = Context->getDecltypeType(ME, ME->getType());
894 }
895 }
Fariborz Jahanian89919cc2012-05-08 23:54:35 +0000896 convertObjCTypeToCStyleType(IvarT);
897 QualType castT = Context->getPointerType(IvarT);
898 std::string TypeString(castT.getAsString(Context->getPrintingPolicy()));
899 S += TypeString;
900 S += ")";
901
902 // ((char *)self + IVAR_OFFSET_SYMBOL_NAME)
903 S += "((char *)self + ";
904 S += IvarOffsetName;
905 S += "))";
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +0000906 if (D->isBitField()) {
907 S += ".";
908 S += D->getNameAsString();
909 }
Fariborz Jahanian89919cc2012-05-08 23:54:35 +0000910 ReferencedIvars[const_cast<ObjCInterfaceDecl *>(ClassDecl)].insert(D);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000911 return S;
912}
913
Fariborz Jahanianf687e7b2012-05-03 22:52:13 +0000914/// mustSynthesizeSetterGetterMethod - returns true if setter or getter has not
915/// been found in the class implementation. In this case, it must be synthesized.
916static bool mustSynthesizeSetterGetterMethod(ObjCImplementationDecl *IMP,
917 ObjCPropertyDecl *PD,
918 bool getter) {
919 return getter ? !IMP->getInstanceMethod(PD->getGetterName())
920 : !IMP->getInstanceMethod(PD->getSetterName());
921
922}
923
Fariborz Jahanian11671902012-02-07 17:11:38 +0000924void RewriteModernObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
925 ObjCImplementationDecl *IMD,
926 ObjCCategoryImplDecl *CID) {
927 static bool objcGetPropertyDefined = false;
928 static bool objcSetPropertyDefined = false;
Fariborz Jahanianf687e7b2012-05-03 22:52:13 +0000929 SourceLocation startGetterSetterLoc;
930
931 if (PID->getLocStart().isValid()) {
932 SourceLocation startLoc = PID->getLocStart();
933 InsertText(startLoc, "// ");
934 const char *startBuf = SM->getCharacterData(startLoc);
935 assert((*startBuf == '@') && "bogus @synthesize location");
936 const char *semiBuf = strchr(startBuf, ';');
937 assert((*semiBuf == ';') && "@synthesize: can't find ';'");
938 startGetterSetterLoc = startLoc.getLocWithOffset(semiBuf-startBuf+1);
939 }
940 else
941 startGetterSetterLoc = IMD ? IMD->getLocEnd() : CID->getLocEnd();
Fariborz Jahanian11671902012-02-07 17:11:38 +0000942
943 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
944 return; // FIXME: is this correct?
945
946 // Generate the 'getter' function.
947 ObjCPropertyDecl *PD = PID->getPropertyDecl();
948 ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
Jordan Rose755a2ff2013-03-15 21:41:35 +0000949 assert(IMD && OID && "Synthesized ivars must be attached to @implementation");
Fariborz Jahanian11671902012-02-07 17:11:38 +0000950
Bill Wendling44426052012-12-20 19:22:21 +0000951 unsigned Attributes = PD->getPropertyAttributes();
Fariborz Jahanianf687e7b2012-05-03 22:52:13 +0000952 if (mustSynthesizeSetterGetterMethod(IMD, PD, true /*getter*/)) {
Bill Wendling44426052012-12-20 19:22:21 +0000953 bool GenGetProperty = !(Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic) &&
954 (Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
Fariborz Jahanian11671902012-02-07 17:11:38 +0000955 ObjCPropertyDecl::OBJC_PR_copy));
956 std::string Getr;
957 if (GenGetProperty && !objcGetPropertyDefined) {
958 objcGetPropertyDefined = true;
959 // FIXME. Is this attribute correct in all cases?
960 Getr = "\nextern \"C\" __declspec(dllimport) "
961 "id objc_getProperty(id, SEL, long, bool);\n";
962 }
963 RewriteObjCMethodDecl(OID->getContainingInterface(),
964 PD->getGetterMethodDecl(), Getr);
965 Getr += "{ ";
966 // Synthesize an explicit cast to gain access to the ivar.
967 // See objc-act.c:objc_synthesize_new_getter() for details.
968 if (GenGetProperty) {
969 // return objc_getProperty(self, _cmd, offsetof(ClassDecl, OID), 1)
970 Getr += "typedef ";
Craig Topper8ae12032014-05-07 06:21:57 +0000971 const FunctionType *FPRetType = nullptr;
Alp Toker314cc812014-01-25 16:55:45 +0000972 RewriteTypeIntoString(PD->getGetterMethodDecl()->getReturnType(), Getr,
Fariborz Jahanian11671902012-02-07 17:11:38 +0000973 FPRetType);
974 Getr += " _TYPE";
975 if (FPRetType) {
976 Getr += ")"; // close the precedence "scope" for "*".
977
978 // Now, emit the argument types (if any).
979 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)){
980 Getr += "(";
Alp Toker9cacbab2014-01-20 20:26:09 +0000981 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
Fariborz Jahanian11671902012-02-07 17:11:38 +0000982 if (i) Getr += ", ";
Alp Toker9cacbab2014-01-20 20:26:09 +0000983 std::string ParamStr =
984 FT->getParamType(i).getAsString(Context->getPrintingPolicy());
Fariborz Jahanian11671902012-02-07 17:11:38 +0000985 Getr += ParamStr;
986 }
987 if (FT->isVariadic()) {
Alp Toker9cacbab2014-01-20 20:26:09 +0000988 if (FT->getNumParams())
989 Getr += ", ";
Fariborz Jahanian11671902012-02-07 17:11:38 +0000990 Getr += "...";
991 }
992 Getr += ")";
993 } else
994 Getr += "()";
995 }
996 Getr += ";\n";
997 Getr += "return (_TYPE)";
998 Getr += "objc_getProperty(self, _cmd, ";
999 RewriteIvarOffsetComputation(OID, Getr);
1000 Getr += ", 1)";
1001 }
1002 else
1003 Getr += "return " + getIvarAccessString(OID);
1004 Getr += "; }";
Fariborz Jahanianf687e7b2012-05-03 22:52:13 +00001005 InsertText(startGetterSetterLoc, Getr);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001006 }
1007
Fariborz Jahanianf687e7b2012-05-03 22:52:13 +00001008 if (PD->isReadOnly() ||
1009 !mustSynthesizeSetterGetterMethod(IMD, PD, false /*setter*/))
Fariborz Jahanian11671902012-02-07 17:11:38 +00001010 return;
1011
1012 // Generate the 'setter' function.
1013 std::string Setr;
Bill Wendling44426052012-12-20 19:22:21 +00001014 bool GenSetProperty = Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
Fariborz Jahanian11671902012-02-07 17:11:38 +00001015 ObjCPropertyDecl::OBJC_PR_copy);
1016 if (GenSetProperty && !objcSetPropertyDefined) {
1017 objcSetPropertyDefined = true;
1018 // FIXME. Is this attribute correct in all cases?
1019 Setr = "\nextern \"C\" __declspec(dllimport) "
1020 "void objc_setProperty (id, SEL, long, id, bool, bool);\n";
1021 }
1022
1023 RewriteObjCMethodDecl(OID->getContainingInterface(),
1024 PD->getSetterMethodDecl(), Setr);
1025 Setr += "{ ";
1026 // Synthesize an explicit cast to initialize the ivar.
1027 // See objc-act.c:objc_synthesize_new_setter() for details.
1028 if (GenSetProperty) {
1029 Setr += "objc_setProperty (self, _cmd, ";
1030 RewriteIvarOffsetComputation(OID, Setr);
1031 Setr += ", (id)";
1032 Setr += PD->getName();
1033 Setr += ", ";
Bill Wendling44426052012-12-20 19:22:21 +00001034 if (Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic)
Fariborz Jahanian11671902012-02-07 17:11:38 +00001035 Setr += "0, ";
1036 else
1037 Setr += "1, ";
Bill Wendling44426052012-12-20 19:22:21 +00001038 if (Attributes & ObjCPropertyDecl::OBJC_PR_copy)
Fariborz Jahanian11671902012-02-07 17:11:38 +00001039 Setr += "1)";
1040 else
1041 Setr += "0)";
1042 }
1043 else {
1044 Setr += getIvarAccessString(OID) + " = ";
1045 Setr += PD->getName();
1046 }
Fariborz Jahanianf687e7b2012-05-03 22:52:13 +00001047 Setr += "; }\n";
1048 InsertText(startGetterSetterLoc, Setr);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001049}
1050
1051static void RewriteOneForwardClassDecl(ObjCInterfaceDecl *ForwardDecl,
1052 std::string &typedefString) {
Fariborz Jahaniane8730a32013-02-08 17:15:07 +00001053 typedefString += "\n#ifndef _REWRITER_typedef_";
Fariborz Jahanian11671902012-02-07 17:11:38 +00001054 typedefString += ForwardDecl->getNameAsString();
1055 typedefString += "\n";
1056 typedefString += "#define _REWRITER_typedef_";
1057 typedefString += ForwardDecl->getNameAsString();
1058 typedefString += "\n";
1059 typedefString += "typedef struct objc_object ";
1060 typedefString += ForwardDecl->getNameAsString();
Fariborz Jahanian2cc29af2012-03-12 23:58:28 +00001061 // typedef struct { } _objc_exc_Classname;
1062 typedefString += ";\ntypedef struct {} _objc_exc_";
1063 typedefString += ForwardDecl->getNameAsString();
Fariborz Jahanian11671902012-02-07 17:11:38 +00001064 typedefString += ";\n#endif\n";
1065}
1066
1067void RewriteModernObjC::RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
1068 const std::string &typedefString) {
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00001069 SourceLocation startLoc = ClassDecl->getLocStart();
1070 const char *startBuf = SM->getCharacterData(startLoc);
1071 const char *semiPtr = strchr(startBuf, ';');
1072 // Replace the @class with typedefs corresponding to the classes.
1073 ReplaceText(startLoc, semiPtr-startBuf+1, typedefString);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001074}
1075
1076void RewriteModernObjC::RewriteForwardClassDecl(DeclGroupRef D) {
1077 std::string typedefString;
1078 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
Fariborz Jahanian0dded8a2013-09-24 17:03:07 +00001079 if (ObjCInterfaceDecl *ForwardDecl = dyn_cast<ObjCInterfaceDecl>(*I)) {
1080 if (I == D.begin()) {
1081 // Translate to typedef's that forward reference structs with the same name
1082 // as the class. As a convenience, we include the original declaration
1083 // as a comment.
1084 typedefString += "// @class ";
1085 typedefString += ForwardDecl->getNameAsString();
1086 typedefString += ";";
1087 }
1088 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001089 }
Fariborz Jahanian0dded8a2013-09-24 17:03:07 +00001090 else
1091 HandleTopLevelSingleDecl(*I);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001092 }
1093 DeclGroupRef::iterator I = D.begin();
1094 RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(*I), typedefString);
1095}
1096
1097void RewriteModernObjC::RewriteForwardClassDecl(
Craig Topper5603df42013-07-05 19:34:19 +00001098 const SmallVectorImpl<Decl *> &D) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00001099 std::string typedefString;
1100 for (unsigned i = 0; i < D.size(); i++) {
1101 ObjCInterfaceDecl *ForwardDecl = cast<ObjCInterfaceDecl>(D[i]);
1102 if (i == 0) {
1103 typedefString += "// @class ";
1104 typedefString += ForwardDecl->getNameAsString();
Fariborz Jahaniane8730a32013-02-08 17:15:07 +00001105 typedefString += ";";
Fariborz Jahanian11671902012-02-07 17:11:38 +00001106 }
1107 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
1108 }
1109 RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(D[0]), typedefString);
1110}
1111
1112void RewriteModernObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
1113 // When method is a synthesized one, such as a getter/setter there is
1114 // nothing to rewrite.
1115 if (Method->isImplicit())
1116 return;
1117 SourceLocation LocStart = Method->getLocStart();
1118 SourceLocation LocEnd = Method->getLocEnd();
1119
1120 if (SM->getExpansionLineNumber(LocEnd) >
1121 SM->getExpansionLineNumber(LocStart)) {
1122 InsertText(LocStart, "#if 0\n");
1123 ReplaceText(LocEnd, 1, ";\n#endif\n");
1124 } else {
1125 InsertText(LocStart, "// ");
1126 }
1127}
1128
1129void RewriteModernObjC::RewriteProperty(ObjCPropertyDecl *prop) {
1130 SourceLocation Loc = prop->getAtLoc();
1131
1132 ReplaceText(Loc, 0, "// ");
1133 // FIXME: handle properties that are declared across multiple lines.
1134}
1135
1136void RewriteModernObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
1137 SourceLocation LocStart = CatDecl->getLocStart();
1138
1139 // FIXME: handle category headers that are declared across multiple lines.
Fariborz Jahanian144b7222012-05-01 17:46:45 +00001140 if (CatDecl->getIvarRBraceLoc().isValid()) {
1141 ReplaceText(LocStart, 1, "/** ");
1142 ReplaceText(CatDecl->getIvarRBraceLoc(), 1, "**/ ");
1143 }
1144 else {
Fariborz Jahanian2b383d212012-02-19 19:00:05 +00001145 ReplaceText(LocStart, 0, "// ");
Fariborz Jahanian144b7222012-05-01 17:46:45 +00001146 }
Fariborz Jahaniana7765fe2012-02-20 20:09:20 +00001147
Manman Rena7a8b1f2016-01-26 18:05:23 +00001148 for (auto *I : CatDecl->instance_properties())
Aaron Ballmandc4bea42014-03-13 18:47:37 +00001149 RewriteProperty(I);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001150
Aaron Ballmanf26acce2014-03-13 19:50:17 +00001151 for (auto *I : CatDecl->instance_methods())
1152 RewriteMethodDeclaration(I);
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00001153 for (auto *I : CatDecl->class_methods())
1154 RewriteMethodDeclaration(I);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001155
1156 // Lastly, comment out the @end.
1157 ReplaceText(CatDecl->getAtEndRange().getBegin(),
Fariborz Jahanian3a65ce32013-04-03 19:11:21 +00001158 strlen("@end"), "/* @end */\n");
Fariborz Jahanian11671902012-02-07 17:11:38 +00001159}
1160
1161void RewriteModernObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
1162 SourceLocation LocStart = PDecl->getLocStart();
1163 assert(PDecl->isThisDeclarationADefinition());
1164
1165 // FIXME: handle protocol headers that are declared across multiple lines.
1166 ReplaceText(LocStart, 0, "// ");
1167
Aaron Ballmanf26acce2014-03-13 19:50:17 +00001168 for (auto *I : PDecl->instance_methods())
1169 RewriteMethodDeclaration(I);
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00001170 for (auto *I : PDecl->class_methods())
1171 RewriteMethodDeclaration(I);
Manman Rena7a8b1f2016-01-26 18:05:23 +00001172 for (auto *I : PDecl->instance_properties())
Aaron Ballmandc4bea42014-03-13 18:47:37 +00001173 RewriteProperty(I);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001174
1175 // Lastly, comment out the @end.
1176 SourceLocation LocEnd = PDecl->getAtEndRange().getBegin();
Fariborz Jahanian3a65ce32013-04-03 19:11:21 +00001177 ReplaceText(LocEnd, strlen("@end"), "/* @end */\n");
Fariborz Jahanian11671902012-02-07 17:11:38 +00001178
1179 // Must comment out @optional/@required
1180 const char *startBuf = SM->getCharacterData(LocStart);
1181 const char *endBuf = SM->getCharacterData(LocEnd);
1182 for (const char *p = startBuf; p < endBuf; p++) {
1183 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
1184 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
1185 ReplaceText(OptionalLoc, strlen("@optional"), "/* @optional */");
1186
1187 }
1188 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
1189 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
1190 ReplaceText(OptionalLoc, strlen("@required"), "/* @required */");
1191
1192 }
1193 }
1194}
1195
1196void RewriteModernObjC::RewriteForwardProtocolDecl(DeclGroupRef D) {
1197 SourceLocation LocStart = (*D.begin())->getLocStart();
1198 if (LocStart.isInvalid())
1199 llvm_unreachable("Invalid SourceLocation");
1200 // FIXME: handle forward protocol that are declared across multiple lines.
1201 ReplaceText(LocStart, 0, "// ");
1202}
1203
1204void
Craig Topper5603df42013-07-05 19:34:19 +00001205RewriteModernObjC::RewriteForwardProtocolDecl(const SmallVectorImpl<Decl *> &DG) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00001206 SourceLocation LocStart = DG[0]->getLocStart();
1207 if (LocStart.isInvalid())
1208 llvm_unreachable("Invalid SourceLocation");
1209 // FIXME: handle forward protocol that are declared across multiple lines.
1210 ReplaceText(LocStart, 0, "// ");
1211}
1212
Fariborz Jahanian08ed8922012-04-03 17:35:38 +00001213void
1214RewriteModernObjC::RewriteLinkageSpec(LinkageSpecDecl *LSD) {
1215 SourceLocation LocStart = LSD->getExternLoc();
1216 if (LocStart.isInvalid())
1217 llvm_unreachable("Invalid extern SourceLocation");
1218
1219 ReplaceText(LocStart, 0, "// ");
1220 if (!LSD->hasBraces())
1221 return;
1222 // FIXME. We don't rewrite well if '{' is not on same line as 'extern'.
1223 SourceLocation LocRBrace = LSD->getRBraceLoc();
1224 if (LocRBrace.isInvalid())
1225 llvm_unreachable("Invalid rbrace SourceLocation");
1226 ReplaceText(LocRBrace, 0, "// ");
1227}
1228
Fariborz Jahanian11671902012-02-07 17:11:38 +00001229void RewriteModernObjC::RewriteTypeIntoString(QualType T, std::string &ResultStr,
1230 const FunctionType *&FPRetType) {
1231 if (T->isObjCQualifiedIdType())
1232 ResultStr += "id";
1233 else if (T->isFunctionPointerType() ||
1234 T->isBlockPointerType()) {
1235 // needs special handling, since pointer-to-functions have special
1236 // syntax (where a decaration models use).
1237 QualType retType = T;
1238 QualType PointeeTy;
1239 if (const PointerType* PT = retType->getAs<PointerType>())
1240 PointeeTy = PT->getPointeeType();
1241 else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>())
1242 PointeeTy = BPT->getPointeeType();
1243 if ((FPRetType = PointeeTy->getAs<FunctionType>())) {
Alp Toker314cc812014-01-25 16:55:45 +00001244 ResultStr +=
1245 FPRetType->getReturnType().getAsString(Context->getPrintingPolicy());
Fariborz Jahanian11671902012-02-07 17:11:38 +00001246 ResultStr += "(*";
1247 }
1248 } else
1249 ResultStr += T.getAsString(Context->getPrintingPolicy());
1250}
1251
1252void RewriteModernObjC::RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
1253 ObjCMethodDecl *OMD,
1254 std::string &ResultStr) {
1255 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
Craig Topper8ae12032014-05-07 06:21:57 +00001256 const FunctionType *FPRetType = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00001257 ResultStr += "\nstatic ";
Alp Toker314cc812014-01-25 16:55:45 +00001258 RewriteTypeIntoString(OMD->getReturnType(), ResultStr, FPRetType);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001259 ResultStr += " ";
1260
1261 // Unique method name
1262 std::string NameStr;
1263
1264 if (OMD->isInstanceMethod())
1265 NameStr += "_I_";
1266 else
1267 NameStr += "_C_";
1268
1269 NameStr += IDecl->getNameAsString();
1270 NameStr += "_";
1271
1272 if (ObjCCategoryImplDecl *CID =
1273 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
1274 NameStr += CID->getNameAsString();
1275 NameStr += "_";
1276 }
1277 // Append selector names, replacing ':' with '_'
1278 {
1279 std::string selString = OMD->getSelector().getAsString();
1280 int len = selString.size();
1281 for (int i = 0; i < len; i++)
1282 if (selString[i] == ':')
1283 selString[i] = '_';
1284 NameStr += selString;
1285 }
1286 // Remember this name for metadata emission
1287 MethodInternalNames[OMD] = NameStr;
1288 ResultStr += NameStr;
1289
1290 // Rewrite arguments
1291 ResultStr += "(";
1292
1293 // invisible arguments
1294 if (OMD->isInstanceMethod()) {
1295 QualType selfTy = Context->getObjCInterfaceType(IDecl);
1296 selfTy = Context->getPointerType(selfTy);
1297 if (!LangOpts.MicrosoftExt) {
1298 if (ObjCSynthesizedStructs.count(const_cast<ObjCInterfaceDecl*>(IDecl)))
1299 ResultStr += "struct ";
1300 }
1301 // When rewriting for Microsoft, explicitly omit the structure name.
1302 ResultStr += IDecl->getNameAsString();
1303 ResultStr += " *";
1304 }
1305 else
1306 ResultStr += Context->getObjCClassType().getAsString(
1307 Context->getPrintingPolicy());
1308
1309 ResultStr += " self, ";
1310 ResultStr += Context->getObjCSelType().getAsString(Context->getPrintingPolicy());
1311 ResultStr += " _cmd";
1312
1313 // Method arguments.
Aaron Ballman43b68be2014-03-07 17:50:17 +00001314 for (const auto *PDecl : OMD->params()) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00001315 ResultStr += ", ";
1316 if (PDecl->getType()->isObjCQualifiedIdType()) {
1317 ResultStr += "id ";
1318 ResultStr += PDecl->getNameAsString();
1319 } else {
1320 std::string Name = PDecl->getNameAsString();
1321 QualType QT = PDecl->getType();
1322 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian835cabe2012-03-27 16:42:20 +00001323 (void)convertBlockPointerToFunctionPointer(QT);
1324 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
Fariborz Jahanian11671902012-02-07 17:11:38 +00001325 ResultStr += Name;
1326 }
1327 }
1328 if (OMD->isVariadic())
1329 ResultStr += ", ...";
1330 ResultStr += ") ";
1331
1332 if (FPRetType) {
1333 ResultStr += ")"; // close the precedence "scope" for "*".
1334
1335 // Now, emit the argument types (if any).
1336 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
1337 ResultStr += "(";
Alp Toker9cacbab2014-01-20 20:26:09 +00001338 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00001339 if (i) ResultStr += ", ";
Alp Toker9cacbab2014-01-20 20:26:09 +00001340 std::string ParamStr =
1341 FT->getParamType(i).getAsString(Context->getPrintingPolicy());
Fariborz Jahanian11671902012-02-07 17:11:38 +00001342 ResultStr += ParamStr;
1343 }
1344 if (FT->isVariadic()) {
Alp Toker9cacbab2014-01-20 20:26:09 +00001345 if (FT->getNumParams())
1346 ResultStr += ", ";
Fariborz Jahanian11671902012-02-07 17:11:38 +00001347 ResultStr += "...";
1348 }
1349 ResultStr += ")";
1350 } else {
1351 ResultStr += "()";
1352 }
1353 }
1354}
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00001355
Fariborz Jahanian11671902012-02-07 17:11:38 +00001356void RewriteModernObjC::RewriteImplementationDecl(Decl *OID) {
1357 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
1358 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
1359
Fariborz Jahanian2b383d212012-02-19 19:00:05 +00001360 if (IMD) {
Fariborz Jahanian144b7222012-05-01 17:46:45 +00001361 if (IMD->getIvarRBraceLoc().isValid()) {
1362 ReplaceText(IMD->getLocStart(), 1, "/** ");
1363 ReplaceText(IMD->getIvarRBraceLoc(), 1, "**/ ");
Fariborz Jahanian2b383d212012-02-19 19:00:05 +00001364 }
Fariborz Jahanian144b7222012-05-01 17:46:45 +00001365 else {
1366 InsertText(IMD->getLocStart(), "// ");
1367 }
Fariborz Jahanian2b383d212012-02-19 19:00:05 +00001368 }
1369 else
1370 InsertText(CID->getLocStart(), "// ");
Fariborz Jahanian11671902012-02-07 17:11:38 +00001371
Aaron Ballmanf26acce2014-03-13 19:50:17 +00001372 for (auto *OMD : IMD ? IMD->instance_methods() : CID->instance_methods()) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00001373 std::string ResultStr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00001374 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
1375 SourceLocation LocStart = OMD->getLocStart();
1376 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
1377
1378 const char *startBuf = SM->getCharacterData(LocStart);
1379 const char *endBuf = SM->getCharacterData(LocEnd);
1380 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
1381 }
1382
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00001383 for (auto *OMD : IMD ? IMD->class_methods() : CID->class_methods()) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00001384 std::string ResultStr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00001385 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
1386 SourceLocation LocStart = OMD->getLocStart();
1387 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
1388
1389 const char *startBuf = SM->getCharacterData(LocStart);
1390 const char *endBuf = SM->getCharacterData(LocEnd);
1391 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
1392 }
Aaron Ballmand85eff42014-03-14 15:02:45 +00001393 for (auto *I : IMD ? IMD->property_impls() : CID->property_impls())
1394 RewritePropertyImplDecl(I, IMD, CID);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001395
1396 InsertText(IMD ? IMD->getLocEnd() : CID->getLocEnd(), "// ");
1397}
1398
1399void RewriteModernObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Fariborz Jahanian088959a2012-02-11 20:10:52 +00001400 // Do not synthesize more than once.
1401 if (ObjCSynthesizedStructs.count(ClassDecl))
1402 return;
1403 // Make sure super class's are written before current class is written.
1404 ObjCInterfaceDecl *SuperClass = ClassDecl->getSuperClass();
1405 while (SuperClass) {
1406 RewriteInterfaceDecl(SuperClass);
1407 SuperClass = SuperClass->getSuperClass();
1408 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00001409 std::string ResultStr;
Fariborz Jahaniand268b0c2012-02-17 22:20:12 +00001410 if (!ObjCWrittenInterfaces.count(ClassDecl->getCanonicalDecl())) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00001411 // we haven't seen a forward decl - generate a typedef.
Fariborz Jahanian2cc29af2012-03-12 23:58:28 +00001412 RewriteOneForwardClassDecl(ClassDecl, ResultStr);
Fariborz Jahanian5e49eb92012-02-22 18:13:25 +00001413 RewriteIvarOffsetSymbols(ClassDecl, ResultStr);
1414
Fariborz Jahanianff513382012-02-15 22:01:47 +00001415 RewriteObjCInternalStruct(ClassDecl, ResultStr);
Fariborz Jahaniand268b0c2012-02-17 22:20:12 +00001416 // Mark this typedef as having been written into its c++ equivalent.
1417 ObjCWrittenInterfaces.insert(ClassDecl->getCanonicalDecl());
Fariborz Jahanianff513382012-02-15 22:01:47 +00001418
Manman Rena7a8b1f2016-01-26 18:05:23 +00001419 for (auto *I : ClassDecl->instance_properties())
Aaron Ballmandc4bea42014-03-13 18:47:37 +00001420 RewriteProperty(I);
Aaron Ballmanf26acce2014-03-13 19:50:17 +00001421 for (auto *I : ClassDecl->instance_methods())
1422 RewriteMethodDeclaration(I);
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00001423 for (auto *I : ClassDecl->class_methods())
1424 RewriteMethodDeclaration(I);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001425
Fariborz Jahanianff513382012-02-15 22:01:47 +00001426 // Lastly, comment out the @end.
1427 ReplaceText(ClassDecl->getAtEndRange().getBegin(), strlen("@end"),
Fariborz Jahanian3a65ce32013-04-03 19:11:21 +00001428 "/* @end */\n");
Fariborz Jahanianff513382012-02-15 22:01:47 +00001429 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00001430}
1431
1432Stmt *RewriteModernObjC::RewritePropertyOrImplicitSetter(PseudoObjectExpr *PseudoOp) {
1433 SourceRange OldRange = PseudoOp->getSourceRange();
1434
1435 // We just magically know some things about the structure of this
1436 // expression.
1437 ObjCMessageExpr *OldMsg =
1438 cast<ObjCMessageExpr>(PseudoOp->getSemanticExpr(
1439 PseudoOp->getNumSemanticExprs() - 1));
1440
1441 // Because the rewriter doesn't allow us to rewrite rewritten code,
1442 // we need to suppress rewriting the sub-statements.
Fariborz Jahanian31176b12012-04-10 22:06:54 +00001443 Expr *Base;
1444 SmallVector<Expr*, 2> Args;
Fariborz Jahanian11671902012-02-07 17:11:38 +00001445 {
1446 DisableReplaceStmtScope S(*this);
1447
1448 // Rebuild the base expression if we have one.
Craig Topper8ae12032014-05-07 06:21:57 +00001449 Base = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00001450 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1451 Base = OldMsg->getInstanceReceiver();
1452 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1453 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1454 }
Fariborz Jahanian31176b12012-04-10 22:06:54 +00001455
1456 unsigned numArgs = OldMsg->getNumArgs();
1457 for (unsigned i = 0; i < numArgs; i++) {
1458 Expr *Arg = OldMsg->getArg(i);
1459 if (isa<OpaqueValueExpr>(Arg))
1460 Arg = cast<OpaqueValueExpr>(Arg)->getSourceExpr();
1461 Arg = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Arg));
1462 Args.push_back(Arg);
1463 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00001464 }
1465
1466 // TODO: avoid this copy.
1467 SmallVector<SourceLocation, 1> SelLocs;
1468 OldMsg->getSelectorLocs(SelLocs);
1469
Craig Topper8ae12032014-05-07 06:21:57 +00001470 ObjCMessageExpr *NewMsg = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00001471 switch (OldMsg->getReceiverKind()) {
1472 case ObjCMessageExpr::Class:
1473 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1474 OldMsg->getValueKind(),
1475 OldMsg->getLeftLoc(),
1476 OldMsg->getClassReceiverTypeInfo(),
1477 OldMsg->getSelector(),
1478 SelLocs,
1479 OldMsg->getMethodDecl(),
Fariborz Jahanian31176b12012-04-10 22:06:54 +00001480 Args,
Fariborz Jahanian11671902012-02-07 17:11:38 +00001481 OldMsg->getRightLoc(),
1482 OldMsg->isImplicit());
1483 break;
1484
1485 case ObjCMessageExpr::Instance:
1486 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1487 OldMsg->getValueKind(),
1488 OldMsg->getLeftLoc(),
1489 Base,
1490 OldMsg->getSelector(),
1491 SelLocs,
1492 OldMsg->getMethodDecl(),
Fariborz Jahanian31176b12012-04-10 22:06:54 +00001493 Args,
Fariborz Jahanian11671902012-02-07 17:11:38 +00001494 OldMsg->getRightLoc(),
1495 OldMsg->isImplicit());
1496 break;
1497
1498 case ObjCMessageExpr::SuperClass:
1499 case ObjCMessageExpr::SuperInstance:
1500 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1501 OldMsg->getValueKind(),
1502 OldMsg->getLeftLoc(),
1503 OldMsg->getSuperLoc(),
1504 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1505 OldMsg->getSuperType(),
1506 OldMsg->getSelector(),
1507 SelLocs,
1508 OldMsg->getMethodDecl(),
Fariborz Jahanian31176b12012-04-10 22:06:54 +00001509 Args,
Fariborz Jahanian11671902012-02-07 17:11:38 +00001510 OldMsg->getRightLoc(),
1511 OldMsg->isImplicit());
1512 break;
1513 }
1514
1515 Stmt *Replacement = SynthMessageExpr(NewMsg);
1516 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1517 return Replacement;
1518}
1519
1520Stmt *RewriteModernObjC::RewritePropertyOrImplicitGetter(PseudoObjectExpr *PseudoOp) {
1521 SourceRange OldRange = PseudoOp->getSourceRange();
1522
1523 // We just magically know some things about the structure of this
1524 // expression.
1525 ObjCMessageExpr *OldMsg =
1526 cast<ObjCMessageExpr>(PseudoOp->getResultExpr()->IgnoreImplicit());
1527
1528 // Because the rewriter doesn't allow us to rewrite rewritten code,
1529 // we need to suppress rewriting the sub-statements.
Craig Topper8ae12032014-05-07 06:21:57 +00001530 Expr *Base = nullptr;
Fariborz Jahanian31176b12012-04-10 22:06:54 +00001531 SmallVector<Expr*, 1> Args;
Fariborz Jahanian11671902012-02-07 17:11:38 +00001532 {
1533 DisableReplaceStmtScope S(*this);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001534 // Rebuild the base expression if we have one.
1535 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1536 Base = OldMsg->getInstanceReceiver();
1537 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1538 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1539 }
Fariborz Jahanian31176b12012-04-10 22:06:54 +00001540 unsigned numArgs = OldMsg->getNumArgs();
1541 for (unsigned i = 0; i < numArgs; i++) {
1542 Expr *Arg = OldMsg->getArg(i);
1543 if (isa<OpaqueValueExpr>(Arg))
1544 Arg = cast<OpaqueValueExpr>(Arg)->getSourceExpr();
1545 Arg = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Arg));
1546 Args.push_back(Arg);
1547 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00001548 }
1549
1550 // Intentionally empty.
1551 SmallVector<SourceLocation, 1> SelLocs;
Fariborz Jahanian11671902012-02-07 17:11:38 +00001552
Craig Topper8ae12032014-05-07 06:21:57 +00001553 ObjCMessageExpr *NewMsg = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00001554 switch (OldMsg->getReceiverKind()) {
1555 case ObjCMessageExpr::Class:
1556 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1557 OldMsg->getValueKind(),
1558 OldMsg->getLeftLoc(),
1559 OldMsg->getClassReceiverTypeInfo(),
1560 OldMsg->getSelector(),
1561 SelLocs,
1562 OldMsg->getMethodDecl(),
1563 Args,
1564 OldMsg->getRightLoc(),
1565 OldMsg->isImplicit());
1566 break;
1567
1568 case ObjCMessageExpr::Instance:
1569 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1570 OldMsg->getValueKind(),
1571 OldMsg->getLeftLoc(),
1572 Base,
1573 OldMsg->getSelector(),
1574 SelLocs,
1575 OldMsg->getMethodDecl(),
1576 Args,
1577 OldMsg->getRightLoc(),
1578 OldMsg->isImplicit());
1579 break;
1580
1581 case ObjCMessageExpr::SuperClass:
1582 case ObjCMessageExpr::SuperInstance:
1583 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1584 OldMsg->getValueKind(),
1585 OldMsg->getLeftLoc(),
1586 OldMsg->getSuperLoc(),
1587 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1588 OldMsg->getSuperType(),
1589 OldMsg->getSelector(),
1590 SelLocs,
1591 OldMsg->getMethodDecl(),
1592 Args,
1593 OldMsg->getRightLoc(),
1594 OldMsg->isImplicit());
1595 break;
1596 }
1597
1598 Stmt *Replacement = SynthMessageExpr(NewMsg);
1599 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1600 return Replacement;
1601}
1602
1603/// SynthCountByEnumWithState - To print:
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001604/// ((NSUInteger (*)
1605/// (id, SEL, struct __objcFastEnumerationState *, id *, NSUInteger))
Fariborz Jahanian11671902012-02-07 17:11:38 +00001606/// (void *)objc_msgSend)((id)l_collection,
1607/// sel_registerName(
1608/// "countByEnumeratingWithState:objects:count:"),
1609/// &enumState,
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001610/// (id *)__rw_items, (NSUInteger)16)
Fariborz Jahanian11671902012-02-07 17:11:38 +00001611///
1612void RewriteModernObjC::SynthCountByEnumWithState(std::string &buf) {
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001613 buf += "((_WIN_NSUInteger (*) (id, SEL, struct __objcFastEnumerationState *, "
1614 "id *, _WIN_NSUInteger))(void *)objc_msgSend)";
Fariborz Jahanian11671902012-02-07 17:11:38 +00001615 buf += "\n\t\t";
1616 buf += "((id)l_collection,\n\t\t";
1617 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1618 buf += "\n\t\t";
1619 buf += "&enumState, "
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001620 "(id *)__rw_items, (_WIN_NSUInteger)16)";
Fariborz Jahanian11671902012-02-07 17:11:38 +00001621}
1622
1623/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1624/// statement to exit to its outer synthesized loop.
1625///
1626Stmt *RewriteModernObjC::RewriteBreakStmt(BreakStmt *S) {
1627 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1628 return S;
1629 // replace break with goto __break_label
1630 std::string buf;
1631
1632 SourceLocation startLoc = S->getLocStart();
1633 buf = "goto __break_label_";
1634 buf += utostr(ObjCBcLabelNo.back());
1635 ReplaceText(startLoc, strlen("break"), buf);
1636
Craig Topper8ae12032014-05-07 06:21:57 +00001637 return nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00001638}
1639
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00001640void RewriteModernObjC::ConvertSourceLocationToLineDirective(
1641 SourceLocation Loc,
1642 std::string &LineString) {
Fariborz Jahaniane4c7e852013-02-08 00:27:34 +00001643 if (Loc.isFileID() && GenerateLineInfo) {
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00001644 LineString += "\n#line ";
1645 PresumedLoc PLoc = SM->getPresumedLoc(Loc);
1646 LineString += utostr(PLoc.getLine());
1647 LineString += " \"";
1648 LineString += Lexer::Stringify(PLoc.getFilename());
1649 LineString += "\"\n";
1650 }
1651}
1652
Fariborz Jahanian11671902012-02-07 17:11:38 +00001653/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1654/// statement to continue with its inner synthesized loop.
1655///
1656Stmt *RewriteModernObjC::RewriteContinueStmt(ContinueStmt *S) {
1657 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1658 return S;
1659 // replace continue with goto __continue_label
1660 std::string buf;
1661
1662 SourceLocation startLoc = S->getLocStart();
1663 buf = "goto __continue_label_";
1664 buf += utostr(ObjCBcLabelNo.back());
1665 ReplaceText(startLoc, strlen("continue"), buf);
1666
Craig Topper8ae12032014-05-07 06:21:57 +00001667 return nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00001668}
1669
1670/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
1671/// It rewrites:
1672/// for ( type elem in collection) { stmts; }
1673
1674/// Into:
1675/// {
1676/// type elem;
1677/// struct __objcFastEnumerationState enumState = { 0 };
1678/// id __rw_items[16];
1679/// id l_collection = (id)collection;
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001680/// NSUInteger limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian11671902012-02-07 17:11:38 +00001681/// objects:__rw_items count:16];
1682/// if (limit) {
1683/// unsigned long startMutations = *enumState.mutationsPtr;
1684/// do {
1685/// unsigned long counter = 0;
1686/// do {
1687/// if (startMutations != *enumState.mutationsPtr)
1688/// objc_enumerationMutation(l_collection);
1689/// elem = (type)enumState.itemsPtr[counter++];
1690/// stmts;
1691/// __continue_label: ;
1692/// } while (counter < limit);
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001693/// } while ((limit = [l_collection countByEnumeratingWithState:&enumState
1694/// objects:__rw_items count:16]));
Fariborz Jahanian11671902012-02-07 17:11:38 +00001695/// elem = nil;
1696/// __break_label: ;
1697/// }
1698/// else
1699/// elem = nil;
1700/// }
1701///
1702Stmt *RewriteModernObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
1703 SourceLocation OrigEnd) {
1704 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
1705 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
1706 "ObjCForCollectionStmt Statement stack mismatch");
1707 assert(!ObjCBcLabelNo.empty() &&
1708 "ObjCForCollectionStmt - Label No stack empty");
1709
1710 SourceLocation startLoc = S->getLocStart();
1711 const char *startBuf = SM->getCharacterData(startLoc);
1712 StringRef elementName;
1713 std::string elementTypeAsString;
1714 std::string buf;
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00001715 // line directive first.
1716 SourceLocation ForEachLoc = S->getForLoc();
1717 ConvertSourceLocationToLineDirective(ForEachLoc, buf);
1718 buf += "{\n\t";
Fariborz Jahanian11671902012-02-07 17:11:38 +00001719 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1720 // type elem;
1721 NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
1722 QualType ElementType = cast<ValueDecl>(D)->getType();
1723 if (ElementType->isObjCQualifiedIdType() ||
1724 ElementType->isObjCQualifiedInterfaceType())
1725 // Simply use 'id' for all qualified types.
1726 elementTypeAsString = "id";
1727 else
1728 elementTypeAsString = ElementType.getAsString(Context->getPrintingPolicy());
1729 buf += elementTypeAsString;
1730 buf += " ";
1731 elementName = D->getName();
1732 buf += elementName;
1733 buf += ";\n\t";
1734 }
1735 else {
1736 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
1737 elementName = DR->getDecl()->getName();
1738 ValueDecl *VD = cast<ValueDecl>(DR->getDecl());
1739 if (VD->getType()->isObjCQualifiedIdType() ||
1740 VD->getType()->isObjCQualifiedInterfaceType())
1741 // Simply use 'id' for all qualified types.
1742 elementTypeAsString = "id";
1743 else
1744 elementTypeAsString = VD->getType().getAsString(Context->getPrintingPolicy());
1745 }
1746
1747 // struct __objcFastEnumerationState enumState = { 0 };
1748 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1749 // id __rw_items[16];
1750 buf += "id __rw_items[16];\n\t";
1751 // id l_collection = (id)
1752 buf += "id l_collection = (id)";
1753 // Find start location of 'collection' the hard way!
1754 const char *startCollectionBuf = startBuf;
1755 startCollectionBuf += 3; // skip 'for'
1756 startCollectionBuf = strchr(startCollectionBuf, '(');
1757 startCollectionBuf++; // skip '('
1758 // find 'in' and skip it.
1759 while (*startCollectionBuf != ' ' ||
1760 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1761 (*(startCollectionBuf+3) != ' ' &&
1762 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1763 startCollectionBuf++;
1764 startCollectionBuf += 3;
1765
1766 // Replace: "for (type element in" with string constructed thus far.
1767 ReplaceText(startLoc, startCollectionBuf - startBuf, buf);
1768 // Replace ')' in for '(' type elem in collection ')' with ';'
1769 SourceLocation rightParenLoc = S->getRParenLoc();
1770 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1771 SourceLocation lparenLoc = startLoc.getLocWithOffset(rparenBuf-startBuf);
1772 buf = ";\n\t";
1773
1774 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1775 // objects:__rw_items count:16];
1776 // which is synthesized into:
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001777 // NSUInteger limit =
1778 // ((NSUInteger (*)
1779 // (id, SEL, struct __objcFastEnumerationState *, id *, NSUInteger))
Fariborz Jahanian11671902012-02-07 17:11:38 +00001780 // (void *)objc_msgSend)((id)l_collection,
1781 // sel_registerName(
1782 // "countByEnumeratingWithState:objects:count:"),
1783 // (struct __objcFastEnumerationState *)&state,
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001784 // (id *)__rw_items, (NSUInteger)16);
1785 buf += "_WIN_NSUInteger limit =\n\t\t";
Fariborz Jahanian11671902012-02-07 17:11:38 +00001786 SynthCountByEnumWithState(buf);
1787 buf += ";\n\t";
1788 /// if (limit) {
1789 /// unsigned long startMutations = *enumState.mutationsPtr;
1790 /// do {
1791 /// unsigned long counter = 0;
1792 /// do {
1793 /// if (startMutations != *enumState.mutationsPtr)
1794 /// objc_enumerationMutation(l_collection);
1795 /// elem = (type)enumState.itemsPtr[counter++];
1796 buf += "if (limit) {\n\t";
1797 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1798 buf += "do {\n\t\t";
1799 buf += "unsigned long counter = 0;\n\t\t";
1800 buf += "do {\n\t\t\t";
1801 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1802 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1803 buf += elementName;
1804 buf += " = (";
1805 buf += elementTypeAsString;
1806 buf += ")enumState.itemsPtr[counter++];";
1807 // Replace ')' in for '(' type elem in collection ')' with all of these.
1808 ReplaceText(lparenLoc, 1, buf);
1809
1810 /// __continue_label: ;
1811 /// } while (counter < limit);
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001812 /// } while ((limit = [l_collection countByEnumeratingWithState:&enumState
1813 /// objects:__rw_items count:16]));
Fariborz Jahanian11671902012-02-07 17:11:38 +00001814 /// elem = nil;
1815 /// __break_label: ;
1816 /// }
1817 /// else
1818 /// elem = nil;
1819 /// }
1820 ///
1821 buf = ";\n\t";
1822 buf += "__continue_label_";
1823 buf += utostr(ObjCBcLabelNo.back());
1824 buf += ": ;";
1825 buf += "\n\t\t";
1826 buf += "} while (counter < limit);\n\t";
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001827 buf += "} while ((limit = ";
Fariborz Jahanian11671902012-02-07 17:11:38 +00001828 SynthCountByEnumWithState(buf);
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001829 buf += "));\n\t";
Fariborz Jahanian11671902012-02-07 17:11:38 +00001830 buf += elementName;
1831 buf += " = ((";
1832 buf += elementTypeAsString;
1833 buf += ")0);\n\t";
1834 buf += "__break_label_";
1835 buf += utostr(ObjCBcLabelNo.back());
1836 buf += ": ;\n\t";
1837 buf += "}\n\t";
1838 buf += "else\n\t\t";
1839 buf += elementName;
1840 buf += " = ((";
1841 buf += elementTypeAsString;
1842 buf += ")0);\n\t";
1843 buf += "}\n";
1844
1845 // Insert all these *after* the statement body.
1846 // FIXME: If this should support Obj-C++, support CXXTryStmt
1847 if (isa<CompoundStmt>(S->getBody())) {
1848 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(1);
1849 InsertText(endBodyLoc, buf);
1850 } else {
1851 /* Need to treat single statements specially. For example:
1852 *
1853 * for (A *a in b) if (stuff()) break;
1854 * for (A *a in b) xxxyy;
1855 *
1856 * The following code simply scans ahead to the semi to find the actual end.
1857 */
1858 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1859 const char *semiBuf = strchr(stmtBuf, ';');
1860 assert(semiBuf && "Can't find ';'");
1861 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(semiBuf-stmtBuf+1);
1862 InsertText(endBodyLoc, buf);
1863 }
1864 Stmts.pop_back();
1865 ObjCBcLabelNo.pop_back();
Craig Topper8ae12032014-05-07 06:21:57 +00001866 return nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00001867}
1868
Fariborz Jahanianfe6268e2012-03-16 21:33:16 +00001869static void Write_RethrowObject(std::string &buf) {
1870 buf += "{ struct _FIN { _FIN(id reth) : rethrow(reth) {}\n";
1871 buf += "\t~_FIN() { if (rethrow) objc_exception_throw(rethrow); }\n";
1872 buf += "\tid rethrow;\n";
1873 buf += "\t} _fin_force_rethow(_rethrow);";
1874}
1875
Fariborz Jahanian11671902012-02-07 17:11:38 +00001876/// RewriteObjCSynchronizedStmt -
1877/// This routine rewrites @synchronized(expr) stmt;
1878/// into:
1879/// objc_sync_enter(expr);
1880/// @try stmt @finally { objc_sync_exit(expr); }
1881///
1882Stmt *RewriteModernObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
1883 // Get the start location and compute the semi location.
1884 SourceLocation startLoc = S->getLocStart();
1885 const char *startBuf = SM->getCharacterData(startLoc);
1886
1887 assert((*startBuf == '@') && "bogus @synchronized location");
1888
1889 std::string buf;
Fariborz Jahaniane030a632012-11-07 00:43:05 +00001890 SourceLocation SynchLoc = S->getAtSynchronizedLoc();
1891 ConvertSourceLocationToLineDirective(SynchLoc, buf);
Fariborz Jahanianff0c4602013-09-17 17:51:48 +00001892 buf += "{ id _rethrow = 0; id _sync_obj = (id)";
Fariborz Jahanianfe6268e2012-03-16 21:33:16 +00001893
Fariborz Jahanian11671902012-02-07 17:11:38 +00001894 const char *lparenBuf = startBuf;
1895 while (*lparenBuf != '(') lparenBuf++;
1896 ReplaceText(startLoc, lparenBuf-startBuf+1, buf);
Fariborz Jahaniane8810762012-03-17 17:46:02 +00001897
1898 buf = "; objc_sync_enter(_sync_obj);\n";
1899 buf += "try {\n\tstruct _SYNC_EXIT { _SYNC_EXIT(id arg) : sync_exit(arg) {}";
1900 buf += "\n\t~_SYNC_EXIT() {objc_sync_exit(sync_exit);}";
1901 buf += "\n\tid sync_exit;";
1902 buf += "\n\t} _sync_exit(_sync_obj);\n";
1903
1904 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1905 // the sync expression is typically a message expression that's already
1906 // been rewritten! (which implies the SourceLocation's are invalid).
1907 SourceLocation RParenExprLoc = S->getSynchBody()->getLocStart();
1908 const char *RParenExprLocBuf = SM->getCharacterData(RParenExprLoc);
1909 while (*RParenExprLocBuf != ')') RParenExprLocBuf--;
1910 RParenExprLoc = startLoc.getLocWithOffset(RParenExprLocBuf-startBuf);
1911
1912 SourceLocation LBranceLoc = S->getSynchBody()->getLocStart();
1913 const char *LBraceLocBuf = SM->getCharacterData(LBranceLoc);
1914 assert (*LBraceLocBuf == '{');
1915 ReplaceText(RParenExprLoc, (LBraceLocBuf - SM->getCharacterData(RParenExprLoc) + 1), buf);
Fariborz Jahanianfe6268e2012-03-16 21:33:16 +00001916
Fariborz Jahanian1d24a0252012-03-16 21:43:45 +00001917 SourceLocation startRBraceLoc = S->getSynchBody()->getLocEnd();
Matt Beaumont-Gay6e177d32012-03-16 22:20:39 +00001918 assert((*SM->getCharacterData(startRBraceLoc) == '}') &&
1919 "bogus @synchronized block");
Fariborz Jahanianfe6268e2012-03-16 21:33:16 +00001920
1921 buf = "} catch (id e) {_rethrow = e;}\n";
1922 Write_RethrowObject(buf);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001923 buf += "}\n";
Fariborz Jahanianfe6268e2012-03-16 21:33:16 +00001924 buf += "}\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00001925
Fariborz Jahanian1d24a0252012-03-16 21:43:45 +00001926 ReplaceText(startRBraceLoc, 1, buf);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001927
Craig Topper8ae12032014-05-07 06:21:57 +00001928 return nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00001929}
1930
1931void RewriteModernObjC::WarnAboutReturnGotoStmts(Stmt *S)
1932{
1933 // Perform a bottom up traversal of all children.
Benjamin Kramer642f1732015-07-02 21:03:14 +00001934 for (Stmt *SubStmt : S->children())
1935 if (SubStmt)
1936 WarnAboutReturnGotoStmts(SubStmt);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001937
1938 if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
1939 Diags.Report(Context->getFullLoc(S->getLocStart()),
1940 TryFinallyContainsReturnDiag);
1941 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00001942}
1943
Fariborz Jahanian9b43c3f2012-05-23 23:47:20 +00001944Stmt *RewriteModernObjC::RewriteObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S) {
1945 SourceLocation startLoc = S->getAtLoc();
1946 ReplaceText(startLoc, strlen("@autoreleasepool"), "/* @autoreleasepool */");
Fariborz Jahanianc37a1d62012-05-24 22:59:56 +00001947 ReplaceText(S->getSubStmt()->getLocStart(), 1,
1948 "{ __AtAutoreleasePool __autoreleasepool; ");
Craig Topper8ae12032014-05-07 06:21:57 +00001949
1950 return nullptr;
Fariborz Jahanian9b43c3f2012-05-23 23:47:20 +00001951}
1952
Fariborz Jahanian11671902012-02-07 17:11:38 +00001953Stmt *RewriteModernObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Fariborz Jahanian3b71b172012-03-15 22:42:15 +00001954 ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt();
Fariborz Jahanianb960db42012-03-15 23:50:33 +00001955 bool noCatch = S->getNumCatchStmts() == 0;
Fariborz Jahanian3b71b172012-03-15 22:42:15 +00001956 std::string buf;
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00001957 SourceLocation TryLocation = S->getAtTryLoc();
1958 ConvertSourceLocationToLineDirective(TryLocation, buf);
Fariborz Jahanian3b71b172012-03-15 22:42:15 +00001959
1960 if (finalStmt) {
Fariborz Jahanianb960db42012-03-15 23:50:33 +00001961 if (noCatch)
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00001962 buf += "{ id volatile _rethrow = 0;\n";
Fariborz Jahanianb960db42012-03-15 23:50:33 +00001963 else {
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00001964 buf += "{ id volatile _rethrow = 0;\ntry {\n";
Fariborz Jahanianb960db42012-03-15 23:50:33 +00001965 }
Fariborz Jahanian3b71b172012-03-15 22:42:15 +00001966 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00001967 // Get the start location and compute the semi location.
1968 SourceLocation startLoc = S->getLocStart();
1969 const char *startBuf = SM->getCharacterData(startLoc);
1970
1971 assert((*startBuf == '@') && "bogus @try location");
Fariborz Jahanian3b71b172012-03-15 22:42:15 +00001972 if (finalStmt)
1973 ReplaceText(startLoc, 1, buf);
1974 else
1975 // @try -> try
1976 ReplaceText(startLoc, 1, "");
1977
Fariborz Jahanian11671902012-02-07 17:11:38 +00001978 for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I) {
1979 ObjCAtCatchStmt *Catch = S->getCatchStmt(I);
Fariborz Jahanianf232bb42012-03-15 20:11:10 +00001980 VarDecl *catchDecl = Catch->getCatchParamDecl();
Fariborz Jahanian2cc29af2012-03-12 23:58:28 +00001981
Fariborz Jahanian11671902012-02-07 17:11:38 +00001982 startLoc = Catch->getLocStart();
Fariborz Jahanianf232bb42012-03-15 20:11:10 +00001983 bool AtRemoved = false;
1984 if (catchDecl) {
1985 QualType t = catchDecl->getType();
1986 if (const ObjCObjectPointerType *Ptr = t->getAs<ObjCObjectPointerType>()) {
1987 // Should be a pointer to a class.
1988 ObjCInterfaceDecl *IDecl = Ptr->getObjectType()->getInterface();
1989 if (IDecl) {
1990 std::string Result;
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00001991 ConvertSourceLocationToLineDirective(Catch->getLocStart(), Result);
1992
Fariborz Jahanianf232bb42012-03-15 20:11:10 +00001993 startBuf = SM->getCharacterData(startLoc);
1994 assert((*startBuf == '@') && "bogus @catch location");
1995 SourceLocation rParenLoc = Catch->getRParenLoc();
1996 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1997
1998 // _objc_exc_Foo *_e as argument to catch.
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00001999 Result += "catch (_objc_exc_"; Result += IDecl->getNameAsString();
Fariborz Jahanianf232bb42012-03-15 20:11:10 +00002000 Result += " *_"; Result += catchDecl->getNameAsString();
2001 Result += ")";
2002 ReplaceText(startLoc, rParenBuf-startBuf+1, Result);
2003 // Foo *e = (Foo *)_e;
2004 Result.clear();
2005 Result = "{ ";
2006 Result += IDecl->getNameAsString();
2007 Result += " *"; Result += catchDecl->getNameAsString();
2008 Result += " = ("; Result += IDecl->getNameAsString(); Result += "*)";
2009 Result += "_"; Result += catchDecl->getNameAsString();
2010
2011 Result += "; ";
2012 SourceLocation lBraceLoc = Catch->getCatchBody()->getLocStart();
2013 ReplaceText(lBraceLoc, 1, Result);
2014 AtRemoved = true;
2015 }
2016 }
2017 }
2018 if (!AtRemoved)
2019 // @catch -> catch
2020 ReplaceText(startLoc, 1, "");
Fariborz Jahanian2cc29af2012-03-12 23:58:28 +00002021
Fariborz Jahanian11671902012-02-07 17:11:38 +00002022 }
Fariborz Jahanianb960db42012-03-15 23:50:33 +00002023 if (finalStmt) {
2024 buf.clear();
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00002025 SourceLocation FinallyLoc = finalStmt->getLocStart();
2026
2027 if (noCatch) {
2028 ConvertSourceLocationToLineDirective(FinallyLoc, buf);
2029 buf += "catch (id e) {_rethrow = e;}\n";
2030 }
2031 else {
2032 buf += "}\n";
2033 ConvertSourceLocationToLineDirective(FinallyLoc, buf);
2034 buf += "catch (id e) {_rethrow = e;}\n";
2035 }
2036
Fariborz Jahanianb960db42012-03-15 23:50:33 +00002037 SourceLocation startFinalLoc = finalStmt->getLocStart();
2038 ReplaceText(startFinalLoc, 8, buf);
2039 Stmt *body = finalStmt->getFinallyBody();
2040 SourceLocation startFinalBodyLoc = body->getLocStart();
2041 buf.clear();
Fariborz Jahanianfe6268e2012-03-16 21:33:16 +00002042 Write_RethrowObject(buf);
Fariborz Jahanianb960db42012-03-15 23:50:33 +00002043 ReplaceText(startFinalBodyLoc, 1, buf);
2044
2045 SourceLocation endFinalBodyLoc = body->getLocEnd();
2046 ReplaceText(endFinalBodyLoc, 1, "}\n}");
Fariborz Jahaniane8810762012-03-17 17:46:02 +00002047 // Now check for any return/continue/go statements within the @try.
2048 WarnAboutReturnGotoStmts(S->getTryBody());
Fariborz Jahanianb960db42012-03-15 23:50:33 +00002049 }
2050
Craig Topper8ae12032014-05-07 06:21:57 +00002051 return nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00002052}
2053
2054// This can't be done with ReplaceStmt(S, ThrowExpr), since
2055// the throw expression is typically a message expression that's already
2056// been rewritten! (which implies the SourceLocation's are invalid).
2057Stmt *RewriteModernObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
2058 // Get the start location and compute the semi location.
2059 SourceLocation startLoc = S->getLocStart();
2060 const char *startBuf = SM->getCharacterData(startLoc);
2061
2062 assert((*startBuf == '@') && "bogus @throw location");
2063
2064 std::string buf;
2065 /* void objc_exception_throw(id) __attribute__((noreturn)); */
2066 if (S->getThrowExpr())
2067 buf = "objc_exception_throw(";
Fariborz Jahanian52fe6a02012-03-16 16:52:06 +00002068 else
2069 buf = "throw";
Fariborz Jahanian11671902012-02-07 17:11:38 +00002070
2071 // handle "@ throw" correctly.
2072 const char *wBuf = strchr(startBuf, 'w');
2073 assert((*wBuf == 'w') && "@throw: can't find 'w'");
2074 ReplaceText(startLoc, wBuf-startBuf+1, buf);
2075
Fariborz Jahanianb0fdab22013-02-11 19:30:33 +00002076 SourceLocation endLoc = S->getLocEnd();
2077 const char *endBuf = SM->getCharacterData(endLoc);
2078 const char *semiBuf = strchr(endBuf, ';');
Fariborz Jahanian11671902012-02-07 17:11:38 +00002079 assert((*semiBuf == ';') && "@throw: can't find ';'");
2080 SourceLocation semiLoc = startLoc.getLocWithOffset(semiBuf-startBuf);
Fariborz Jahanian52fe6a02012-03-16 16:52:06 +00002081 if (S->getThrowExpr())
2082 ReplaceText(semiLoc, 1, ");");
Craig Topper8ae12032014-05-07 06:21:57 +00002083 return nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00002084}
2085
2086Stmt *RewriteModernObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
2087 // Create a new string expression.
Fariborz Jahanian11671902012-02-07 17:11:38 +00002088 std::string StrEncoding;
2089 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
Benjamin Kramerfc188422014-02-25 12:26:11 +00002090 Expr *Replacement = getStringLiteral(StrEncoding);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002091 ReplaceStmt(Exp, Replacement);
2092
2093 // Replace this subexpr in the parent.
2094 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2095 return Replacement;
2096}
2097
2098Stmt *RewriteModernObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
2099 if (!SelGetUidFunctionDecl)
2100 SynthSelGetUidFunctionDecl();
2101 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
2102 // Create a call to sel_registerName("selName").
2103 SmallVector<Expr*, 8> SelExprs;
Benjamin Kramerfc188422014-02-25 12:26:11 +00002104 SelExprs.push_back(getStringLiteral(Exp->getSelector().getAsString()));
Fariborz Jahanian11671902012-02-07 17:11:38 +00002105 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
Craig Toppercf2126e2015-10-22 03:13:07 +00002106 SelExprs);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002107 ReplaceStmt(Exp, SelExp);
2108 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2109 return SelExp;
2110}
2111
Craig Toppercf2126e2015-10-22 03:13:07 +00002112CallExpr *
2113RewriteModernObjC::SynthesizeCallToFunctionDecl(FunctionDecl *FD,
2114 ArrayRef<Expr *> Args,
2115 SourceLocation StartLoc,
2116 SourceLocation EndLoc) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00002117 // Get the type, we will need to reference it in a couple spots.
2118 QualType msgSendType = FD->getType();
2119
2120 // Create a reference to the objc_msgSend() declaration.
2121 DeclRefExpr *DRE =
John McCall113bee02012-03-10 09:33:50 +00002122 new (Context) DeclRefExpr(FD, false, msgSendType, VK_LValue, SourceLocation());
Fariborz Jahanian11671902012-02-07 17:11:38 +00002123
2124 // Now, we cast the reference to a pointer to the objc_msgSend type.
2125 QualType pToFunc = Context->getPointerType(msgSendType);
2126 ImplicitCastExpr *ICE =
2127 ImplicitCastExpr::Create(*Context, pToFunc, CK_FunctionToPointerDecay,
Craig Topper8ae12032014-05-07 06:21:57 +00002128 DRE, nullptr, VK_RValue);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002129
2130 const FunctionType *FT = msgSendType->getAs<FunctionType>();
2131
Craig Toppercf2126e2015-10-22 03:13:07 +00002132 CallExpr *Exp = new (Context) CallExpr(*Context, ICE, Args,
2133 FT->getCallResultType(*Context),
2134 VK_RValue, EndLoc);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002135 return Exp;
2136}
2137
2138static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
2139 const char *&startRef, const char *&endRef) {
2140 while (startBuf < endBuf) {
2141 if (*startBuf == '<')
2142 startRef = startBuf; // mark the start.
2143 if (*startBuf == '>') {
2144 if (startRef && *startRef == '<') {
2145 endRef = startBuf; // mark the end.
2146 return true;
2147 }
2148 return false;
2149 }
2150 startBuf++;
2151 }
2152 return false;
2153}
2154
2155static void scanToNextArgument(const char *&argRef) {
2156 int angle = 0;
2157 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
2158 if (*argRef == '<')
2159 angle++;
2160 else if (*argRef == '>')
2161 angle--;
2162 argRef++;
2163 }
2164 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
2165}
2166
2167bool RewriteModernObjC::needToScanForQualifiers(QualType T) {
2168 if (T->isObjCQualifiedIdType())
2169 return true;
2170 if (const PointerType *PT = T->getAs<PointerType>()) {
2171 if (PT->getPointeeType()->isObjCQualifiedIdType())
2172 return true;
2173 }
2174 if (T->isObjCObjectPointerType()) {
2175 T = T->getPointeeType();
2176 return T->isObjCQualifiedInterfaceType();
2177 }
2178 if (T->isArrayType()) {
2179 QualType ElemTy = Context->getBaseElementType(T);
2180 return needToScanForQualifiers(ElemTy);
2181 }
2182 return false;
2183}
2184
2185void RewriteModernObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
2186 QualType Type = E->getType();
2187 if (needToScanForQualifiers(Type)) {
2188 SourceLocation Loc, EndLoc;
2189
2190 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
2191 Loc = ECE->getLParenLoc();
2192 EndLoc = ECE->getRParenLoc();
2193 } else {
2194 Loc = E->getLocStart();
2195 EndLoc = E->getLocEnd();
2196 }
2197 // This will defend against trying to rewrite synthesized expressions.
2198 if (Loc.isInvalid() || EndLoc.isInvalid())
2199 return;
2200
2201 const char *startBuf = SM->getCharacterData(Loc);
2202 const char *endBuf = SM->getCharacterData(EndLoc);
Craig Topper8ae12032014-05-07 06:21:57 +00002203 const char *startRef = nullptr, *endRef = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00002204 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2205 // Get the locations of the startRef, endRef.
2206 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-startBuf);
2207 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-startBuf+1);
2208 // Comment out the protocol references.
2209 InsertText(LessLoc, "/*");
2210 InsertText(GreaterLoc, "*/");
2211 }
2212 }
2213}
2214
2215void RewriteModernObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
2216 SourceLocation Loc;
2217 QualType Type;
Craig Topper8ae12032014-05-07 06:21:57 +00002218 const FunctionProtoType *proto = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00002219 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
2220 Loc = VD->getLocation();
2221 Type = VD->getType();
2222 }
2223 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
2224 Loc = FD->getLocation();
2225 // Check for ObjC 'id' and class types that have been adorned with protocol
2226 // information (id<p>, C<p>*). The protocol references need to be rewritten!
2227 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2228 assert(funcType && "missing function type");
2229 proto = dyn_cast<FunctionProtoType>(funcType);
2230 if (!proto)
2231 return;
Alp Toker314cc812014-01-25 16:55:45 +00002232 Type = proto->getReturnType();
Fariborz Jahanian11671902012-02-07 17:11:38 +00002233 }
2234 else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
2235 Loc = FD->getLocation();
2236 Type = FD->getType();
2237 }
Fariborz Jahanian3a65ce32013-04-03 19:11:21 +00002238 else if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(Dcl)) {
2239 Loc = TD->getLocation();
2240 Type = TD->getUnderlyingType();
2241 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00002242 else
2243 return;
2244
2245 if (needToScanForQualifiers(Type)) {
2246 // Since types are unique, we need to scan the buffer.
2247
2248 const char *endBuf = SM->getCharacterData(Loc);
2249 const char *startBuf = endBuf;
2250 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
2251 startBuf--; // scan backward (from the decl location) for return type.
Craig Topper8ae12032014-05-07 06:21:57 +00002252 const char *startRef = nullptr, *endRef = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00002253 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2254 // Get the locations of the startRef, endRef.
2255 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-endBuf);
2256 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-endBuf+1);
2257 // Comment out the protocol references.
2258 InsertText(LessLoc, "/*");
2259 InsertText(GreaterLoc, "*/");
2260 }
2261 }
2262 if (!proto)
2263 return; // most likely, was a variable
2264 // Now check arguments.
2265 const char *startBuf = SM->getCharacterData(Loc);
2266 const char *startFuncBuf = startBuf;
Alp Toker9cacbab2014-01-20 20:26:09 +00002267 for (unsigned i = 0; i < proto->getNumParams(); i++) {
2268 if (needToScanForQualifiers(proto->getParamType(i))) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00002269 // Since types are unique, we need to scan the buffer.
2270
2271 const char *endBuf = startBuf;
2272 // scan forward (from the decl location) for argument types.
2273 scanToNextArgument(endBuf);
Craig Topper8ae12032014-05-07 06:21:57 +00002274 const char *startRef = nullptr, *endRef = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00002275 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2276 // Get the locations of the startRef, endRef.
2277 SourceLocation LessLoc =
2278 Loc.getLocWithOffset(startRef-startFuncBuf);
2279 SourceLocation GreaterLoc =
2280 Loc.getLocWithOffset(endRef-startFuncBuf+1);
2281 // Comment out the protocol references.
2282 InsertText(LessLoc, "/*");
2283 InsertText(GreaterLoc, "*/");
2284 }
2285 startBuf = ++endBuf;
2286 }
2287 else {
2288 // If the function name is derived from a macro expansion, then the
2289 // argument buffer will not follow the name. Need to speak with Chris.
2290 while (*startBuf && *startBuf != ')' && *startBuf != ',')
2291 startBuf++; // scan forward (from the decl location) for argument types.
2292 startBuf++;
2293 }
2294 }
2295}
2296
2297void RewriteModernObjC::RewriteTypeOfDecl(VarDecl *ND) {
2298 QualType QT = ND->getType();
2299 const Type* TypePtr = QT->getAs<Type>();
2300 if (!isa<TypeOfExprType>(TypePtr))
2301 return;
2302 while (isa<TypeOfExprType>(TypePtr)) {
2303 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
2304 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
2305 TypePtr = QT->getAs<Type>();
2306 }
2307 // FIXME. This will not work for multiple declarators; as in:
2308 // __typeof__(a) b,c,d;
2309 std::string TypeAsString(QT.getAsString(Context->getPrintingPolicy()));
2310 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
2311 const char *startBuf = SM->getCharacterData(DeclLoc);
2312 if (ND->getInit()) {
2313 std::string Name(ND->getNameAsString());
2314 TypeAsString += " " + Name + " = ";
2315 Expr *E = ND->getInit();
2316 SourceLocation startLoc;
2317 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
2318 startLoc = ECE->getLParenLoc();
2319 else
2320 startLoc = E->getLocStart();
2321 startLoc = SM->getExpansionLoc(startLoc);
2322 const char *endBuf = SM->getCharacterData(startLoc);
2323 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
2324 }
2325 else {
2326 SourceLocation X = ND->getLocEnd();
2327 X = SM->getExpansionLoc(X);
2328 const char *endBuf = SM->getCharacterData(X);
2329 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
2330 }
2331}
2332
2333// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
2334void RewriteModernObjC::SynthSelGetUidFunctionDecl() {
2335 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
2336 SmallVector<QualType, 16> ArgTys;
2337 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2338 QualType getFuncType =
Jordan Rose5c382722013-03-08 21:51:21 +00002339 getSimpleFunctionType(Context->getObjCSelType(), ArgTys);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002340 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002341 SourceLocation(),
2342 SourceLocation(),
Craig Topper8ae12032014-05-07 06:21:57 +00002343 SelGetUidIdent, getFuncType,
2344 nullptr, SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002345}
2346
2347void RewriteModernObjC::RewriteFunctionDecl(FunctionDecl *FD) {
2348 // declared in <objc/objc.h>
2349 if (FD->getIdentifier() &&
2350 FD->getName() == "sel_registerName") {
2351 SelGetUidFunctionDecl = FD;
2352 return;
2353 }
2354 RewriteObjCQualifiedInterfaceTypes(FD);
2355}
2356
2357void RewriteModernObjC::RewriteBlockPointerType(std::string& Str, QualType Type) {
2358 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
2359 const char *argPtr = TypeString.c_str();
2360 if (!strchr(argPtr, '^')) {
2361 Str += TypeString;
2362 return;
2363 }
2364 while (*argPtr) {
2365 Str += (*argPtr == '^' ? '*' : *argPtr);
2366 argPtr++;
2367 }
2368}
2369
2370// FIXME. Consolidate this routine with RewriteBlockPointerType.
2371void RewriteModernObjC::RewriteBlockPointerTypeVariable(std::string& Str,
2372 ValueDecl *VD) {
2373 QualType Type = VD->getType();
2374 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
2375 const char *argPtr = TypeString.c_str();
2376 int paren = 0;
2377 while (*argPtr) {
2378 switch (*argPtr) {
2379 case '(':
2380 Str += *argPtr;
2381 paren++;
2382 break;
2383 case ')':
2384 Str += *argPtr;
2385 paren--;
2386 break;
2387 case '^':
2388 Str += '*';
2389 if (paren == 1)
2390 Str += VD->getNameAsString();
2391 break;
2392 default:
2393 Str += *argPtr;
2394 break;
2395 }
2396 argPtr++;
2397 }
2398}
2399
Fariborz Jahanianca357d92012-04-19 00:50:01 +00002400void RewriteModernObjC::RewriteBlockLiteralFunctionDecl(FunctionDecl *FD) {
2401 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
2402 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2403 const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(funcType);
2404 if (!proto)
2405 return;
Alp Toker314cc812014-01-25 16:55:45 +00002406 QualType Type = proto->getReturnType();
Fariborz Jahanianca357d92012-04-19 00:50:01 +00002407 std::string FdStr = Type.getAsString(Context->getPrintingPolicy());
2408 FdStr += " ";
2409 FdStr += FD->getName();
2410 FdStr += "(";
Alp Toker9cacbab2014-01-20 20:26:09 +00002411 unsigned numArgs = proto->getNumParams();
Fariborz Jahanianca357d92012-04-19 00:50:01 +00002412 for (unsigned i = 0; i < numArgs; i++) {
Alp Toker9cacbab2014-01-20 20:26:09 +00002413 QualType ArgType = proto->getParamType(i);
Fariborz Jahanianca357d92012-04-19 00:50:01 +00002414 RewriteBlockPointerType(FdStr, ArgType);
2415 if (i+1 < numArgs)
2416 FdStr += ", ";
2417 }
Fariborz Jahaniandf0577d2012-04-19 16:30:28 +00002418 if (FD->isVariadic()) {
2419 FdStr += (numArgs > 0) ? ", ...);\n" : "...);\n";
2420 }
2421 else
2422 FdStr += ");\n";
Fariborz Jahanianca357d92012-04-19 00:50:01 +00002423 InsertText(FunLocStart, FdStr);
2424}
2425
Benjamin Kramer60509af2013-09-09 14:48:42 +00002426// SynthSuperConstructorFunctionDecl - id __rw_objc_super(id obj, id super);
2427void RewriteModernObjC::SynthSuperConstructorFunctionDecl() {
2428 if (SuperConstructorFunctionDecl)
Fariborz Jahanian11671902012-02-07 17:11:38 +00002429 return;
2430 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
2431 SmallVector<QualType, 16> ArgTys;
2432 QualType argT = Context->getObjCIdType();
2433 assert(!argT.isNull() && "Can't find 'id' type");
2434 ArgTys.push_back(argT);
2435 ArgTys.push_back(argT);
2436 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002437 ArgTys);
Benjamin Kramer60509af2013-09-09 14:48:42 +00002438 SuperConstructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002439 SourceLocation(),
2440 SourceLocation(),
2441 msgSendIdent, msgSendType,
Craig Topper8ae12032014-05-07 06:21:57 +00002442 nullptr, SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002443}
2444
2445// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
2446void RewriteModernObjC::SynthMsgSendFunctionDecl() {
2447 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
2448 SmallVector<QualType, 16> ArgTys;
2449 QualType argT = Context->getObjCIdType();
2450 assert(!argT.isNull() && "Can't find 'id' type");
2451 ArgTys.push_back(argT);
2452 argT = Context->getObjCSelType();
2453 assert(!argT.isNull() && "Can't find 'SEL' type");
2454 ArgTys.push_back(argT);
2455 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002456 ArgTys, /*isVariadic=*/true);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002457 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002458 SourceLocation(),
2459 SourceLocation(),
Craig Topper8ae12032014-05-07 06:21:57 +00002460 msgSendIdent, msgSendType, nullptr,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002461 SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002462}
2463
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00002464// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(void);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002465void RewriteModernObjC::SynthMsgSendSuperFunctionDecl() {
2466 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00002467 SmallVector<QualType, 2> ArgTys;
2468 ArgTys.push_back(Context->VoidTy);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002469 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002470 ArgTys, /*isVariadic=*/true);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002471 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002472 SourceLocation(),
2473 SourceLocation(),
Craig Topper8ae12032014-05-07 06:21:57 +00002474 msgSendIdent, msgSendType,
2475 nullptr, SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002476}
2477
2478// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
2479void RewriteModernObjC::SynthMsgSendStretFunctionDecl() {
2480 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
2481 SmallVector<QualType, 16> ArgTys;
2482 QualType argT = Context->getObjCIdType();
2483 assert(!argT.isNull() && "Can't find 'id' type");
2484 ArgTys.push_back(argT);
2485 argT = Context->getObjCSelType();
2486 assert(!argT.isNull() && "Can't find 'SEL' type");
2487 ArgTys.push_back(argT);
2488 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002489 ArgTys, /*isVariadic=*/true);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002490 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002491 SourceLocation(),
2492 SourceLocation(),
Craig Topper8ae12032014-05-07 06:21:57 +00002493 msgSendIdent, msgSendType,
2494 nullptr, SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002495}
2496
2497// SynthMsgSendSuperStretFunctionDecl -
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00002498// id objc_msgSendSuper_stret(void);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002499void RewriteModernObjC::SynthMsgSendSuperStretFunctionDecl() {
2500 IdentifierInfo *msgSendIdent =
2501 &Context->Idents.get("objc_msgSendSuper_stret");
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00002502 SmallVector<QualType, 2> ArgTys;
2503 ArgTys.push_back(Context->VoidTy);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002504 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002505 ArgTys, /*isVariadic=*/true);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002506 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2507 SourceLocation(),
2508 SourceLocation(),
Chad Rosierac00fbc2013-01-04 22:40:33 +00002509 msgSendIdent,
Craig Topper8ae12032014-05-07 06:21:57 +00002510 msgSendType, nullptr,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002511 SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002512}
2513
2514// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
2515void RewriteModernObjC::SynthMsgSendFpretFunctionDecl() {
2516 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
2517 SmallVector<QualType, 16> ArgTys;
2518 QualType argT = Context->getObjCIdType();
2519 assert(!argT.isNull() && "Can't find 'id' type");
2520 ArgTys.push_back(argT);
2521 argT = Context->getObjCSelType();
2522 assert(!argT.isNull() && "Can't find 'SEL' type");
2523 ArgTys.push_back(argT);
2524 QualType msgSendType = getSimpleFunctionType(Context->DoubleTy,
Jordan Rose5c382722013-03-08 21:51:21 +00002525 ArgTys, /*isVariadic=*/true);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002526 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002527 SourceLocation(),
2528 SourceLocation(),
Craig Topper8ae12032014-05-07 06:21:57 +00002529 msgSendIdent, msgSendType,
2530 nullptr, SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002531}
2532
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00002533// SynthGetClassFunctionDecl - Class objc_getClass(const char *name);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002534void RewriteModernObjC::SynthGetClassFunctionDecl() {
2535 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
2536 SmallVector<QualType, 16> ArgTys;
2537 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00002538 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002539 ArgTys);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002540 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002541 SourceLocation(),
2542 SourceLocation(),
Craig Topper8ae12032014-05-07 06:21:57 +00002543 getClassIdent, getClassType,
2544 nullptr, SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002545}
2546
2547// SynthGetSuperClassFunctionDecl - Class class_getSuperclass(Class cls);
2548void RewriteModernObjC::SynthGetSuperClassFunctionDecl() {
2549 IdentifierInfo *getSuperClassIdent =
2550 &Context->Idents.get("class_getSuperclass");
2551 SmallVector<QualType, 16> ArgTys;
2552 ArgTys.push_back(Context->getObjCClassType());
2553 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002554 ArgTys);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002555 GetSuperClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2556 SourceLocation(),
2557 SourceLocation(),
2558 getSuperClassIdent,
Craig Topper8ae12032014-05-07 06:21:57 +00002559 getClassType, nullptr,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002560 SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002561}
2562
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00002563// SynthGetMetaClassFunctionDecl - Class objc_getMetaClass(const char *name);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002564void RewriteModernObjC::SynthGetMetaClassFunctionDecl() {
2565 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
2566 SmallVector<QualType, 16> ArgTys;
2567 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00002568 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002569 ArgTys);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002570 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002571 SourceLocation(),
2572 SourceLocation(),
2573 getClassIdent, getClassType,
Craig Topper8ae12032014-05-07 06:21:57 +00002574 nullptr, SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002575}
2576
2577Stmt *RewriteModernObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Richard Trieuddd01ce2014-06-09 22:53:25 +00002578 assert (Exp != nullptr && "Expected non-null ObjCStringLiteral");
Fariborz Jahanian11671902012-02-07 17:11:38 +00002579 QualType strType = getConstantStringStructType();
2580
2581 std::string S = "__NSConstantStringImpl_";
2582
2583 std::string tmpName = InFileName;
2584 unsigned i;
2585 for (i=0; i < tmpName.length(); i++) {
2586 char c = tmpName.at(i);
Alp Tokerd4733632013-12-05 04:47:09 +00002587 // replace any non-alphanumeric characters with '_'.
Jordan Rosea7d03842013-02-08 22:30:41 +00002588 if (!isAlphanumeric(c))
Fariborz Jahanian11671902012-02-07 17:11:38 +00002589 tmpName[i] = '_';
2590 }
2591 S += tmpName;
2592 S += "_";
2593 S += utostr(NumObjCStringLiterals++);
2594
2595 Preamble += "static __NSConstantStringImpl " + S;
2596 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2597 Preamble += "0x000007c8,"; // utf8_str
2598 // The pretty printer for StringLiteral handles escape characters properly.
2599 std::string prettyBufS;
2600 llvm::raw_string_ostream prettyBuf(prettyBufS);
Craig Topper8ae12032014-05-07 06:21:57 +00002601 Exp->getString()->printPretty(prettyBuf, nullptr, PrintingPolicy(LangOpts));
Fariborz Jahanian11671902012-02-07 17:11:38 +00002602 Preamble += prettyBuf.str();
2603 Preamble += ",";
2604 Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
2605
2606 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
2607 SourceLocation(), &Context->Idents.get(S),
Craig Topper8ae12032014-05-07 06:21:57 +00002608 strType, nullptr, SC_Static);
John McCall113bee02012-03-10 09:33:50 +00002609 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, false, strType, VK_LValue,
Fariborz Jahanian11671902012-02-07 17:11:38 +00002610 SourceLocation());
2611 Expr *Unop = new (Context) UnaryOperator(DRE, UO_AddrOf,
2612 Context->getPointerType(DRE->getType()),
2613 VK_RValue, OK_Ordinary,
2614 SourceLocation());
2615 // cast to NSConstantString *
2616 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Exp->getType(),
2617 CK_CPointerToObjCPointerCast, Unop);
2618 ReplaceStmt(Exp, cast);
2619 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2620 return cast;
2621}
2622
Fariborz Jahanian307b7ad2012-03-27 20:17:30 +00002623Stmt *RewriteModernObjC::RewriteObjCBoolLiteralExpr(ObjCBoolLiteralExpr *Exp) {
2624 unsigned IntSize =
2625 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
2626
2627 Expr *FlagExp = IntegerLiteral::Create(*Context,
2628 llvm::APInt(IntSize, Exp->getValue()),
2629 Context->IntTy, Exp->getLocation());
2630 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Context->ObjCBuiltinBoolTy,
2631 CK_BitCast, FlagExp);
2632 ParenExpr *PE = new (Context) ParenExpr(Exp->getLocation(), Exp->getExprLoc(),
2633 cast);
2634 ReplaceStmt(Exp, PE);
2635 return PE;
2636}
2637
Patrick Beard0caa3942012-04-19 00:25:12 +00002638Stmt *RewriteModernObjC::RewriteObjCBoxedExpr(ObjCBoxedExpr *Exp) {
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002639 // synthesize declaration of helper functions needed in this routine.
2640 if (!SelGetUidFunctionDecl)
2641 SynthSelGetUidFunctionDecl();
2642 // use objc_msgSend() for all.
2643 if (!MsgSendFunctionDecl)
2644 SynthMsgSendFunctionDecl();
2645 if (!GetClassFunctionDecl)
2646 SynthGetClassFunctionDecl();
2647
2648 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2649 SourceLocation StartLoc = Exp->getLocStart();
2650 SourceLocation EndLoc = Exp->getLocEnd();
2651
2652 // Synthesize a call to objc_msgSend().
2653 SmallVector<Expr*, 4> MsgExprs;
2654 SmallVector<Expr*, 4> ClsExprs;
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002655
Patrick Beard0caa3942012-04-19 00:25:12 +00002656 // Create a call to objc_getClass("<BoxingClass>"). It will be the 1st argument.
2657 ObjCMethodDecl *BoxingMethod = Exp->getBoxingMethod();
2658 ObjCInterfaceDecl *BoxingClass = BoxingMethod->getClassInterface();
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002659
Patrick Beard0caa3942012-04-19 00:25:12 +00002660 IdentifierInfo *clsName = BoxingClass->getIdentifier();
Benjamin Kramerfc188422014-02-25 12:26:11 +00002661 ClsExprs.push_back(getStringLiteral(clsName->getName()));
Craig Toppercf2126e2015-10-22 03:13:07 +00002662 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl, ClsExprs,
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002663 StartLoc, EndLoc);
2664 MsgExprs.push_back(Cls);
2665
Patrick Beard0caa3942012-04-19 00:25:12 +00002666 // Create a call to sel_registerName("<BoxingMethod>:"), etc.
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002667 // it will be the 2nd argument.
2668 SmallVector<Expr*, 4> SelExprs;
Benjamin Kramerfc188422014-02-25 12:26:11 +00002669 SelExprs.push_back(
2670 getStringLiteral(BoxingMethod->getSelector().getAsString()));
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002671 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
Craig Toppercf2126e2015-10-22 03:13:07 +00002672 SelExprs, StartLoc, EndLoc);
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002673 MsgExprs.push_back(SelExp);
2674
Patrick Beard0caa3942012-04-19 00:25:12 +00002675 // User provided sub-expression is the 3rd, and last, argument.
2676 Expr *subExpr = Exp->getSubExpr();
2677 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(subExpr)) {
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002678 QualType type = ICE->getType();
2679 const Expr *SubExpr = ICE->IgnoreParenImpCasts();
2680 CastKind CK = CK_BitCast;
2681 if (SubExpr->getType()->isIntegralType(*Context) && type->isBooleanType())
2682 CK = CK_IntegralToBoolean;
Patrick Beard0caa3942012-04-19 00:25:12 +00002683 subExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, subExpr);
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002684 }
Patrick Beard0caa3942012-04-19 00:25:12 +00002685 MsgExprs.push_back(subExpr);
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002686
2687 SmallVector<QualType, 4> ArgTypes;
Fariborz Jahanianf8e68e22015-04-09 18:36:50 +00002688 ArgTypes.push_back(Context->getObjCClassType());
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002689 ArgTypes.push_back(Context->getObjCSelType());
Aaron Ballman43b68be2014-03-07 17:50:17 +00002690 for (const auto PI : BoxingMethod->parameters())
2691 ArgTypes.push_back(PI->getType());
Patrick Beard0caa3942012-04-19 00:25:12 +00002692
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002693 QualType returnType = Exp->getType();
2694 // Get the type, we will need to reference it in a couple spots.
2695 QualType msgSendType = MsgSendFlavor->getType();
2696
2697 // Create a reference to the objc_msgSend() declaration.
2698 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
2699 VK_LValue, SourceLocation());
2700
2701 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
Patrick Beard0caa3942012-04-19 00:25:12 +00002702 Context->getPointerType(Context->VoidTy),
2703 CK_BitCast, DRE);
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002704
2705 // Now do the "normal" pointer to function cast.
2706 QualType castType =
Jordan Rose5c382722013-03-08 21:51:21 +00002707 getSimpleFunctionType(returnType, ArgTypes, BoxingMethod->isVariadic());
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002708 castType = Context->getPointerType(castType);
2709 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2710 cast);
2711
2712 // Don't forget the parens to enforce the proper binding.
2713 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
2714
2715 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Alp Toker314cc812014-01-25 16:55:45 +00002716 CallExpr *CE = new (Context)
2717 CallExpr(*Context, PE, MsgExprs, FT->getReturnType(), VK_RValue, EndLoc);
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002718 ReplaceStmt(Exp, CE);
2719 return CE;
2720}
2721
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002722Stmt *RewriteModernObjC::RewriteObjCArrayLiteralExpr(ObjCArrayLiteral *Exp) {
2723 // synthesize declaration of helper functions needed in this routine.
2724 if (!SelGetUidFunctionDecl)
2725 SynthSelGetUidFunctionDecl();
2726 // use objc_msgSend() for all.
2727 if (!MsgSendFunctionDecl)
2728 SynthMsgSendFunctionDecl();
2729 if (!GetClassFunctionDecl)
2730 SynthGetClassFunctionDecl();
2731
2732 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2733 SourceLocation StartLoc = Exp->getLocStart();
2734 SourceLocation EndLoc = Exp->getLocEnd();
2735
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002736 // Build the expression: __NSContainer_literal(int, ...).arr
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00002737 QualType IntQT = Context->IntTy;
2738 QualType NSArrayFType =
Jordan Rose5c382722013-03-08 21:51:21 +00002739 getSimpleFunctionType(Context->VoidTy, IntQT, true);
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002740 std::string NSArrayFName("__NSContainer_literal");
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00002741 FunctionDecl *NSArrayFD = SynthBlockInitFunctionDecl(NSArrayFName);
2742 DeclRefExpr *NSArrayDRE =
2743 new (Context) DeclRefExpr(NSArrayFD, false, NSArrayFType, VK_RValue,
2744 SourceLocation());
2745
2746 SmallVector<Expr*, 16> InitExprs;
2747 unsigned NumElements = Exp->getNumElements();
2748 unsigned UnsignedIntSize =
2749 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
2750 Expr *count = IntegerLiteral::Create(*Context,
2751 llvm::APInt(UnsignedIntSize, NumElements),
2752 Context->UnsignedIntTy, SourceLocation());
2753 InitExprs.push_back(count);
2754 for (unsigned i = 0; i < NumElements; i++)
2755 InitExprs.push_back(Exp->getElement(i));
2756 Expr *NSArrayCallExpr =
Benjamin Kramerc215e762012-08-24 11:54:20 +00002757 new (Context) CallExpr(*Context, NSArrayDRE, InitExprs,
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00002758 NSArrayFType, VK_LValue, SourceLocation());
Craig Topper8ae12032014-05-07 06:21:57 +00002759
2760 FieldDecl *ARRFD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00002761 SourceLocation(),
2762 &Context->Idents.get("arr"),
Fariborz Jahanianf8e68e22015-04-09 18:36:50 +00002763 Context->getPointerType(Context->VoidPtrTy),
2764 nullptr, /*BitWidth=*/nullptr,
2765 /*Mutable=*/true, ICIS_NoInit);
2766 MemberExpr *ArrayLiteralME = new (Context)
2767 MemberExpr(NSArrayCallExpr, false, SourceLocation(), ARRFD,
2768 SourceLocation(), ARRFD->getType(), VK_LValue, OK_Ordinary);
2769 QualType ConstIdT = Context->getObjCIdType().withConst();
2770 CStyleCastExpr * ArrayLiteralObjects =
2771 NoTypeInfoCStyleCastExpr(Context,
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00002772 Context->getPointerType(ConstIdT),
2773 CK_BitCast,
2774 ArrayLiteralME);
2775
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002776 // Synthesize a call to objc_msgSend().
2777 SmallVector<Expr*, 32> MsgExprs;
2778 SmallVector<Expr*, 4> ClsExprs;
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002779 QualType expType = Exp->getType();
2780
2781 // Create a call to objc_getClass("NSArray"). It will be th 1st argument.
2782 ObjCInterfaceDecl *Class =
2783 expType->getPointeeType()->getAs<ObjCObjectType>()->getInterface();
2784
2785 IdentifierInfo *clsName = Class->getIdentifier();
Benjamin Kramerfc188422014-02-25 12:26:11 +00002786 ClsExprs.push_back(getStringLiteral(clsName->getName()));
Craig Toppercf2126e2015-10-22 03:13:07 +00002787 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl, ClsExprs,
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002788 StartLoc, EndLoc);
2789 MsgExprs.push_back(Cls);
2790
2791 // Create a call to sel_registerName("arrayWithObjects:count:").
2792 // it will be the 2nd argument.
2793 SmallVector<Expr*, 4> SelExprs;
2794 ObjCMethodDecl *ArrayMethod = Exp->getArrayWithObjectsMethod();
Benjamin Kramerfc188422014-02-25 12:26:11 +00002795 SelExprs.push_back(
2796 getStringLiteral(ArrayMethod->getSelector().getAsString()));
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002797 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
Craig Toppercf2126e2015-10-22 03:13:07 +00002798 SelExprs, StartLoc, EndLoc);
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002799 MsgExprs.push_back(SelExp);
2800
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00002801 // (const id [])objects
2802 MsgExprs.push_back(ArrayLiteralObjects);
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002803
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00002804 // (NSUInteger)cnt
2805 Expr *cnt = IntegerLiteral::Create(*Context,
2806 llvm::APInt(UnsignedIntSize, NumElements),
2807 Context->UnsignedIntTy, SourceLocation());
2808 MsgExprs.push_back(cnt);
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002809
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002810 SmallVector<QualType, 4> ArgTypes;
Fariborz Jahanianf8e68e22015-04-09 18:36:50 +00002811 ArgTypes.push_back(Context->getObjCClassType());
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002812 ArgTypes.push_back(Context->getObjCSelType());
Aaron Ballman43b68be2014-03-07 17:50:17 +00002813 for (const auto *PI : ArrayMethod->params())
2814 ArgTypes.push_back(PI->getType());
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002815
2816 QualType returnType = Exp->getType();
2817 // Get the type, we will need to reference it in a couple spots.
2818 QualType msgSendType = MsgSendFlavor->getType();
2819
2820 // Create a reference to the objc_msgSend() declaration.
2821 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
2822 VK_LValue, SourceLocation());
2823
2824 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
2825 Context->getPointerType(Context->VoidTy),
2826 CK_BitCast, DRE);
2827
2828 // Now do the "normal" pointer to function cast.
2829 QualType castType =
Jordan Rose5c382722013-03-08 21:51:21 +00002830 getSimpleFunctionType(returnType, ArgTypes, ArrayMethod->isVariadic());
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002831 castType = Context->getPointerType(castType);
2832 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2833 cast);
2834
2835 // Don't forget the parens to enforce the proper binding.
2836 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
2837
2838 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Alp Toker314cc812014-01-25 16:55:45 +00002839 CallExpr *CE = new (Context)
2840 CallExpr(*Context, PE, MsgExprs, FT->getReturnType(), VK_RValue, EndLoc);
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002841 ReplaceStmt(Exp, CE);
2842 return CE;
2843}
2844
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002845Stmt *RewriteModernObjC::RewriteObjCDictionaryLiteralExpr(ObjCDictionaryLiteral *Exp) {
2846 // synthesize declaration of helper functions needed in this routine.
2847 if (!SelGetUidFunctionDecl)
2848 SynthSelGetUidFunctionDecl();
2849 // use objc_msgSend() for all.
2850 if (!MsgSendFunctionDecl)
2851 SynthMsgSendFunctionDecl();
2852 if (!GetClassFunctionDecl)
2853 SynthGetClassFunctionDecl();
2854
2855 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2856 SourceLocation StartLoc = Exp->getLocStart();
2857 SourceLocation EndLoc = Exp->getLocEnd();
2858
2859 // Build the expression: __NSContainer_literal(int, ...).arr
2860 QualType IntQT = Context->IntTy;
2861 QualType NSDictFType =
Jordan Rose5c382722013-03-08 21:51:21 +00002862 getSimpleFunctionType(Context->VoidTy, IntQT, true);
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002863 std::string NSDictFName("__NSContainer_literal");
2864 FunctionDecl *NSDictFD = SynthBlockInitFunctionDecl(NSDictFName);
2865 DeclRefExpr *NSDictDRE =
2866 new (Context) DeclRefExpr(NSDictFD, false, NSDictFType, VK_RValue,
2867 SourceLocation());
2868
2869 SmallVector<Expr*, 16> KeyExprs;
2870 SmallVector<Expr*, 16> ValueExprs;
2871
2872 unsigned NumElements = Exp->getNumElements();
2873 unsigned UnsignedIntSize =
2874 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
2875 Expr *count = IntegerLiteral::Create(*Context,
2876 llvm::APInt(UnsignedIntSize, NumElements),
2877 Context->UnsignedIntTy, SourceLocation());
2878 KeyExprs.push_back(count);
2879 ValueExprs.push_back(count);
2880 for (unsigned i = 0; i < NumElements; i++) {
2881 ObjCDictionaryElement Element = Exp->getKeyValueElement(i);
2882 KeyExprs.push_back(Element.Key);
2883 ValueExprs.push_back(Element.Value);
2884 }
2885
2886 // (const id [])objects
2887 Expr *NSValueCallExpr =
Benjamin Kramerc215e762012-08-24 11:54:20 +00002888 new (Context) CallExpr(*Context, NSDictDRE, ValueExprs,
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002889 NSDictFType, VK_LValue, SourceLocation());
Craig Topper8ae12032014-05-07 06:21:57 +00002890
2891 FieldDecl *ARRFD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002892 SourceLocation(),
2893 &Context->Idents.get("arr"),
Fariborz Jahanianf8e68e22015-04-09 18:36:50 +00002894 Context->getPointerType(Context->VoidPtrTy),
2895 nullptr, /*BitWidth=*/nullptr,
2896 /*Mutable=*/true, ICIS_NoInit);
2897 MemberExpr *DictLiteralValueME = new (Context)
2898 MemberExpr(NSValueCallExpr, false, SourceLocation(), ARRFD,
2899 SourceLocation(), ARRFD->getType(), VK_LValue, OK_Ordinary);
2900 QualType ConstIdT = Context->getObjCIdType().withConst();
2901 CStyleCastExpr * DictValueObjects =
2902 NoTypeInfoCStyleCastExpr(Context,
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002903 Context->getPointerType(ConstIdT),
2904 CK_BitCast,
2905 DictLiteralValueME);
2906 // (const id <NSCopying> [])keys
Fariborz Jahanianf8e68e22015-04-09 18:36:50 +00002907 Expr *NSKeyCallExpr =
2908 new (Context) CallExpr(*Context, NSDictDRE, KeyExprs,
2909 NSDictFType, VK_LValue, SourceLocation());
2910
2911 MemberExpr *DictLiteralKeyME = new (Context)
2912 MemberExpr(NSKeyCallExpr, false, SourceLocation(), ARRFD,
2913 SourceLocation(), ARRFD->getType(), VK_LValue, OK_Ordinary);
2914
2915 CStyleCastExpr * DictKeyObjects =
2916 NoTypeInfoCStyleCastExpr(Context,
2917 Context->getPointerType(ConstIdT),
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002918 CK_BitCast,
2919 DictLiteralKeyME);
2920
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002921 // Synthesize a call to objc_msgSend().
2922 SmallVector<Expr*, 32> MsgExprs;
2923 SmallVector<Expr*, 4> ClsExprs;
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002924 QualType expType = Exp->getType();
2925
2926 // Create a call to objc_getClass("NSArray"). It will be th 1st argument.
2927 ObjCInterfaceDecl *Class =
2928 expType->getPointeeType()->getAs<ObjCObjectType>()->getInterface();
2929
2930 IdentifierInfo *clsName = Class->getIdentifier();
Benjamin Kramerfc188422014-02-25 12:26:11 +00002931 ClsExprs.push_back(getStringLiteral(clsName->getName()));
Craig Toppercf2126e2015-10-22 03:13:07 +00002932 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl, ClsExprs,
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002933 StartLoc, EndLoc);
2934 MsgExprs.push_back(Cls);
2935
2936 // Create a call to sel_registerName("arrayWithObjects:count:").
2937 // it will be the 2nd argument.
2938 SmallVector<Expr*, 4> SelExprs;
2939 ObjCMethodDecl *DictMethod = Exp->getDictWithObjectsMethod();
Benjamin Kramerfc188422014-02-25 12:26:11 +00002940 SelExprs.push_back(getStringLiteral(DictMethod->getSelector().getAsString()));
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002941 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
Craig Toppercf2126e2015-10-22 03:13:07 +00002942 SelExprs, StartLoc, EndLoc);
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002943 MsgExprs.push_back(SelExp);
2944
2945 // (const id [])objects
2946 MsgExprs.push_back(DictValueObjects);
2947
2948 // (const id <NSCopying> [])keys
2949 MsgExprs.push_back(DictKeyObjects);
2950
2951 // (NSUInteger)cnt
2952 Expr *cnt = IntegerLiteral::Create(*Context,
2953 llvm::APInt(UnsignedIntSize, NumElements),
2954 Context->UnsignedIntTy, SourceLocation());
2955 MsgExprs.push_back(cnt);
2956
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002957 SmallVector<QualType, 8> ArgTypes;
Fariborz Jahanianf8e68e22015-04-09 18:36:50 +00002958 ArgTypes.push_back(Context->getObjCClassType());
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002959 ArgTypes.push_back(Context->getObjCSelType());
Aaron Ballman43b68be2014-03-07 17:50:17 +00002960 for (const auto *PI : DictMethod->params()) {
2961 QualType T = PI->getType();
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002962 if (const PointerType* PT = T->getAs<PointerType>()) {
2963 QualType PointeeTy = PT->getPointeeType();
2964 convertToUnqualifiedObjCType(PointeeTy);
2965 T = Context->getPointerType(PointeeTy);
2966 }
2967 ArgTypes.push_back(T);
2968 }
2969
2970 QualType returnType = Exp->getType();
2971 // Get the type, we will need to reference it in a couple spots.
2972 QualType msgSendType = MsgSendFlavor->getType();
2973
2974 // Create a reference to the objc_msgSend() declaration.
2975 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
2976 VK_LValue, SourceLocation());
2977
2978 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
2979 Context->getPointerType(Context->VoidTy),
2980 CK_BitCast, DRE);
2981
2982 // Now do the "normal" pointer to function cast.
2983 QualType castType =
Jordan Rose5c382722013-03-08 21:51:21 +00002984 getSimpleFunctionType(returnType, ArgTypes, DictMethod->isVariadic());
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002985 castType = Context->getPointerType(castType);
2986 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2987 cast);
2988
2989 // Don't forget the parens to enforce the proper binding.
2990 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
2991
2992 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Alp Toker314cc812014-01-25 16:55:45 +00002993 CallExpr *CE = new (Context)
2994 CallExpr(*Context, PE, MsgExprs, FT->getReturnType(), VK_RValue, EndLoc);
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002995 ReplaceStmt(Exp, CE);
2996 return CE;
2997}
2998
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00002999// struct __rw_objc_super {
3000// struct objc_object *object; struct objc_object *superClass;
3001// };
Fariborz Jahanian11671902012-02-07 17:11:38 +00003002QualType RewriteModernObjC::getSuperStructType() {
3003 if (!SuperStructDecl) {
3004 SuperStructDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
3005 SourceLocation(), SourceLocation(),
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003006 &Context->Idents.get("__rw_objc_super"));
Fariborz Jahanian11671902012-02-07 17:11:38 +00003007 QualType FieldTypes[2];
3008
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003009 // struct objc_object *object;
Fariborz Jahanian11671902012-02-07 17:11:38 +00003010 FieldTypes[0] = Context->getObjCIdType();
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003011 // struct objc_object *superClass;
3012 FieldTypes[1] = Context->getObjCIdType();
Fariborz Jahanian11671902012-02-07 17:11:38 +00003013
3014 // Create fields
3015 for (unsigned i = 0; i < 2; ++i) {
3016 SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
3017 SourceLocation(),
Craig Topper8ae12032014-05-07 06:21:57 +00003018 SourceLocation(), nullptr,
3019 FieldTypes[i], nullptr,
3020 /*BitWidth=*/nullptr,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003021 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00003022 ICIS_NoInit));
Fariborz Jahanian11671902012-02-07 17:11:38 +00003023 }
3024
3025 SuperStructDecl->completeDefinition();
3026 }
3027 return Context->getTagDeclType(SuperStructDecl);
3028}
3029
3030QualType RewriteModernObjC::getConstantStringStructType() {
3031 if (!ConstantStringDecl) {
3032 ConstantStringDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
3033 SourceLocation(), SourceLocation(),
3034 &Context->Idents.get("__NSConstantStringImpl"));
3035 QualType FieldTypes[4];
3036
3037 // struct objc_object *receiver;
3038 FieldTypes[0] = Context->getObjCIdType();
3039 // int flags;
3040 FieldTypes[1] = Context->IntTy;
3041 // char *str;
3042 FieldTypes[2] = Context->getPointerType(Context->CharTy);
3043 // long length;
3044 FieldTypes[3] = Context->LongTy;
3045
3046 // Create fields
3047 for (unsigned i = 0; i < 4; ++i) {
3048 ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
3049 ConstantStringDecl,
3050 SourceLocation(),
Craig Topper8ae12032014-05-07 06:21:57 +00003051 SourceLocation(), nullptr,
3052 FieldTypes[i], nullptr,
3053 /*BitWidth=*/nullptr,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003054 /*Mutable=*/true,
Richard Smith2b013182012-06-10 03:12:00 +00003055 ICIS_NoInit));
Fariborz Jahanian11671902012-02-07 17:11:38 +00003056 }
3057
3058 ConstantStringDecl->completeDefinition();
3059 }
3060 return Context->getTagDeclType(ConstantStringDecl);
3061}
3062
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003063/// getFunctionSourceLocation - returns start location of a function
3064/// definition. Complication arises when function has declared as
3065/// extern "C" or extern "C" {...}
3066static SourceLocation getFunctionSourceLocation (RewriteModernObjC &R,
3067 FunctionDecl *FD) {
3068 if (FD->isExternC() && !FD->isMain()) {
3069 const DeclContext *DC = FD->getDeclContext();
3070 if (const LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(DC))
3071 // if it is extern "C" {...}, return function decl's own location.
3072 if (!LSD->getRBraceLoc().isValid())
3073 return LSD->getExternLoc();
3074 }
Rafael Espindola6ae7e502013-04-03 19:27:57 +00003075 if (FD->getStorageClass() != SC_None)
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003076 R.RewriteBlockLiteralFunctionDecl(FD);
3077 return FD->getTypeSpecStartLoc();
3078}
3079
Fariborz Jahanianaa4a2422012-11-06 17:30:23 +00003080void RewriteModernObjC::RewriteLineDirective(const Decl *D) {
3081
3082 SourceLocation Location = D->getLocation();
3083
Fariborz Jahaniane4c7e852013-02-08 00:27:34 +00003084 if (Location.isFileID() && GenerateLineInfo) {
Fariborz Jahanian83dadc72012-11-07 18:15:53 +00003085 std::string LineString("\n#line ");
Fariborz Jahanianaa4a2422012-11-06 17:30:23 +00003086 PresumedLoc PLoc = SM->getPresumedLoc(Location);
3087 LineString += utostr(PLoc.getLine());
3088 LineString += " \"";
NAKAMURA Takumib46a05c2012-11-06 22:45:31 +00003089 LineString += Lexer::Stringify(PLoc.getFilename());
Fariborz Jahanianaa4a2422012-11-06 17:30:23 +00003090 if (isa<ObjCMethodDecl>(D))
3091 LineString += "\"";
3092 else LineString += "\"\n";
3093
3094 Location = D->getLocStart();
3095 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
3096 if (FD->isExternC() && !FD->isMain()) {
3097 const DeclContext *DC = FD->getDeclContext();
3098 if (const LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(DC))
3099 // if it is extern "C" {...}, return function decl's own location.
3100 if (!LSD->getRBraceLoc().isValid())
3101 Location = LSD->getExternLoc();
3102 }
3103 }
3104 InsertText(Location, LineString);
3105 }
3106}
3107
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003108/// SynthMsgSendStretCallExpr - This routine translates message expression
3109/// into a call to objc_msgSend_stret() entry point. Tricky part is that
3110/// nil check on receiver must be performed before calling objc_msgSend_stret.
3111/// MsgSendStretFlavor - function declaration objc_msgSend_stret(...)
3112/// msgSendType - function type of objc_msgSend_stret(...)
3113/// returnType - Result type of the method being synthesized.
3114/// ArgTypes - type of the arguments passed to objc_msgSend_stret, starting with receiver type.
3115/// MsgExprs - list of argument expressions being passed to objc_msgSend_stret,
3116/// starting with receiver.
3117/// Method - Method being rewritten.
3118Expr *RewriteModernObjC::SynthMsgSendStretCallExpr(FunctionDecl *MsgSendStretFlavor,
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003119 QualType returnType,
3120 SmallVectorImpl<QualType> &ArgTypes,
3121 SmallVectorImpl<Expr*> &MsgExprs,
3122 ObjCMethodDecl *Method) {
3123 // Now do the "normal" pointer to function cast.
Jordan Rose5c382722013-03-08 21:51:21 +00003124 QualType castType = getSimpleFunctionType(returnType, ArgTypes,
3125 Method ? Method->isVariadic()
3126 : false);
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003127 castType = Context->getPointerType(castType);
3128
3129 // build type for containing the objc_msgSend_stret object.
3130 static unsigned stretCount=0;
3131 std::string name = "__Stret"; name += utostr(stretCount);
Fariborz Jahanian1a112522012-07-25 21:48:36 +00003132 std::string str =
3133 "extern \"C\" void * __cdecl memset(void *_Dst, int _Val, size_t _Size);\n";
Fariborz Jahanianb1a21242013-09-09 19:59:59 +00003134 str += "namespace {\n";
Fariborz Jahanian1a112522012-07-25 21:48:36 +00003135 str += "struct "; str += name;
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003136 str += " {\n\t";
3137 str += name;
3138 str += "(id receiver, SEL sel";
3139 for (unsigned i = 2; i < ArgTypes.size(); i++) {
Fariborz Jahanian2794ad52012-06-29 19:55:46 +00003140 std::string ArgName = "arg"; ArgName += utostr(i);
3141 ArgTypes[i].getAsStringInternal(ArgName, Context->getPrintingPolicy());
3142 str += ", "; str += ArgName;
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003143 }
3144 // could be vararg.
3145 for (unsigned i = ArgTypes.size(); i < MsgExprs.size(); i++) {
Fariborz Jahanian2794ad52012-06-29 19:55:46 +00003146 std::string ArgName = "arg"; ArgName += utostr(i);
3147 MsgExprs[i]->getType().getAsStringInternal(ArgName,
3148 Context->getPrintingPolicy());
3149 str += ", "; str += ArgName;
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003150 }
3151
3152 str += ") {\n";
Fariborz Jahanianb1a21242013-09-09 19:59:59 +00003153 str += "\t unsigned size = sizeof(";
3154 str += returnType.getAsString(Context->getPrintingPolicy()); str += ");\n";
3155
3156 str += "\t if (size == 1 || size == 2 || size == 4 || size == 8)\n";
3157
3158 str += "\t s = (("; str += castType.getAsString(Context->getPrintingPolicy());
3159 str += ")(void *)objc_msgSend)(receiver, sel";
3160 for (unsigned i = 2; i < ArgTypes.size(); i++) {
3161 str += ", arg"; str += utostr(i);
3162 }
3163 // could be vararg.
3164 for (unsigned i = ArgTypes.size(); i < MsgExprs.size(); i++) {
3165 str += ", arg"; str += utostr(i);
3166 }
3167 str+= ");\n";
3168
3169 str += "\t else if (receiver == 0)\n";
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003170 str += "\t memset((void*)&s, 0, sizeof(s));\n";
3171 str += "\t else\n";
Fariborz Jahanianb1a21242013-09-09 19:59:59 +00003172
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003173 str += "\t s = (("; str += castType.getAsString(Context->getPrintingPolicy());
3174 str += ")(void *)objc_msgSend_stret)(receiver, sel";
3175 for (unsigned i = 2; i < ArgTypes.size(); i++) {
3176 str += ", arg"; str += utostr(i);
3177 }
3178 // could be vararg.
3179 for (unsigned i = ArgTypes.size(); i < MsgExprs.size(); i++) {
3180 str += ", arg"; str += utostr(i);
3181 }
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003182 str += ");\n";
Fariborz Jahanianb1a21242013-09-09 19:59:59 +00003183
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003184 str += "\t}\n";
3185 str += "\t"; str += returnType.getAsString(Context->getPrintingPolicy());
3186 str += " s;\n";
Fariborz Jahanianb1a21242013-09-09 19:59:59 +00003187 str += "};\n};\n\n";
Fariborz Jahanianf1f36c62012-08-21 18:56:50 +00003188 SourceLocation FunLocStart;
3189 if (CurFunctionDef)
3190 FunLocStart = getFunctionSourceLocation(*this, CurFunctionDef);
3191 else {
3192 assert(CurMethodDef && "SynthMsgSendStretCallExpr - CurMethodDef is null");
3193 FunLocStart = CurMethodDef->getLocStart();
3194 }
3195
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003196 InsertText(FunLocStart, str);
3197 ++stretCount;
3198
3199 // AST for __Stretn(receiver, args).s;
3200 IdentifierInfo *ID = &Context->Idents.get(name);
3201 FunctionDecl *FD = FunctionDecl::Create(*Context, TUDecl, SourceLocation(),
Craig Topper8ae12032014-05-07 06:21:57 +00003202 SourceLocation(), ID, castType,
3203 nullptr, SC_Extern, false, false);
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003204 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, false, castType, VK_RValue,
3205 SourceLocation());
Benjamin Kramerc215e762012-08-24 11:54:20 +00003206 CallExpr *STCE = new (Context) CallExpr(*Context, DRE, MsgExprs,
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003207 castType, VK_LValue, SourceLocation());
Craig Topper8ae12032014-05-07 06:21:57 +00003208
3209 FieldDecl *FieldD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003210 SourceLocation(),
3211 &Context->Idents.get("s"),
Fariborz Jahanianf8e68e22015-04-09 18:36:50 +00003212 returnType, nullptr,
3213 /*BitWidth=*/nullptr,
3214 /*Mutable=*/true, ICIS_NoInit);
3215 MemberExpr *ME = new (Context)
3216 MemberExpr(STCE, false, SourceLocation(), FieldD, SourceLocation(),
3217 FieldD->getType(), VK_LValue, OK_Ordinary);
3218
3219 return ME;
3220}
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003221
Fariborz Jahanian11671902012-02-07 17:11:38 +00003222Stmt *RewriteModernObjC::SynthMessageExpr(ObjCMessageExpr *Exp,
3223 SourceLocation StartLoc,
3224 SourceLocation EndLoc) {
3225 if (!SelGetUidFunctionDecl)
3226 SynthSelGetUidFunctionDecl();
3227 if (!MsgSendFunctionDecl)
3228 SynthMsgSendFunctionDecl();
3229 if (!MsgSendSuperFunctionDecl)
3230 SynthMsgSendSuperFunctionDecl();
3231 if (!MsgSendStretFunctionDecl)
3232 SynthMsgSendStretFunctionDecl();
3233 if (!MsgSendSuperStretFunctionDecl)
3234 SynthMsgSendSuperStretFunctionDecl();
3235 if (!MsgSendFpretFunctionDecl)
3236 SynthMsgSendFpretFunctionDecl();
3237 if (!GetClassFunctionDecl)
3238 SynthGetClassFunctionDecl();
3239 if (!GetSuperClassFunctionDecl)
3240 SynthGetSuperClassFunctionDecl();
3241 if (!GetMetaClassFunctionDecl)
3242 SynthGetMetaClassFunctionDecl();
3243
3244 // default to objc_msgSend().
3245 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
3246 // May need to use objc_msgSend_stret() as well.
Craig Topper8ae12032014-05-07 06:21:57 +00003247 FunctionDecl *MsgSendStretFlavor = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00003248 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
Alp Toker314cc812014-01-25 16:55:45 +00003249 QualType resultType = mDecl->getReturnType();
Fariborz Jahanian11671902012-02-07 17:11:38 +00003250 if (resultType->isRecordType())
3251 MsgSendStretFlavor = MsgSendStretFunctionDecl;
3252 else if (resultType->isRealFloatingType())
3253 MsgSendFlavor = MsgSendFpretFunctionDecl;
3254 }
3255
3256 // Synthesize a call to objc_msgSend().
3257 SmallVector<Expr*, 8> MsgExprs;
3258 switch (Exp->getReceiverKind()) {
3259 case ObjCMessageExpr::SuperClass: {
3260 MsgSendFlavor = MsgSendSuperFunctionDecl;
3261 if (MsgSendStretFlavor)
3262 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
3263 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
3264
3265 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
3266
3267 SmallVector<Expr*, 4> InitExprs;
3268
3269 // set the receiver to self, the first argument to all methods.
3270 InitExprs.push_back(
3271 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3272 CK_BitCast,
3273 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCall113bee02012-03-10 09:33:50 +00003274 false,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003275 Context->getObjCIdType(),
3276 VK_RValue,
3277 SourceLocation()))
3278 ); // set the 'receiver'.
3279
3280 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3281 SmallVector<Expr*, 8> ClsExprs;
Benjamin Kramerfc188422014-02-25 12:26:11 +00003282 ClsExprs.push_back(getStringLiteral(ClassDecl->getIdentifier()->getName()));
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00003283 // (Class)objc_getClass("CurrentClass")
Fariborz Jahanian11671902012-02-07 17:11:38 +00003284 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
Craig Toppercf2126e2015-10-22 03:13:07 +00003285 ClsExprs, StartLoc, EndLoc);
Fariborz Jahanian11671902012-02-07 17:11:38 +00003286 ClsExprs.clear();
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00003287 ClsExprs.push_back(Cls);
Craig Toppercf2126e2015-10-22 03:13:07 +00003288 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl, ClsExprs,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003289 StartLoc, EndLoc);
3290
3291 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3292 // To turn off a warning, type-cast to 'id'
3293 InitExprs.push_back( // set 'super class', using class_getSuperclass().
3294 NoTypeInfoCStyleCastExpr(Context,
3295 Context->getObjCIdType(),
3296 CK_BitCast, Cls));
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003297 // struct __rw_objc_super
Fariborz Jahanian11671902012-02-07 17:11:38 +00003298 QualType superType = getSuperStructType();
3299 Expr *SuperRep;
3300
3301 if (LangOpts.MicrosoftExt) {
Benjamin Kramer60509af2013-09-09 14:48:42 +00003302 SynthSuperConstructorFunctionDecl();
3303 // Simulate a constructor call...
3304 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperConstructorFunctionDecl,
John McCall113bee02012-03-10 09:33:50 +00003305 false, superType, VK_LValue,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003306 SourceLocation());
Benjamin Kramerc215e762012-08-24 11:54:20 +00003307 SuperRep = new (Context) CallExpr(*Context, DRE, InitExprs,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003308 superType, VK_LValue,
3309 SourceLocation());
3310 // The code for super is a little tricky to prevent collision with
3311 // the structure definition in the header. The rewriter has it's own
3312 // internal definition (__rw_objc_super) that is uses. This is why
3313 // we need the cast below. For example:
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003314 // (struct __rw_objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
Fariborz Jahanian11671902012-02-07 17:11:38 +00003315 //
3316 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
3317 Context->getPointerType(SuperRep->getType()),
3318 VK_RValue, OK_Ordinary,
3319 SourceLocation());
3320 SuperRep = NoTypeInfoCStyleCastExpr(Context,
3321 Context->getPointerType(superType),
3322 CK_BitCast, SuperRep);
3323 } else {
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003324 // (struct __rw_objc_super) { <exprs from above> }
Fariborz Jahanian11671902012-02-07 17:11:38 +00003325 InitListExpr *ILE =
Benjamin Kramerc215e762012-08-24 11:54:20 +00003326 new (Context) InitListExpr(*Context, SourceLocation(), InitExprs,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003327 SourceLocation());
3328 TypeSourceInfo *superTInfo
3329 = Context->getTrivialTypeSourceInfo(superType);
3330 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
3331 superType, VK_LValue,
3332 ILE, false);
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003333 // struct __rw_objc_super *
Fariborz Jahanian11671902012-02-07 17:11:38 +00003334 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
3335 Context->getPointerType(SuperRep->getType()),
3336 VK_RValue, OK_Ordinary,
3337 SourceLocation());
3338 }
3339 MsgExprs.push_back(SuperRep);
3340 break;
3341 }
3342
3343 case ObjCMessageExpr::Class: {
3344 SmallVector<Expr*, 8> ClsExprs;
Fariborz Jahanian11671902012-02-07 17:11:38 +00003345 ObjCInterfaceDecl *Class
3346 = Exp->getClassReceiver()->getAs<ObjCObjectType>()->getInterface();
3347 IdentifierInfo *clsName = Class->getIdentifier();
Benjamin Kramerfc188422014-02-25 12:26:11 +00003348 ClsExprs.push_back(getStringLiteral(clsName->getName()));
Craig Toppercf2126e2015-10-22 03:13:07 +00003349 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl, ClsExprs,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003350 StartLoc, EndLoc);
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00003351 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
3352 Context->getObjCIdType(),
3353 CK_BitCast, Cls);
3354 MsgExprs.push_back(ArgExpr);
Fariborz Jahanian11671902012-02-07 17:11:38 +00003355 break;
3356 }
3357
3358 case ObjCMessageExpr::SuperInstance:{
3359 MsgSendFlavor = MsgSendSuperFunctionDecl;
3360 if (MsgSendStretFlavor)
3361 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
3362 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
3363 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
3364 SmallVector<Expr*, 4> InitExprs;
3365
3366 InitExprs.push_back(
3367 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3368 CK_BitCast,
3369 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCall113bee02012-03-10 09:33:50 +00003370 false,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003371 Context->getObjCIdType(),
3372 VK_RValue, SourceLocation()))
3373 ); // set the 'receiver'.
3374
3375 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3376 SmallVector<Expr*, 8> ClsExprs;
Benjamin Kramerfc188422014-02-25 12:26:11 +00003377 ClsExprs.push_back(getStringLiteral(ClassDecl->getIdentifier()->getName()));
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00003378 // (Class)objc_getClass("CurrentClass")
Craig Toppercf2126e2015-10-22 03:13:07 +00003379 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl, ClsExprs,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003380 StartLoc, EndLoc);
Fariborz Jahanian11671902012-02-07 17:11:38 +00003381 ClsExprs.clear();
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00003382 ClsExprs.push_back(Cls);
Craig Toppercf2126e2015-10-22 03:13:07 +00003383 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl, ClsExprs,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003384 StartLoc, EndLoc);
3385
3386 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3387 // To turn off a warning, type-cast to 'id'
3388 InitExprs.push_back(
3389 // set 'super class', using class_getSuperclass().
3390 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3391 CK_BitCast, Cls));
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003392 // struct __rw_objc_super
Fariborz Jahanian11671902012-02-07 17:11:38 +00003393 QualType superType = getSuperStructType();
3394 Expr *SuperRep;
3395
3396 if (LangOpts.MicrosoftExt) {
Benjamin Kramer60509af2013-09-09 14:48:42 +00003397 SynthSuperConstructorFunctionDecl();
3398 // Simulate a constructor call...
3399 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperConstructorFunctionDecl,
John McCall113bee02012-03-10 09:33:50 +00003400 false, superType, VK_LValue,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003401 SourceLocation());
Benjamin Kramerc215e762012-08-24 11:54:20 +00003402 SuperRep = new (Context) CallExpr(*Context, DRE, InitExprs,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003403 superType, VK_LValue, SourceLocation());
3404 // The code for super is a little tricky to prevent collision with
3405 // the structure definition in the header. The rewriter has it's own
3406 // internal definition (__rw_objc_super) that is uses. This is why
3407 // we need the cast below. For example:
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003408 // (struct __rw_objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
Fariborz Jahanian11671902012-02-07 17:11:38 +00003409 //
3410 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
3411 Context->getPointerType(SuperRep->getType()),
3412 VK_RValue, OK_Ordinary,
3413 SourceLocation());
3414 SuperRep = NoTypeInfoCStyleCastExpr(Context,
3415 Context->getPointerType(superType),
3416 CK_BitCast, SuperRep);
3417 } else {
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003418 // (struct __rw_objc_super) { <exprs from above> }
Fariborz Jahanian11671902012-02-07 17:11:38 +00003419 InitListExpr *ILE =
Benjamin Kramerc215e762012-08-24 11:54:20 +00003420 new (Context) InitListExpr(*Context, SourceLocation(), InitExprs,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003421 SourceLocation());
3422 TypeSourceInfo *superTInfo
3423 = Context->getTrivialTypeSourceInfo(superType);
3424 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
3425 superType, VK_RValue, ILE,
3426 false);
3427 }
3428 MsgExprs.push_back(SuperRep);
3429 break;
3430 }
3431
3432 case ObjCMessageExpr::Instance: {
3433 // Remove all type-casts because it may contain objc-style types; e.g.
3434 // Foo<Proto> *.
3435 Expr *recExpr = Exp->getInstanceReceiver();
3436 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
3437 recExpr = CE->getSubExpr();
3438 CastKind CK = recExpr->getType()->isObjCObjectPointerType()
3439 ? CK_BitCast : recExpr->getType()->isBlockPointerType()
3440 ? CK_BlockPointerToObjCPointerCast
3441 : CK_CPointerToObjCPointerCast;
3442
3443 recExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3444 CK, recExpr);
3445 MsgExprs.push_back(recExpr);
3446 break;
3447 }
3448 }
3449
3450 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
3451 SmallVector<Expr*, 8> SelExprs;
Benjamin Kramerfc188422014-02-25 12:26:11 +00003452 SelExprs.push_back(getStringLiteral(Exp->getSelector().getAsString()));
Fariborz Jahanian11671902012-02-07 17:11:38 +00003453 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
Craig Toppercf2126e2015-10-22 03:13:07 +00003454 SelExprs, StartLoc, EndLoc);
Fariborz Jahanian11671902012-02-07 17:11:38 +00003455 MsgExprs.push_back(SelExp);
3456
3457 // Now push any user supplied arguments.
3458 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
3459 Expr *userExpr = Exp->getArg(i);
3460 // Make all implicit casts explicit...ICE comes in handy:-)
3461 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
3462 // Reuse the ICE type, it is exactly what the doctor ordered.
3463 QualType type = ICE->getType();
3464 if (needToScanForQualifiers(type))
3465 type = Context->getObjCIdType();
3466 // Make sure we convert "type (^)(...)" to "type (*)(...)".
3467 (void)convertBlockPointerToFunctionPointer(type);
3468 const Expr *SubExpr = ICE->IgnoreParenImpCasts();
3469 CastKind CK;
3470 if (SubExpr->getType()->isIntegralType(*Context) &&
3471 type->isBooleanType()) {
3472 CK = CK_IntegralToBoolean;
3473 } else if (type->isObjCObjectPointerType()) {
3474 if (SubExpr->getType()->isBlockPointerType()) {
3475 CK = CK_BlockPointerToObjCPointerCast;
3476 } else if (SubExpr->getType()->isPointerType()) {
3477 CK = CK_CPointerToObjCPointerCast;
3478 } else {
3479 CK = CK_BitCast;
3480 }
3481 } else {
3482 CK = CK_BitCast;
3483 }
3484
3485 userExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, userExpr);
3486 }
3487 // Make id<P...> cast into an 'id' cast.
3488 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
3489 if (CE->getType()->isObjCQualifiedIdType()) {
3490 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
3491 userExpr = CE->getSubExpr();
3492 CastKind CK;
3493 if (userExpr->getType()->isIntegralType(*Context)) {
3494 CK = CK_IntegralToPointer;
3495 } else if (userExpr->getType()->isBlockPointerType()) {
3496 CK = CK_BlockPointerToObjCPointerCast;
3497 } else if (userExpr->getType()->isPointerType()) {
3498 CK = CK_CPointerToObjCPointerCast;
3499 } else {
3500 CK = CK_BitCast;
3501 }
3502 userExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3503 CK, userExpr);
3504 }
3505 }
3506 MsgExprs.push_back(userExpr);
3507 // We've transferred the ownership to MsgExprs. For now, we *don't* null
3508 // out the argument in the original expression (since we aren't deleting
3509 // the ObjCMessageExpr). See RewritePropertyOrImplicitSetter() usage for more info.
3510 //Exp->setArg(i, 0);
3511 }
3512 // Generate the funky cast.
3513 CastExpr *cast;
3514 SmallVector<QualType, 8> ArgTypes;
3515 QualType returnType;
3516
3517 // Push 'id' and 'SEL', the 2 implicit arguments.
3518 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
3519 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
3520 else
3521 ArgTypes.push_back(Context->getObjCIdType());
3522 ArgTypes.push_back(Context->getObjCSelType());
3523 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
3524 // Push any user argument types.
Aaron Ballman43b68be2014-03-07 17:50:17 +00003525 for (const auto *PI : OMD->params()) {
3526 QualType t = PI->getType()->isObjCQualifiedIdType()
Fariborz Jahanian11671902012-02-07 17:11:38 +00003527 ? Context->getObjCIdType()
Aaron Ballman43b68be2014-03-07 17:50:17 +00003528 : PI->getType();
Fariborz Jahanian11671902012-02-07 17:11:38 +00003529 // Make sure we convert "t (^)(...)" to "t (*)(...)".
3530 (void)convertBlockPointerToFunctionPointer(t);
3531 ArgTypes.push_back(t);
3532 }
3533 returnType = Exp->getType();
3534 convertToUnqualifiedObjCType(returnType);
3535 (void)convertBlockPointerToFunctionPointer(returnType);
3536 } else {
3537 returnType = Context->getObjCIdType();
3538 }
3539 // Get the type, we will need to reference it in a couple spots.
3540 QualType msgSendType = MsgSendFlavor->getType();
3541
3542 // Create a reference to the objc_msgSend() declaration.
John McCall113bee02012-03-10 09:33:50 +00003543 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003544 VK_LValue, SourceLocation());
3545
3546 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
3547 // If we don't do this cast, we get the following bizarre warning/note:
3548 // xx.m:13: warning: function called through a non-compatible type
3549 // xx.m:13: note: if this code is reached, the program will abort
3550 cast = NoTypeInfoCStyleCastExpr(Context,
3551 Context->getPointerType(Context->VoidTy),
3552 CK_BitCast, DRE);
3553
3554 // Now do the "normal" pointer to function cast.
Jordan Rose5c382722013-03-08 21:51:21 +00003555 // If we don't have a method decl, force a variadic cast.
3556 const ObjCMethodDecl *MD = Exp->getMethodDecl();
Fariborz Jahanian11671902012-02-07 17:11:38 +00003557 QualType castType =
Jordan Rose5c382722013-03-08 21:51:21 +00003558 getSimpleFunctionType(returnType, ArgTypes, MD ? MD->isVariadic() : true);
Fariborz Jahanian11671902012-02-07 17:11:38 +00003559 castType = Context->getPointerType(castType);
3560 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
3561 cast);
3562
3563 // Don't forget the parens to enforce the proper binding.
3564 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
3565
3566 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Alp Toker314cc812014-01-25 16:55:45 +00003567 CallExpr *CE = new (Context)
3568 CallExpr(*Context, PE, MsgExprs, FT->getReturnType(), VK_RValue, EndLoc);
Fariborz Jahanian11671902012-02-07 17:11:38 +00003569 Stmt *ReplacingStmt = CE;
3570 if (MsgSendStretFlavor) {
3571 // We have the method which returns a struct/union. Must also generate
3572 // call to objc_msgSend_stret and hang both varieties on a conditional
3573 // expression which dictate which one to envoke depending on size of
3574 // method's return type.
3575
Fariborz Jahanianb1a21242013-09-09 19:59:59 +00003576 Expr *STCE = SynthMsgSendStretCallExpr(MsgSendStretFlavor,
3577 returnType,
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003578 ArgTypes, MsgExprs,
3579 Exp->getMethodDecl());
Fariborz Jahanianb1a21242013-09-09 19:59:59 +00003580 ReplacingStmt = STCE;
Fariborz Jahanian11671902012-02-07 17:11:38 +00003581 }
3582 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3583 return ReplacingStmt;
3584}
3585
3586Stmt *RewriteModernObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
3587 Stmt *ReplacingStmt = SynthMessageExpr(Exp, Exp->getLocStart(),
3588 Exp->getLocEnd());
3589
3590 // Now do the actual rewrite.
3591 ReplaceStmt(Exp, ReplacingStmt);
3592
3593 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3594 return ReplacingStmt;
3595}
3596
3597// typedef struct objc_object Protocol;
3598QualType RewriteModernObjC::getProtocolType() {
3599 if (!ProtocolTypeDecl) {
3600 TypeSourceInfo *TInfo
3601 = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
3602 ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
3603 SourceLocation(), SourceLocation(),
3604 &Context->Idents.get("Protocol"),
3605 TInfo);
3606 }
3607 return Context->getTypeDeclType(ProtocolTypeDecl);
3608}
3609
3610/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
3611/// a synthesized/forward data reference (to the protocol's metadata).
3612/// The forward references (and metadata) are generated in
3613/// RewriteModernObjC::HandleTranslationUnit().
3614Stmt *RewriteModernObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Fariborz Jahanianb31e3af2012-03-15 17:05:33 +00003615 std::string Name = "_OBJC_PROTOCOL_REFERENCE_$_" +
3616 Exp->getProtocol()->getNameAsString();
Fariborz Jahanian11671902012-02-07 17:11:38 +00003617 IdentifierInfo *ID = &Context->Idents.get(Name);
3618 VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Craig Topper8ae12032014-05-07 06:21:57 +00003619 SourceLocation(), ID, getProtocolType(),
3620 nullptr, SC_Extern);
John McCall113bee02012-03-10 09:33:50 +00003621 DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, false, getProtocolType(),
3622 VK_LValue, SourceLocation());
Fariborz Jahaniand38951a2013-11-22 18:43:41 +00003623 CastExpr *castExpr =
3624 NoTypeInfoCStyleCastExpr(
3625 Context, Context->getPointerType(DRE->getType()), CK_BitCast, DRE);
Fariborz Jahanian11671902012-02-07 17:11:38 +00003626 ReplaceStmt(Exp, castExpr);
3627 ProtocolExprDecls.insert(Exp->getProtocol()->getCanonicalDecl());
3628 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3629 return castExpr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00003630}
3631
3632bool RewriteModernObjC::BufferContainsPPDirectives(const char *startBuf,
3633 const char *endBuf) {
3634 while (startBuf < endBuf) {
3635 if (*startBuf == '#') {
3636 // Skip whitespace.
3637 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
3638 ;
3639 if (!strncmp(startBuf, "if", strlen("if")) ||
3640 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
3641 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
3642 !strncmp(startBuf, "define", strlen("define")) ||
3643 !strncmp(startBuf, "undef", strlen("undef")) ||
3644 !strncmp(startBuf, "else", strlen("else")) ||
3645 !strncmp(startBuf, "elif", strlen("elif")) ||
3646 !strncmp(startBuf, "endif", strlen("endif")) ||
3647 !strncmp(startBuf, "pragma", strlen("pragma")) ||
3648 !strncmp(startBuf, "include", strlen("include")) ||
3649 !strncmp(startBuf, "import", strlen("import")) ||
3650 !strncmp(startBuf, "include_next", strlen("include_next")))
3651 return true;
3652 }
3653 startBuf++;
3654 }
3655 return false;
3656}
3657
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003658/// IsTagDefinedInsideClass - This routine checks that a named tagged type
3659/// is defined inside an objective-c class. If so, it returns true.
Fariborz Jahanian144b7222012-05-01 17:46:45 +00003660bool RewriteModernObjC::IsTagDefinedInsideClass(ObjCContainerDecl *IDecl,
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003661 TagDecl *Tag,
3662 bool &IsNamedDefinition) {
Fariborz Jahanian5979c312012-04-30 19:46:53 +00003663 if (!IDecl)
3664 return false;
3665 SourceLocation TagLocation;
3666 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) {
3667 RD = RD->getDefinition();
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003668 if (!RD || !RD->getDeclName().getAsIdentifierInfo())
Fariborz Jahanian5979c312012-04-30 19:46:53 +00003669 return false;
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003670 IsNamedDefinition = true;
Fariborz Jahanian5979c312012-04-30 19:46:53 +00003671 TagLocation = RD->getLocation();
3672 return Context->getSourceManager().isBeforeInTranslationUnit(
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003673 IDecl->getLocation(), TagLocation);
3674 }
3675 if (EnumDecl *ED = dyn_cast<EnumDecl>(Tag)) {
3676 if (!ED || !ED->getDeclName().getAsIdentifierInfo())
3677 return false;
3678 IsNamedDefinition = true;
3679 TagLocation = ED->getLocation();
3680 return Context->getSourceManager().isBeforeInTranslationUnit(
3681 IDecl->getLocation(), TagLocation);
Fariborz Jahanian5979c312012-04-30 19:46:53 +00003682 }
3683 return false;
3684}
3685
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003686/// RewriteObjCFieldDeclType - This routine rewrites a type into the buffer.
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003687/// It handles elaborated types, as well as enum types in the process.
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003688bool RewriteModernObjC::RewriteObjCFieldDeclType(QualType &Type,
3689 std::string &Result) {
Fariborz Jahaniand7c67772012-05-02 17:34:59 +00003690 if (isa<TypedefType>(Type)) {
3691 Result += "\t";
3692 return false;
3693 }
3694
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003695 if (Type->isArrayType()) {
3696 QualType ElemTy = Context->getBaseElementType(Type);
3697 return RewriteObjCFieldDeclType(ElemTy, Result);
3698 }
3699 else if (Type->isRecordType()) {
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003700 RecordDecl *RD = Type->getAs<RecordType>()->getDecl();
3701 if (RD->isCompleteDefinition()) {
3702 if (RD->isStruct())
3703 Result += "\n\tstruct ";
3704 else if (RD->isUnion())
3705 Result += "\n\tunion ";
3706 else
3707 assert(false && "class not allowed as an ivar type");
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003708
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003709 Result += RD->getName();
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003710 if (GlobalDefinedTags.count(RD)) {
3711 // struct/union is defined globally, use it.
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003712 Result += " ";
3713 return true;
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003714 }
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003715 Result += " {\n";
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00003716 for (auto *FD : RD->fields())
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003717 RewriteObjCFieldDecl(FD, Result);
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003718 Result += "\t} ";
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003719 return true;
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003720 }
3721 }
3722 else if (Type->isEnumeralType()) {
3723 EnumDecl *ED = Type->getAs<EnumType>()->getDecl();
3724 if (ED->isCompleteDefinition()) {
3725 Result += "\n\tenum ";
3726 Result += ED->getName();
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003727 if (GlobalDefinedTags.count(ED)) {
3728 // Enum is globall defined, use it.
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003729 Result += " ";
3730 return true;
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003731 }
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003732
3733 Result += " {\n";
Aaron Ballman23a6dcb2014-03-08 18:45:14 +00003734 for (const auto *EC : ED->enumerators()) {
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003735 Result += "\t"; Result += EC->getName(); Result += " = ";
3736 llvm::APSInt Val = EC->getInitVal();
3737 Result += Val.toString(10);
3738 Result += ",\n";
3739 }
3740 Result += "\t} ";
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003741 return true;
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003742 }
3743 }
3744
3745 Result += "\t";
3746 convertObjCTypeToCStyleType(Type);
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003747 return false;
3748}
3749
3750
3751/// RewriteObjCFieldDecl - This routine rewrites a field into the buffer.
3752/// It handles elaborated types, as well as enum types in the process.
3753void RewriteModernObjC::RewriteObjCFieldDecl(FieldDecl *fieldDecl,
3754 std::string &Result) {
3755 QualType Type = fieldDecl->getType();
3756 std::string Name = fieldDecl->getNameAsString();
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003757
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003758 bool EleboratedType = RewriteObjCFieldDeclType(Type, Result);
3759 if (!EleboratedType)
3760 Type.getAsStringInternal(Name, Context->getPrintingPolicy());
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003761 Result += Name;
3762 if (fieldDecl->isBitField()) {
3763 Result += " : "; Result += utostr(fieldDecl->getBitWidthValue(*Context));
3764 }
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003765 else if (EleboratedType && Type->isArrayType()) {
Eli Friedman07bab732012-12-13 01:43:21 +00003766 const ArrayType *AT = Context->getAsArrayType(Type);
3767 do {
3768 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003769 Result += "[";
3770 llvm::APInt Dim = CAT->getSize();
3771 Result += utostr(Dim.getZExtValue());
3772 Result += "]";
3773 }
Eli Friedman07bab732012-12-13 01:43:21 +00003774 AT = Context->getAsArrayType(AT->getElementType());
3775 } while (AT);
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003776 }
3777
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003778 Result += ";\n";
3779}
3780
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003781/// RewriteLocallyDefinedNamedAggregates - This routine rewrites locally defined
3782/// named aggregate types into the input buffer.
3783void RewriteModernObjC::RewriteLocallyDefinedNamedAggregates(FieldDecl *fieldDecl,
3784 std::string &Result) {
3785 QualType Type = fieldDecl->getType();
Fariborz Jahaniand7c67772012-05-02 17:34:59 +00003786 if (isa<TypedefType>(Type))
3787 return;
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003788 if (Type->isArrayType())
3789 Type = Context->getBaseElementType(Type);
Fariborz Jahanian144b7222012-05-01 17:46:45 +00003790 ObjCContainerDecl *IDecl =
3791 dyn_cast<ObjCContainerDecl>(fieldDecl->getDeclContext());
Craig Topper8ae12032014-05-07 06:21:57 +00003792
3793 TagDecl *TD = nullptr;
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003794 if (Type->isRecordType()) {
3795 TD = Type->getAs<RecordType>()->getDecl();
3796 }
3797 else if (Type->isEnumeralType()) {
3798 TD = Type->getAs<EnumType>()->getDecl();
3799 }
3800
3801 if (TD) {
3802 if (GlobalDefinedTags.count(TD))
3803 return;
3804
3805 bool IsNamedDefinition = false;
3806 if (IsTagDefinedInsideClass(IDecl, TD, IsNamedDefinition)) {
3807 RewriteObjCFieldDeclType(Type, Result);
3808 Result += ";";
3809 }
3810 if (IsNamedDefinition)
3811 GlobalDefinedTags.insert(TD);
3812 }
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003813}
3814
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00003815unsigned RewriteModernObjC::ObjCIvarBitfieldGroupNo(ObjCIvarDecl *IV) {
3816 const ObjCInterfaceDecl *CDecl = IV->getContainingInterface();
3817 if (ObjCInterefaceHasBitfieldGroups.count(CDecl)) {
3818 return IvarGroupNumber[IV];
3819 }
3820 unsigned GroupNo = 0;
3821 SmallVector<const ObjCIvarDecl *, 8> IVars;
3822 for (const ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
3823 IVD; IVD = IVD->getNextIvar())
3824 IVars.push_back(IVD);
3825
3826 for (unsigned i = 0, e = IVars.size(); i < e; i++)
3827 if (IVars[i]->isBitField()) {
3828 IvarGroupNumber[IVars[i++]] = ++GroupNo;
3829 while (i < e && IVars[i]->isBitField())
3830 IvarGroupNumber[IVars[i++]] = GroupNo;
3831 if (i < e)
3832 --i;
3833 }
3834
3835 ObjCInterefaceHasBitfieldGroups.insert(CDecl);
3836 return IvarGroupNumber[IV];
3837}
3838
3839QualType RewriteModernObjC::SynthesizeBitfieldGroupStructType(
3840 ObjCIvarDecl *IV,
3841 SmallVectorImpl<ObjCIvarDecl *> &IVars) {
3842 std::string StructTagName;
3843 ObjCIvarBitfieldGroupType(IV, StructTagName);
3844 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct,
3845 Context->getTranslationUnitDecl(),
3846 SourceLocation(), SourceLocation(),
3847 &Context->Idents.get(StructTagName));
3848 for (unsigned i=0, e = IVars.size(); i < e; i++) {
3849 ObjCIvarDecl *Ivar = IVars[i];
3850 RD->addDecl(FieldDecl::Create(*Context, RD, SourceLocation(), SourceLocation(),
3851 &Context->Idents.get(Ivar->getName()),
3852 Ivar->getType(),
Craig Topper8ae12032014-05-07 06:21:57 +00003853 nullptr, /*Expr *BW */Ivar->getBitWidth(),
3854 false, ICIS_NoInit));
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00003855 }
3856 RD->completeDefinition();
3857 return Context->getTagDeclType(RD);
3858}
3859
3860QualType RewriteModernObjC::GetGroupRecordTypeForObjCIvarBitfield(ObjCIvarDecl *IV) {
3861 const ObjCInterfaceDecl *CDecl = IV->getContainingInterface();
3862 unsigned GroupNo = ObjCIvarBitfieldGroupNo(IV);
3863 std::pair<const ObjCInterfaceDecl*, unsigned> tuple = std::make_pair(CDecl, GroupNo);
3864 if (GroupRecordType.count(tuple))
3865 return GroupRecordType[tuple];
3866
3867 SmallVector<ObjCIvarDecl *, 8> IVars;
3868 for (const ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
3869 IVD; IVD = IVD->getNextIvar()) {
3870 if (IVD->isBitField())
3871 IVars.push_back(const_cast<ObjCIvarDecl *>(IVD));
3872 else {
3873 if (!IVars.empty()) {
3874 unsigned GroupNo = ObjCIvarBitfieldGroupNo(IVars[0]);
3875 // Generate the struct type for this group of bitfield ivars.
3876 GroupRecordType[std::make_pair(CDecl, GroupNo)] =
3877 SynthesizeBitfieldGroupStructType(IVars[0], IVars);
3878 IVars.clear();
3879 }
3880 }
3881 }
3882 if (!IVars.empty()) {
3883 // Do the last one.
3884 unsigned GroupNo = ObjCIvarBitfieldGroupNo(IVars[0]);
3885 GroupRecordType[std::make_pair(CDecl, GroupNo)] =
3886 SynthesizeBitfieldGroupStructType(IVars[0], IVars);
3887 }
3888 QualType RetQT = GroupRecordType[tuple];
3889 assert(!RetQT.isNull() && "GetGroupRecordTypeForObjCIvarBitfield struct type is NULL");
3890
3891 return RetQT;
3892}
3893
3894/// ObjCIvarBitfieldGroupDecl - Names field decl. for ivar bitfield group.
3895/// Name would be: classname__GRBF_n where n is the group number for this ivar.
3896void RewriteModernObjC::ObjCIvarBitfieldGroupDecl(ObjCIvarDecl *IV,
3897 std::string &Result) {
3898 const ObjCInterfaceDecl *CDecl = IV->getContainingInterface();
3899 Result += CDecl->getName();
3900 Result += "__GRBF_";
3901 unsigned GroupNo = ObjCIvarBitfieldGroupNo(IV);
3902 Result += utostr(GroupNo);
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00003903}
3904
3905/// ObjCIvarBitfieldGroupType - Names struct type for ivar bitfield group.
3906/// Name of the struct would be: classname__T_n where n is the group number for
3907/// this ivar.
3908void RewriteModernObjC::ObjCIvarBitfieldGroupType(ObjCIvarDecl *IV,
3909 std::string &Result) {
3910 const ObjCInterfaceDecl *CDecl = IV->getContainingInterface();
3911 Result += CDecl->getName();
3912 Result += "__T_";
3913 unsigned GroupNo = ObjCIvarBitfieldGroupNo(IV);
3914 Result += utostr(GroupNo);
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00003915}
3916
3917/// ObjCIvarBitfieldGroupOffset - Names symbol for ivar bitfield group field offset.
3918/// Name would be: OBJC_IVAR_$_classname__GRBF_n where n is the group number for
3919/// this ivar.
3920void RewriteModernObjC::ObjCIvarBitfieldGroupOffset(ObjCIvarDecl *IV,
3921 std::string &Result) {
3922 Result += "OBJC_IVAR_$_";
3923 ObjCIvarBitfieldGroupDecl(IV, Result);
3924}
3925
3926#define SKIP_BITFIELDS(IX, ENDIX, VEC) { \
3927 while ((IX < ENDIX) && VEC[IX]->isBitField()) \
3928 ++IX; \
3929 if (IX < ENDIX) \
3930 --IX; \
3931}
3932
Fariborz Jahanian11671902012-02-07 17:11:38 +00003933/// RewriteObjCInternalStruct - Rewrite one internal struct corresponding to
3934/// an objective-c class with ivars.
3935void RewriteModernObjC::RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
3936 std::string &Result) {
3937 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
3938 assert(CDecl->getName() != "" &&
3939 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanian11671902012-02-07 17:11:38 +00003940 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Fariborz Jahaniancb1d9f32012-02-10 23:18:24 +00003941 SmallVector<ObjCIvarDecl *, 8> IVars;
3942 for (ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
Fariborz Jahaniand7a32612012-03-06 17:16:27 +00003943 IVD; IVD = IVD->getNextIvar())
Fariborz Jahaniancb1d9f32012-02-10 23:18:24 +00003944 IVars.push_back(IVD);
Fariborz Jahaniand7a32612012-03-06 17:16:27 +00003945
Fariborz Jahanian11671902012-02-07 17:11:38 +00003946 SourceLocation LocStart = CDecl->getLocStart();
3947 SourceLocation LocEnd = CDecl->getEndOfDefinitionLoc();
Fariborz Jahaniancb1d9f32012-02-10 23:18:24 +00003948
Fariborz Jahanian11671902012-02-07 17:11:38 +00003949 const char *startBuf = SM->getCharacterData(LocStart);
3950 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahaniancb1d9f32012-02-10 23:18:24 +00003951
Fariborz Jahanian11671902012-02-07 17:11:38 +00003952 // If no ivars and no root or if its root, directly or indirectly,
3953 // have no ivars (thus not synthesized) then no need to synthesize this class.
Fariborz Jahaniancb1d9f32012-02-10 23:18:24 +00003954 if ((!CDecl->isThisDeclarationADefinition() || IVars.size() == 0) &&
Fariborz Jahanian11671902012-02-07 17:11:38 +00003955 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
3956 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
3957 ReplaceText(LocStart, endBuf-startBuf, Result);
3958 return;
3959 }
Fariborz Jahaniancb1d9f32012-02-10 23:18:24 +00003960
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003961 // Insert named struct/union definitions inside class to
3962 // outer scope. This follows semantics of locally defined
3963 // struct/unions in objective-c classes.
3964 for (unsigned i = 0, e = IVars.size(); i < e; i++)
3965 RewriteLocallyDefinedNamedAggregates(IVars[i], Result);
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00003966
3967 // Insert named structs which are syntheized to group ivar bitfields
3968 // to outer scope as well.
3969 for (unsigned i = 0, e = IVars.size(); i < e; i++)
3970 if (IVars[i]->isBitField()) {
3971 ObjCIvarDecl *IV = IVars[i];
3972 QualType QT = GetGroupRecordTypeForObjCIvarBitfield(IV);
3973 RewriteObjCFieldDeclType(QT, Result);
3974 Result += ";";
3975 // skip over ivar bitfields in this group.
3976 SKIP_BITFIELDS(i , e, IVars);
3977 }
3978
Fariborz Jahanian11671902012-02-07 17:11:38 +00003979 Result += "\nstruct ";
3980 Result += CDecl->getNameAsString();
Fariborz Jahaniancb1d9f32012-02-10 23:18:24 +00003981 Result += "_IMPL {\n";
3982
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00003983 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Fariborz Jahaniancb1d9f32012-02-10 23:18:24 +00003984 Result += "\tstruct "; Result += RCDecl->getNameAsString();
3985 Result += "_IMPL "; Result += RCDecl->getNameAsString();
3986 Result += "_IVARS;\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00003987 }
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003988
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00003989 for (unsigned i = 0, e = IVars.size(); i < e; i++) {
3990 if (IVars[i]->isBitField()) {
3991 ObjCIvarDecl *IV = IVars[i];
3992 Result += "\tstruct ";
3993 ObjCIvarBitfieldGroupType(IV, Result); Result += " ";
3994 ObjCIvarBitfieldGroupDecl(IV, Result); Result += ";\n";
3995 // skip over ivar bitfields in this group.
3996 SKIP_BITFIELDS(i , e, IVars);
3997 }
3998 else
3999 RewriteObjCFieldDecl(IVars[i], Result);
4000 }
Fariborz Jahanian245534d2012-02-12 21:36:23 +00004001
Fariborz Jahaniancb1d9f32012-02-10 23:18:24 +00004002 Result += "};\n";
4003 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
4004 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00004005 // Mark this struct as having been generated.
David Blaikie82e95a32014-11-19 07:49:47 +00004006 if (!ObjCSynthesizedStructs.insert(CDecl).second)
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00004007 llvm_unreachable("struct already synthesize- RewriteObjCInternalStruct");
Fariborz Jahanian11671902012-02-07 17:11:38 +00004008}
4009
Fariborz Jahanian5e49eb92012-02-22 18:13:25 +00004010/// RewriteIvarOffsetSymbols - Rewrite ivar offset symbols of those ivars which
4011/// have been referenced in an ivar access expression.
4012void RewriteModernObjC::RewriteIvarOffsetSymbols(ObjCInterfaceDecl *CDecl,
4013 std::string &Result) {
4014 // write out ivar offset symbols which have been referenced in an ivar
4015 // access expression.
4016 llvm::SmallPtrSet<ObjCIvarDecl *, 8> Ivars = ReferencedIvars[CDecl];
4017 if (Ivars.empty())
4018 return;
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00004019
4020 llvm::DenseSet<std::pair<const ObjCInterfaceDecl*, unsigned> > GroupSymbolOutput;
Craig Topperc6914d02014-08-25 04:15:02 +00004021 for (ObjCIvarDecl *IvarDecl : Ivars) {
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00004022 const ObjCInterfaceDecl *IDecl = IvarDecl->getContainingInterface();
4023 unsigned GroupNo = 0;
4024 if (IvarDecl->isBitField()) {
4025 GroupNo = ObjCIvarBitfieldGroupNo(IvarDecl);
4026 if (GroupSymbolOutput.count(std::make_pair(IDecl, GroupNo)))
4027 continue;
4028 }
Fariborz Jahaniane47bf2b2012-03-12 16:46:58 +00004029 Result += "\n";
4030 if (LangOpts.MicrosoftExt)
4031 Result += "__declspec(allocate(\".objc_ivar$B\")) ";
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00004032 Result += "extern \"C\" ";
Fariborz Jahaniane47bf2b2012-03-12 16:46:58 +00004033 if (LangOpts.MicrosoftExt &&
4034 IvarDecl->getAccessControl() != ObjCIvarDecl::Private &&
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00004035 IvarDecl->getAccessControl() != ObjCIvarDecl::Package)
4036 Result += "__declspec(dllimport) ";
4037
Fariborz Jahanian38c59102012-03-27 16:21:30 +00004038 Result += "unsigned long ";
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00004039 if (IvarDecl->isBitField()) {
4040 ObjCIvarBitfieldGroupOffset(IvarDecl, Result);
4041 GroupSymbolOutput.insert(std::make_pair(IDecl, GroupNo));
4042 }
4043 else
4044 WriteInternalIvarName(CDecl, IvarDecl, Result);
Fariborz Jahaniana854174a2012-03-20 17:13:39 +00004045 Result += ";";
Fariborz Jahanian5e49eb92012-02-22 18:13:25 +00004046 }
4047}
4048
Fariborz Jahanian11671902012-02-07 17:11:38 +00004049//===----------------------------------------------------------------------===//
4050// Meta Data Emission
4051//===----------------------------------------------------------------------===//
4052
Fariborz Jahanian11671902012-02-07 17:11:38 +00004053/// RewriteImplementations - This routine rewrites all method implementations
4054/// and emits meta-data.
4055
4056void RewriteModernObjC::RewriteImplementations() {
4057 int ClsDefCount = ClassImplementation.size();
4058 int CatDefCount = CategoryImplementation.size();
4059
4060 // Rewrite implemented methods
Fariborz Jahanian088959a2012-02-11 20:10:52 +00004061 for (int i = 0; i < ClsDefCount; i++) {
4062 ObjCImplementationDecl *OIMP = ClassImplementation[i];
4063 ObjCInterfaceDecl *CDecl = OIMP->getClassInterface();
4064 if (CDecl->isImplicitInterfaceDecl())
Fariborz Jahaniand268b0c2012-02-17 22:20:12 +00004065 assert(false &&
4066 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian088959a2012-02-11 20:10:52 +00004067 RewriteImplementationDecl(OIMP);
4068 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00004069
Fariborz Jahanian320c88a2012-02-17 20:33:00 +00004070 for (int i = 0; i < CatDefCount; i++) {
4071 ObjCCategoryImplDecl *CIMP = CategoryImplementation[i];
4072 ObjCInterfaceDecl *CDecl = CIMP->getClassInterface();
4073 if (CDecl->isImplicitInterfaceDecl())
4074 assert(false &&
4075 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian320c88a2012-02-17 20:33:00 +00004076 RewriteImplementationDecl(CIMP);
4077 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00004078}
4079
4080void RewriteModernObjC::RewriteByRefString(std::string &ResultStr,
4081 const std::string &Name,
4082 ValueDecl *VD, bool def) {
4083 assert(BlockByRefDeclNo.count(VD) &&
4084 "RewriteByRefString: ByRef decl missing");
4085 if (def)
4086 ResultStr += "struct ";
4087 ResultStr += "__Block_byref_" + Name +
4088 "_" + utostr(BlockByRefDeclNo[VD]) ;
4089}
4090
4091static bool HasLocalVariableExternalStorage(ValueDecl *VD) {
4092 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4093 return (Var->isFunctionOrMethodVarDecl() && !Var->hasLocalStorage());
4094 return false;
4095}
4096
4097std::string RewriteModernObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
4098 StringRef funcName,
4099 std::string Tag) {
4100 const FunctionType *AFT = CE->getFunctionType();
Alp Toker314cc812014-01-25 16:55:45 +00004101 QualType RT = AFT->getReturnType();
Fariborz Jahanian11671902012-02-07 17:11:38 +00004102 std::string StructRef = "struct " + Tag;
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00004103 SourceLocation BlockLoc = CE->getExprLoc();
4104 std::string S;
4105 ConvertSourceLocationToLineDirective(BlockLoc, S);
4106
4107 S += "static " + RT.getAsString(Context->getPrintingPolicy()) + " __" +
4108 funcName.str() + "_block_func_" + utostr(i);
Fariborz Jahanian11671902012-02-07 17:11:38 +00004109
4110 BlockDecl *BD = CE->getBlockDecl();
4111
4112 if (isa<FunctionNoProtoType>(AFT)) {
4113 // No user-supplied arguments. Still need to pass in a pointer to the
4114 // block (to reference imported block decl refs).
4115 S += "(" + StructRef + " *__cself)";
4116 } else if (BD->param_empty()) {
4117 S += "(" + StructRef + " *__cself)";
4118 } else {
4119 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
4120 assert(FT && "SynthesizeBlockFunc: No function proto");
4121 S += '(';
4122 // first add the implicit argument.
4123 S += StructRef + " *__cself, ";
4124 std::string ParamStr;
4125 for (BlockDecl::param_iterator AI = BD->param_begin(),
4126 E = BD->param_end(); AI != E; ++AI) {
4127 if (AI != BD->param_begin()) S += ", ";
4128 ParamStr = (*AI)->getNameAsString();
4129 QualType QT = (*AI)->getType();
Fariborz Jahanian835cabe2012-03-27 16:42:20 +00004130 (void)convertBlockPointerToFunctionPointer(QT);
4131 QT.getAsStringInternal(ParamStr, Context->getPrintingPolicy());
Fariborz Jahanian11671902012-02-07 17:11:38 +00004132 S += ParamStr;
4133 }
4134 if (FT->isVariadic()) {
4135 if (!BD->param_empty()) S += ", ";
4136 S += "...";
4137 }
4138 S += ')';
4139 }
4140 S += " {\n";
4141
4142 // Create local declarations to avoid rewriting all closure decl ref exprs.
4143 // First, emit a declaration for all "by ref" decls.
Craig Topper2341c0d2013-07-04 03:08:24 +00004144 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00004145 E = BlockByRefDecls.end(); I != E; ++I) {
4146 S += " ";
4147 std::string Name = (*I)->getNameAsString();
4148 std::string TypeString;
4149 RewriteByRefString(TypeString, Name, (*I));
4150 TypeString += " *";
4151 Name = TypeString + Name;
4152 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
4153 }
4154 // Next, emit a declaration for all "by copy" declarations.
Craig Topper2341c0d2013-07-04 03:08:24 +00004155 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00004156 E = BlockByCopyDecls.end(); I != E; ++I) {
4157 S += " ";
4158 // Handle nested closure invocation. For example:
4159 //
4160 // void (^myImportedClosure)(void);
4161 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
4162 //
4163 // void (^anotherClosure)(void);
4164 // anotherClosure = ^(void) {
4165 // myImportedClosure(); // import and invoke the closure
4166 // };
4167 //
4168 if (isTopLevelBlockPointerType((*I)->getType())) {
4169 RewriteBlockPointerTypeVariable(S, (*I));
4170 S += " = (";
4171 RewriteBlockPointerType(S, (*I)->getType());
4172 S += ")";
4173 S += "__cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
4174 }
4175 else {
4176 std::string Name = (*I)->getNameAsString();
4177 QualType QT = (*I)->getType();
4178 if (HasLocalVariableExternalStorage(*I))
4179 QT = Context->getPointerType(QT);
4180 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
4181 S += Name + " = __cself->" +
4182 (*I)->getNameAsString() + "; // bound by copy\n";
4183 }
4184 }
4185 std::string RewrittenStr = RewrittenBlockExprs[CE];
4186 const char *cstr = RewrittenStr.c_str();
4187 while (*cstr++ != '{') ;
4188 S += cstr;
4189 S += "\n";
4190 return S;
4191}
4192
4193std::string RewriteModernObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
4194 StringRef funcName,
4195 std::string Tag) {
4196 std::string StructRef = "struct " + Tag;
4197 std::string S = "static void __";
4198
4199 S += funcName;
4200 S += "_block_copy_" + utostr(i);
4201 S += "(" + StructRef;
4202 S += "*dst, " + StructRef;
4203 S += "*src) {";
Craig Topperc6914d02014-08-25 04:15:02 +00004204 for (ValueDecl *VD : ImportedBlockDecls) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00004205 S += "_Block_object_assign((void*)&dst->";
Craig Topperc6914d02014-08-25 04:15:02 +00004206 S += VD->getNameAsString();
Fariborz Jahanian11671902012-02-07 17:11:38 +00004207 S += ", (void*)src->";
Craig Topperc6914d02014-08-25 04:15:02 +00004208 S += VD->getNameAsString();
4209 if (BlockByRefDeclsPtrSet.count(VD))
Fariborz Jahanian11671902012-02-07 17:11:38 +00004210 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
4211 else if (VD->getType()->isBlockPointerType())
4212 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
4213 else
4214 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
4215 }
4216 S += "}\n";
4217
4218 S += "\nstatic void __";
4219 S += funcName;
4220 S += "_block_dispose_" + utostr(i);
4221 S += "(" + StructRef;
4222 S += "*src) {";
Craig Topperc6914d02014-08-25 04:15:02 +00004223 for (ValueDecl *VD : ImportedBlockDecls) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00004224 S += "_Block_object_dispose((void*)src->";
Craig Topperc6914d02014-08-25 04:15:02 +00004225 S += VD->getNameAsString();
4226 if (BlockByRefDeclsPtrSet.count(VD))
Fariborz Jahanian11671902012-02-07 17:11:38 +00004227 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
4228 else if (VD->getType()->isBlockPointerType())
4229 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
4230 else
4231 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
4232 }
4233 S += "}\n";
4234 return S;
4235}
4236
4237std::string RewriteModernObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
4238 std::string Desc) {
4239 std::string S = "\nstruct " + Tag;
4240 std::string Constructor = " " + Tag;
4241
4242 S += " {\n struct __block_impl impl;\n";
4243 S += " struct " + Desc;
4244 S += "* Desc;\n";
4245
4246 Constructor += "(void *fp, "; // Invoke function pointer.
4247 Constructor += "struct " + Desc; // Descriptor pointer.
4248 Constructor += " *desc";
4249
4250 if (BlockDeclRefs.size()) {
4251 // Output all "by copy" declarations.
Craig Topper2341c0d2013-07-04 03:08:24 +00004252 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00004253 E = BlockByCopyDecls.end(); I != E; ++I) {
4254 S += " ";
4255 std::string FieldName = (*I)->getNameAsString();
4256 std::string ArgName = "_" + FieldName;
4257 // Handle nested closure invocation. For example:
4258 //
4259 // void (^myImportedBlock)(void);
4260 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
4261 //
4262 // void (^anotherBlock)(void);
4263 // anotherBlock = ^(void) {
4264 // myImportedBlock(); // import and invoke the closure
4265 // };
4266 //
4267 if (isTopLevelBlockPointerType((*I)->getType())) {
4268 S += "struct __block_impl *";
4269 Constructor += ", void *" + ArgName;
4270 } else {
4271 QualType QT = (*I)->getType();
4272 if (HasLocalVariableExternalStorage(*I))
4273 QT = Context->getPointerType(QT);
4274 QT.getAsStringInternal(FieldName, Context->getPrintingPolicy());
4275 QT.getAsStringInternal(ArgName, Context->getPrintingPolicy());
4276 Constructor += ", " + ArgName;
4277 }
4278 S += FieldName + ";\n";
4279 }
4280 // Output all "by ref" declarations.
Craig Topper2341c0d2013-07-04 03:08:24 +00004281 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00004282 E = BlockByRefDecls.end(); I != E; ++I) {
4283 S += " ";
4284 std::string FieldName = (*I)->getNameAsString();
4285 std::string ArgName = "_" + FieldName;
4286 {
4287 std::string TypeString;
4288 RewriteByRefString(TypeString, FieldName, (*I));
4289 TypeString += " *";
4290 FieldName = TypeString + FieldName;
4291 ArgName = TypeString + ArgName;
4292 Constructor += ", " + ArgName;
4293 }
4294 S += FieldName + "; // by ref\n";
4295 }
4296 // Finish writing the constructor.
4297 Constructor += ", int flags=0)";
4298 // Initialize all "by copy" arguments.
4299 bool firsTime = true;
Craig Topper2341c0d2013-07-04 03:08:24 +00004300 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00004301 E = BlockByCopyDecls.end(); I != E; ++I) {
4302 std::string Name = (*I)->getNameAsString();
4303 if (firsTime) {
4304 Constructor += " : ";
4305 firsTime = false;
4306 }
4307 else
4308 Constructor += ", ";
4309 if (isTopLevelBlockPointerType((*I)->getType()))
4310 Constructor += Name + "((struct __block_impl *)_" + Name + ")";
4311 else
4312 Constructor += Name + "(_" + Name + ")";
4313 }
4314 // Initialize all "by ref" arguments.
Craig Topper2341c0d2013-07-04 03:08:24 +00004315 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00004316 E = BlockByRefDecls.end(); I != E; ++I) {
4317 std::string Name = (*I)->getNameAsString();
4318 if (firsTime) {
4319 Constructor += " : ";
4320 firsTime = false;
4321 }
4322 else
4323 Constructor += ", ";
4324 Constructor += Name + "(_" + Name + "->__forwarding)";
4325 }
4326
4327 Constructor += " {\n";
4328 if (GlobalVarDecl)
4329 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4330 else
4331 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
4332 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
4333
4334 Constructor += " Desc = desc;\n";
4335 } else {
4336 // Finish writing the constructor.
4337 Constructor += ", int flags=0) {\n";
4338 if (GlobalVarDecl)
4339 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4340 else
4341 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
4342 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
4343 Constructor += " Desc = desc;\n";
4344 }
4345 Constructor += " ";
4346 Constructor += "}\n";
4347 S += Constructor;
4348 S += "};\n";
4349 return S;
4350}
4351
4352std::string RewriteModernObjC::SynthesizeBlockDescriptor(std::string DescTag,
4353 std::string ImplTag, int i,
4354 StringRef FunName,
4355 unsigned hasCopy) {
4356 std::string S = "\nstatic struct " + DescTag;
4357
Fariborz Jahanian2e7f6382012-05-03 21:44:12 +00004358 S += " {\n size_t reserved;\n";
4359 S += " size_t Block_size;\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00004360 if (hasCopy) {
4361 S += " void (*copy)(struct ";
4362 S += ImplTag; S += "*, struct ";
4363 S += ImplTag; S += "*);\n";
4364
4365 S += " void (*dispose)(struct ";
4366 S += ImplTag; S += "*);\n";
4367 }
4368 S += "} ";
4369
4370 S += DescTag + "_DATA = { 0, sizeof(struct ";
4371 S += ImplTag + ")";
4372 if (hasCopy) {
4373 S += ", __" + FunName.str() + "_block_copy_" + utostr(i);
4374 S += ", __" + FunName.str() + "_block_dispose_" + utostr(i);
4375 }
4376 S += "};\n";
4377 return S;
4378}
4379
4380void RewriteModernObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
4381 StringRef FunName) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00004382 bool RewriteSC = (GlobalVarDecl &&
4383 !Blocks.empty() &&
4384 GlobalVarDecl->getStorageClass() == SC_Static &&
4385 GlobalVarDecl->getType().getCVRQualifiers());
4386 if (RewriteSC) {
4387 std::string SC(" void __");
4388 SC += GlobalVarDecl->getNameAsString();
4389 SC += "() {}";
4390 InsertText(FunLocStart, SC);
4391 }
4392
4393 // Insert closures that were part of the function.
4394 for (unsigned i = 0, count=0; i < Blocks.size(); i++) {
4395 CollectBlockDeclRefInfo(Blocks[i]);
4396 // Need to copy-in the inner copied-in variables not actually used in this
4397 // block.
4398 for (int j = 0; j < InnerDeclRefsCount[i]; j++) {
John McCall113bee02012-03-10 09:33:50 +00004399 DeclRefExpr *Exp = InnerDeclRefs[count++];
Fariborz Jahanian11671902012-02-07 17:11:38 +00004400 ValueDecl *VD = Exp->getDecl();
4401 BlockDeclRefs.push_back(Exp);
John McCall113bee02012-03-10 09:33:50 +00004402 if (!VD->hasAttr<BlocksAttr>()) {
4403 if (!BlockByCopyDeclsPtrSet.count(VD)) {
4404 BlockByCopyDeclsPtrSet.insert(VD);
4405 BlockByCopyDecls.push_back(VD);
4406 }
4407 continue;
Fariborz Jahanian11671902012-02-07 17:11:38 +00004408 }
John McCall113bee02012-03-10 09:33:50 +00004409
4410 if (!BlockByRefDeclsPtrSet.count(VD)) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00004411 BlockByRefDeclsPtrSet.insert(VD);
4412 BlockByRefDecls.push_back(VD);
4413 }
John McCall113bee02012-03-10 09:33:50 +00004414
Fariborz Jahanian11671902012-02-07 17:11:38 +00004415 // imported objects in the inner blocks not used in the outer
4416 // blocks must be copied/disposed in the outer block as well.
John McCall113bee02012-03-10 09:33:50 +00004417 if (VD->getType()->isObjCObjectPointerType() ||
Fariborz Jahanian11671902012-02-07 17:11:38 +00004418 VD->getType()->isBlockPointerType())
4419 ImportedBlockDecls.insert(VD);
4420 }
4421
4422 std::string ImplTag = "__" + FunName.str() + "_block_impl_" + utostr(i);
4423 std::string DescTag = "__" + FunName.str() + "_block_desc_" + utostr(i);
4424
4425 std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
4426
4427 InsertText(FunLocStart, CI);
4428
4429 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
4430
4431 InsertText(FunLocStart, CF);
4432
4433 if (ImportedBlockDecls.size()) {
4434 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
4435 InsertText(FunLocStart, HF);
4436 }
4437 std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
4438 ImportedBlockDecls.size() > 0);
4439 InsertText(FunLocStart, BD);
4440
4441 BlockDeclRefs.clear();
4442 BlockByRefDecls.clear();
4443 BlockByRefDeclsPtrSet.clear();
4444 BlockByCopyDecls.clear();
4445 BlockByCopyDeclsPtrSet.clear();
4446 ImportedBlockDecls.clear();
4447 }
4448 if (RewriteSC) {
4449 // Must insert any 'const/volatile/static here. Since it has been
4450 // removed as result of rewriting of block literals.
4451 std::string SC;
4452 if (GlobalVarDecl->getStorageClass() == SC_Static)
4453 SC = "static ";
4454 if (GlobalVarDecl->getType().isConstQualified())
4455 SC += "const ";
4456 if (GlobalVarDecl->getType().isVolatileQualified())
4457 SC += "volatile ";
4458 if (GlobalVarDecl->getType().isRestrictQualified())
4459 SC += "restrict ";
4460 InsertText(FunLocStart, SC);
4461 }
Fariborz Jahaniane0050702012-03-23 00:00:49 +00004462 if (GlobalConstructionExp) {
4463 // extra fancy dance for global literal expression.
4464
4465 // Always the latest block expression on the block stack.
4466 std::string Tag = "__";
4467 Tag += FunName;
4468 Tag += "_block_impl_";
4469 Tag += utostr(Blocks.size()-1);
4470 std::string globalBuf = "static ";
4471 globalBuf += Tag; globalBuf += " ";
4472 std::string SStr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00004473
Fariborz Jahaniane0050702012-03-23 00:00:49 +00004474 llvm::raw_string_ostream constructorExprBuf(SStr);
Craig Topper8ae12032014-05-07 06:21:57 +00004475 GlobalConstructionExp->printPretty(constructorExprBuf, nullptr,
4476 PrintingPolicy(LangOpts));
Fariborz Jahaniane0050702012-03-23 00:00:49 +00004477 globalBuf += constructorExprBuf.str();
4478 globalBuf += ";\n";
4479 InsertText(FunLocStart, globalBuf);
Craig Topper8ae12032014-05-07 06:21:57 +00004480 GlobalConstructionExp = nullptr;
Fariborz Jahaniane0050702012-03-23 00:00:49 +00004481 }
4482
Fariborz Jahanian11671902012-02-07 17:11:38 +00004483 Blocks.clear();
4484 InnerDeclRefsCount.clear();
4485 InnerDeclRefs.clear();
4486 RewrittenBlockExprs.clear();
4487}
4488
4489void RewriteModernObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
Fariborz Jahaniane49a42c2012-04-25 17:56:48 +00004490 SourceLocation FunLocStart =
4491 (!Blocks.empty()) ? getFunctionSourceLocation(*this, FD)
4492 : FD->getTypeSpecStartLoc();
Fariborz Jahanian11671902012-02-07 17:11:38 +00004493 StringRef FuncName = FD->getName();
4494
4495 SynthesizeBlockLiterals(FunLocStart, FuncName);
4496}
4497
4498static void BuildUniqueMethodName(std::string &Name,
4499 ObjCMethodDecl *MD) {
4500 ObjCInterfaceDecl *IFace = MD->getClassInterface();
4501 Name = IFace->getName();
4502 Name += "__" + MD->getSelector().getAsString();
4503 // Convert colons to underscores.
4504 std::string::size_type loc = 0;
4505 while ((loc = Name.find(":", loc)) != std::string::npos)
4506 Name.replace(loc, 1, "_");
4507}
4508
4509void RewriteModernObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
4510 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
4511 //SourceLocation FunLocStart = MD->getLocStart();
4512 SourceLocation FunLocStart = MD->getLocStart();
4513 std::string FuncName;
4514 BuildUniqueMethodName(FuncName, MD);
4515 SynthesizeBlockLiterals(FunLocStart, FuncName);
4516}
4517
4518void RewriteModernObjC::GetBlockDeclRefExprs(Stmt *S) {
Benjamin Kramer642f1732015-07-02 21:03:14 +00004519 for (Stmt *SubStmt : S->children())
4520 if (SubStmt) {
4521 if (BlockExpr *CBE = dyn_cast<BlockExpr>(SubStmt))
Fariborz Jahanian11671902012-02-07 17:11:38 +00004522 GetBlockDeclRefExprs(CBE->getBody());
4523 else
Benjamin Kramer642f1732015-07-02 21:03:14 +00004524 GetBlockDeclRefExprs(SubStmt);
Fariborz Jahanian11671902012-02-07 17:11:38 +00004525 }
4526 // Handle specific things.
Alexey Bataevf841bd92014-12-16 07:00:22 +00004527 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S))
Alexey Bataev19acc3d2015-01-12 10:17:46 +00004528 if (DRE->refersToEnclosingVariableOrCapture() ||
Alexey Bataevf841bd92014-12-16 07:00:22 +00004529 HasLocalVariableExternalStorage(DRE->getDecl()))
Fariborz Jahanian35f6e122012-04-16 23:00:57 +00004530 // FIXME: Handle enums.
Alexey Bataevf841bd92014-12-16 07:00:22 +00004531 BlockDeclRefs.push_back(DRE);
Fariborz Jahanian11671902012-02-07 17:11:38 +00004532}
4533
Craig Topper5603df42013-07-05 19:34:19 +00004534void RewriteModernObjC::GetInnerBlockDeclRefExprs(Stmt *S,
4535 SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs,
Craig Topper4dd9b432014-08-17 23:49:53 +00004536 llvm::SmallPtrSetImpl<const DeclContext *> &InnerContexts) {
Benjamin Kramer642f1732015-07-02 21:03:14 +00004537 for (Stmt *SubStmt : S->children())
4538 if (SubStmt) {
4539 if (BlockExpr *CBE = dyn_cast<BlockExpr>(SubStmt)) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00004540 InnerContexts.insert(cast<DeclContext>(CBE->getBlockDecl()));
4541 GetInnerBlockDeclRefExprs(CBE->getBody(),
4542 InnerBlockDeclRefs,
4543 InnerContexts);
4544 }
4545 else
Benjamin Kramer642f1732015-07-02 21:03:14 +00004546 GetInnerBlockDeclRefExprs(SubStmt, InnerBlockDeclRefs, InnerContexts);
Fariborz Jahanian11671902012-02-07 17:11:38 +00004547 }
4548 // Handle specific things.
John McCall113bee02012-03-10 09:33:50 +00004549 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
Alexey Bataev19acc3d2015-01-12 10:17:46 +00004550 if (DRE->refersToEnclosingVariableOrCapture() ||
Alexey Bataevf841bd92014-12-16 07:00:22 +00004551 HasLocalVariableExternalStorage(DRE->getDecl())) {
4552 if (!InnerContexts.count(DRE->getDecl()->getDeclContext()))
John McCall113bee02012-03-10 09:33:50 +00004553 InnerBlockDeclRefs.push_back(DRE);
Alexey Bataevf841bd92014-12-16 07:00:22 +00004554 if (VarDecl *Var = cast<VarDecl>(DRE->getDecl()))
John McCall113bee02012-03-10 09:33:50 +00004555 if (Var->isFunctionOrMethodVarDecl())
4556 ImportedLocalExternalDecls.insert(Var);
4557 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00004558 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00004559}
4560
Fariborz Jahanianc3cdc412012-02-13 18:57:49 +00004561/// convertObjCTypeToCStyleType - This routine converts such objc types
4562/// as qualified objects, and blocks to their closest c/c++ types that
4563/// it can. It returns true if input type was modified.
4564bool RewriteModernObjC::convertObjCTypeToCStyleType(QualType &T) {
4565 QualType oldT = T;
4566 convertBlockPointerToFunctionPointer(T);
4567 if (T->isFunctionPointerType()) {
4568 QualType PointeeTy;
4569 if (const PointerType* PT = T->getAs<PointerType>()) {
4570 PointeeTy = PT->getPointeeType();
4571 if (const FunctionType *FT = PointeeTy->getAs<FunctionType>()) {
4572 T = convertFunctionTypeOfBlocks(FT);
4573 T = Context->getPointerType(T);
4574 }
4575 }
4576 }
4577
4578 convertToUnqualifiedObjCType(T);
4579 return T != oldT;
4580}
4581
Fariborz Jahanian11671902012-02-07 17:11:38 +00004582/// convertFunctionTypeOfBlocks - This routine converts a function type
4583/// whose result type may be a block pointer or whose argument type(s)
4584/// might be block pointers to an equivalent function type replacing
4585/// all block pointers to function pointers.
4586QualType RewriteModernObjC::convertFunctionTypeOfBlocks(const FunctionType *FT) {
4587 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
4588 // FTP will be null for closures that don't take arguments.
4589 // Generate a funky cast.
4590 SmallVector<QualType, 8> ArgTypes;
Alp Toker314cc812014-01-25 16:55:45 +00004591 QualType Res = FT->getReturnType();
Fariborz Jahanianc3cdc412012-02-13 18:57:49 +00004592 bool modified = convertObjCTypeToCStyleType(Res);
Fariborz Jahanian11671902012-02-07 17:11:38 +00004593
4594 if (FTP) {
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00004595 for (auto &I : FTP->param_types()) {
4596 QualType t = I;
Fariborz Jahanian11671902012-02-07 17:11:38 +00004597 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanianc3cdc412012-02-13 18:57:49 +00004598 if (convertObjCTypeToCStyleType(t))
4599 modified = true;
Fariborz Jahanian11671902012-02-07 17:11:38 +00004600 ArgTypes.push_back(t);
4601 }
4602 }
4603 QualType FuncType;
Fariborz Jahanianc3cdc412012-02-13 18:57:49 +00004604 if (modified)
Jordan Rose5c382722013-03-08 21:51:21 +00004605 FuncType = getSimpleFunctionType(Res, ArgTypes);
Fariborz Jahanian11671902012-02-07 17:11:38 +00004606 else FuncType = QualType(FT, 0);
4607 return FuncType;
4608}
4609
4610Stmt *RewriteModernObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
4611 // Navigate to relevant type information.
Craig Topper8ae12032014-05-07 06:21:57 +00004612 const BlockPointerType *CPT = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00004613
4614 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
4615 CPT = DRE->getType()->getAs<BlockPointerType>();
Fariborz Jahanian11671902012-02-07 17:11:38 +00004616 } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
4617 CPT = MExpr->getType()->getAs<BlockPointerType>();
4618 }
4619 else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
4620 return SynthesizeBlockCall(Exp, PRE->getSubExpr());
4621 }
4622 else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
4623 CPT = IEXPR->getType()->getAs<BlockPointerType>();
4624 else if (const ConditionalOperator *CEXPR =
4625 dyn_cast<ConditionalOperator>(BlockExp)) {
4626 Expr *LHSExp = CEXPR->getLHS();
4627 Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
4628 Expr *RHSExp = CEXPR->getRHS();
4629 Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
4630 Expr *CONDExp = CEXPR->getCond();
4631 ConditionalOperator *CondExpr =
4632 new (Context) ConditionalOperator(CONDExp,
4633 SourceLocation(), cast<Expr>(LHSStmt),
4634 SourceLocation(), cast<Expr>(RHSStmt),
4635 Exp->getType(), VK_RValue, OK_Ordinary);
4636 return CondExpr;
4637 } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
4638 CPT = IRE->getType()->getAs<BlockPointerType>();
4639 } else if (const PseudoObjectExpr *POE
4640 = dyn_cast<PseudoObjectExpr>(BlockExp)) {
4641 CPT = POE->getType()->castAs<BlockPointerType>();
4642 } else {
Craig Topper0da20762016-04-24 02:08:22 +00004643 assert(false && "RewriteBlockClass: Bad type");
Fariborz Jahanian11671902012-02-07 17:11:38 +00004644 }
4645 assert(CPT && "RewriteBlockClass: Bad type");
4646 const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
4647 assert(FT && "RewriteBlockClass: Bad type");
4648 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
4649 // FTP will be null for closures that don't take arguments.
4650
4651 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
4652 SourceLocation(), SourceLocation(),
4653 &Context->Idents.get("__block_impl"));
4654 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
4655
4656 // Generate a funky cast.
4657 SmallVector<QualType, 8> ArgTypes;
4658
4659 // Push the block argument type.
4660 ArgTypes.push_back(PtrBlock);
4661 if (FTP) {
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00004662 for (auto &I : FTP->param_types()) {
4663 QualType t = I;
Fariborz Jahanian11671902012-02-07 17:11:38 +00004664 // Make sure we convert "t (^)(...)" to "t (*)(...)".
4665 if (!convertBlockPointerToFunctionPointer(t))
4666 convertToUnqualifiedObjCType(t);
4667 ArgTypes.push_back(t);
4668 }
4669 }
4670 // Now do the pointer to function cast.
Jordan Rose5c382722013-03-08 21:51:21 +00004671 QualType PtrToFuncCastType = getSimpleFunctionType(Exp->getType(), ArgTypes);
Fariborz Jahanian11671902012-02-07 17:11:38 +00004672
4673 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
4674
4675 CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock,
4676 CK_BitCast,
4677 const_cast<Expr*>(BlockExp));
4678 // Don't forget the parens to enforce the proper binding.
4679 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4680 BlkCast);
4681 //PE->dump();
4682
Craig Topper8ae12032014-05-07 06:21:57 +00004683 FieldDecl *FD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00004684 SourceLocation(),
4685 &Context->Idents.get("FuncPtr"),
Fariborz Jahanianf8e68e22015-04-09 18:36:50 +00004686 Context->VoidPtrTy, nullptr,
4687 /*BitWidth=*/nullptr, /*Mutable=*/true,
4688 ICIS_NoInit);
4689 MemberExpr *ME =
4690 new (Context) MemberExpr(PE, true, SourceLocation(), FD, SourceLocation(),
4691 FD->getType(), VK_LValue, OK_Ordinary);
4692
4693 CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType,
4694 CK_BitCast, ME);
4695 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
Fariborz Jahanian11671902012-02-07 17:11:38 +00004696
4697 SmallVector<Expr*, 8> BlkExprs;
4698 // Add the implicit argument.
4699 BlkExprs.push_back(BlkCast);
4700 // Add the user arguments.
4701 for (CallExpr::arg_iterator I = Exp->arg_begin(),
4702 E = Exp->arg_end(); I != E; ++I) {
4703 BlkExprs.push_back(*I);
4704 }
Benjamin Kramerc215e762012-08-24 11:54:20 +00004705 CallExpr *CE = new (Context) CallExpr(*Context, PE, BlkExprs,
Fariborz Jahanian11671902012-02-07 17:11:38 +00004706 Exp->getType(), VK_RValue,
4707 SourceLocation());
4708 return CE;
4709}
4710
4711// We need to return the rewritten expression to handle cases where the
John McCall113bee02012-03-10 09:33:50 +00004712// DeclRefExpr is embedded in another expression being rewritten.
Fariborz Jahanian11671902012-02-07 17:11:38 +00004713// For example:
4714//
4715// int main() {
4716// __block Foo *f;
4717// __block int i;
4718//
4719// void (^myblock)() = ^() {
John McCall113bee02012-03-10 09:33:50 +00004720// [f test]; // f is a DeclRefExpr embedded in a message (which is being rewritten).
Fariborz Jahanian11671902012-02-07 17:11:38 +00004721// i = 77;
4722// };
4723//}
John McCall113bee02012-03-10 09:33:50 +00004724Stmt *RewriteModernObjC::RewriteBlockDeclRefExpr(DeclRefExpr *DeclRefExp) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00004725 // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
4726 // for each DeclRefExp where BYREFVAR is name of the variable.
John McCall113bee02012-03-10 09:33:50 +00004727 ValueDecl *VD = DeclRefExp->getDecl();
Alexey Bataev19acc3d2015-01-12 10:17:46 +00004728 bool isArrow = DeclRefExp->refersToEnclosingVariableOrCapture() ||
Alexey Bataevf841bd92014-12-16 07:00:22 +00004729 HasLocalVariableExternalStorage(DeclRefExp->getDecl());
Craig Topper8ae12032014-05-07 06:21:57 +00004730
4731 FieldDecl *FD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00004732 SourceLocation(),
4733 &Context->Idents.get("__forwarding"),
Fariborz Jahanianf8e68e22015-04-09 18:36:50 +00004734 Context->VoidPtrTy, nullptr,
4735 /*BitWidth=*/nullptr, /*Mutable=*/true,
4736 ICIS_NoInit);
4737 MemberExpr *ME = new (Context)
4738 MemberExpr(DeclRefExp, isArrow, SourceLocation(), FD, SourceLocation(),
4739 FD->getType(), VK_LValue, OK_Ordinary);
4740
4741 StringRef Name = VD->getName();
4742 FD = FieldDecl::Create(*Context, nullptr, SourceLocation(), SourceLocation(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00004743 &Context->Idents.get(Name),
Fariborz Jahanianf8e68e22015-04-09 18:36:50 +00004744 Context->VoidPtrTy, nullptr,
4745 /*BitWidth=*/nullptr, /*Mutable=*/true,
4746 ICIS_NoInit);
4747 ME =
4748 new (Context) MemberExpr(ME, true, SourceLocation(), FD, SourceLocation(),
4749 DeclRefExp->getType(), VK_LValue, OK_Ordinary);
4750
4751 // Need parens to enforce precedence.
4752 ParenExpr *PE = new (Context) ParenExpr(DeclRefExp->getExprLoc(),
4753 DeclRefExp->getExprLoc(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00004754 ME);
4755 ReplaceStmt(DeclRefExp, PE);
4756 return PE;
4757}
4758
4759// Rewrites the imported local variable V with external storage
4760// (static, extern, etc.) as *V
4761//
4762Stmt *RewriteModernObjC::RewriteLocalVariableExternalStorage(DeclRefExpr *DRE) {
4763 ValueDecl *VD = DRE->getDecl();
4764 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4765 if (!ImportedLocalExternalDecls.count(Var))
4766 return DRE;
4767 Expr *Exp = new (Context) UnaryOperator(DRE, UO_Deref, DRE->getType(),
4768 VK_LValue, OK_Ordinary,
4769 DRE->getLocation());
4770 // Need parens to enforce precedence.
4771 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4772 Exp);
4773 ReplaceStmt(DRE, PE);
4774 return PE;
4775}
4776
4777void RewriteModernObjC::RewriteCastExpr(CStyleCastExpr *CE) {
4778 SourceLocation LocStart = CE->getLParenLoc();
4779 SourceLocation LocEnd = CE->getRParenLoc();
4780
4781 // Need to avoid trying to rewrite synthesized casts.
4782 if (LocStart.isInvalid())
4783 return;
4784 // Need to avoid trying to rewrite casts contained in macros.
4785 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
4786 return;
4787
4788 const char *startBuf = SM->getCharacterData(LocStart);
4789 const char *endBuf = SM->getCharacterData(LocEnd);
4790 QualType QT = CE->getType();
4791 const Type* TypePtr = QT->getAs<Type>();
4792 if (isa<TypeOfExprType>(TypePtr)) {
4793 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
4794 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
4795 std::string TypeAsString = "(";
4796 RewriteBlockPointerType(TypeAsString, QT);
4797 TypeAsString += ")";
4798 ReplaceText(LocStart, endBuf-startBuf+1, TypeAsString);
4799 return;
4800 }
4801 // advance the location to startArgList.
4802 const char *argPtr = startBuf;
4803
4804 while (*argPtr++ && (argPtr < endBuf)) {
4805 switch (*argPtr) {
4806 case '^':
4807 // Replace the '^' with '*'.
4808 LocStart = LocStart.getLocWithOffset(argPtr-startBuf);
4809 ReplaceText(LocStart, 1, "*");
4810 break;
4811 }
4812 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00004813}
4814
Fariborz Jahanian2c00acd2012-04-10 00:08:18 +00004815void RewriteModernObjC::RewriteImplicitCastObjCExpr(CastExpr *IC) {
4816 CastKind CastKind = IC->getCastKind();
Fariborz Jahaniancc172282012-04-16 22:14:01 +00004817 if (CastKind != CK_BlockPointerToObjCPointerCast &&
4818 CastKind != CK_AnyPointerToBlockPointerCast)
4819 return;
Fariborz Jahanian2c00acd2012-04-10 00:08:18 +00004820
Fariborz Jahaniancc172282012-04-16 22:14:01 +00004821 QualType QT = IC->getType();
4822 (void)convertBlockPointerToFunctionPointer(QT);
4823 std::string TypeString(QT.getAsString(Context->getPrintingPolicy()));
4824 std::string Str = "(";
4825 Str += TypeString;
4826 Str += ")";
Craig Toppera2a8d9c2015-10-22 03:13:10 +00004827 InsertText(IC->getSubExpr()->getLocStart(), Str);
Fariborz Jahanian2c00acd2012-04-10 00:08:18 +00004828}
4829
Fariborz Jahanian11671902012-02-07 17:11:38 +00004830void RewriteModernObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
4831 SourceLocation DeclLoc = FD->getLocation();
4832 unsigned parenCount = 0;
4833
4834 // We have 1 or more arguments that have closure pointers.
4835 const char *startBuf = SM->getCharacterData(DeclLoc);
4836 const char *startArgList = strchr(startBuf, '(');
4837
4838 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
4839
4840 parenCount++;
4841 // advance the location to startArgList.
4842 DeclLoc = DeclLoc.getLocWithOffset(startArgList-startBuf);
4843 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
4844
4845 const char *argPtr = startArgList;
4846
4847 while (*argPtr++ && parenCount) {
4848 switch (*argPtr) {
4849 case '^':
4850 // Replace the '^' with '*'.
4851 DeclLoc = DeclLoc.getLocWithOffset(argPtr-startArgList);
4852 ReplaceText(DeclLoc, 1, "*");
4853 break;
4854 case '(':
4855 parenCount++;
4856 break;
4857 case ')':
4858 parenCount--;
4859 break;
4860 }
4861 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00004862}
4863
4864bool RewriteModernObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
4865 const FunctionProtoType *FTP;
4866 const PointerType *PT = QT->getAs<PointerType>();
4867 if (PT) {
4868 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4869 } else {
4870 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4871 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4872 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4873 }
4874 if (FTP) {
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00004875 for (const auto &I : FTP->param_types())
4876 if (isTopLevelBlockPointerType(I))
Fariborz Jahanian11671902012-02-07 17:11:38 +00004877 return true;
4878 }
4879 return false;
4880}
4881
4882bool RewriteModernObjC::PointerTypeTakesAnyObjCQualifiedType(QualType QT) {
4883 const FunctionProtoType *FTP;
4884 const PointerType *PT = QT->getAs<PointerType>();
4885 if (PT) {
4886 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4887 } else {
4888 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4889 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4890 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4891 }
4892 if (FTP) {
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00004893 for (const auto &I : FTP->param_types()) {
4894 if (I->isObjCQualifiedIdType())
Fariborz Jahanian11671902012-02-07 17:11:38 +00004895 return true;
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00004896 if (I->isObjCObjectPointerType() &&
4897 I->getPointeeType()->isObjCQualifiedInterfaceType())
Fariborz Jahanian11671902012-02-07 17:11:38 +00004898 return true;
4899 }
4900
4901 }
4902 return false;
4903}
4904
4905void RewriteModernObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
4906 const char *&RParen) {
4907 const char *argPtr = strchr(Name, '(');
4908 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
4909
4910 LParen = argPtr; // output the start.
4911 argPtr++; // skip past the left paren.
4912 unsigned parenCount = 1;
4913
4914 while (*argPtr && parenCount) {
4915 switch (*argPtr) {
4916 case '(': parenCount++; break;
4917 case ')': parenCount--; break;
4918 default: break;
4919 }
4920 if (parenCount) argPtr++;
4921 }
4922 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
4923 RParen = argPtr; // output the end
4924}
4925
4926void RewriteModernObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
4927 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4928 RewriteBlockPointerFunctionArgs(FD);
4929 return;
4930 }
4931 // Handle Variables and Typedefs.
4932 SourceLocation DeclLoc = ND->getLocation();
4933 QualType DeclT;
4934 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
4935 DeclT = VD->getType();
4936 else if (TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(ND))
4937 DeclT = TDD->getUnderlyingType();
4938 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
4939 DeclT = FD->getType();
4940 else
4941 llvm_unreachable("RewriteBlockPointerDecl(): Decl type not yet handled");
4942
4943 const char *startBuf = SM->getCharacterData(DeclLoc);
4944 const char *endBuf = startBuf;
4945 // scan backward (from the decl location) for the end of the previous decl.
4946 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
4947 startBuf--;
4948 SourceLocation Start = DeclLoc.getLocWithOffset(startBuf-endBuf);
4949 std::string buf;
4950 unsigned OrigLength=0;
4951 // *startBuf != '^' if we are dealing with a pointer to function that
4952 // may take block argument types (which will be handled below).
4953 if (*startBuf == '^') {
4954 // Replace the '^' with '*', computing a negative offset.
4955 buf = '*';
4956 startBuf++;
4957 OrigLength++;
4958 }
4959 while (*startBuf != ')') {
4960 buf += *startBuf;
4961 startBuf++;
4962 OrigLength++;
4963 }
4964 buf += ')';
4965 OrigLength++;
4966
4967 if (PointerTypeTakesAnyBlockArguments(DeclT) ||
4968 PointerTypeTakesAnyObjCQualifiedType(DeclT)) {
4969 // Replace the '^' with '*' for arguments.
4970 // Replace id<P> with id/*<>*/
4971 DeclLoc = ND->getLocation();
4972 startBuf = SM->getCharacterData(DeclLoc);
4973 const char *argListBegin, *argListEnd;
4974 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
4975 while (argListBegin < argListEnd) {
4976 if (*argListBegin == '^')
4977 buf += '*';
4978 else if (*argListBegin == '<') {
4979 buf += "/*";
4980 buf += *argListBegin++;
Dmitri Gribenko76bb5cabfa2012-09-10 21:20:09 +00004981 OrigLength++;
Fariborz Jahanian11671902012-02-07 17:11:38 +00004982 while (*argListBegin != '>') {
4983 buf += *argListBegin++;
4984 OrigLength++;
4985 }
4986 buf += *argListBegin;
4987 buf += "*/";
4988 }
4989 else
4990 buf += *argListBegin;
4991 argListBegin++;
4992 OrigLength++;
4993 }
4994 buf += ')';
4995 OrigLength++;
4996 }
4997 ReplaceText(Start, OrigLength, buf);
Fariborz Jahanian11671902012-02-07 17:11:38 +00004998}
4999
Fariborz Jahanian11671902012-02-07 17:11:38 +00005000/// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
5001/// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
5002/// struct Block_byref_id_object *src) {
5003/// _Block_object_assign (&_dest->object, _src->object,
5004/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
5005/// [|BLOCK_FIELD_IS_WEAK]) // object
5006/// _Block_object_assign(&_dest->object, _src->object,
5007/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
5008/// [|BLOCK_FIELD_IS_WEAK]) // block
5009/// }
5010/// And:
5011/// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
5012/// _Block_object_dispose(_src->object,
5013/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
5014/// [|BLOCK_FIELD_IS_WEAK]) // object
5015/// _Block_object_dispose(_src->object,
5016/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
5017/// [|BLOCK_FIELD_IS_WEAK]) // block
5018/// }
5019
5020std::string RewriteModernObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
5021 int flag) {
5022 std::string S;
5023 if (CopyDestroyCache.count(flag))
5024 return S;
5025 CopyDestroyCache.insert(flag);
5026 S = "static void __Block_byref_id_object_copy_";
5027 S += utostr(flag);
5028 S += "(void *dst, void *src) {\n";
5029
5030 // offset into the object pointer is computed as:
5031 // void * + void* + int + int + void* + void *
5032 unsigned IntSize =
5033 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
5034 unsigned VoidPtrSize =
5035 static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
5036
5037 unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/Context->getCharWidth();
5038 S += " _Block_object_assign((char*)dst + ";
5039 S += utostr(offset);
5040 S += ", *(void * *) ((char*)src + ";
5041 S += utostr(offset);
5042 S += "), ";
5043 S += utostr(flag);
5044 S += ");\n}\n";
5045
5046 S += "static void __Block_byref_id_object_dispose_";
5047 S += utostr(flag);
5048 S += "(void *src) {\n";
5049 S += " _Block_object_dispose(*(void * *) ((char*)src + ";
5050 S += utostr(offset);
5051 S += "), ";
5052 S += utostr(flag);
5053 S += ");\n}\n";
5054 return S;
5055}
5056
5057/// RewriteByRefVar - For each __block typex ND variable this routine transforms
5058/// the declaration into:
5059/// struct __Block_byref_ND {
5060/// void *__isa; // NULL for everything except __weak pointers
5061/// struct __Block_byref_ND *__forwarding;
5062/// int32_t __flags;
5063/// int32_t __size;
5064/// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
5065/// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
5066/// typex ND;
5067/// };
5068///
5069/// It then replaces declaration of ND variable with:
5070/// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
5071/// __size=sizeof(struct __Block_byref_ND),
5072/// ND=initializer-if-any};
5073///
5074///
Fariborz Jahanian847713a2012-04-24 19:38:45 +00005075void RewriteModernObjC::RewriteByRefVar(VarDecl *ND, bool firstDecl,
5076 bool lastDecl) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00005077 int flag = 0;
5078 int isa = 0;
5079 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
5080 if (DeclLoc.isInvalid())
5081 // If type location is missing, it is because of missing type (a warning).
5082 // Use variable's location which is good for this case.
5083 DeclLoc = ND->getLocation();
5084 const char *startBuf = SM->getCharacterData(DeclLoc);
5085 SourceLocation X = ND->getLocEnd();
5086 X = SM->getExpansionLoc(X);
5087 const char *endBuf = SM->getCharacterData(X);
5088 std::string Name(ND->getNameAsString());
5089 std::string ByrefType;
5090 RewriteByRefString(ByrefType, Name, ND, true);
5091 ByrefType += " {\n";
5092 ByrefType += " void *__isa;\n";
5093 RewriteByRefString(ByrefType, Name, ND);
5094 ByrefType += " *__forwarding;\n";
5095 ByrefType += " int __flags;\n";
5096 ByrefType += " int __size;\n";
5097 // Add void *__Block_byref_id_object_copy;
5098 // void *__Block_byref_id_object_dispose; if needed.
5099 QualType Ty = ND->getType();
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00005100 bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty, ND);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005101 if (HasCopyAndDispose) {
5102 ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
5103 ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
5104 }
5105
5106 QualType T = Ty;
5107 (void)convertBlockPointerToFunctionPointer(T);
5108 T.getAsStringInternal(Name, Context->getPrintingPolicy());
5109
5110 ByrefType += " " + Name + ";\n";
5111 ByrefType += "};\n";
5112 // Insert this type in global scope. It is needed by helper function.
5113 SourceLocation FunLocStart;
5114 if (CurFunctionDef)
Fariborz Jahanianca357d92012-04-19 00:50:01 +00005115 FunLocStart = getFunctionSourceLocation(*this, CurFunctionDef);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005116 else {
5117 assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null");
5118 FunLocStart = CurMethodDef->getLocStart();
5119 }
5120 InsertText(FunLocStart, ByrefType);
Fariborz Jahanian3fd9bbd2012-04-24 16:45:27 +00005121
Fariborz Jahanian11671902012-02-07 17:11:38 +00005122 if (Ty.isObjCGCWeak()) {
5123 flag |= BLOCK_FIELD_IS_WEAK;
5124 isa = 1;
5125 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00005126 if (HasCopyAndDispose) {
5127 flag = BLOCK_BYREF_CALLER;
5128 QualType Ty = ND->getType();
5129 // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
5130 if (Ty->isBlockPointerType())
5131 flag |= BLOCK_FIELD_IS_BLOCK;
5132 else
5133 flag |= BLOCK_FIELD_IS_OBJECT;
5134 std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
5135 if (!HF.empty())
Fariborz Jahaniane4996132013-02-07 22:50:40 +00005136 Preamble += HF;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005137 }
5138
5139 // struct __Block_byref_ND ND =
5140 // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
5141 // initializer-if-any};
Craig Topper8ae12032014-05-07 06:21:57 +00005142 bool hasInit = (ND->getInit() != nullptr);
Fariborz Jahanian5811fd62012-04-11 23:57:12 +00005143 // FIXME. rewriter does not support __block c++ objects which
5144 // require construction.
Fariborz Jahanian16d0d6c2012-04-26 23:20:25 +00005145 if (hasInit)
5146 if (CXXConstructExpr *CExp = dyn_cast<CXXConstructExpr>(ND->getInit())) {
5147 CXXConstructorDecl *CXXDecl = CExp->getConstructor();
5148 if (CXXDecl && CXXDecl->isDefaultConstructor())
5149 hasInit = false;
5150 }
5151
Fariborz Jahanian11671902012-02-07 17:11:38 +00005152 unsigned flags = 0;
5153 if (HasCopyAndDispose)
5154 flags |= BLOCK_HAS_COPY_DISPOSE;
5155 Name = ND->getNameAsString();
5156 ByrefType.clear();
5157 RewriteByRefString(ByrefType, Name, ND);
5158 std::string ForwardingCastType("(");
5159 ForwardingCastType += ByrefType + " *)";
Fariborz Jahanian3fd9bbd2012-04-24 16:45:27 +00005160 ByrefType += " " + Name + " = {(void*)";
5161 ByrefType += utostr(isa);
5162 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
5163 ByrefType += utostr(flags);
5164 ByrefType += ", ";
5165 ByrefType += "sizeof(";
5166 RewriteByRefString(ByrefType, Name, ND);
5167 ByrefType += ")";
5168 if (HasCopyAndDispose) {
5169 ByrefType += ", __Block_byref_id_object_copy_";
5170 ByrefType += utostr(flag);
5171 ByrefType += ", __Block_byref_id_object_dispose_";
5172 ByrefType += utostr(flag);
5173 }
5174
Fariborz Jahanian847713a2012-04-24 19:38:45 +00005175 if (!firstDecl) {
5176 // In multiple __block declarations, and for all but 1st declaration,
5177 // find location of the separating comma. This would be start location
5178 // where new text is to be inserted.
5179 DeclLoc = ND->getLocation();
5180 const char *startDeclBuf = SM->getCharacterData(DeclLoc);
5181 const char *commaBuf = startDeclBuf;
5182 while (*commaBuf != ',')
5183 commaBuf--;
5184 assert((*commaBuf == ',') && "RewriteByRefVar: can't find ','");
5185 DeclLoc = DeclLoc.getLocWithOffset(commaBuf - startDeclBuf);
5186 startBuf = commaBuf;
5187 }
5188
Fariborz Jahanian11671902012-02-07 17:11:38 +00005189 if (!hasInit) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00005190 ByrefType += "};\n";
5191 unsigned nameSize = Name.size();
5192 // for block or function pointer declaration. Name is aleady
5193 // part of the declaration.
5194 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType())
5195 nameSize = 1;
5196 ReplaceText(DeclLoc, endBuf-startBuf+nameSize, ByrefType);
5197 }
5198 else {
Fariborz Jahanian3fd9bbd2012-04-24 16:45:27 +00005199 ByrefType += ", ";
Fariborz Jahanian11671902012-02-07 17:11:38 +00005200 SourceLocation startLoc;
5201 Expr *E = ND->getInit();
5202 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
5203 startLoc = ECE->getLParenLoc();
5204 else
5205 startLoc = E->getLocStart();
5206 startLoc = SM->getExpansionLoc(startLoc);
5207 endBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005208 ReplaceText(DeclLoc, endBuf-startBuf, ByrefType);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005209
Fariborz Jahanian847713a2012-04-24 19:38:45 +00005210 const char separator = lastDecl ? ';' : ',';
5211 const char *startInitializerBuf = SM->getCharacterData(startLoc);
5212 const char *separatorBuf = strchr(startInitializerBuf, separator);
5213 assert((*separatorBuf == separator) &&
5214 "RewriteByRefVar: can't find ';' or ','");
5215 SourceLocation separatorLoc =
5216 startLoc.getLocWithOffset(separatorBuf-startInitializerBuf);
5217
5218 InsertText(separatorLoc, lastDecl ? "}" : "};\n");
Fariborz Jahanian11671902012-02-07 17:11:38 +00005219 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00005220}
5221
5222void RewriteModernObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
5223 // Add initializers for any closure decl refs.
5224 GetBlockDeclRefExprs(Exp->getBody());
5225 if (BlockDeclRefs.size()) {
5226 // Unique all "by copy" declarations.
5227 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCall113bee02012-03-10 09:33:50 +00005228 if (!BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00005229 if (!BlockByCopyDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
5230 BlockByCopyDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
5231 BlockByCopyDecls.push_back(BlockDeclRefs[i]->getDecl());
5232 }
5233 }
5234 // Unique all "by ref" declarations.
5235 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCall113bee02012-03-10 09:33:50 +00005236 if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00005237 if (!BlockByRefDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
5238 BlockByRefDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
5239 BlockByRefDecls.push_back(BlockDeclRefs[i]->getDecl());
5240 }
5241 }
5242 // Find any imported blocks...they will need special attention.
5243 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCall113bee02012-03-10 09:33:50 +00005244 if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
Fariborz Jahanian11671902012-02-07 17:11:38 +00005245 BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
5246 BlockDeclRefs[i]->getType()->isBlockPointerType())
5247 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
5248 }
5249}
5250
5251FunctionDecl *RewriteModernObjC::SynthBlockInitFunctionDecl(StringRef name) {
5252 IdentifierInfo *ID = &Context->Idents.get(name);
5253 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
5254 return FunctionDecl::Create(*Context, TUDecl, SourceLocation(),
Craig Topper8ae12032014-05-07 06:21:57 +00005255 SourceLocation(), ID, FType, nullptr, SC_Extern,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00005256 false, false);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005257}
5258
5259Stmt *RewriteModernObjC::SynthBlockInitExpr(BlockExpr *Exp,
Craig Topper5603df42013-07-05 19:34:19 +00005260 const SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00005261 const BlockDecl *block = Exp->getBlockDecl();
Fariborz Jahanianbdf975e2012-03-22 19:54:39 +00005262
Fariborz Jahanian11671902012-02-07 17:11:38 +00005263 Blocks.push_back(Exp);
5264
5265 CollectBlockDeclRefInfo(Exp);
5266
5267 // Add inner imported variables now used in current block.
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00005268 int countOfInnerDecls = 0;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005269 if (!InnerBlockDeclRefs.empty()) {
5270 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++) {
John McCall113bee02012-03-10 09:33:50 +00005271 DeclRefExpr *Exp = InnerBlockDeclRefs[i];
Fariborz Jahanian11671902012-02-07 17:11:38 +00005272 ValueDecl *VD = Exp->getDecl();
John McCall113bee02012-03-10 09:33:50 +00005273 if (!VD->hasAttr<BlocksAttr>() && !BlockByCopyDeclsPtrSet.count(VD)) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00005274 // We need to save the copied-in variables in nested
5275 // blocks because it is needed at the end for some of the API generations.
5276 // See SynthesizeBlockLiterals routine.
5277 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5278 BlockDeclRefs.push_back(Exp);
5279 BlockByCopyDeclsPtrSet.insert(VD);
5280 BlockByCopyDecls.push_back(VD);
5281 }
John McCall113bee02012-03-10 09:33:50 +00005282 if (VD->hasAttr<BlocksAttr>() && !BlockByRefDeclsPtrSet.count(VD)) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00005283 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5284 BlockDeclRefs.push_back(Exp);
5285 BlockByRefDeclsPtrSet.insert(VD);
5286 BlockByRefDecls.push_back(VD);
5287 }
5288 }
5289 // Find any imported blocks...they will need special attention.
5290 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++)
John McCall113bee02012-03-10 09:33:50 +00005291 if (InnerBlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
Fariborz Jahanian11671902012-02-07 17:11:38 +00005292 InnerBlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
5293 InnerBlockDeclRefs[i]->getType()->isBlockPointerType())
5294 ImportedBlockDecls.insert(InnerBlockDeclRefs[i]->getDecl());
5295 }
5296 InnerDeclRefsCount.push_back(countOfInnerDecls);
5297
5298 std::string FuncName;
5299
5300 if (CurFunctionDef)
5301 FuncName = CurFunctionDef->getNameAsString();
5302 else if (CurMethodDef)
5303 BuildUniqueMethodName(FuncName, CurMethodDef);
5304 else if (GlobalVarDecl)
5305 FuncName = std::string(GlobalVarDecl->getNameAsString());
5306
Fariborz Jahaniane0050702012-03-23 00:00:49 +00005307 bool GlobalBlockExpr =
5308 block->getDeclContext()->getRedeclContext()->isFileContext();
5309
5310 if (GlobalBlockExpr && !GlobalVarDecl) {
5311 Diags.Report(block->getLocation(), GlobalBlockRewriteFailedDiag);
5312 GlobalBlockExpr = false;
5313 }
5314
Fariborz Jahanian11671902012-02-07 17:11:38 +00005315 std::string BlockNumber = utostr(Blocks.size()-1);
5316
Fariborz Jahanian11671902012-02-07 17:11:38 +00005317 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
5318
5319 // Get a pointer to the function type so we can cast appropriately.
5320 QualType BFT = convertFunctionTypeOfBlocks(Exp->getFunctionType());
5321 QualType FType = Context->getPointerType(BFT);
5322
5323 FunctionDecl *FD;
5324 Expr *NewRep;
5325
Benjamin Kramer60509af2013-09-09 14:48:42 +00005326 // Simulate a constructor call...
Fariborz Jahaniane0050702012-03-23 00:00:49 +00005327 std::string Tag;
5328
5329 if (GlobalBlockExpr)
5330 Tag = "__global_";
5331 else
5332 Tag = "__";
5333 Tag += FuncName + "_block_impl_" + BlockNumber;
5334
Fariborz Jahanian11671902012-02-07 17:11:38 +00005335 FD = SynthBlockInitFunctionDecl(Tag);
John McCall113bee02012-03-10 09:33:50 +00005336 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, false, FType, VK_RValue,
Fariborz Jahanian11671902012-02-07 17:11:38 +00005337 SourceLocation());
5338
5339 SmallVector<Expr*, 4> InitExprs;
5340
5341 // Initialize the block function.
5342 FD = SynthBlockInitFunctionDecl(Func);
John McCall113bee02012-03-10 09:33:50 +00005343 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, false, FD->getType(),
5344 VK_LValue, SourceLocation());
Fariborz Jahanian11671902012-02-07 17:11:38 +00005345 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
5346 CK_BitCast, Arg);
5347 InitExprs.push_back(castExpr);
5348
5349 // Initialize the block descriptor.
5350 std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
5351
5352 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl,
5353 SourceLocation(), SourceLocation(),
5354 &Context->Idents.get(DescData.c_str()),
Craig Topper8ae12032014-05-07 06:21:57 +00005355 Context->VoidPtrTy, nullptr,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00005356 SC_Static);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005357 UnaryOperator *DescRefExpr =
John McCall113bee02012-03-10 09:33:50 +00005358 new (Context) UnaryOperator(new (Context) DeclRefExpr(NewVD, false,
Fariborz Jahanian11671902012-02-07 17:11:38 +00005359 Context->VoidPtrTy,
5360 VK_LValue,
5361 SourceLocation()),
5362 UO_AddrOf,
5363 Context->getPointerType(Context->VoidPtrTy),
5364 VK_RValue, OK_Ordinary,
5365 SourceLocation());
5366 InitExprs.push_back(DescRefExpr);
5367
5368 // Add initializers for any closure decl refs.
5369 if (BlockDeclRefs.size()) {
5370 Expr *Exp;
5371 // Output all "by copy" declarations.
Craig Topper2341c0d2013-07-04 03:08:24 +00005372 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00005373 E = BlockByCopyDecls.end(); I != E; ++I) {
5374 if (isObjCType((*I)->getType())) {
5375 // FIXME: Conform to ABI ([[obj retain] autorelease]).
5376 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCall113bee02012-03-10 09:33:50 +00005377 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(),
5378 VK_LValue, SourceLocation());
Fariborz Jahanian11671902012-02-07 17:11:38 +00005379 if (HasLocalVariableExternalStorage(*I)) {
5380 QualType QT = (*I)->getType();
5381 QT = Context->getPointerType(QT);
5382 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
5383 OK_Ordinary, SourceLocation());
5384 }
5385 } else if (isTopLevelBlockPointerType((*I)->getType())) {
5386 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCall113bee02012-03-10 09:33:50 +00005387 Arg = new (Context) DeclRefExpr(FD, false, FD->getType(),
5388 VK_LValue, SourceLocation());
Fariborz Jahanian11671902012-02-07 17:11:38 +00005389 Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
5390 CK_BitCast, Arg);
5391 } else {
5392 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCall113bee02012-03-10 09:33:50 +00005393 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(),
5394 VK_LValue, SourceLocation());
Fariborz Jahanian11671902012-02-07 17:11:38 +00005395 if (HasLocalVariableExternalStorage(*I)) {
5396 QualType QT = (*I)->getType();
5397 QT = Context->getPointerType(QT);
5398 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
5399 OK_Ordinary, SourceLocation());
5400 }
5401
5402 }
5403 InitExprs.push_back(Exp);
5404 }
5405 // Output all "by ref" declarations.
Craig Topper2341c0d2013-07-04 03:08:24 +00005406 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00005407 E = BlockByRefDecls.end(); I != E; ++I) {
5408 ValueDecl *ND = (*I);
5409 std::string Name(ND->getNameAsString());
5410 std::string RecName;
5411 RewriteByRefString(RecName, Name, ND, true);
5412 IdentifierInfo *II = &Context->Idents.get(RecName.c_str()
5413 + sizeof("struct"));
5414 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
5415 SourceLocation(), SourceLocation(),
5416 II);
5417 assert(RD && "SynthBlockInitExpr(): Can't find RecordDecl");
5418 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
5419
5420 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCall113bee02012-03-10 09:33:50 +00005421 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(), VK_LValue,
Fariborz Jahanian11671902012-02-07 17:11:38 +00005422 SourceLocation());
5423 bool isNestedCapturedVar = false;
5424 if (block)
Aaron Ballman9371dd22014-03-14 18:34:04 +00005425 for (const auto &CI : block->captures()) {
5426 const VarDecl *variable = CI.getVariable();
5427 if (variable == ND && CI.isNested()) {
5428 assert (CI.isByRef() &&
Fariborz Jahanian11671902012-02-07 17:11:38 +00005429 "SynthBlockInitExpr - captured block variable is not byref");
5430 isNestedCapturedVar = true;
5431 break;
5432 }
5433 }
5434 // captured nested byref variable has its address passed. Do not take
5435 // its address again.
5436 if (!isNestedCapturedVar)
5437 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf,
5438 Context->getPointerType(Exp->getType()),
5439 VK_RValue, OK_Ordinary, SourceLocation());
5440 Exp = NoTypeInfoCStyleCastExpr(Context, castT, CK_BitCast, Exp);
5441 InitExprs.push_back(Exp);
5442 }
5443 }
5444 if (ImportedBlockDecls.size()) {
5445 // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
5446 int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
5447 unsigned IntSize =
5448 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
5449 Expr *FlagExp = IntegerLiteral::Create(*Context, llvm::APInt(IntSize, flag),
5450 Context->IntTy, SourceLocation());
5451 InitExprs.push_back(FlagExp);
5452 }
Benjamin Kramerc215e762012-08-24 11:54:20 +00005453 NewRep = new (Context) CallExpr(*Context, DRE, InitExprs,
Fariborz Jahanian11671902012-02-07 17:11:38 +00005454 FType, VK_LValue, SourceLocation());
Fariborz Jahaniane0050702012-03-23 00:00:49 +00005455
5456 if (GlobalBlockExpr) {
Craig Topper8ae12032014-05-07 06:21:57 +00005457 assert (!GlobalConstructionExp &&
Fariborz Jahaniane0050702012-03-23 00:00:49 +00005458 "SynthBlockInitExpr - GlobalConstructionExp must be null");
5459 GlobalConstructionExp = NewRep;
5460 NewRep = DRE;
5461 }
5462
Fariborz Jahanian11671902012-02-07 17:11:38 +00005463 NewRep = new (Context) UnaryOperator(NewRep, UO_AddrOf,
5464 Context->getPointerType(NewRep->getType()),
5465 VK_RValue, OK_Ordinary, SourceLocation());
5466 NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CK_BitCast,
5467 NewRep);
Fariborz Jahanian937224772014-10-28 23:46:58 +00005468 // Put Paren around the call.
5469 NewRep = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
5470 NewRep);
5471
Fariborz Jahanian11671902012-02-07 17:11:38 +00005472 BlockDeclRefs.clear();
5473 BlockByRefDecls.clear();
5474 BlockByRefDeclsPtrSet.clear();
5475 BlockByCopyDecls.clear();
5476 BlockByCopyDeclsPtrSet.clear();
5477 ImportedBlockDecls.clear();
5478 return NewRep;
5479}
5480
5481bool RewriteModernObjC::IsDeclStmtInForeachHeader(DeclStmt *DS) {
5482 if (const ObjCForCollectionStmt * CS =
5483 dyn_cast<ObjCForCollectionStmt>(Stmts.back()))
5484 return CS->getElement() == DS;
5485 return false;
5486}
5487
5488//===----------------------------------------------------------------------===//
5489// Function Body / Expression rewriting
5490//===----------------------------------------------------------------------===//
5491
5492Stmt *RewriteModernObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
5493 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
5494 isa<DoStmt>(S) || isa<ForStmt>(S))
5495 Stmts.push_back(S);
5496 else if (isa<ObjCForCollectionStmt>(S)) {
5497 Stmts.push_back(S);
5498 ObjCBcLabelNo.push_back(++BcLabelCount);
5499 }
5500
5501 // Pseudo-object operations and ivar references need special
5502 // treatment because we're going to recursively rewrite them.
5503 if (PseudoObjectExpr *PseudoOp = dyn_cast<PseudoObjectExpr>(S)) {
5504 if (isa<BinaryOperator>(PseudoOp->getSyntacticForm())) {
5505 return RewritePropertyOrImplicitSetter(PseudoOp);
5506 } else {
5507 return RewritePropertyOrImplicitGetter(PseudoOp);
5508 }
5509 } else if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
5510 return RewriteObjCIvarRefExpr(IvarRefExpr);
5511 }
Fariborz Jahanian4254cdb2013-02-08 18:57:50 +00005512 else if (isa<OpaqueValueExpr>(S))
5513 S = cast<OpaqueValueExpr>(S)->getSourceExpr();
Fariborz Jahanian11671902012-02-07 17:11:38 +00005514
5515 SourceRange OrigStmtRange = S->getSourceRange();
5516
5517 // Perform a bottom up rewrite of all children.
Benjamin Kramer642f1732015-07-02 21:03:14 +00005518 for (Stmt *&childStmt : S->children())
5519 if (childStmt) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00005520 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(childStmt);
5521 if (newStmt) {
Benjamin Kramer642f1732015-07-02 21:03:14 +00005522 childStmt = newStmt;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005523 }
5524 }
5525
5526 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
John McCall113bee02012-03-10 09:33:50 +00005527 SmallVector<DeclRefExpr *, 8> InnerBlockDeclRefs;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005528 llvm::SmallPtrSet<const DeclContext *, 8> InnerContexts;
5529 InnerContexts.insert(BE->getBlockDecl());
5530 ImportedLocalExternalDecls.clear();
5531 GetInnerBlockDeclRefExprs(BE->getBody(),
5532 InnerBlockDeclRefs, InnerContexts);
5533 // Rewrite the block body in place.
5534 Stmt *SaveCurrentBody = CurrentBody;
5535 CurrentBody = BE->getBody();
Craig Topper8ae12032014-05-07 06:21:57 +00005536 PropParentMap = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005537 // block literal on rhs of a property-dot-sytax assignment
5538 // must be replaced by its synthesize ast so getRewrittenText
5539 // works as expected. In this case, what actually ends up on RHS
5540 // is the blockTranscribed which is the helper function for the
5541 // block literal; as in: self.c = ^() {[ace ARR];};
5542 bool saveDisableReplaceStmt = DisableReplaceStmt;
5543 DisableReplaceStmt = false;
5544 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
5545 DisableReplaceStmt = saveDisableReplaceStmt;
5546 CurrentBody = SaveCurrentBody;
Craig Topper8ae12032014-05-07 06:21:57 +00005547 PropParentMap = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005548 ImportedLocalExternalDecls.clear();
5549 // Now we snarf the rewritten text and stash it away for later use.
5550 std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
5551 RewrittenBlockExprs[BE] = Str;
5552
5553 Stmt *blockTranscribed = SynthBlockInitExpr(BE, InnerBlockDeclRefs);
5554
5555 //blockTranscribed->dump();
5556 ReplaceStmt(S, blockTranscribed);
5557 return blockTranscribed;
5558 }
5559 // Handle specific things.
5560 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
5561 return RewriteAtEncode(AtEncode);
5562
5563 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
5564 return RewriteAtSelector(AtSelector);
5565
5566 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
5567 return RewriteObjCStringLiteral(AtString);
Fariborz Jahanian307b7ad2012-03-27 20:17:30 +00005568
5569 if (ObjCBoolLiteralExpr *BoolLitExpr = dyn_cast<ObjCBoolLiteralExpr>(S))
5570 return RewriteObjCBoolLiteralExpr(BoolLitExpr);
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00005571
Patrick Beard0caa3942012-04-19 00:25:12 +00005572 if (ObjCBoxedExpr *BoxedExpr = dyn_cast<ObjCBoxedExpr>(S))
5573 return RewriteObjCBoxedExpr(BoxedExpr);
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00005574
5575 if (ObjCArrayLiteral *ArrayLitExpr = dyn_cast<ObjCArrayLiteral>(S))
5576 return RewriteObjCArrayLiteralExpr(ArrayLitExpr);
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00005577
5578 if (ObjCDictionaryLiteral *DictionaryLitExpr =
5579 dyn_cast<ObjCDictionaryLiteral>(S))
5580 return RewriteObjCDictionaryLiteralExpr(DictionaryLitExpr);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005581
5582 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
5583#if 0
5584 // Before we rewrite it, put the original message expression in a comment.
5585 SourceLocation startLoc = MessExpr->getLocStart();
5586 SourceLocation endLoc = MessExpr->getLocEnd();
5587
5588 const char *startBuf = SM->getCharacterData(startLoc);
5589 const char *endBuf = SM->getCharacterData(endLoc);
5590
5591 std::string messString;
5592 messString += "// ";
5593 messString.append(startBuf, endBuf-startBuf+1);
5594 messString += "\n";
5595
5596 // FIXME: Missing definition of
5597 // InsertText(clang::SourceLocation, char const*, unsigned int).
Craig Toppera2a8d9c2015-10-22 03:13:10 +00005598 // InsertText(startLoc, messString);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005599 // Tried this, but it didn't work either...
5600 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
5601#endif
5602 return RewriteMessageExpr(MessExpr);
5603 }
5604
Fariborz Jahanian9b43c3f2012-05-23 23:47:20 +00005605 if (ObjCAutoreleasePoolStmt *StmtAutoRelease =
5606 dyn_cast<ObjCAutoreleasePoolStmt>(S)) {
5607 return RewriteObjCAutoreleasePoolStmt(StmtAutoRelease);
5608 }
5609
Fariborz Jahanian11671902012-02-07 17:11:38 +00005610 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
5611 return RewriteObjCTryStmt(StmtTry);
5612
5613 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
5614 return RewriteObjCSynchronizedStmt(StmtTry);
5615
5616 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
5617 return RewriteObjCThrowStmt(StmtThrow);
5618
5619 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
5620 return RewriteObjCProtocolExpr(ProtocolExp);
5621
5622 if (ObjCForCollectionStmt *StmtForCollection =
5623 dyn_cast<ObjCForCollectionStmt>(S))
5624 return RewriteObjCForCollectionStmt(StmtForCollection,
5625 OrigStmtRange.getEnd());
5626 if (BreakStmt *StmtBreakStmt =
5627 dyn_cast<BreakStmt>(S))
5628 return RewriteBreakStmt(StmtBreakStmt);
5629 if (ContinueStmt *StmtContinueStmt =
5630 dyn_cast<ContinueStmt>(S))
5631 return RewriteContinueStmt(StmtContinueStmt);
5632
5633 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
5634 // and cast exprs.
5635 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
5636 // FIXME: What we're doing here is modifying the type-specifier that
5637 // precedes the first Decl. In the future the DeclGroup should have
5638 // a separate type-specifier that we can rewrite.
5639 // NOTE: We need to avoid rewriting the DeclStmt if it is within
5640 // the context of an ObjCForCollectionStmt. For example:
5641 // NSArray *someArray;
5642 // for (id <FooProtocol> index in someArray) ;
5643 // This is because RewriteObjCForCollectionStmt() does textual rewriting
5644 // and it depends on the original text locations/positions.
5645 if (Stmts.empty() || !IsDeclStmtInForeachHeader(DS))
5646 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
5647
5648 // Blocks rewrite rules.
5649 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
5650 DI != DE; ++DI) {
5651 Decl *SD = *DI;
5652 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
5653 if (isTopLevelBlockPointerType(ND->getType()))
5654 RewriteBlockPointerDecl(ND);
5655 else if (ND->getType()->isFunctionPointerType())
5656 CheckFunctionPointerDecl(ND->getType(), ND);
5657 if (VarDecl *VD = dyn_cast<VarDecl>(SD)) {
5658 if (VD->hasAttr<BlocksAttr>()) {
5659 static unsigned uniqueByrefDeclCount = 0;
5660 assert(!BlockByRefDeclNo.count(ND) &&
5661 "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl");
5662 BlockByRefDeclNo[ND] = uniqueByrefDeclCount++;
Fariborz Jahanian847713a2012-04-24 19:38:45 +00005663 RewriteByRefVar(VD, (DI == DS->decl_begin()), ((DI+1) == DE));
Fariborz Jahanian11671902012-02-07 17:11:38 +00005664 }
5665 else
5666 RewriteTypeOfDecl(VD);
5667 }
5668 }
5669 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(SD)) {
5670 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
5671 RewriteBlockPointerDecl(TD);
5672 else if (TD->getUnderlyingType()->isFunctionPointerType())
5673 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5674 }
5675 }
5676 }
5677
5678 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
5679 RewriteObjCQualifiedInterfaceTypes(CE);
5680
5681 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
5682 isa<DoStmt>(S) || isa<ForStmt>(S)) {
5683 assert(!Stmts.empty() && "Statement stack is empty");
5684 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
5685 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
5686 && "Statement stack mismatch");
5687 Stmts.pop_back();
5688 }
5689 // Handle blocks rewriting.
Fariborz Jahanian11671902012-02-07 17:11:38 +00005690 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
5691 ValueDecl *VD = DRE->getDecl();
5692 if (VD->hasAttr<BlocksAttr>())
5693 return RewriteBlockDeclRefExpr(DRE);
5694 if (HasLocalVariableExternalStorage(VD))
5695 return RewriteLocalVariableExternalStorage(DRE);
5696 }
5697
5698 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
5699 if (CE->getCallee()->getType()->isBlockPointerType()) {
5700 Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
5701 ReplaceStmt(S, BlockCall);
5702 return BlockCall;
5703 }
5704 }
5705 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
5706 RewriteCastExpr(CE);
5707 }
Fariborz Jahanian2c00acd2012-04-10 00:08:18 +00005708 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
5709 RewriteImplicitCastObjCExpr(ICE);
5710 }
Fariborz Jahaniancc172282012-04-16 22:14:01 +00005711#if 0
Fariborz Jahanian3a5d5522012-04-13 18:00:54 +00005712
Fariborz Jahanian11671902012-02-07 17:11:38 +00005713 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
5714 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(),
5715 ICE->getSubExpr(),
5716 SourceLocation());
5717 // Get the new text.
5718 std::string SStr;
5719 llvm::raw_string_ostream Buf(SStr);
Richard Smith235341b2012-08-16 03:56:14 +00005720 Replacement->printPretty(Buf);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005721 const std::string &Str = Buf.str();
5722
5723 printf("CAST = %s\n", &Str[0]);
Craig Toppera2a8d9c2015-10-22 03:13:10 +00005724 InsertText(ICE->getSubExpr()->getLocStart(), Str);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005725 delete S;
5726 return Replacement;
5727 }
5728#endif
5729 // Return this stmt unmodified.
5730 return S;
5731}
5732
5733void RewriteModernObjC::RewriteRecordBody(RecordDecl *RD) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005734 for (auto *FD : RD->fields()) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00005735 if (isTopLevelBlockPointerType(FD->getType()))
5736 RewriteBlockPointerDecl(FD);
5737 if (FD->getType()->isObjCQualifiedIdType() ||
5738 FD->getType()->isObjCQualifiedInterfaceType())
5739 RewriteObjCQualifiedInterfaceTypes(FD);
5740 }
5741}
5742
5743/// HandleDeclInMainFile - This is called for each top-level decl defined in the
5744/// main file of the input.
5745void RewriteModernObjC::HandleDeclInMainFile(Decl *D) {
5746 switch (D->getKind()) {
5747 case Decl::Function: {
5748 FunctionDecl *FD = cast<FunctionDecl>(D);
5749 if (FD->isOverloadedOperator())
5750 return;
5751
5752 // Since function prototypes don't have ParmDecl's, we check the function
5753 // prototype. This enables us to rewrite function declarations and
5754 // definitions using the same code.
5755 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
5756
Argyrios Kyrtzidis75627ad2012-02-12 04:48:45 +00005757 if (!FD->isThisDeclarationADefinition())
5758 break;
5759
Fariborz Jahanian11671902012-02-07 17:11:38 +00005760 // FIXME: If this should support Obj-C++, support CXXTryStmt
5761 if (CompoundStmt *Body = dyn_cast_or_null<CompoundStmt>(FD->getBody())) {
5762 CurFunctionDef = FD;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005763 CurrentBody = Body;
5764 Body =
5765 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5766 FD->setBody(Body);
Craig Topper8ae12032014-05-07 06:21:57 +00005767 CurrentBody = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005768 if (PropParentMap) {
5769 delete PropParentMap;
Craig Topper8ae12032014-05-07 06:21:57 +00005770 PropParentMap = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005771 }
5772 // This synthesizes and inserts the block "impl" struct, invoke function,
5773 // and any copy/dispose helper functions.
5774 InsertBlockLiteralsWithinFunction(FD);
Fariborz Jahanianaa4a2422012-11-06 17:30:23 +00005775 RewriteLineDirective(D);
Craig Topper8ae12032014-05-07 06:21:57 +00005776 CurFunctionDef = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005777 }
5778 break;
5779 }
5780 case Decl::ObjCMethod: {
5781 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(D);
5782 if (CompoundStmt *Body = MD->getCompoundBody()) {
5783 CurMethodDef = MD;
5784 CurrentBody = Body;
5785 Body =
5786 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5787 MD->setBody(Body);
Craig Topper8ae12032014-05-07 06:21:57 +00005788 CurrentBody = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005789 if (PropParentMap) {
5790 delete PropParentMap;
Craig Topper8ae12032014-05-07 06:21:57 +00005791 PropParentMap = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005792 }
5793 InsertBlockLiteralsWithinMethod(MD);
Fariborz Jahanianaa4a2422012-11-06 17:30:23 +00005794 RewriteLineDirective(D);
Craig Topper8ae12032014-05-07 06:21:57 +00005795 CurMethodDef = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005796 }
5797 break;
5798 }
5799 case Decl::ObjCImplementation: {
5800 ObjCImplementationDecl *CI = cast<ObjCImplementationDecl>(D);
5801 ClassImplementation.push_back(CI);
5802 break;
5803 }
5804 case Decl::ObjCCategoryImpl: {
5805 ObjCCategoryImplDecl *CI = cast<ObjCCategoryImplDecl>(D);
5806 CategoryImplementation.push_back(CI);
5807 break;
5808 }
5809 case Decl::Var: {
5810 VarDecl *VD = cast<VarDecl>(D);
5811 RewriteObjCQualifiedInterfaceTypes(VD);
5812 if (isTopLevelBlockPointerType(VD->getType()))
5813 RewriteBlockPointerDecl(VD);
5814 else if (VD->getType()->isFunctionPointerType()) {
5815 CheckFunctionPointerDecl(VD->getType(), VD);
5816 if (VD->getInit()) {
5817 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
5818 RewriteCastExpr(CE);
5819 }
5820 }
5821 } else if (VD->getType()->isRecordType()) {
5822 RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
5823 if (RD->isCompleteDefinition())
5824 RewriteRecordBody(RD);
5825 }
5826 if (VD->getInit()) {
5827 GlobalVarDecl = VD;
5828 CurrentBody = VD->getInit();
5829 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
Craig Topper8ae12032014-05-07 06:21:57 +00005830 CurrentBody = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005831 if (PropParentMap) {
5832 delete PropParentMap;
Craig Topper8ae12032014-05-07 06:21:57 +00005833 PropParentMap = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005834 }
5835 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(), VD->getName());
Craig Topper8ae12032014-05-07 06:21:57 +00005836 GlobalVarDecl = nullptr;
5837
Fariborz Jahanian11671902012-02-07 17:11:38 +00005838 // This is needed for blocks.
5839 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
5840 RewriteCastExpr(CE);
5841 }
5842 }
5843 break;
5844 }
5845 case Decl::TypeAlias:
5846 case Decl::Typedef: {
5847 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
5848 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
5849 RewriteBlockPointerDecl(TD);
5850 else if (TD->getUnderlyingType()->isFunctionPointerType())
5851 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
Fariborz Jahanian3a65ce32013-04-03 19:11:21 +00005852 else
5853 RewriteObjCQualifiedInterfaceTypes(TD);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005854 }
5855 break;
5856 }
5857 case Decl::CXXRecord:
5858 case Decl::Record: {
5859 RecordDecl *RD = cast<RecordDecl>(D);
5860 if (RD->isCompleteDefinition())
5861 RewriteRecordBody(RD);
5862 break;
5863 }
5864 default:
5865 break;
5866 }
5867 // Nothing yet.
5868}
5869
Fariborz Jahanianb31e3af2012-03-15 17:05:33 +00005870/// Write_ProtocolExprReferencedMetadata - This routine writer out the
5871/// protocol reference symbols in the for of:
5872/// struct _protocol_t *PROTOCOL_REF = &PROTOCOL_METADATA.
5873static void Write_ProtocolExprReferencedMetadata(ASTContext *Context,
5874 ObjCProtocolDecl *PDecl,
5875 std::string &Result) {
5876 // Also output .objc_protorefs$B section and its meta-data.
5877 if (Context->getLangOpts().MicrosoftExt)
Fariborz Jahanian75f2e3c2012-04-27 21:39:49 +00005878 Result += "static ";
Fariborz Jahanianb31e3af2012-03-15 17:05:33 +00005879 Result += "struct _protocol_t *";
5880 Result += "_OBJC_PROTOCOL_REFERENCE_$_";
5881 Result += PDecl->getNameAsString();
5882 Result += " = &";
5883 Result += "_OBJC_PROTOCOL_"; Result += PDecl->getNameAsString();
5884 Result += ";\n";
5885}
5886
Fariborz Jahanian11671902012-02-07 17:11:38 +00005887void RewriteModernObjC::HandleTranslationUnit(ASTContext &C) {
5888 if (Diags.hasErrorOccurred())
5889 return;
5890
5891 RewriteInclude();
5892
Fariborz Jahaniane4996132013-02-07 22:50:40 +00005893 for (unsigned i = 0, e = FunctionDefinitionsSeen.size(); i < e; i++) {
Alp Tokerf6a24ce2013-12-05 16:25:25 +00005894 // translation of function bodies were postponed until all class and
Fariborz Jahaniane4996132013-02-07 22:50:40 +00005895 // their extensions and implementations are seen. This is because, we
Alp Tokerf6a24ce2013-12-05 16:25:25 +00005896 // cannot build grouping structs for bitfields until they are all seen.
Fariborz Jahaniane4996132013-02-07 22:50:40 +00005897 FunctionDecl *FDecl = FunctionDefinitionsSeen[i];
5898 HandleTopLevelSingleDecl(FDecl);
5899 }
5900
Fariborz Jahanian11671902012-02-07 17:11:38 +00005901 // Here's a great place to add any extra declarations that may be needed.
5902 // Write out meta data for each @protocol(<expr>).
Craig Topperc6914d02014-08-25 04:15:02 +00005903 for (ObjCProtocolDecl *ProtDecl : ProtocolExprDecls) {
5904 RewriteObjCProtocolMetaData(ProtDecl, Preamble);
5905 Write_ProtocolExprReferencedMetadata(Context, ProtDecl, Preamble);
Fariborz Jahanianb31e3af2012-03-15 17:05:33 +00005906 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00005907
5908 InsertText(SM->getLocForStartOfFile(MainFileID), Preamble, false);
Fariborz Jahanian89919cc2012-05-08 23:54:35 +00005909
5910 if (ClassImplementation.size() || CategoryImplementation.size())
5911 RewriteImplementations();
5912
Fariborz Jahanian8e1118cbd2012-02-21 23:58:41 +00005913 for (unsigned i = 0, e = ObjCInterfacesSeen.size(); i < e; i++) {
5914 ObjCInterfaceDecl *CDecl = ObjCInterfacesSeen[i];
5915 // Write struct declaration for the class matching its ivar declarations.
5916 // Note that for modern abi, this is postponed until the end of TU
5917 // because class extensions and the implementation might declare their own
5918 // private ivars.
5919 RewriteInterfaceDecl(CDecl);
5920 }
Fariborz Jahaniane4996132013-02-07 22:50:40 +00005921
Fariborz Jahanian11671902012-02-07 17:11:38 +00005922 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
5923 // we are done.
5924 if (const RewriteBuffer *RewriteBuf =
5925 Rewrite.getRewriteBufferFor(MainFileID)) {
5926 //printf("Changed:\n");
5927 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
5928 } else {
5929 llvm::errs() << "No changes\n";
5930 }
5931
5932 if (ClassImplementation.size() || CategoryImplementation.size() ||
5933 ProtocolExprDecls.size()) {
5934 // Rewrite Objective-c meta data*
5935 std::string ResultStr;
5936 RewriteMetaDataIntoBuffer(ResultStr);
5937 // Emit metadata.
5938 *OutFile << ResultStr;
5939 }
Fariborz Jahanianddddca32012-03-14 21:44:09 +00005940 // Emit ImageInfo;
5941 {
5942 std::string ResultStr;
5943 WriteImageInfo(ResultStr);
5944 *OutFile << ResultStr;
5945 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00005946 OutFile->flush();
5947}
5948
5949void RewriteModernObjC::Initialize(ASTContext &context) {
5950 InitializeCommon(context);
5951
Fariborz Jahanianb52221e2012-03-10 17:45:38 +00005952 Preamble += "#ifndef __OBJC2__\n";
5953 Preamble += "#define __OBJC2__\n";
5954 Preamble += "#endif\n";
5955
Fariborz Jahanian11671902012-02-07 17:11:38 +00005956 // declaring objc_selector outside the parameter list removes a silly
5957 // scope related warning...
5958 if (IsHeader)
5959 Preamble = "#pragma once\n";
5960 Preamble += "struct objc_selector; struct objc_class;\n";
Fariborz Jahanian27db0b32012-04-12 23:52:52 +00005961 Preamble += "struct __rw_objc_super { \n\tstruct objc_object *object; ";
5962 Preamble += "\n\tstruct objc_object *superClass; ";
5963 // Add a constructor for creating temporary objects.
5964 Preamble += "\n\t__rw_objc_super(struct objc_object *o, struct objc_object *s) ";
5965 Preamble += ": object(o), superClass(s) {} ";
5966 Preamble += "\n};\n";
5967
Fariborz Jahanian11671902012-02-07 17:11:38 +00005968 if (LangOpts.MicrosoftExt) {
Fariborz Jahanian008dfe22012-03-11 19:41:56 +00005969 // Define all sections using syntax that makes sense.
Fariborz Jahanianddddca32012-03-14 21:44:09 +00005970 // These are currently generated.
5971 Preamble += "\n#pragma section(\".objc_classlist$B\", long, read, write)\n";
Fariborz Jahanian008dfe22012-03-11 19:41:56 +00005972 Preamble += "#pragma section(\".objc_catlist$B\", long, read, write)\n";
Fariborz Jahanianddddca32012-03-14 21:44:09 +00005973 Preamble += "#pragma section(\".objc_imageinfo$B\", long, read, write)\n";
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00005974 Preamble += "#pragma section(\".objc_nlclslist$B\", long, read, write)\n";
5975 Preamble += "#pragma section(\".objc_nlcatlist$B\", long, read, write)\n";
Fariborz Jahanianddddca32012-03-14 21:44:09 +00005976 // These are generated but not necessary for functionality.
Fariborz Jahanianddddca32012-03-14 21:44:09 +00005977 Preamble += "#pragma section(\".cat_cls_meth$B\", long, read, write)\n";
Fariborz Jahanian008dfe22012-03-11 19:41:56 +00005978 Preamble += "#pragma section(\".inst_meth$B\", long, read, write)\n";
5979 Preamble += "#pragma section(\".cls_meth$B\", long, read, write)\n";
Fariborz Jahaniane47bf2b2012-03-12 16:46:58 +00005980 Preamble += "#pragma section(\".objc_ivar$B\", long, read, write)\n";
Fariborz Jahanian45489622012-03-14 18:09:23 +00005981
Fariborz Jahanianb31e3af2012-03-15 17:05:33 +00005982 // These need be generated for performance. Currently they are not,
5983 // using API calls instead.
5984 Preamble += "#pragma section(\".objc_selrefs$B\", long, read, write)\n";
5985 Preamble += "#pragma section(\".objc_classrefs$B\", long, read, write)\n";
5986 Preamble += "#pragma section(\".objc_superrefs$B\", long, read, write)\n";
5987
Fariborz Jahanian11671902012-02-07 17:11:38 +00005988 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00005989 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
5990 Preamble += "typedef struct objc_object Protocol;\n";
5991 Preamble += "#define _REWRITER_typedef_Protocol\n";
5992 Preamble += "#endif\n";
5993 if (LangOpts.MicrosoftExt) {
5994 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
5995 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
Fariborz Jahanian167384d2012-03-21 23:41:04 +00005996 }
5997 else
Fariborz Jahanian11671902012-02-07 17:11:38 +00005998 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
Fariborz Jahanian167384d2012-03-21 23:41:04 +00005999
6000 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend(void);\n";
6001 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSendSuper(void);\n";
6002 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend_stret(void);\n";
6003 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSendSuper_stret(void);\n";
6004 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend_fpret(void);\n";
6005
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00006006 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *objc_getClass";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006007 Preamble += "(const char *);\n";
6008 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *class_getSuperclass";
6009 Preamble += "(struct objc_class *);\n";
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00006010 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *objc_getMetaClass";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006011 Preamble += "(const char *);\n";
Fariborz Jahanian34660592012-03-19 18:11:32 +00006012 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw( struct objc_object *);\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006013 // @synchronized hooks.
Aaron Ballman9c004462012-09-06 16:44:16 +00006014 Preamble += "__OBJC_RW_DLLIMPORT int objc_sync_enter( struct objc_object *);\n";
6015 Preamble += "__OBJC_RW_DLLIMPORT int objc_sync_exit( struct objc_object *);\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006016 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00006017 Preamble += "#ifdef _WIN64\n";
6018 Preamble += "typedef unsigned long long _WIN_NSUInteger;\n";
6019 Preamble += "#else\n";
6020 Preamble += "typedef unsigned int _WIN_NSUInteger;\n";
6021 Preamble += "#endif\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006022 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
6023 Preamble += "struct __objcFastEnumerationState {\n\t";
6024 Preamble += "unsigned long state;\n\t";
6025 Preamble += "void **itemsPtr;\n\t";
6026 Preamble += "unsigned long *mutationsPtr;\n\t";
6027 Preamble += "unsigned long extra[5];\n};\n";
6028 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
6029 Preamble += "#define __FASTENUMERATIONSTATE\n";
6030 Preamble += "#endif\n";
6031 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
6032 Preamble += "struct __NSConstantStringImpl {\n";
6033 Preamble += " int *isa;\n";
6034 Preamble += " int flags;\n";
6035 Preamble += " char *str;\n";
Fariborz Jahaniandb3a5dc2014-04-16 17:03:06 +00006036 Preamble += "#if _WIN64\n";
Fariborz Jahanian287e79a2014-04-01 19:32:35 +00006037 Preamble += " long long length;\n";
6038 Preamble += "#else\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006039 Preamble += " long length;\n";
Fariborz Jahanian287e79a2014-04-01 19:32:35 +00006040 Preamble += "#endif\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006041 Preamble += "};\n";
6042 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
6043 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
6044 Preamble += "#else\n";
6045 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
6046 Preamble += "#endif\n";
6047 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
6048 Preamble += "#endif\n";
6049 // Blocks preamble.
6050 Preamble += "#ifndef BLOCK_IMPL\n";
6051 Preamble += "#define BLOCK_IMPL\n";
6052 Preamble += "struct __block_impl {\n";
6053 Preamble += " void *isa;\n";
6054 Preamble += " int Flags;\n";
6055 Preamble += " int Reserved;\n";
6056 Preamble += " void *FuncPtr;\n";
6057 Preamble += "};\n";
6058 Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
6059 Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n";
6060 Preamble += "extern \"C\" __declspec(dllexport) "
6061 "void _Block_object_assign(void *, const void *, const int);\n";
6062 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
6063 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
6064 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
6065 Preamble += "#else\n";
6066 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n";
6067 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n";
6068 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
6069 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
6070 Preamble += "#endif\n";
6071 Preamble += "#endif\n";
6072 if (LangOpts.MicrosoftExt) {
6073 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
6074 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
6075 Preamble += "#ifndef KEEP_ATTRIBUTES\n"; // We use this for clang tests.
6076 Preamble += "#define __attribute__(X)\n";
6077 Preamble += "#endif\n";
Fariborz Jahaniane1240fe2012-04-12 16:33:31 +00006078 Preamble += "#ifndef __weak\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006079 Preamble += "#define __weak\n";
Fariborz Jahaniane1240fe2012-04-12 16:33:31 +00006080 Preamble += "#endif\n";
6081 Preamble += "#ifndef __block\n";
6082 Preamble += "#define __block\n";
6083 Preamble += "#endif\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006084 }
6085 else {
6086 Preamble += "#define __block\n";
6087 Preamble += "#define __weak\n";
6088 }
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00006089
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00006090 // Declarations required for modern objective-c array and dictionary literals.
6091 Preamble += "\n#include <stdarg.h>\n";
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00006092 Preamble += "struct __NSContainer_literal {\n";
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00006093 Preamble += " void * *arr;\n";
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00006094 Preamble += " __NSContainer_literal (unsigned int count, ...) {\n";
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00006095 Preamble += "\tva_list marker;\n";
6096 Preamble += "\tva_start(marker, count);\n";
6097 Preamble += "\tarr = new void *[count];\n";
6098 Preamble += "\tfor (unsigned i = 0; i < count; i++)\n";
6099 Preamble += "\t arr[i] = va_arg(marker, void *);\n";
6100 Preamble += "\tva_end( marker );\n";
6101 Preamble += " };\n";
Fariborz Jahanian70ef9292012-05-02 23:53:46 +00006102 Preamble += " ~__NSContainer_literal() {\n";
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00006103 Preamble += "\tdelete[] arr;\n";
6104 Preamble += " }\n";
6105 Preamble += "};\n";
6106
Fariborz Jahanian9b43c3f2012-05-23 23:47:20 +00006107 // Declaration required for implementation of @autoreleasepool statement.
6108 Preamble += "extern \"C\" __declspec(dllimport) void * objc_autoreleasePoolPush(void);\n";
6109 Preamble += "extern \"C\" __declspec(dllimport) void objc_autoreleasePoolPop(void *);\n\n";
6110 Preamble += "struct __AtAutoreleasePool {\n";
6111 Preamble += " __AtAutoreleasePool() {atautoreleasepoolobj = objc_autoreleasePoolPush();}\n";
6112 Preamble += " ~__AtAutoreleasePool() {objc_autoreleasePoolPop(atautoreleasepoolobj);}\n";
6113 Preamble += " void * atautoreleasepoolobj;\n";
6114 Preamble += "};\n";
6115
Fariborz Jahanian11671902012-02-07 17:11:38 +00006116 // NOTE! Windows uses LLP64 for 64bit mode. So, cast pointer to long long
6117 // as this avoids warning in any 64bit/32bit compilation model.
6118 Preamble += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long long) &((TYPE *)0)->MEMBER)\n";
6119}
6120
6121/// RewriteIvarOffsetComputation - This rutine synthesizes computation of
6122/// ivar offset.
6123void RewriteModernObjC::RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
6124 std::string &Result) {
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006125 Result += "__OFFSETOFIVAR__(struct ";
6126 Result += ivar->getContainingInterface()->getNameAsString();
6127 if (LangOpts.MicrosoftExt)
6128 Result += "_IMPL";
6129 Result += ", ";
6130 if (ivar->isBitField())
6131 ObjCIvarBitfieldGroupDecl(ivar, Result);
6132 else
Fariborz Jahanian11671902012-02-07 17:11:38 +00006133 Result += ivar->getNameAsString();
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006134 Result += ")";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006135}
6136
6137/// WriteModernMetadataDeclarations - Writes out metadata declarations for modern ABI.
6138/// struct _prop_t {
Fariborz Jahanian67f7c552012-02-07 23:31:52 +00006139/// const char *name;
Fariborz Jahanian11671902012-02-07 17:11:38 +00006140/// char *attributes;
6141/// }
6142
6143/// struct _prop_list_t {
6144/// uint32_t entsize; // sizeof(struct _prop_t)
6145/// uint32_t count_of_properties;
6146/// struct _prop_t prop_list[count_of_properties];
6147/// }
6148
6149/// struct _protocol_t;
6150
6151/// struct _protocol_list_t {
6152/// long protocol_count; // Note, this is 32/64 bit
6153/// struct _protocol_t * protocol_list[protocol_count];
6154/// }
6155
6156/// struct _objc_method {
6157/// SEL _cmd;
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006158/// const char *method_type;
Fariborz Jahanian11671902012-02-07 17:11:38 +00006159/// char *_imp;
6160/// }
6161
6162/// struct _method_list_t {
6163/// uint32_t entsize; // sizeof(struct _objc_method)
6164/// uint32_t method_count;
6165/// struct _objc_method method_list[method_count];
6166/// }
6167
6168/// struct _protocol_t {
6169/// id isa; // NULL
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006170/// const char *protocol_name;
Fariborz Jahanian11671902012-02-07 17:11:38 +00006171/// const struct _protocol_list_t * protocol_list; // super protocols
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006172/// const struct method_list_t *instance_methods;
6173/// const struct method_list_t *class_methods;
Fariborz Jahanian11671902012-02-07 17:11:38 +00006174/// const struct method_list_t *optionalInstanceMethods;
6175/// const struct method_list_t *optionalClassMethods;
6176/// const struct _prop_list_t * properties;
6177/// const uint32_t size; // sizeof(struct _protocol_t)
6178/// const uint32_t flags; // = 0
6179/// const char ** extendedMethodTypes;
6180/// }
6181
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006182/// struct _ivar_t {
6183/// unsigned long int *offset; // pointer to ivar offset location
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006184/// const char *name;
6185/// const char *type;
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006186/// uint32_t alignment;
6187/// uint32_t size;
6188/// }
6189
6190/// struct _ivar_list_t {
6191/// uint32 entsize; // sizeof(struct _ivar_t)
6192/// uint32 count;
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006193/// struct _ivar_t list[count];
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006194/// }
6195
6196/// struct _class_ro_t {
Fariborz Jahanian34134812012-03-24 16:53:16 +00006197/// uint32_t flags;
6198/// uint32_t instanceStart;
6199/// uint32_t instanceSize;
6200/// uint32_t reserved; // only when building for 64bit targets
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006201/// const uint8_t *ivarLayout;
6202/// const char *name;
6203/// const struct _method_list_t *baseMethods;
6204/// const struct _protocol_list_t *baseProtocols;
6205/// const struct _ivar_list_t *ivars;
6206/// const uint8_t *weakIvarLayout;
6207/// const struct _prop_list_t *properties;
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006208/// }
6209
6210/// struct _class_t {
6211/// struct _class_t *isa;
Fariborz Jahanian6e60c132012-03-20 17:34:50 +00006212/// struct _class_t *superclass;
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006213/// void *cache;
6214/// IMP *vtable;
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006215/// struct _class_ro_t *ro;
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006216/// }
6217
6218/// struct _category_t {
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006219/// const char *name;
Fariborz Jahaniancd79a492012-03-20 21:41:28 +00006220/// struct _class_t *cls;
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006221/// const struct _method_list_t *instance_methods;
6222/// const struct _method_list_t *class_methods;
6223/// const struct _protocol_list_t *protocols;
6224/// const struct _prop_list_t *properties;
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006225/// }
6226
6227/// MessageRefTy - LLVM for:
6228/// struct _message_ref_t {
6229/// IMP messenger;
6230/// SEL name;
6231/// };
6232
6233/// SuperMessageRefTy - LLVM for:
6234/// struct _super_message_ref_t {
6235/// SUPER_IMP messenger;
6236/// SEL name;
6237/// };
6238
Fariborz Jahanian45489622012-03-14 18:09:23 +00006239static void WriteModernMetadataDeclarations(ASTContext *Context, std::string &Result) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00006240 static bool meta_data_declared = false;
6241 if (meta_data_declared)
6242 return;
6243
6244 Result += "\nstruct _prop_t {\n";
Fariborz Jahanian67f7c552012-02-07 23:31:52 +00006245 Result += "\tconst char *name;\n";
6246 Result += "\tconst char *attributes;\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006247 Result += "};\n";
6248
6249 Result += "\nstruct _protocol_t;\n";
6250
Fariborz Jahanian11671902012-02-07 17:11:38 +00006251 Result += "\nstruct _objc_method {\n";
6252 Result += "\tstruct objc_selector * _cmd;\n";
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006253 Result += "\tconst char *method_type;\n";
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006254 Result += "\tvoid *_imp;\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006255 Result += "};\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006256
6257 Result += "\nstruct _protocol_t {\n";
6258 Result += "\tvoid * isa; // NULL\n";
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006259 Result += "\tconst char *protocol_name;\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006260 Result += "\tconst struct _protocol_list_t * protocol_list; // super protocols\n";
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006261 Result += "\tconst struct method_list_t *instance_methods;\n";
6262 Result += "\tconst struct method_list_t *class_methods;\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006263 Result += "\tconst struct method_list_t *optionalInstanceMethods;\n";
6264 Result += "\tconst struct method_list_t *optionalClassMethods;\n";
6265 Result += "\tconst struct _prop_list_t * properties;\n";
6266 Result += "\tconst unsigned int size; // sizeof(struct _protocol_t)\n";
6267 Result += "\tconst unsigned int flags; // = 0\n";
6268 Result += "\tconst char ** extendedMethodTypes;\n";
6269 Result += "};\n";
6270
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006271 Result += "\nstruct _ivar_t {\n";
6272 Result += "\tunsigned long int *offset; // pointer to ivar offset location\n";
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006273 Result += "\tconst char *name;\n";
6274 Result += "\tconst char *type;\n";
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006275 Result += "\tunsigned int alignment;\n";
6276 Result += "\tunsigned int size;\n";
6277 Result += "};\n";
6278
6279 Result += "\nstruct _class_ro_t {\n";
Fariborz Jahanian34134812012-03-24 16:53:16 +00006280 Result += "\tunsigned int flags;\n";
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006281 Result += "\tunsigned int instanceStart;\n";
Fariborz Jahanian34134812012-03-24 16:53:16 +00006282 Result += "\tunsigned int instanceSize;\n";
Fariborz Jahanian45489622012-03-14 18:09:23 +00006283 const llvm::Triple &Triple(Context->getTargetInfo().getTriple());
6284 if (Triple.getArch() == llvm::Triple::x86_64)
Fariborz Jahanian34134812012-03-24 16:53:16 +00006285 Result += "\tunsigned int reserved;\n";
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006286 Result += "\tconst unsigned char *ivarLayout;\n";
6287 Result += "\tconst char *name;\n";
6288 Result += "\tconst struct _method_list_t *baseMethods;\n";
6289 Result += "\tconst struct _objc_protocol_list *baseProtocols;\n";
6290 Result += "\tconst struct _ivar_list_t *ivars;\n";
6291 Result += "\tconst unsigned char *weakIvarLayout;\n";
6292 Result += "\tconst struct _prop_list_t *properties;\n";
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006293 Result += "};\n";
6294
6295 Result += "\nstruct _class_t {\n";
6296 Result += "\tstruct _class_t *isa;\n";
Fariborz Jahanian6e60c132012-03-20 17:34:50 +00006297 Result += "\tstruct _class_t *superclass;\n";
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006298 Result += "\tvoid *cache;\n";
6299 Result += "\tvoid *vtable;\n";
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006300 Result += "\tstruct _class_ro_t *ro;\n";
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006301 Result += "};\n";
6302
6303 Result += "\nstruct _category_t {\n";
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006304 Result += "\tconst char *name;\n";
Fariborz Jahaniancd79a492012-03-20 21:41:28 +00006305 Result += "\tstruct _class_t *cls;\n";
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006306 Result += "\tconst struct _method_list_t *instance_methods;\n";
6307 Result += "\tconst struct _method_list_t *class_methods;\n";
6308 Result += "\tconst struct _protocol_list_t *protocols;\n";
6309 Result += "\tconst struct _prop_list_t *properties;\n";
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006310 Result += "};\n";
6311
Fariborz Jahanian38c59102012-03-27 16:21:30 +00006312 Result += "extern \"C\" __declspec(dllimport) struct objc_cache _objc_empty_cache;\n";
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00006313 Result += "#pragma warning(disable:4273)\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006314 meta_data_declared = true;
6315}
6316
Fariborz Jahaniane18961b2012-02-08 19:53:58 +00006317static void Write_protocol_list_t_TypeDecl(std::string &Result,
6318 long super_protocol_count) {
6319 Result += "struct /*_protocol_list_t*/"; Result += " {\n";
6320 Result += "\tlong protocol_count; // Note, this is 32/64 bit\n";
6321 Result += "\tstruct _protocol_t *super_protocols[";
6322 Result += utostr(super_protocol_count); Result += "];\n";
6323 Result += "}";
6324}
6325
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006326static void Write_method_list_t_TypeDecl(std::string &Result,
6327 unsigned int method_count) {
6328 Result += "struct /*_method_list_t*/"; Result += " {\n";
6329 Result += "\tunsigned int entsize; // sizeof(struct _objc_method)\n";
6330 Result += "\tunsigned int method_count;\n";
6331 Result += "\tstruct _objc_method method_list[";
6332 Result += utostr(method_count); Result += "];\n";
6333 Result += "}";
6334}
6335
Fariborz Jahanian67f7c552012-02-07 23:31:52 +00006336static void Write__prop_list_t_TypeDecl(std::string &Result,
6337 unsigned int property_count) {
6338 Result += "struct /*_prop_list_t*/"; Result += " {\n";
6339 Result += "\tunsigned int entsize; // sizeof(struct _prop_t)\n";
6340 Result += "\tunsigned int count_of_properties;\n";
6341 Result += "\tstruct _prop_t prop_list[";
6342 Result += utostr(property_count); Result += "];\n";
6343 Result += "}";
6344}
6345
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006346static void Write__ivar_list_t_TypeDecl(std::string &Result,
6347 unsigned int ivar_count) {
6348 Result += "struct /*_ivar_list_t*/"; Result += " {\n";
6349 Result += "\tunsigned int entsize; // sizeof(struct _prop_t)\n";
6350 Result += "\tunsigned int count;\n";
6351 Result += "\tstruct _ivar_t ivar_list[";
6352 Result += utostr(ivar_count); Result += "];\n";
6353 Result += "}";
6354}
6355
Fariborz Jahaniane18961b2012-02-08 19:53:58 +00006356static void Write_protocol_list_initializer(ASTContext *Context, std::string &Result,
6357 ArrayRef<ObjCProtocolDecl *> SuperProtocols,
6358 StringRef VarName,
6359 StringRef ProtocolName) {
6360 if (SuperProtocols.size() > 0) {
6361 Result += "\nstatic ";
6362 Write_protocol_list_t_TypeDecl(Result, SuperProtocols.size());
6363 Result += " "; Result += VarName;
6364 Result += ProtocolName;
6365 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6366 Result += "\t"; Result += utostr(SuperProtocols.size()); Result += ",\n";
6367 for (unsigned i = 0, e = SuperProtocols.size(); i < e; i++) {
6368 ObjCProtocolDecl *SuperPD = SuperProtocols[i];
6369 Result += "\t&"; Result += "_OBJC_PROTOCOL_";
6370 Result += SuperPD->getNameAsString();
6371 if (i == e-1)
6372 Result += "\n};\n";
6373 else
6374 Result += ",\n";
6375 }
6376 }
6377}
6378
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006379static void Write_method_list_t_initializer(RewriteModernObjC &RewriteObj,
6380 ASTContext *Context, std::string &Result,
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006381 ArrayRef<ObjCMethodDecl *> Methods,
6382 StringRef VarName,
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006383 StringRef TopLevelDeclName,
6384 bool MethodImpl) {
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006385 if (Methods.size() > 0) {
6386 Result += "\nstatic ";
6387 Write_method_list_t_TypeDecl(Result, Methods.size());
6388 Result += " "; Result += VarName;
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006389 Result += TopLevelDeclName;
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006390 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6391 Result += "\t"; Result += "sizeof(_objc_method)"; Result += ",\n";
6392 Result += "\t"; Result += utostr(Methods.size()); Result += ",\n";
6393 for (unsigned i = 0, e = Methods.size(); i < e; i++) {
6394 ObjCMethodDecl *MD = Methods[i];
6395 if (i == 0)
6396 Result += "\t{{(struct objc_selector *)\"";
6397 else
6398 Result += "\t{(struct objc_selector *)\"";
6399 Result += (MD)->getSelector().getAsString(); Result += "\"";
6400 Result += ", ";
6401 std::string MethodTypeString;
6402 Context->getObjCEncodingForMethodDecl(MD, MethodTypeString);
6403 Result += "\""; Result += MethodTypeString; Result += "\"";
6404 Result += ", ";
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006405 if (!MethodImpl)
6406 Result += "0";
6407 else {
6408 Result += "(void *)";
6409 Result += RewriteObj.MethodInternalNames[MD];
6410 }
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006411 if (i == e-1)
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006412 Result += "}}\n";
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006413 else
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006414 Result += "},\n";
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006415 }
6416 Result += "};\n";
6417 }
6418}
6419
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006420static void Write_prop_list_t_initializer(RewriteModernObjC &RewriteObj,
Fariborz Jahanian67f7c552012-02-07 23:31:52 +00006421 ASTContext *Context, std::string &Result,
6422 ArrayRef<ObjCPropertyDecl *> Properties,
6423 const Decl *Container,
6424 StringRef VarName,
6425 StringRef ProtocolName) {
6426 if (Properties.size() > 0) {
6427 Result += "\nstatic ";
6428 Write__prop_list_t_TypeDecl(Result, Properties.size());
6429 Result += " "; Result += VarName;
6430 Result += ProtocolName;
6431 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6432 Result += "\t"; Result += "sizeof(_prop_t)"; Result += ",\n";
6433 Result += "\t"; Result += utostr(Properties.size()); Result += ",\n";
6434 for (unsigned i = 0, e = Properties.size(); i < e; i++) {
6435 ObjCPropertyDecl *PropDecl = Properties[i];
6436 if (i == 0)
6437 Result += "\t{{\"";
6438 else
6439 Result += "\t{\"";
6440 Result += PropDecl->getName(); Result += "\",";
6441 std::string PropertyTypeString, QuotePropertyTypeString;
6442 Context->getObjCEncodingForPropertyDecl(PropDecl, Container, PropertyTypeString);
6443 RewriteObj.QuoteDoublequotes(PropertyTypeString, QuotePropertyTypeString);
6444 Result += "\""; Result += QuotePropertyTypeString; Result += "\"";
6445 if (i == e-1)
6446 Result += "}}\n";
6447 else
6448 Result += "},\n";
6449 }
6450 Result += "};\n";
6451 }
6452}
6453
Fariborz Jahanian0a256882012-02-16 18:54:09 +00006454// Metadata flags
6455enum MetaDataDlags {
6456 CLS = 0x0,
6457 CLS_META = 0x1,
6458 CLS_ROOT = 0x2,
6459 OBJC2_CLS_HIDDEN = 0x10,
6460 CLS_EXCEPTION = 0x20,
6461
6462 /// (Obsolete) ARC-specific: this class has a .release_ivars method
6463 CLS_HAS_IVAR_RELEASER = 0x40,
6464 /// class was compiled with -fobjc-arr
6465 CLS_COMPILED_BY_ARC = 0x80 // (1<<7)
6466};
6467
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006468static void Write__class_ro_t_initializer(ASTContext *Context, std::string &Result,
6469 unsigned int flags,
6470 const std::string &InstanceStart,
6471 const std::string &InstanceSize,
6472 ArrayRef<ObjCMethodDecl *>baseMethods,
6473 ArrayRef<ObjCProtocolDecl *>baseProtocols,
6474 ArrayRef<ObjCIvarDecl *>ivars,
6475 ArrayRef<ObjCPropertyDecl *>Properties,
6476 StringRef VarName,
6477 StringRef ClassName) {
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006478 Result += "\nstatic struct _class_ro_t ";
6479 Result += VarName; Result += ClassName;
6480 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6481 Result += "\t";
6482 Result += llvm::utostr(flags); Result += ", ";
6483 Result += InstanceStart; Result += ", ";
6484 Result += InstanceSize; Result += ", \n";
6485 Result += "\t";
Fariborz Jahanian45489622012-03-14 18:09:23 +00006486 const llvm::Triple &Triple(Context->getTargetInfo().getTriple());
6487 if (Triple.getArch() == llvm::Triple::x86_64)
6488 // uint32_t const reserved; // only when building for 64bit targets
6489 Result += "(unsigned int)0, \n\t";
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006490 // const uint8_t * const ivarLayout;
6491 Result += "0, \n\t";
6492 Result += "\""; Result += ClassName; Result += "\",\n\t";
Fariborz Jahanian0a256882012-02-16 18:54:09 +00006493 bool metaclass = ((flags & CLS_META) != 0);
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006494 if (baseMethods.size() > 0) {
6495 Result += "(const struct _method_list_t *)&";
Fariborz Jahanian0a256882012-02-16 18:54:09 +00006496 if (metaclass)
6497 Result += "_OBJC_$_CLASS_METHODS_";
6498 else
6499 Result += "_OBJC_$_INSTANCE_METHODS_";
6500 Result += ClassName;
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006501 Result += ",\n\t";
6502 }
6503 else
6504 Result += "0, \n\t";
6505
Fariborz Jahanian0a256882012-02-16 18:54:09 +00006506 if (!metaclass && baseProtocols.size() > 0) {
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006507 Result += "(const struct _objc_protocol_list *)&";
6508 Result += "_OBJC_CLASS_PROTOCOLS_$_"; Result += ClassName;
6509 Result += ",\n\t";
6510 }
6511 else
6512 Result += "0, \n\t";
6513
Fariborz Jahanian0a256882012-02-16 18:54:09 +00006514 if (!metaclass && ivars.size() > 0) {
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006515 Result += "(const struct _ivar_list_t *)&";
6516 Result += "_OBJC_$_INSTANCE_VARIABLES_"; Result += ClassName;
6517 Result += ",\n\t";
6518 }
6519 else
6520 Result += "0, \n\t";
6521
6522 // weakIvarLayout
6523 Result += "0, \n\t";
Fariborz Jahanian0a256882012-02-16 18:54:09 +00006524 if (!metaclass && Properties.size() > 0) {
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006525 Result += "(const struct _prop_list_t *)&";
Fariborz Jahanianc41d8282012-02-16 21:57:59 +00006526 Result += "_OBJC_$_PROP_LIST_"; Result += ClassName;
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006527 Result += ",\n";
6528 }
6529 else
6530 Result += "0, \n";
6531
6532 Result += "};\n";
6533}
6534
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006535static void Write_class_t(ASTContext *Context, std::string &Result,
6536 StringRef VarName,
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006537 const ObjCInterfaceDecl *CDecl, bool metaclass) {
6538 bool rootClass = (!CDecl->getSuperClass());
6539 const ObjCInterfaceDecl *RootClass = CDecl;
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006540
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006541 if (!rootClass) {
6542 // Find the Root class
6543 RootClass = CDecl->getSuperClass();
6544 while (RootClass->getSuperClass()) {
6545 RootClass = RootClass->getSuperClass();
6546 }
6547 }
6548
6549 if (metaclass && rootClass) {
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006550 // Need to handle a case of use of forward declaration.
Fariborz Jahanianfca65102012-03-10 18:25:06 +00006551 Result += "\n";
Fariborz Jahanian38c59102012-03-27 16:21:30 +00006552 Result += "extern \"C\" ";
Fariborz Jahanianfca65102012-03-10 18:25:06 +00006553 if (CDecl->getImplementation())
6554 Result += "__declspec(dllexport) ";
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00006555 else
6556 Result += "__declspec(dllimport) ";
6557
Fariborz Jahanian38c59102012-03-27 16:21:30 +00006558 Result += "struct _class_t OBJC_CLASS_$_";
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006559 Result += CDecl->getNameAsString();
6560 Result += ";\n";
6561 }
6562 // Also, for possibility of 'super' metadata class not having been defined yet.
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006563 if (!rootClass) {
Fariborz Jahanian064b5382012-03-29 19:04:10 +00006564 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahanianfca65102012-03-10 18:25:06 +00006565 Result += "\n";
Fariborz Jahanian38c59102012-03-27 16:21:30 +00006566 Result += "extern \"C\" ";
Fariborz Jahanian064b5382012-03-29 19:04:10 +00006567 if (SuperClass->getImplementation())
Fariborz Jahanianfca65102012-03-10 18:25:06 +00006568 Result += "__declspec(dllexport) ";
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00006569 else
6570 Result += "__declspec(dllimport) ";
6571
Fariborz Jahanian38c59102012-03-27 16:21:30 +00006572 Result += "struct _class_t ";
Fariborz Jahanianfca65102012-03-10 18:25:06 +00006573 Result += VarName;
Fariborz Jahanian064b5382012-03-29 19:04:10 +00006574 Result += SuperClass->getNameAsString();
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006575 Result += ";\n";
Fariborz Jahanian35465592012-03-20 21:09:58 +00006576
Fariborz Jahanian064b5382012-03-29 19:04:10 +00006577 if (metaclass && RootClass != SuperClass) {
Fariborz Jahanian38c59102012-03-27 16:21:30 +00006578 Result += "extern \"C\" ";
Fariborz Jahanian35465592012-03-20 21:09:58 +00006579 if (RootClass->getImplementation())
6580 Result += "__declspec(dllexport) ";
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00006581 else
6582 Result += "__declspec(dllimport) ";
6583
Fariborz Jahanian38c59102012-03-27 16:21:30 +00006584 Result += "struct _class_t ";
Fariborz Jahanian35465592012-03-20 21:09:58 +00006585 Result += VarName;
6586 Result += RootClass->getNameAsString();
6587 Result += ";\n";
6588 }
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006589 }
6590
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00006591 Result += "\nextern \"C\" __declspec(dllexport) struct _class_t ";
6592 Result += VarName; Result += CDecl->getNameAsString();
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006593 Result += " __attribute__ ((used, section (\"__DATA,__objc_data\"))) = {\n";
6594 Result += "\t";
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006595 if (metaclass) {
6596 if (!rootClass) {
6597 Result += "0, // &"; Result += VarName;
6598 Result += RootClass->getNameAsString();
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006599 Result += ",\n\t";
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006600 Result += "0, // &"; Result += VarName;
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006601 Result += CDecl->getSuperClass()->getNameAsString();
6602 Result += ",\n\t";
6603 }
6604 else {
Fariborz Jahanian35465592012-03-20 21:09:58 +00006605 Result += "0, // &"; Result += VarName;
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006606 Result += CDecl->getNameAsString();
6607 Result += ",\n\t";
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006608 Result += "0, // &OBJC_CLASS_$_"; Result += CDecl->getNameAsString();
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006609 Result += ",\n\t";
6610 }
6611 }
6612 else {
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006613 Result += "0, // &OBJC_METACLASS_$_";
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006614 Result += CDecl->getNameAsString();
6615 Result += ",\n\t";
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006616 if (!rootClass) {
6617 Result += "0, // &"; Result += VarName;
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006618 Result += CDecl->getSuperClass()->getNameAsString();
6619 Result += ",\n\t";
6620 }
6621 else
6622 Result += "0,\n\t";
6623 }
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006624 Result += "0, // (void *)&_objc_empty_cache,\n\t";
6625 Result += "0, // unused, was (void *)&_objc_empty_vtable,\n\t";
6626 if (metaclass)
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006627 Result += "&_OBJC_METACLASS_RO_$_";
6628 else
6629 Result += "&_OBJC_CLASS_RO_$_";
6630 Result += CDecl->getNameAsString();
6631 Result += ",\n};\n";
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006632
6633 // Add static function to initialize some of the meta-data fields.
6634 // avoid doing it twice.
6635 if (metaclass)
6636 return;
6637
6638 const ObjCInterfaceDecl *SuperClass =
6639 rootClass ? CDecl : CDecl->getSuperClass();
6640
6641 Result += "static void OBJC_CLASS_SETUP_$_";
6642 Result += CDecl->getNameAsString();
6643 Result += "(void ) {\n";
6644 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
6645 Result += ".isa = "; Result += "&OBJC_METACLASS_$_";
Fariborz Jahanian35465592012-03-20 21:09:58 +00006646 Result += RootClass->getNameAsString(); Result += ";\n";
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006647
6648 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
Fariborz Jahanian35465592012-03-20 21:09:58 +00006649 Result += ".superclass = ";
6650 if (rootClass)
6651 Result += "&OBJC_CLASS_$_";
6652 else
6653 Result += "&OBJC_METACLASS_$_";
6654
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006655 Result += SuperClass->getNameAsString(); Result += ";\n";
6656
6657 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
6658 Result += ".cache = "; Result += "&_objc_empty_cache"; Result += ";\n";
6659
6660 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6661 Result += ".isa = "; Result += "&OBJC_METACLASS_$_";
6662 Result += CDecl->getNameAsString(); Result += ";\n";
6663
6664 if (!rootClass) {
6665 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6666 Result += ".superclass = "; Result += "&OBJC_CLASS_$_";
6667 Result += SuperClass->getNameAsString(); Result += ";\n";
6668 }
6669
6670 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6671 Result += ".cache = "; Result += "&_objc_empty_cache"; Result += ";\n";
6672 Result += "}\n";
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006673}
6674
Fariborz Jahanianf2055052012-02-17 18:40:41 +00006675static void Write_category_t(RewriteModernObjC &RewriteObj, ASTContext *Context,
6676 std::string &Result,
Fariborz Jahanian5ed21c32012-03-27 18:41:05 +00006677 ObjCCategoryDecl *CatDecl,
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00006678 ObjCInterfaceDecl *ClassDecl,
Fariborz Jahanianf2055052012-02-17 18:40:41 +00006679 ArrayRef<ObjCMethodDecl *> InstanceMethods,
6680 ArrayRef<ObjCMethodDecl *> ClassMethods,
6681 ArrayRef<ObjCProtocolDecl *> RefedProtocols,
6682 ArrayRef<ObjCPropertyDecl *> ClassProperties) {
Fariborz Jahanian5ed21c32012-03-27 18:41:05 +00006683 StringRef CatName = CatDecl->getName();
NAKAMURA Takumi3eb0edd2012-03-21 03:21:46 +00006684 StringRef ClassName = ClassDecl->getName();
Fariborz Jahanian320c88a2012-02-17 20:33:00 +00006685 // must declare an extern class object in case this class is not implemented
6686 // in this TU.
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00006687 Result += "\n";
Fariborz Jahanian38c59102012-03-27 16:21:30 +00006688 Result += "extern \"C\" ";
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00006689 if (ClassDecl->getImplementation())
6690 Result += "__declspec(dllexport) ";
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00006691 else
6692 Result += "__declspec(dllimport) ";
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00006693
Fariborz Jahanian38c59102012-03-27 16:21:30 +00006694 Result += "struct _class_t ";
Fariborz Jahanian320c88a2012-02-17 20:33:00 +00006695 Result += "OBJC_CLASS_$_"; Result += ClassName;
6696 Result += ";\n";
6697
Fariborz Jahanianf2055052012-02-17 18:40:41 +00006698 Result += "\nstatic struct _category_t ";
6699 Result += "_OBJC_$_CATEGORY_";
6700 Result += ClassName; Result += "_$_"; Result += CatName;
6701 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = \n";
6702 Result += "{\n";
6703 Result += "\t\""; Result += ClassName; Result += "\",\n";
Fariborz Jahaniancd79a492012-03-20 21:41:28 +00006704 Result += "\t0, // &"; Result += "OBJC_CLASS_$_"; Result += ClassName;
Fariborz Jahanianf2055052012-02-17 18:40:41 +00006705 Result += ",\n";
6706 if (InstanceMethods.size() > 0) {
6707 Result += "\t(const struct _method_list_t *)&";
6708 Result += "_OBJC_$_CATEGORY_INSTANCE_METHODS_";
6709 Result += ClassName; Result += "_$_"; Result += CatName;
6710 Result += ",\n";
6711 }
6712 else
6713 Result += "\t0,\n";
6714
6715 if (ClassMethods.size() > 0) {
6716 Result += "\t(const struct _method_list_t *)&";
6717 Result += "_OBJC_$_CATEGORY_CLASS_METHODS_";
6718 Result += ClassName; Result += "_$_"; Result += CatName;
6719 Result += ",\n";
6720 }
6721 else
6722 Result += "\t0,\n";
6723
6724 if (RefedProtocols.size() > 0) {
6725 Result += "\t(const struct _protocol_list_t *)&";
6726 Result += "_OBJC_CATEGORY_PROTOCOLS_$_";
6727 Result += ClassName; Result += "_$_"; Result += CatName;
6728 Result += ",\n";
6729 }
6730 else
6731 Result += "\t0,\n";
6732
6733 if (ClassProperties.size() > 0) {
6734 Result += "\t(const struct _prop_list_t *)&"; Result += "_OBJC_$_PROP_LIST_";
6735 Result += ClassName; Result += "_$_"; Result += CatName;
6736 Result += ",\n";
6737 }
6738 else
6739 Result += "\t0,\n";
6740
6741 Result += "};\n";
Fariborz Jahaniancd79a492012-03-20 21:41:28 +00006742
6743 // Add static function to initialize the class pointer in the category structure.
6744 Result += "static void OBJC_CATEGORY_SETUP_$_";
6745 Result += ClassDecl->getNameAsString();
6746 Result += "_$_";
6747 Result += CatName;
6748 Result += "(void ) {\n";
6749 Result += "\t_OBJC_$_CATEGORY_";
6750 Result += ClassDecl->getNameAsString();
6751 Result += "_$_";
6752 Result += CatName;
6753 Result += ".cls = "; Result += "&OBJC_CLASS_$_"; Result += ClassName;
6754 Result += ";\n}\n";
Fariborz Jahanianf2055052012-02-17 18:40:41 +00006755}
6756
Fariborz Jahaniana8395a62012-02-08 22:23:26 +00006757static void Write__extendedMethodTypes_initializer(RewriteModernObjC &RewriteObj,
6758 ASTContext *Context, std::string &Result,
6759 ArrayRef<ObjCMethodDecl *> Methods,
6760 StringRef VarName,
6761 StringRef ProtocolName) {
6762 if (Methods.size() == 0)
6763 return;
6764
6765 Result += "\nstatic const char *";
6766 Result += VarName; Result += ProtocolName;
6767 Result += " [] __attribute__ ((used, section (\"__DATA,__objc_const\"))) = \n";
6768 Result += "{\n";
6769 for (unsigned i = 0, e = Methods.size(); i < e; i++) {
6770 ObjCMethodDecl *MD = Methods[i];
6771 std::string MethodTypeString, QuoteMethodTypeString;
6772 Context->getObjCEncodingForMethodDecl(MD, MethodTypeString, true);
6773 RewriteObj.QuoteDoublequotes(MethodTypeString, QuoteMethodTypeString);
6774 Result += "\t\""; Result += QuoteMethodTypeString; Result += "\"";
6775 if (i == e-1)
6776 Result += "\n};\n";
6777 else {
6778 Result += ",\n";
6779 }
6780 }
6781}
6782
Fariborz Jahanianaaf4d692012-04-11 21:12:36 +00006783static void Write_IvarOffsetVar(RewriteModernObjC &RewriteObj,
6784 ASTContext *Context,
Fariborz Jahaniane47bf2b2012-03-12 16:46:58 +00006785 std::string &Result,
Fariborz Jahanian75e71b92012-02-13 20:59:02 +00006786 ArrayRef<ObjCIvarDecl *> Ivars,
Fariborz Jahaniana854174a2012-03-20 17:13:39 +00006787 ObjCInterfaceDecl *CDecl) {
Fariborz Jahanian75e71b92012-02-13 20:59:02 +00006788 // FIXME. visibilty of offset symbols may have to be set; for Darwin
6789 // this is what happens:
6790 /**
6791 if (Ivar->getAccessControl() == ObjCIvarDecl::Private ||
6792 Ivar->getAccessControl() == ObjCIvarDecl::Package ||
6793 Class->getVisibility() == HiddenVisibility)
6794 Visibility shoud be: HiddenVisibility;
6795 else
6796 Visibility shoud be: DefaultVisibility;
6797 */
6798
Fariborz Jahanian1c1da172012-02-13 21:34:45 +00006799 Result += "\n";
6800 for (unsigned i =0, e = Ivars.size(); i < e; i++) {
6801 ObjCIvarDecl *IvarDecl = Ivars[i];
Fariborz Jahaniane47bf2b2012-03-12 16:46:58 +00006802 if (Context->getLangOpts().MicrosoftExt)
6803 Result += "__declspec(allocate(\".objc_ivar$B\")) ";
6804
6805 if (!Context->getLangOpts().MicrosoftExt ||
6806 IvarDecl->getAccessControl() == ObjCIvarDecl::Private ||
Fariborz Jahanianc9295ec2012-03-10 01:34:42 +00006807 IvarDecl->getAccessControl() == ObjCIvarDecl::Package)
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00006808 Result += "extern \"C\" unsigned long int ";
Fariborz Jahanian2677ded2012-03-10 00:53:02 +00006809 else
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00006810 Result += "extern \"C\" __declspec(dllexport) unsigned long int ";
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006811 if (Ivars[i]->isBitField())
6812 RewriteObj.ObjCIvarBitfieldGroupOffset(IvarDecl, Result);
6813 else
6814 WriteInternalIvarName(CDecl, IvarDecl, Result);
Fariborz Jahanian1c1da172012-02-13 21:34:45 +00006815 Result += " __attribute__ ((used, section (\"__DATA,__objc_ivar\")))";
6816 Result += " = ";
Fariborz Jahanianaaf4d692012-04-11 21:12:36 +00006817 RewriteObj.RewriteIvarOffsetComputation(IvarDecl, Result);
6818 Result += ";\n";
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006819 if (Ivars[i]->isBitField()) {
6820 // skip over rest of the ivar bitfields.
6821 SKIP_BITFIELDS(i , e, Ivars);
6822 }
Fariborz Jahanian75e71b92012-02-13 20:59:02 +00006823 }
6824}
6825
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006826static void Write__ivar_list_t_initializer(RewriteModernObjC &RewriteObj,
6827 ASTContext *Context, std::string &Result,
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006828 ArrayRef<ObjCIvarDecl *> OriginalIvars,
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006829 StringRef VarName,
Fariborz Jahaniana854174a2012-03-20 17:13:39 +00006830 ObjCInterfaceDecl *CDecl) {
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006831 if (OriginalIvars.size() > 0) {
6832 Write_IvarOffsetVar(RewriteObj, Context, Result, OriginalIvars, CDecl);
6833 SmallVector<ObjCIvarDecl *, 8> Ivars;
6834 // strip off all but the first ivar bitfield from each group of ivars.
6835 // Such ivars in the ivar list table will be replaced by their grouping struct
6836 // 'ivar'.
6837 for (unsigned i = 0, e = OriginalIvars.size(); i < e; i++) {
6838 if (OriginalIvars[i]->isBitField()) {
6839 Ivars.push_back(OriginalIvars[i]);
6840 // skip over rest of the ivar bitfields.
6841 SKIP_BITFIELDS(i , e, OriginalIvars);
6842 }
6843 else
6844 Ivars.push_back(OriginalIvars[i]);
6845 }
Fariborz Jahanian1c1da172012-02-13 21:34:45 +00006846
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006847 Result += "\nstatic ";
6848 Write__ivar_list_t_TypeDecl(Result, Ivars.size());
6849 Result += " "; Result += VarName;
Fariborz Jahaniana854174a2012-03-20 17:13:39 +00006850 Result += CDecl->getNameAsString();
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006851 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6852 Result += "\t"; Result += "sizeof(_ivar_t)"; Result += ",\n";
6853 Result += "\t"; Result += utostr(Ivars.size()); Result += ",\n";
6854 for (unsigned i =0, e = Ivars.size(); i < e; i++) {
6855 ObjCIvarDecl *IvarDecl = Ivars[i];
6856 if (i == 0)
6857 Result += "\t{{";
6858 else
6859 Result += "\t {";
Fariborz Jahaniana854174a2012-03-20 17:13:39 +00006860 Result += "(unsigned long int *)&";
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006861 if (Ivars[i]->isBitField())
6862 RewriteObj.ObjCIvarBitfieldGroupOffset(IvarDecl, Result);
6863 else
6864 WriteInternalIvarName(CDecl, IvarDecl, Result);
Fariborz Jahanian75e71b92012-02-13 20:59:02 +00006865 Result += ", ";
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006866
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006867 Result += "\"";
6868 if (Ivars[i]->isBitField())
6869 RewriteObj.ObjCIvarBitfieldGroupDecl(Ivars[i], Result);
6870 else
6871 Result += IvarDecl->getName();
6872 Result += "\", ";
6873
6874 QualType IVQT = IvarDecl->getType();
6875 if (IvarDecl->isBitField())
6876 IVQT = RewriteObj.GetGroupRecordTypeForObjCIvarBitfield(IvarDecl);
6877
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006878 std::string IvarTypeString, QuoteIvarTypeString;
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006879 Context->getObjCEncodingForType(IVQT, IvarTypeString,
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006880 IvarDecl);
6881 RewriteObj.QuoteDoublequotes(IvarTypeString, QuoteIvarTypeString);
6882 Result += "\""; Result += QuoteIvarTypeString; Result += "\", ";
6883
Fariborz Jahanian088959a2012-02-11 20:10:52 +00006884 // FIXME. this alignment represents the host alignment and need be changed to
6885 // represent the target alignment.
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006886 unsigned Align = Context->getTypeAlign(IVQT)/8;
Fariborz Jahanian088959a2012-02-11 20:10:52 +00006887 Align = llvm::Log2_32(Align);
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006888 Result += llvm::utostr(Align); Result += ", ";
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006889 CharUnits Size = Context->getTypeSizeInChars(IVQT);
Fariborz Jahaniancb1d9f32012-02-10 23:18:24 +00006890 Result += llvm::utostr(Size.getQuantity());
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006891 if (i == e-1)
6892 Result += "}}\n";
6893 else
6894 Result += "},\n";
6895 }
6896 Result += "};\n";
6897 }
6898}
6899
Fariborz Jahanian11671902012-02-07 17:11:38 +00006900/// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
Fariborz Jahaniane18961b2012-02-08 19:53:58 +00006901void RewriteModernObjC::RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl,
6902 std::string &Result) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00006903
Fariborz Jahanian11671902012-02-07 17:11:38 +00006904 // Do not synthesize the protocol more than once.
6905 if (ObjCSynthesizedProtocols.count(PDecl->getCanonicalDecl()))
6906 return;
Fariborz Jahanian45489622012-03-14 18:09:23 +00006907 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanian11671902012-02-07 17:11:38 +00006908
6909 if (ObjCProtocolDecl *Def = PDecl->getDefinition())
6910 PDecl = Def;
Fariborz Jahaniane18961b2012-02-08 19:53:58 +00006911 // Must write out all protocol definitions in current qualifier list,
6912 // and in their nested qualifiers before writing out current definition.
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00006913 for (auto *I : PDecl->protocols())
6914 RewriteObjCProtocolMetaData(I, Result);
Fariborz Jahanian11671902012-02-07 17:11:38 +00006915
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006916 // Construct method lists.
6917 std::vector<ObjCMethodDecl *> InstanceMethods, ClassMethods;
6918 std::vector<ObjCMethodDecl *> OptInstanceMethods, OptClassMethods;
Aaron Ballmanf26acce2014-03-13 19:50:17 +00006919 for (auto *MD : PDecl->instance_methods()) {
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006920 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
6921 OptInstanceMethods.push_back(MD);
6922 } else {
6923 InstanceMethods.push_back(MD);
6924 }
6925 }
6926
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00006927 for (auto *MD : PDecl->class_methods()) {
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006928 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
6929 OptClassMethods.push_back(MD);
6930 } else {
6931 ClassMethods.push_back(MD);
6932 }
6933 }
Fariborz Jahaniana8395a62012-02-08 22:23:26 +00006934 std::vector<ObjCMethodDecl *> AllMethods;
6935 for (unsigned i = 0, e = InstanceMethods.size(); i < e; i++)
6936 AllMethods.push_back(InstanceMethods[i]);
6937 for (unsigned i = 0, e = ClassMethods.size(); i < e; i++)
6938 AllMethods.push_back(ClassMethods[i]);
6939 for (unsigned i = 0, e = OptInstanceMethods.size(); i < e; i++)
6940 AllMethods.push_back(OptInstanceMethods[i]);
6941 for (unsigned i = 0, e = OptClassMethods.size(); i < e; i++)
6942 AllMethods.push_back(OptClassMethods[i]);
6943
6944 Write__extendedMethodTypes_initializer(*this, Context, Result,
6945 AllMethods,
6946 "_OBJC_PROTOCOL_METHOD_TYPES_",
6947 PDecl->getNameAsString());
Fariborz Jahaniane18961b2012-02-08 19:53:58 +00006948 // Protocol's super protocol list
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00006949 SmallVector<ObjCProtocolDecl *, 8> SuperProtocols(PDecl->protocols());
Fariborz Jahaniane18961b2012-02-08 19:53:58 +00006950 Write_protocol_list_initializer(Context, Result, SuperProtocols,
6951 "_OBJC_PROTOCOL_REFS_",
6952 PDecl->getNameAsString());
6953
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006954 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006955 "_OBJC_PROTOCOL_INSTANCE_METHODS_",
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006956 PDecl->getNameAsString(), false);
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006957
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006958 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006959 "_OBJC_PROTOCOL_CLASS_METHODS_",
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006960 PDecl->getNameAsString(), false);
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006961
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006962 Write_method_list_t_initializer(*this, Context, Result, OptInstanceMethods,
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006963 "_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_",
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006964 PDecl->getNameAsString(), false);
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006965
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006966 Write_method_list_t_initializer(*this, Context, Result, OptClassMethods,
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006967 "_OBJC_PROTOCOL_OPT_CLASS_METHODS_",
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006968 PDecl->getNameAsString(), false);
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006969
Fariborz Jahanian67f7c552012-02-07 23:31:52 +00006970 // Protocol's property metadata.
Manman Rena7a8b1f2016-01-26 18:05:23 +00006971 SmallVector<ObjCPropertyDecl *, 8> ProtocolProperties(
6972 PDecl->instance_properties());
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006973 Write_prop_list_t_initializer(*this, Context, Result, ProtocolProperties,
Craig Topper8ae12032014-05-07 06:21:57 +00006974 /* Container */nullptr,
Fariborz Jahanian67f7c552012-02-07 23:31:52 +00006975 "_OBJC_PROTOCOL_PROPERTIES_",
6976 PDecl->getNameAsString());
Craig Topper8ae12032014-05-07 06:21:57 +00006977
Fariborz Jahanian48985802012-02-08 00:50:52 +00006978 // Writer out root metadata for current protocol: struct _protocol_t
Fariborz Jahanian008dfe22012-03-11 19:41:56 +00006979 Result += "\n";
6980 if (LangOpts.MicrosoftExt)
Fariborz Jahanian1b085422012-04-14 17:13:08 +00006981 Result += "static ";
Fariborz Jahanianb31e3af2012-03-15 17:05:33 +00006982 Result += "struct _protocol_t _OBJC_PROTOCOL_";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006983 Result += PDecl->getNameAsString();
Akira Hatanaka7f550f32016-02-11 06:36:35 +00006984 Result += " __attribute__ ((used)) = {\n";
Fariborz Jahanian48985802012-02-08 00:50:52 +00006985 Result += "\t0,\n"; // id is; is null
6986 Result += "\t\""; Result += PDecl->getNameAsString(); Result += "\",\n";
Fariborz Jahaniane18961b2012-02-08 19:53:58 +00006987 if (SuperProtocols.size() > 0) {
6988 Result += "\t(const struct _protocol_list_t *)&"; Result += "_OBJC_PROTOCOL_REFS_";
6989 Result += PDecl->getNameAsString(); Result += ",\n";
6990 }
6991 else
6992 Result += "\t0,\n";
Fariborz Jahanian48985802012-02-08 00:50:52 +00006993 if (InstanceMethods.size() > 0) {
6994 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
6995 Result += PDecl->getNameAsString(); Result += ",\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006996 }
6997 else
Fariborz Jahanian48985802012-02-08 00:50:52 +00006998 Result += "\t0,\n";
6999
7000 if (ClassMethods.size() > 0) {
7001 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_CLASS_METHODS_";
7002 Result += PDecl->getNameAsString(); Result += ",\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00007003 }
7004 else
Fariborz Jahanian48985802012-02-08 00:50:52 +00007005 Result += "\t0,\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00007006
Fariborz Jahanian48985802012-02-08 00:50:52 +00007007 if (OptInstanceMethods.size() > 0) {
7008 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_";
7009 Result += PDecl->getNameAsString(); Result += ",\n";
7010 }
7011 else
7012 Result += "\t0,\n";
7013
7014 if (OptClassMethods.size() > 0) {
7015 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_CLASS_METHODS_";
7016 Result += PDecl->getNameAsString(); Result += ",\n";
7017 }
7018 else
7019 Result += "\t0,\n";
7020
7021 if (ProtocolProperties.size() > 0) {
7022 Result += "\t(const struct _prop_list_t *)&_OBJC_PROTOCOL_PROPERTIES_";
7023 Result += PDecl->getNameAsString(); Result += ",\n";
7024 }
7025 else
7026 Result += "\t0,\n";
7027
7028 Result += "\t"; Result += "sizeof(_protocol_t)"; Result += ",\n";
7029 Result += "\t0,\n";
7030
Fariborz Jahaniana8395a62012-02-08 22:23:26 +00007031 if (AllMethods.size() > 0) {
7032 Result += "\t(const char **)&"; Result += "_OBJC_PROTOCOL_METHOD_TYPES_";
7033 Result += PDecl->getNameAsString();
7034 Result += "\n};\n";
7035 }
7036 else
7037 Result += "\t0\n};\n";
Fariborz Jahanianddddca32012-03-14 21:44:09 +00007038
Fariborz Jahanianddddca32012-03-14 21:44:09 +00007039 if (LangOpts.MicrosoftExt)
Fariborz Jahanian1b085422012-04-14 17:13:08 +00007040 Result += "static ";
Fariborz Jahanianddddca32012-03-14 21:44:09 +00007041 Result += "struct _protocol_t *";
7042 Result += "_OBJC_LABEL_PROTOCOL_$_"; Result += PDecl->getNameAsString();
7043 Result += " = &_OBJC_PROTOCOL_"; Result += PDecl->getNameAsString();
7044 Result += ";\n";
Fariborz Jahanian48985802012-02-08 00:50:52 +00007045
Fariborz Jahanian11671902012-02-07 17:11:38 +00007046 // Mark this protocol as having been generated.
David Blaikie82e95a32014-11-19 07:49:47 +00007047 if (!ObjCSynthesizedProtocols.insert(PDecl->getCanonicalDecl()).second)
Fariborz Jahanian11671902012-02-07 17:11:38 +00007048 llvm_unreachable("protocol already synthesized");
Fariborz Jahanian11671902012-02-07 17:11:38 +00007049}
7050
7051void RewriteModernObjC::RewriteObjCProtocolListMetaData(
7052 const ObjCList<ObjCProtocolDecl> &Protocols,
7053 StringRef prefix, StringRef ClassName,
7054 std::string &Result) {
7055 if (Protocols.empty()) return;
7056
7057 for (unsigned i = 0; i != Protocols.size(); i++)
Fariborz Jahaniane18961b2012-02-08 19:53:58 +00007058 RewriteObjCProtocolMetaData(Protocols[i], Result);
Fariborz Jahanian11671902012-02-07 17:11:38 +00007059
7060 // Output the top lovel protocol meta-data for the class.
7061 /* struct _objc_protocol_list {
7062 struct _objc_protocol_list *next;
7063 int protocol_count;
7064 struct _objc_protocol *class_protocols[];
7065 }
7066 */
Fariborz Jahanian008dfe22012-03-11 19:41:56 +00007067 Result += "\n";
7068 if (LangOpts.MicrosoftExt)
7069 Result += "__declspec(allocate(\".cat_cls_meth$B\")) ";
7070 Result += "static struct {\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00007071 Result += "\tstruct _objc_protocol_list *next;\n";
7072 Result += "\tint protocol_count;\n";
7073 Result += "\tstruct _objc_protocol *class_protocols[";
7074 Result += utostr(Protocols.size());
7075 Result += "];\n} _OBJC_";
7076 Result += prefix;
7077 Result += "_PROTOCOLS_";
7078 Result += ClassName;
7079 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
7080 "{\n\t0, ";
7081 Result += utostr(Protocols.size());
7082 Result += "\n";
7083
7084 Result += "\t,{&_OBJC_PROTOCOL_";
7085 Result += Protocols[0]->getNameAsString();
7086 Result += " \n";
7087
7088 for (unsigned i = 1; i != Protocols.size(); i++) {
7089 Result += "\t ,&_OBJC_PROTOCOL_";
7090 Result += Protocols[i]->getNameAsString();
7091 Result += "\n";
7092 }
7093 Result += "\t }\n};\n";
7094}
7095
Fariborz Jahanian0a256882012-02-16 18:54:09 +00007096/// hasObjCExceptionAttribute - Return true if this class or any super
7097/// class has the __objc_exception__ attribute.
7098/// FIXME. Move this to ASTContext.cpp as it is also used for IRGen.
7099static bool hasObjCExceptionAttribute(ASTContext &Context,
7100 const ObjCInterfaceDecl *OID) {
7101 if (OID->hasAttr<ObjCExceptionAttr>())
7102 return true;
7103 if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
7104 return hasObjCExceptionAttribute(Context, Super);
7105 return false;
7106}
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007107
Fariborz Jahanian11671902012-02-07 17:11:38 +00007108void RewriteModernObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
7109 std::string &Result) {
7110 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
7111
7112 // Explicitly declared @interface's are already synthesized.
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00007113 if (CDecl->isImplicitInterfaceDecl())
7114 assert(false &&
7115 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian088959a2012-02-11 20:10:52 +00007116
Fariborz Jahanian45489622012-03-14 18:09:23 +00007117 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00007118 SmallVector<ObjCIvarDecl *, 8> IVars;
7119
7120 for (ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
7121 IVD; IVD = IVD->getNextIvar()) {
7122 // Ignore unnamed bit-fields.
7123 if (!IVD->getDeclName())
7124 continue;
7125 IVars.push_back(IVD);
Fariborz Jahanian11671902012-02-07 17:11:38 +00007126 }
7127
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00007128 Write__ivar_list_t_initializer(*this, Context, Result, IVars,
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007129 "_OBJC_$_INSTANCE_VARIABLES_",
Fariborz Jahaniana854174a2012-03-20 17:13:39 +00007130 CDecl);
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007131
7132 // Build _objc_method_list for class's instance methods if needed
Aaron Ballmanf26acce2014-03-13 19:50:17 +00007133 SmallVector<ObjCMethodDecl *, 32> InstanceMethods(IDecl->instance_methods());
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007134
7135 // If any of our property implementations have associated getters or
7136 // setters, produce metadata for them as well.
Aaron Ballmand85eff42014-03-14 15:02:45 +00007137 for (const auto *Prop : IDecl->property_impls()) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00007138 if (Prop->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007139 continue;
David Blaikie2d7c57e2012-04-30 02:36:29 +00007140 if (!Prop->getPropertyIvarDecl())
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007141 continue;
David Blaikie2d7c57e2012-04-30 02:36:29 +00007142 ObjCPropertyDecl *PD = Prop->getPropertyDecl();
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007143 if (!PD)
7144 continue;
7145 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
Fariborz Jahanianf687e7b2012-05-03 22:52:13 +00007146 if (mustSynthesizeSetterGetterMethod(IDecl, PD, true /*getter*/))
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007147 InstanceMethods.push_back(Getter);
7148 if (PD->isReadOnly())
7149 continue;
7150 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
Fariborz Jahanianf687e7b2012-05-03 22:52:13 +00007151 if (mustSynthesizeSetterGetterMethod(IDecl, PD, false /*setter*/))
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007152 InstanceMethods.push_back(Setter);
7153 }
7154
7155 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
7156 "_OBJC_$_INSTANCE_METHODS_",
7157 IDecl->getNameAsString(), true);
7158
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00007159 SmallVector<ObjCMethodDecl *, 32> ClassMethods(IDecl->class_methods());
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007160
7161 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
7162 "_OBJC_$_CLASS_METHODS_",
7163 IDecl->getNameAsString(), true);
Fariborz Jahanianbce367742012-02-14 19:31:35 +00007164
7165 // Protocols referenced in class declaration?
7166 // Protocol's super protocol list
7167 std::vector<ObjCProtocolDecl *> RefedProtocols;
7168 const ObjCList<ObjCProtocolDecl> &Protocols = CDecl->getReferencedProtocols();
7169 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
7170 E = Protocols.end();
7171 I != E; ++I) {
7172 RefedProtocols.push_back(*I);
7173 // Must write out all protocol definitions in current qualifier list,
7174 // and in their nested qualifiers before writing out current definition.
7175 RewriteObjCProtocolMetaData(*I, Result);
7176 }
7177
7178 Write_protocol_list_initializer(Context, Result,
7179 RefedProtocols,
7180 "_OBJC_CLASS_PROTOCOLS_$_",
7181 IDecl->getNameAsString());
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007182
7183 // Protocol's property metadata.
Manman Rena7a8b1f2016-01-26 18:05:23 +00007184 SmallVector<ObjCPropertyDecl *, 8> ClassProperties(
7185 CDecl->instance_properties());
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007186 Write_prop_list_t_initializer(*this, Context, Result, ClassProperties,
Fariborz Jahanianee1db7a2012-03-22 17:39:35 +00007187 /* Container */IDecl,
Fariborz Jahanianc41d8282012-02-16 21:57:59 +00007188 "_OBJC_$_PROP_LIST_",
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007189 CDecl->getNameAsString());
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007190
Fariborz Jahanian0a256882012-02-16 18:54:09 +00007191 // Data for initializing _class_ro_t metaclass meta-data
7192 uint32_t flags = CLS_META;
7193 std::string InstanceSize;
7194 std::string InstanceStart;
7195
Fariborz Jahanian0a256882012-02-16 18:54:09 +00007196 bool classIsHidden = CDecl->getVisibility() == HiddenVisibility;
7197 if (classIsHidden)
7198 flags |= OBJC2_CLS_HIDDEN;
7199
7200 if (!CDecl->getSuperClass())
7201 // class is root
7202 flags |= CLS_ROOT;
7203 InstanceSize = "sizeof(struct _class_t)";
7204 InstanceStart = InstanceSize;
7205 Write__class_ro_t_initializer(Context, Result, flags,
7206 InstanceStart, InstanceSize,
7207 ClassMethods,
Craig Topper8ae12032014-05-07 06:21:57 +00007208 nullptr,
7209 nullptr,
7210 nullptr,
Fariborz Jahanian0a256882012-02-16 18:54:09 +00007211 "_OBJC_METACLASS_RO_$_",
7212 CDecl->getNameAsString());
7213
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007214 // Data for initializing _class_ro_t meta-data
Fariborz Jahanian0a256882012-02-16 18:54:09 +00007215 flags = CLS;
7216 if (classIsHidden)
7217 flags |= OBJC2_CLS_HIDDEN;
7218
7219 if (hasObjCExceptionAttribute(*Context, CDecl))
7220 flags |= CLS_EXCEPTION;
7221
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007222 if (!CDecl->getSuperClass())
7223 // class is root
7224 flags |= CLS_ROOT;
7225
Fariborz Jahanian0a256882012-02-16 18:54:09 +00007226 InstanceSize.clear();
7227 InstanceStart.clear();
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007228 if (!ObjCSynthesizedStructs.count(CDecl)) {
7229 InstanceSize = "0";
7230 InstanceStart = "0";
7231 }
7232 else {
7233 InstanceSize = "sizeof(struct ";
7234 InstanceSize += CDecl->getNameAsString();
7235 InstanceSize += "_IMPL)";
7236
7237 ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
7238 if (IVD) {
Fariborz Jahanianaaf4d692012-04-11 21:12:36 +00007239 RewriteIvarOffsetComputation(IVD, InstanceStart);
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007240 }
7241 else
7242 InstanceStart = InstanceSize;
7243 }
7244 Write__class_ro_t_initializer(Context, Result, flags,
7245 InstanceStart, InstanceSize,
7246 InstanceMethods,
7247 RefedProtocols,
7248 IVars,
7249 ClassProperties,
7250 "_OBJC_CLASS_RO_$_",
7251 CDecl->getNameAsString());
Fariborz Jahanian638252f2012-02-16 21:37:05 +00007252
7253 Write_class_t(Context, Result,
7254 "OBJC_METACLASS_$_",
7255 CDecl, /*metaclass*/true);
7256
7257 Write_class_t(Context, Result,
7258 "OBJC_CLASS_$_",
7259 CDecl, /*metaclass*/false);
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00007260
7261 if (ImplementationIsNonLazy(IDecl))
7262 DefinedNonLazyClasses.push_back(CDecl);
Fariborz Jahanian11671902012-02-07 17:11:38 +00007263}
7264
Fariborz Jahanian5ed21c32012-03-27 18:41:05 +00007265void RewriteModernObjC::RewriteClassSetupInitHook(std::string &Result) {
7266 int ClsDefCount = ClassImplementation.size();
7267 if (!ClsDefCount)
7268 return;
7269 Result += "#pragma section(\".objc_inithooks$B\", long, read, write)\n";
7270 Result += "__declspec(allocate(\".objc_inithooks$B\")) ";
7271 Result += "static void *OBJC_CLASS_SETUP[] = {\n";
7272 for (int i = 0; i < ClsDefCount; i++) {
7273 ObjCImplementationDecl *IDecl = ClassImplementation[i];
7274 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
7275 Result += "\t(void *)&OBJC_CLASS_SETUP_$_";
7276 Result += CDecl->getName(); Result += ",\n";
7277 }
7278 Result += "};\n";
7279}
7280
Fariborz Jahanian11671902012-02-07 17:11:38 +00007281void RewriteModernObjC::RewriteMetaDataIntoBuffer(std::string &Result) {
7282 int ClsDefCount = ClassImplementation.size();
7283 int CatDefCount = CategoryImplementation.size();
7284
7285 // For each implemented class, write out all its meta data.
7286 for (int i = 0; i < ClsDefCount; i++)
7287 RewriteObjCClassMetaData(ClassImplementation[i], Result);
7288
Fariborz Jahanian5ed21c32012-03-27 18:41:05 +00007289 RewriteClassSetupInitHook(Result);
7290
Fariborz Jahanian11671902012-02-07 17:11:38 +00007291 // For each implemented category, write out all its meta data.
7292 for (int i = 0; i < CatDefCount; i++)
7293 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
7294
Fariborz Jahanian5ed21c32012-03-27 18:41:05 +00007295 RewriteCategorySetupInitHook(Result);
7296
Fariborz Jahaniane7a0c932012-02-17 00:06:14 +00007297 if (ClsDefCount > 0) {
Fariborz Jahanian008dfe22012-03-11 19:41:56 +00007298 if (LangOpts.MicrosoftExt)
7299 Result += "__declspec(allocate(\".objc_classlist$B\")) ";
Fariborz Jahaniane7a0c932012-02-17 00:06:14 +00007300 Result += "static struct _class_t *L_OBJC_LABEL_CLASS_$ [";
7301 Result += llvm::utostr(ClsDefCount); Result += "]";
7302 Result +=
7303 " __attribute__((used, section (\"__DATA, __objc_classlist,"
7304 "regular,no_dead_strip\")))= {\n";
7305 for (int i = 0; i < ClsDefCount; i++) {
7306 Result += "\t&OBJC_CLASS_$_";
7307 Result += ClassImplementation[i]->getNameAsString();
7308 Result += ",\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00007309 }
Fariborz Jahaniane7a0c932012-02-17 00:06:14 +00007310 Result += "};\n";
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00007311
7312 if (!DefinedNonLazyClasses.empty()) {
7313 if (LangOpts.MicrosoftExt)
7314 Result += "__declspec(allocate(\".objc_nlclslist$B\")) \n";
7315 Result += "static struct _class_t *_OBJC_LABEL_NONLAZY_CLASS_$[] = {\n\t";
7316 for (unsigned i = 0, e = DefinedNonLazyClasses.size(); i < e; i++) {
7317 Result += "\t&OBJC_CLASS_$_"; Result += DefinedNonLazyClasses[i]->getNameAsString();
7318 Result += ",\n";
7319 }
7320 Result += "};\n";
7321 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00007322 }
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007323
7324 if (CatDefCount > 0) {
Fariborz Jahanian008dfe22012-03-11 19:41:56 +00007325 if (LangOpts.MicrosoftExt)
7326 Result += "__declspec(allocate(\".objc_catlist$B\")) ";
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007327 Result += "static struct _category_t *L_OBJC_LABEL_CATEGORY_$ [";
7328 Result += llvm::utostr(CatDefCount); Result += "]";
7329 Result +=
7330 " __attribute__((used, section (\"__DATA, __objc_catlist,"
7331 "regular,no_dead_strip\")))= {\n";
7332 for (int i = 0; i < CatDefCount; i++) {
7333 Result += "\t&_OBJC_$_CATEGORY_";
7334 Result +=
7335 CategoryImplementation[i]->getClassInterface()->getNameAsString();
7336 Result += "_$_";
7337 Result += CategoryImplementation[i]->getNameAsString();
7338 Result += ",\n";
7339 }
7340 Result += "};\n";
7341 }
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00007342
7343 if (!DefinedNonLazyCategories.empty()) {
7344 if (LangOpts.MicrosoftExt)
7345 Result += "__declspec(allocate(\".objc_nlcatlist$B\")) \n";
7346 Result += "static struct _category_t *_OBJC_LABEL_NONLAZY_CATEGORY_$[] = {\n\t";
7347 for (unsigned i = 0, e = DefinedNonLazyCategories.size(); i < e; i++) {
7348 Result += "\t&_OBJC_$_CATEGORY_";
7349 Result +=
7350 DefinedNonLazyCategories[i]->getClassInterface()->getNameAsString();
7351 Result += "_$_";
7352 Result += DefinedNonLazyCategories[i]->getNameAsString();
7353 Result += ",\n";
7354 }
7355 Result += "};\n";
7356 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00007357}
7358
Fariborz Jahanianddddca32012-03-14 21:44:09 +00007359void RewriteModernObjC::WriteImageInfo(std::string &Result) {
7360 if (LangOpts.MicrosoftExt)
7361 Result += "__declspec(allocate(\".objc_imageinfo$B\")) \n";
7362
7363 Result += "static struct IMAGE_INFO { unsigned version; unsigned flag; } ";
7364 // version 0, ObjCABI is 2
Fariborz Jahanianb31e3af2012-03-15 17:05:33 +00007365 Result += "_OBJC_IMAGE_INFO = { 0, 2 };\n";
Fariborz Jahanianddddca32012-03-14 21:44:09 +00007366}
7367
Fariborz Jahanian11671902012-02-07 17:11:38 +00007368/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
7369/// implementation.
7370void RewriteModernObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
7371 std::string &Result) {
Fariborz Jahanian45489622012-03-14 18:09:23 +00007372 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanian11671902012-02-07 17:11:38 +00007373 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
7374 // Find category declaration for this implementation.
Douglas Gregor048fbfa2013-01-16 23:00:23 +00007375 ObjCCategoryDecl *CDecl
7376 = ClassDecl->FindCategoryDeclaration(IDecl->getIdentifier());
Fariborz Jahanian11671902012-02-07 17:11:38 +00007377
7378 std::string FullCategoryName = ClassDecl->getNameAsString();
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007379 FullCategoryName += "_$_";
7380 FullCategoryName += CDecl->getNameAsString();
Fariborz Jahanian11671902012-02-07 17:11:38 +00007381
7382 // Build _objc_method_list for class's instance methods if needed
Aaron Ballmanf26acce2014-03-13 19:50:17 +00007383 SmallVector<ObjCMethodDecl *, 32> InstanceMethods(IDecl->instance_methods());
Fariborz Jahanian11671902012-02-07 17:11:38 +00007384
7385 // If any of our property implementations have associated getters or
7386 // setters, produce metadata for them as well.
Aaron Ballmand85eff42014-03-14 15:02:45 +00007387 for (const auto *Prop : IDecl->property_impls()) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00007388 if (Prop->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
Fariborz Jahanian11671902012-02-07 17:11:38 +00007389 continue;
David Blaikie2d7c57e2012-04-30 02:36:29 +00007390 if (!Prop->getPropertyIvarDecl())
Fariborz Jahanian11671902012-02-07 17:11:38 +00007391 continue;
David Blaikie2d7c57e2012-04-30 02:36:29 +00007392 ObjCPropertyDecl *PD = Prop->getPropertyDecl();
Fariborz Jahanian11671902012-02-07 17:11:38 +00007393 if (!PD)
7394 continue;
7395 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
7396 InstanceMethods.push_back(Getter);
7397 if (PD->isReadOnly())
7398 continue;
7399 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
7400 InstanceMethods.push_back(Setter);
7401 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00007402
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007403 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
7404 "_OBJC_$_CATEGORY_INSTANCE_METHODS_",
7405 FullCategoryName, true);
7406
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00007407 SmallVector<ObjCMethodDecl *, 32> ClassMethods(IDecl->class_methods());
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007408
7409 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
7410 "_OBJC_$_CATEGORY_CLASS_METHODS_",
7411 FullCategoryName, true);
Fariborz Jahanian11671902012-02-07 17:11:38 +00007412
7413 // Protocols referenced in class declaration?
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007414 // Protocol's super protocol list
Aaron Ballman19a41762014-03-14 12:55:57 +00007415 SmallVector<ObjCProtocolDecl *, 8> RefedProtocols(CDecl->protocols());
7416 for (auto *I : CDecl->protocols())
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007417 // Must write out all protocol definitions in current qualifier list,
7418 // and in their nested qualifiers before writing out current definition.
Aaron Ballman19a41762014-03-14 12:55:57 +00007419 RewriteObjCProtocolMetaData(I, Result);
Fariborz Jahanian11671902012-02-07 17:11:38 +00007420
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007421 Write_protocol_list_initializer(Context, Result,
7422 RefedProtocols,
7423 "_OBJC_CATEGORY_PROTOCOLS_$_",
7424 FullCategoryName);
Fariborz Jahanian11671902012-02-07 17:11:38 +00007425
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007426 // Protocol's property metadata.
Manman Rena7a8b1f2016-01-26 18:05:23 +00007427 SmallVector<ObjCPropertyDecl *, 8> ClassProperties(
7428 CDecl->instance_properties());
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007429 Write_prop_list_t_initializer(*this, Context, Result, ClassProperties,
Fariborz Jahaniane9863b52012-05-03 23:19:33 +00007430 /* Container */IDecl,
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007431 "_OBJC_$_PROP_LIST_",
7432 FullCategoryName);
7433
7434 Write_category_t(*this, Context, Result,
Fariborz Jahanian5ed21c32012-03-27 18:41:05 +00007435 CDecl,
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00007436 ClassDecl,
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007437 InstanceMethods,
7438 ClassMethods,
7439 RefedProtocols,
7440 ClassProperties);
7441
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00007442 // Determine if this category is also "non-lazy".
7443 if (ImplementationIsNonLazy(IDecl))
7444 DefinedNonLazyCategories.push_back(CDecl);
Fariborz Jahanian5ed21c32012-03-27 18:41:05 +00007445}
7446
7447void RewriteModernObjC::RewriteCategorySetupInitHook(std::string &Result) {
7448 int CatDefCount = CategoryImplementation.size();
7449 if (!CatDefCount)
7450 return;
7451 Result += "#pragma section(\".objc_inithooks$B\", long, read, write)\n";
7452 Result += "__declspec(allocate(\".objc_inithooks$B\")) ";
7453 Result += "static void *OBJC_CATEGORY_SETUP[] = {\n";
7454 for (int i = 0; i < CatDefCount; i++) {
7455 ObjCCategoryImplDecl *IDecl = CategoryImplementation[i];
7456 ObjCCategoryDecl *CatDecl= IDecl->getCategoryDecl();
7457 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
7458 Result += "\t(void *)&OBJC_CATEGORY_SETUP_$_";
7459 Result += ClassDecl->getName();
7460 Result += "_$_";
7461 Result += CatDecl->getName();
7462 Result += ",\n";
7463 }
7464 Result += "};\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00007465}
7466
7467// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
7468/// class methods.
7469template<typename MethodIterator>
7470void RewriteModernObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
7471 MethodIterator MethodEnd,
7472 bool IsInstanceMethod,
7473 StringRef prefix,
7474 StringRef ClassName,
7475 std::string &Result) {
7476 if (MethodBegin == MethodEnd) return;
7477
7478 if (!objc_impl_method) {
7479 /* struct _objc_method {
7480 SEL _cmd;
7481 char *method_types;
7482 void *_imp;
7483 }
7484 */
7485 Result += "\nstruct _objc_method {\n";
7486 Result += "\tSEL _cmd;\n";
7487 Result += "\tchar *method_types;\n";
7488 Result += "\tvoid *_imp;\n";
7489 Result += "};\n";
7490
7491 objc_impl_method = true;
7492 }
7493
7494 // Build _objc_method_list for class's methods if needed
7495
7496 /* struct {
7497 struct _objc_method_list *next_method;
7498 int method_count;
7499 struct _objc_method method_list[];
7500 }
7501 */
7502 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
Fariborz Jahanian008dfe22012-03-11 19:41:56 +00007503 Result += "\n";
7504 if (LangOpts.MicrosoftExt) {
7505 if (IsInstanceMethod)
7506 Result += "__declspec(allocate(\".inst_meth$B\")) ";
7507 else
7508 Result += "__declspec(allocate(\".cls_meth$B\")) ";
7509 }
7510 Result += "static struct {\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00007511 Result += "\tstruct _objc_method_list *next_method;\n";
7512 Result += "\tint method_count;\n";
7513 Result += "\tstruct _objc_method method_list[";
7514 Result += utostr(NumMethods);
7515 Result += "];\n} _OBJC_";
7516 Result += prefix;
7517 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
7518 Result += "_METHODS_";
7519 Result += ClassName;
7520 Result += " __attribute__ ((used, section (\"__OBJC, __";
7521 Result += IsInstanceMethod ? "inst" : "cls";
7522 Result += "_meth\")))= ";
7523 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
7524
7525 Result += "\t,{{(SEL)\"";
7526 Result += (*MethodBegin)->getSelector().getAsString().c_str();
7527 std::string MethodTypeString;
7528 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
7529 Result += "\", \"";
7530 Result += MethodTypeString;
7531 Result += "\", (void *)";
7532 Result += MethodInternalNames[*MethodBegin];
7533 Result += "}\n";
7534 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
7535 Result += "\t ,{(SEL)\"";
7536 Result += (*MethodBegin)->getSelector().getAsString().c_str();
7537 std::string MethodTypeString;
7538 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
7539 Result += "\", \"";
7540 Result += MethodTypeString;
7541 Result += "\", (void *)";
7542 Result += MethodInternalNames[*MethodBegin];
7543 Result += "}\n";
7544 }
7545 Result += "\t }\n};\n";
7546}
7547
7548Stmt *RewriteModernObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) {
7549 SourceRange OldRange = IV->getSourceRange();
7550 Expr *BaseExpr = IV->getBase();
7551
7552 // Rewrite the base, but without actually doing replaces.
7553 {
7554 DisableReplaceStmtScope S(*this);
7555 BaseExpr = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(BaseExpr));
7556 IV->setBase(BaseExpr);
7557 }
7558
7559 ObjCIvarDecl *D = IV->getDecl();
7560
7561 Expr *Replacement = IV;
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007562
Fariborz Jahanian11671902012-02-07 17:11:38 +00007563 if (BaseExpr->getType()->isObjCObjectPointerType()) {
7564 const ObjCInterfaceType *iFaceDecl =
Fariborz Jahanian89919cc2012-05-08 23:54:35 +00007565 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
Fariborz Jahanian11671902012-02-07 17:11:38 +00007566 assert(iFaceDecl && "RewriteObjCIvarRefExpr - iFaceDecl is null");
7567 // lookup which class implements the instance variable.
Craig Topper8ae12032014-05-07 06:21:57 +00007568 ObjCInterfaceDecl *clsDeclared = nullptr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00007569 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
7570 clsDeclared);
7571 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
7572
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007573 // Build name of symbol holding ivar offset.
Fariborz Jahaniana854174a2012-03-20 17:13:39 +00007574 std::string IvarOffsetName;
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00007575 if (D->isBitField())
7576 ObjCIvarBitfieldGroupOffset(D, IvarOffsetName);
7577 else
7578 WriteInternalIvarName(clsDeclared, D, IvarOffsetName);
Fariborz Jahaniana854174a2012-03-20 17:13:39 +00007579
Fariborz Jahanian5e49eb92012-02-22 18:13:25 +00007580 ReferencedIvars[clsDeclared].insert(D);
7581
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007582 // cast offset to "char *".
7583 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context,
7584 Context->getPointerType(Context->CharTy),
Fariborz Jahanian11671902012-02-07 17:11:38 +00007585 CK_BitCast,
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007586 BaseExpr);
7587 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
7588 SourceLocation(), &Context->Idents.get(IvarOffsetName),
Craig Topper8ae12032014-05-07 06:21:57 +00007589 Context->UnsignedLongTy, nullptr,
7590 SC_Extern);
John McCall113bee02012-03-10 09:33:50 +00007591 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, false,
7592 Context->UnsignedLongTy, VK_LValue,
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007593 SourceLocation());
7594 BinaryOperator *addExpr =
7595 new (Context) BinaryOperator(castExpr, DRE, BO_Add,
7596 Context->getPointerType(Context->CharTy),
Lang Hames5de91cc2012-10-02 04:45:10 +00007597 VK_RValue, OK_Ordinary, SourceLocation(), false);
Fariborz Jahanian11671902012-02-07 17:11:38 +00007598 // Don't forget the parens to enforce the proper binding.
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007599 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(),
7600 SourceLocation(),
7601 addExpr);
Fariborz Jahaniandd5a59b2012-02-24 17:35:35 +00007602 QualType IvarT = D->getType();
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00007603 if (D->isBitField())
7604 IvarT = GetGroupRecordTypeForObjCIvarBitfield(D);
Fariborz Jahanianbf217c82012-04-27 22:48:54 +00007605
Fariborz Jahaniand7c67772012-05-02 17:34:59 +00007606 if (!isa<TypedefType>(IvarT) && IvarT->isRecordType()) {
Fariborz Jahanianbf217c82012-04-27 22:48:54 +00007607 RecordDecl *RD = IvarT->getAs<RecordType>()->getDecl();
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00007608 RD = RD->getDefinition();
7609 if (RD && !RD->getDeclName().getAsIdentifierInfo()) {
Fariborz Jahanianbf217c82012-04-27 22:48:54 +00007610 // decltype(((Foo_IMPL*)0)->bar) *
Fariborz Jahaniand7c67772012-05-02 17:34:59 +00007611 ObjCContainerDecl *CDecl =
7612 dyn_cast<ObjCContainerDecl>(D->getDeclContext());
7613 // ivar in class extensions requires special treatment.
7614 if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(CDecl))
7615 CDecl = CatDecl->getClassInterface();
7616 std::string RecName = CDecl->getName();
Fariborz Jahanianbf217c82012-04-27 22:48:54 +00007617 RecName += "_IMPL";
7618 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
7619 SourceLocation(), SourceLocation(),
7620 &Context->Idents.get(RecName.c_str()));
7621 QualType PtrStructIMPL = Context->getPointerType(Context->getTagDeclType(RD));
7622 unsigned UnsignedIntSize =
7623 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
7624 Expr *Zero = IntegerLiteral::Create(*Context,
7625 llvm::APInt(UnsignedIntSize, 0),
7626 Context->UnsignedIntTy, SourceLocation());
7627 Zero = NoTypeInfoCStyleCastExpr(Context, PtrStructIMPL, CK_BitCast, Zero);
7628 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
7629 Zero);
Craig Topper8ae12032014-05-07 06:21:57 +00007630 FieldDecl *FD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
Fariborz Jahanianbf217c82012-04-27 22:48:54 +00007631 SourceLocation(),
7632 &Context->Idents.get(D->getNameAsString()),
Fariborz Jahanianf8e68e22015-04-09 18:36:50 +00007633 IvarT, nullptr,
7634 /*BitWidth=*/nullptr,
7635 /*Mutable=*/true, ICIS_NoInit);
7636 MemberExpr *ME = new (Context)
7637 MemberExpr(PE, true, SourceLocation(), FD, SourceLocation(),
7638 FD->getType(), VK_LValue, OK_Ordinary);
7639 IvarT = Context->getDecltypeType(ME, ME->getType());
7640 }
7641 }
Fariborz Jahanian1dc712f2012-02-29 00:26:20 +00007642 convertObjCTypeToCStyleType(IvarT);
Fariborz Jahaniandd5a59b2012-02-24 17:35:35 +00007643 QualType castT = Context->getPointerType(IvarT);
Fariborz Jahanianbf217c82012-04-27 22:48:54 +00007644
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007645 castExpr = NoTypeInfoCStyleCastExpr(Context,
7646 castT,
7647 CK_BitCast,
7648 PE);
Fariborz Jahanianbf217c82012-04-27 22:48:54 +00007649
7650
Fariborz Jahanian1dc712f2012-02-29 00:26:20 +00007651 Expr *Exp = new (Context) UnaryOperator(castExpr, UO_Deref, IvarT,
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007652 VK_LValue, OK_Ordinary,
7653 SourceLocation());
7654 PE = new (Context) ParenExpr(OldRange.getBegin(),
7655 OldRange.getEnd(),
7656 Exp);
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00007657
7658 if (D->isBitField()) {
Craig Topper8ae12032014-05-07 06:21:57 +00007659 FieldDecl *FD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00007660 SourceLocation(),
7661 &Context->Idents.get(D->getNameAsString()),
Fariborz Jahanianf8e68e22015-04-09 18:36:50 +00007662 D->getType(), nullptr,
7663 /*BitWidth=*/D->getBitWidth(),
7664 /*Mutable=*/true, ICIS_NoInit);
7665 MemberExpr *ME = new (Context)
7666 MemberExpr(PE, /*isArrow*/ false, SourceLocation(), FD,
7667 SourceLocation(), FD->getType(), VK_LValue, OK_Ordinary);
7668 Replacement = ME;
7669
7670 }
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00007671 else
7672 Replacement = PE;
Fariborz Jahanian11671902012-02-07 17:11:38 +00007673 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00007674
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007675 ReplaceStmtWithRange(IV, Replacement, OldRange);
7676 return Replacement;
Fariborz Jahanian11671902012-02-07 17:11:38 +00007677}
Alp Toker0621cb22014-07-16 16:48:33 +00007678
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00007679#endif // CLANG_ENABLE_OBJC_REWRITER