blob: 759e57e32b580e8be10ec6a89ca489ced5cf75cd [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"
27#include "llvm/ADT/OwningPtr.h"
28#include "llvm/ADT/SmallPtrSet.h"
29#include "llvm/ADT/StringExtras.h"
Fariborz Jahanian11671902012-02-07 17:11:38 +000030#include "llvm/Support/MemoryBuffer.h"
31#include "llvm/Support/raw_ostream.h"
Fariborz Jahanian11671902012-02-07 17:11:38 +000032
33using namespace clang;
34using llvm::utostr;
35
36namespace {
37 class RewriteModernObjC : public ASTConsumer {
38 protected:
39
40 enum {
41 BLOCK_FIELD_IS_OBJECT = 3, /* id, NSObject, __attribute__((NSObject)),
42 block, ... */
43 BLOCK_FIELD_IS_BLOCK = 7, /* a block variable */
44 BLOCK_FIELD_IS_BYREF = 8, /* the on stack structure holding the
45 __block variable */
46 BLOCK_FIELD_IS_WEAK = 16, /* declared __weak, only used in byref copy
47 helpers */
48 BLOCK_BYREF_CALLER = 128, /* called from __block (byref) copy/dispose
49 support routines */
50 BLOCK_BYREF_CURRENT_MAX = 256
51 };
52
53 enum {
54 BLOCK_NEEDS_FREE = (1 << 24),
55 BLOCK_HAS_COPY_DISPOSE = (1 << 25),
56 BLOCK_HAS_CXX_OBJ = (1 << 26),
57 BLOCK_IS_GC = (1 << 27),
58 BLOCK_IS_GLOBAL = (1 << 28),
59 BLOCK_HAS_DESCRIPTOR = (1 << 29)
60 };
Fariborz Jahanian11671902012-02-07 17:11:38 +000061
62 Rewriter Rewrite;
63 DiagnosticsEngine &Diags;
64 const LangOptions &LangOpts;
65 ASTContext *Context;
66 SourceManager *SM;
67 TranslationUnitDecl *TUDecl;
68 FileID MainFileID;
69 const char *MainFileStart, *MainFileEnd;
70 Stmt *CurrentBody;
71 ParentMap *PropParentMap; // created lazily.
72 std::string InFileName;
73 raw_ostream* OutFile;
74 std::string Preamble;
75
76 TypeDecl *ProtocolTypeDecl;
77 VarDecl *GlobalVarDecl;
Fariborz Jahaniane0050702012-03-23 00:00:49 +000078 Expr *GlobalConstructionExp;
Fariborz Jahanian11671902012-02-07 17:11:38 +000079 unsigned RewriteFailedDiag;
Fariborz Jahanianbdf975e2012-03-22 19:54:39 +000080 unsigned GlobalBlockRewriteFailedDiag;
Fariborz Jahanian11671902012-02-07 17:11:38 +000081 // ObjC string constant support.
82 unsigned NumObjCStringLiterals;
83 VarDecl *ConstantStringClassReference;
84 RecordDecl *NSStringRecord;
85
86 // ObjC foreach break/continue generation support.
87 int BcLabelCount;
88
89 unsigned TryFinallyContainsReturnDiag;
90 // Needed for super.
91 ObjCMethodDecl *CurMethodDef;
92 RecordDecl *SuperStructDecl;
93 RecordDecl *ConstantStringDecl;
94
95 FunctionDecl *MsgSendFunctionDecl;
96 FunctionDecl *MsgSendSuperFunctionDecl;
97 FunctionDecl *MsgSendStretFunctionDecl;
98 FunctionDecl *MsgSendSuperStretFunctionDecl;
99 FunctionDecl *MsgSendFpretFunctionDecl;
100 FunctionDecl *GetClassFunctionDecl;
101 FunctionDecl *GetMetaClassFunctionDecl;
102 FunctionDecl *GetSuperClassFunctionDecl;
103 FunctionDecl *SelGetUidFunctionDecl;
104 FunctionDecl *CFStringFunctionDecl;
Benjamin Kramer60509af2013-09-09 14:48:42 +0000105 FunctionDecl *SuperConstructorFunctionDecl;
Fariborz Jahanian11671902012-02-07 17:11:38 +0000106 FunctionDecl *CurFunctionDef;
Fariborz Jahanian11671902012-02-07 17:11:38 +0000107
108 /* Misc. containers needed for meta-data rewrite. */
109 SmallVector<ObjCImplementationDecl *, 8> ClassImplementation;
110 SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation;
111 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCSynthesizedStructs;
112 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> ObjCSynthesizedProtocols;
Fariborz Jahaniand268b0c2012-02-17 22:20:12 +0000113 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCWrittenInterfaces;
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +0000114 llvm::SmallPtrSet<TagDecl*, 32> GlobalDefinedTags;
Fariborz Jahaniand268b0c2012-02-17 22:20:12 +0000115 SmallVector<ObjCInterfaceDecl*, 32> ObjCInterfacesSeen;
Fariborz Jahanian07a423d2012-03-14 23:18:19 +0000116 /// DefinedNonLazyClasses - List of defined "non-lazy" classes.
117 SmallVector<ObjCInterfaceDecl*, 8> DefinedNonLazyClasses;
118
119 /// DefinedNonLazyCategories - List of defined "non-lazy" categories.
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000120 SmallVector<ObjCCategoryDecl *, 8> DefinedNonLazyCategories;
Fariborz Jahanian07a423d2012-03-14 23:18:19 +0000121
Fariborz Jahanian11671902012-02-07 17:11:38 +0000122 SmallVector<Stmt *, 32> Stmts;
123 SmallVector<int, 8> ObjCBcLabelNo;
124 // Remember all the @protocol(<expr>) expressions.
125 llvm::SmallPtrSet<ObjCProtocolDecl *, 32> ProtocolExprDecls;
126
127 llvm::DenseSet<uint64_t> CopyDestroyCache;
128
129 // Block expressions.
130 SmallVector<BlockExpr *, 32> Blocks;
131 SmallVector<int, 32> InnerDeclRefsCount;
John McCall113bee02012-03-10 09:33:50 +0000132 SmallVector<DeclRefExpr *, 32> InnerDeclRefs;
Fariborz Jahanian11671902012-02-07 17:11:38 +0000133
John McCall113bee02012-03-10 09:33:50 +0000134 SmallVector<DeclRefExpr *, 32> BlockDeclRefs;
Fariborz Jahanian11671902012-02-07 17:11:38 +0000135
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +0000136
Fariborz Jahanian11671902012-02-07 17:11:38 +0000137 // Block related declarations.
138 SmallVector<ValueDecl *, 8> BlockByCopyDecls;
139 llvm::SmallPtrSet<ValueDecl *, 8> BlockByCopyDeclsPtrSet;
140 SmallVector<ValueDecl *, 8> BlockByRefDecls;
141 llvm::SmallPtrSet<ValueDecl *, 8> BlockByRefDeclsPtrSet;
142 llvm::DenseMap<ValueDecl *, unsigned> BlockByRefDeclNo;
143 llvm::SmallPtrSet<ValueDecl *, 8> ImportedBlockDecls;
144 llvm::SmallPtrSet<VarDecl *, 8> ImportedLocalExternalDecls;
145
146 llvm::DenseMap<BlockExpr *, std::string> RewrittenBlockExprs;
Fariborz Jahanian5e49eb92012-02-22 18:13:25 +0000147 llvm::DenseMap<ObjCInterfaceDecl *,
148 llvm::SmallPtrSet<ObjCIvarDecl *, 8> > ReferencedIvars;
149
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +0000150 // ivar bitfield grouping containers
151 llvm::DenseSet<const ObjCInterfaceDecl *> ObjCInterefaceHasBitfieldGroups;
152 llvm::DenseMap<const ObjCIvarDecl* , unsigned> IvarGroupNumber;
153 // This container maps an <class, group number for ivar> tuple to the type
154 // of the struct where the bitfield belongs.
155 llvm::DenseMap<std::pair<const ObjCInterfaceDecl*, unsigned>, QualType> GroupRecordType;
Fariborz Jahaniane4996132013-02-07 22:50:40 +0000156 SmallVector<FunctionDecl*, 32> FunctionDefinitionsSeen;
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +0000157
Fariborz Jahanian11671902012-02-07 17:11:38 +0000158 // This maps an original source AST to it's rewritten form. This allows
159 // us to avoid rewriting the same node twice (which is very uncommon).
160 // This is needed to support some of the exotic property rewriting.
161 llvm::DenseMap<Stmt *, Stmt *> ReplacedNodes;
162
163 // Needed for header files being rewritten
164 bool IsHeader;
165 bool SilenceRewriteMacroWarning;
Fariborz Jahaniane4c7e852013-02-08 00:27:34 +0000166 bool GenerateLineInfo;
Fariborz Jahanian11671902012-02-07 17:11:38 +0000167 bool objc_impl_method;
168
169 bool DisableReplaceStmt;
170 class DisableReplaceStmtScope {
171 RewriteModernObjC &R;
172 bool SavedValue;
173
174 public:
175 DisableReplaceStmtScope(RewriteModernObjC &R)
176 : R(R), SavedValue(R.DisableReplaceStmt) {
177 R.DisableReplaceStmt = true;
178 }
179 ~DisableReplaceStmtScope() {
180 R.DisableReplaceStmt = SavedValue;
181 }
182 };
183 void InitializeCommon(ASTContext &context);
184
185 public:
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +0000186 llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames;
Fariborz Jahanian11671902012-02-07 17:11:38 +0000187 // Top Level Driver code.
188 virtual bool HandleTopLevelDecl(DeclGroupRef D) {
189 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
190 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(*I)) {
191 if (!Class->isThisDeclarationADefinition()) {
192 RewriteForwardClassDecl(D);
193 break;
Fariborz Jahaniand268b0c2012-02-17 22:20:12 +0000194 } else {
195 // Keep track of all interface declarations seen.
Fariborz Jahanian0ed6cb72012-02-24 21:42:38 +0000196 ObjCInterfacesSeen.push_back(Class);
Fariborz Jahaniand268b0c2012-02-17 22:20:12 +0000197 break;
Fariborz Jahanian11671902012-02-07 17:11:38 +0000198 }
199 }
200
201 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>(*I)) {
202 if (!Proto->isThisDeclarationADefinition()) {
203 RewriteForwardProtocolDecl(D);
204 break;
205 }
206 }
207
Fariborz Jahaniane4996132013-02-07 22:50:40 +0000208 if (FunctionDecl *FDecl = dyn_cast<FunctionDecl>(*I)) {
209 // Under modern abi, we cannot translate body of the function
210 // yet until all class extensions and its implementation is seen.
211 // This is because they may introduce new bitfields which must go
212 // into their grouping struct.
213 if (FDecl->isThisDeclarationADefinition() &&
214 // Not c functions defined inside an objc container.
215 !FDecl->isTopLevelDeclInObjCContainer()) {
216 FunctionDefinitionsSeen.push_back(FDecl);
217 break;
218 }
219 }
Fariborz Jahanian11671902012-02-07 17:11:38 +0000220 HandleTopLevelSingleDecl(*I);
221 }
222 return true;
223 }
Fariborz Jahaniand2940622013-10-07 19:54:22 +0000224
225 virtual void HandleTopLevelDeclInObjCContainer(DeclGroupRef D) {
226 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
227 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(*I)) {
228 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
229 RewriteBlockPointerDecl(TD);
230 else if (TD->getUnderlyingType()->isFunctionPointerType())
231 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
232 else
233 RewriteObjCQualifiedInterfaceTypes(TD);
234 }
235 }
236 return;
237 }
238
Fariborz Jahanian11671902012-02-07 17:11:38 +0000239 void HandleTopLevelSingleDecl(Decl *D);
240 void HandleDeclInMainFile(Decl *D);
241 RewriteModernObjC(std::string inFile, raw_ostream *OS,
242 DiagnosticsEngine &D, const LangOptions &LOpts,
Fariborz Jahaniane4c7e852013-02-08 00:27:34 +0000243 bool silenceMacroWarn, bool LineInfo);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000244
245 ~RewriteModernObjC() {}
246
247 virtual void HandleTranslationUnit(ASTContext &C);
248
249 void ReplaceStmt(Stmt *Old, Stmt *New) {
250 Stmt *ReplacingStmt = ReplacedNodes[Old];
251
252 if (ReplacingStmt)
253 return; // We can't rewrite the same node twice.
254
255 if (DisableReplaceStmt)
256 return;
257
258 // If replacement succeeded or warning disabled return with no warning.
259 if (!Rewrite.ReplaceStmt(Old, New)) {
260 ReplacedNodes[Old] = New;
261 return;
262 }
263 if (SilenceRewriteMacroWarning)
264 return;
265 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
266 << Old->getSourceRange();
267 }
268
269 void ReplaceStmtWithRange(Stmt *Old, Stmt *New, SourceRange SrcRange) {
270 if (DisableReplaceStmt)
271 return;
272
273 // Measure the old text.
274 int Size = Rewrite.getRangeSize(SrcRange);
275 if (Size == -1) {
276 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
277 << Old->getSourceRange();
278 return;
279 }
280 // Get the new text.
281 std::string SStr;
282 llvm::raw_string_ostream S(SStr);
Richard Smith235341b2012-08-16 03:56:14 +0000283 New->printPretty(S, 0, PrintingPolicy(LangOpts));
Fariborz Jahanian11671902012-02-07 17:11:38 +0000284 const std::string &Str = S.str();
285
286 // If replacement succeeded or warning disabled return with no warning.
287 if (!Rewrite.ReplaceText(SrcRange.getBegin(), Size, Str)) {
288 ReplacedNodes[Old] = New;
289 return;
290 }
291 if (SilenceRewriteMacroWarning)
292 return;
293 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
294 << Old->getSourceRange();
295 }
296
297 void InsertText(SourceLocation Loc, StringRef Str,
298 bool InsertAfter = true) {
299 // If insertion succeeded or warning disabled return with no warning.
300 if (!Rewrite.InsertText(Loc, Str, InsertAfter) ||
301 SilenceRewriteMacroWarning)
302 return;
303
304 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
305 }
306
307 void ReplaceText(SourceLocation Start, unsigned OrigLength,
308 StringRef Str) {
309 // If removal succeeded or warning disabled return with no warning.
310 if (!Rewrite.ReplaceText(Start, OrigLength, Str) ||
311 SilenceRewriteMacroWarning)
312 return;
313
314 Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
315 }
316
317 // Syntactic Rewriting.
318 void RewriteRecordBody(RecordDecl *RD);
319 void RewriteInclude();
Fariborz Jahanianaa4a2422012-11-06 17:30:23 +0000320 void RewriteLineDirective(const Decl *D);
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +0000321 void ConvertSourceLocationToLineDirective(SourceLocation Loc,
322 std::string &LineString);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000323 void RewriteForwardClassDecl(DeclGroupRef D);
Craig Topper5603df42013-07-05 19:34:19 +0000324 void RewriteForwardClassDecl(const SmallVectorImpl<Decl *> &DG);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000325 void RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
326 const std::string &typedefString);
327 void RewriteImplementations();
328 void RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
329 ObjCImplementationDecl *IMD,
330 ObjCCategoryImplDecl *CID);
331 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
332 void RewriteImplementationDecl(Decl *Dcl);
333 void RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
334 ObjCMethodDecl *MDecl, std::string &ResultStr);
335 void RewriteTypeIntoString(QualType T, std::string &ResultStr,
336 const FunctionType *&FPRetType);
337 void RewriteByRefString(std::string &ResultStr, const std::string &Name,
338 ValueDecl *VD, bool def=false);
339 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
340 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
341 void RewriteForwardProtocolDecl(DeclGroupRef D);
Craig Topper5603df42013-07-05 19:34:19 +0000342 void RewriteForwardProtocolDecl(const SmallVectorImpl<Decl *> &DG);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000343 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
344 void RewriteProperty(ObjCPropertyDecl *prop);
345 void RewriteFunctionDecl(FunctionDecl *FD);
346 void RewriteBlockPointerType(std::string& Str, QualType Type);
347 void RewriteBlockPointerTypeVariable(std::string& Str, ValueDecl *VD);
Fariborz Jahanianca357d92012-04-19 00:50:01 +0000348 void RewriteBlockLiteralFunctionDecl(FunctionDecl *FD);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000349 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
350 void RewriteTypeOfDecl(VarDecl *VD);
351 void RewriteObjCQualifiedInterfaceTypes(Expr *E);
Fariborz Jahanian89919cc2012-05-08 23:54:35 +0000352
353 std::string getIvarAccessString(ObjCIvarDecl *D);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000354
355 // Expression Rewriting.
356 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
357 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
358 Stmt *RewritePropertyOrImplicitGetter(PseudoObjectExpr *Pseudo);
359 Stmt *RewritePropertyOrImplicitSetter(PseudoObjectExpr *Pseudo);
360 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
361 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
362 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian307b7ad2012-03-27 20:17:30 +0000363 Stmt *RewriteObjCBoolLiteralExpr(ObjCBoolLiteralExpr *Exp);
Patrick Beard0caa3942012-04-19 00:25:12 +0000364 Stmt *RewriteObjCBoxedExpr(ObjCBoxedExpr *Exp);
Fariborz Jahanian991a08d2012-03-30 23:35:47 +0000365 Stmt *RewriteObjCArrayLiteralExpr(ObjCArrayLiteral *Exp);
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +0000366 Stmt *RewriteObjCDictionaryLiteralExpr(ObjCDictionaryLiteral *Exp);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000367 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000368 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
Fariborz Jahanian9b43c3f2012-05-23 23:47:20 +0000369 Stmt *RewriteObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000370 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
371 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
372 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
373 SourceLocation OrigEnd);
374 Stmt *RewriteBreakStmt(BreakStmt *S);
375 Stmt *RewriteContinueStmt(ContinueStmt *S);
376 void RewriteCastExpr(CStyleCastExpr *CE);
Fariborz Jahanian2c00acd2012-04-10 00:08:18 +0000377 void RewriteImplicitCastObjCExpr(CastExpr *IE);
Fariborz Jahanian08ed8922012-04-03 17:35:38 +0000378 void RewriteLinkageSpec(LinkageSpecDecl *LSD);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000379
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +0000380 // Computes ivar bitfield group no.
381 unsigned ObjCIvarBitfieldGroupNo(ObjCIvarDecl *IV);
382 // Names field decl. for ivar bitfield group.
383 void ObjCIvarBitfieldGroupDecl(ObjCIvarDecl *IV, std::string &Result);
384 // Names struct type for ivar bitfield group.
385 void ObjCIvarBitfieldGroupType(ObjCIvarDecl *IV, std::string &Result);
386 // Names symbol for ivar bitfield group field offset.
387 void ObjCIvarBitfieldGroupOffset(ObjCIvarDecl *IV, std::string &Result);
388 // Given an ivar bitfield, it builds (or finds) its group record type.
389 QualType GetGroupRecordTypeForObjCIvarBitfield(ObjCIvarDecl *IV);
390 QualType SynthesizeBitfieldGroupStructType(
391 ObjCIvarDecl *IV,
392 SmallVectorImpl<ObjCIvarDecl *> &IVars);
393
Fariborz Jahanian11671902012-02-07 17:11:38 +0000394 // Block rewriting.
395 void RewriteBlocksInFunctionProtoType(QualType funcType, NamedDecl *D);
396
397 // Block specific rewrite rules.
398 void RewriteBlockPointerDecl(NamedDecl *VD);
Fariborz Jahanian847713a2012-04-24 19:38:45 +0000399 void RewriteByRefVar(VarDecl *VD, bool firstDecl, bool lastDecl);
John McCall113bee02012-03-10 09:33:50 +0000400 Stmt *RewriteBlockDeclRefExpr(DeclRefExpr *VD);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000401 Stmt *RewriteLocalVariableExternalStorage(DeclRefExpr *DRE);
402 void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
403
404 void RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
405 std::string &Result);
406
Fariborz Jahanian265a4212012-02-28 22:45:07 +0000407 void RewriteObjCFieldDecl(FieldDecl *fieldDecl, std::string &Result);
Fariborz Jahanian144b7222012-05-01 17:46:45 +0000408 bool IsTagDefinedInsideClass(ObjCContainerDecl *IDecl, TagDecl *Tag,
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +0000409 bool &IsNamedDefinition);
410 void RewriteLocallyDefinedNamedAggregates(FieldDecl *fieldDecl,
411 std::string &Result);
Fariborz Jahanian265a4212012-02-28 22:45:07 +0000412
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +0000413 bool RewriteObjCFieldDeclType(QualType &Type, std::string &Result);
414
Fariborz Jahanian5e49eb92012-02-22 18:13:25 +0000415 void RewriteIvarOffsetSymbols(ObjCInterfaceDecl *CDecl,
416 std::string &Result);
417
Fariborz Jahanian11671902012-02-07 17:11:38 +0000418 virtual void Initialize(ASTContext &context);
419
Benjamin Kramer474261a2012-06-02 10:20:41 +0000420 // Misc. AST transformation routines. Sometimes they end up calling
Fariborz Jahanian11671902012-02-07 17:11:38 +0000421 // rewriting routines on the new ASTs.
422 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
423 Expr **args, unsigned nargs,
424 SourceLocation StartLoc=SourceLocation(),
425 SourceLocation EndLoc=SourceLocation());
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +0000426
427 Expr *SynthMsgSendStretCallExpr(FunctionDecl *MsgSendStretFlavor,
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +0000428 QualType returnType,
429 SmallVectorImpl<QualType> &ArgTypes,
430 SmallVectorImpl<Expr*> &MsgExprs,
431 ObjCMethodDecl *Method);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000432
433 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp,
434 SourceLocation StartLoc=SourceLocation(),
435 SourceLocation EndLoc=SourceLocation());
436
437 void SynthCountByEnumWithState(std::string &buf);
438 void SynthMsgSendFunctionDecl();
439 void SynthMsgSendSuperFunctionDecl();
440 void SynthMsgSendStretFunctionDecl();
441 void SynthMsgSendFpretFunctionDecl();
442 void SynthMsgSendSuperStretFunctionDecl();
443 void SynthGetClassFunctionDecl();
444 void SynthGetMetaClassFunctionDecl();
445 void SynthGetSuperClassFunctionDecl();
446 void SynthSelGetUidFunctionDecl();
Benjamin Kramer60509af2013-09-09 14:48:42 +0000447 void SynthSuperConstructorFunctionDecl();
Fariborz Jahanian11671902012-02-07 17:11:38 +0000448
449 // Rewriting metadata
450 template<typename MethodIterator>
451 void RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
452 MethodIterator MethodEnd,
453 bool IsInstanceMethod,
454 StringRef prefix,
455 StringRef ClassName,
456 std::string &Result);
Fariborz Jahaniane18961b2012-02-08 19:53:58 +0000457 void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
458 std::string &Result);
Fariborz Jahanian95badad2012-04-30 16:57:52 +0000459 void RewriteObjCProtocolListMetaData(
Fariborz Jahanian11671902012-02-07 17:11:38 +0000460 const ObjCList<ObjCProtocolDecl> &Prots,
461 StringRef prefix, StringRef ClassName, std::string &Result);
Fariborz Jahanian95badad2012-04-30 16:57:52 +0000462 void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanian11671902012-02-07 17:11:38 +0000463 std::string &Result);
Fariborz Jahanian95badad2012-04-30 16:57:52 +0000464 void RewriteClassSetupInitHook(std::string &Result);
Fariborz Jahanian5ed21c32012-03-27 18:41:05 +0000465
Fariborz Jahanian95badad2012-04-30 16:57:52 +0000466 void RewriteMetaDataIntoBuffer(std::string &Result);
467 void WriteImageInfo(std::string &Result);
468 void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
Fariborz Jahanian11671902012-02-07 17:11:38 +0000469 std::string &Result);
Fariborz Jahanian95badad2012-04-30 16:57:52 +0000470 void RewriteCategorySetupInitHook(std::string &Result);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000471
472 // Rewriting ivar
Fariborz Jahanian95badad2012-04-30 16:57:52 +0000473 void RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
Fariborz Jahanian11671902012-02-07 17:11:38 +0000474 std::string &Result);
Fariborz Jahanian95badad2012-04-30 16:57:52 +0000475 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000476
477
478 std::string SynthesizeByrefCopyDestroyHelper(VarDecl *VD, int flag);
479 std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
480 StringRef funcName, std::string Tag);
481 std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
482 StringRef funcName, std::string Tag);
483 std::string SynthesizeBlockImpl(BlockExpr *CE,
484 std::string Tag, std::string Desc);
485 std::string SynthesizeBlockDescriptor(std::string DescTag,
486 std::string ImplTag,
487 int i, StringRef funcName,
488 unsigned hasCopy);
489 Stmt *SynthesizeBlockCall(CallExpr *Exp, const Expr* BlockExp);
490 void SynthesizeBlockLiterals(SourceLocation FunLocStart,
491 StringRef FunName);
492 FunctionDecl *SynthBlockInitFunctionDecl(StringRef name);
493 Stmt *SynthBlockInitExpr(BlockExpr *Exp,
Craig Topper5603df42013-07-05 19:34:19 +0000494 const SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000495
496 // Misc. helper routines.
497 QualType getProtocolType();
498 void WarnAboutReturnGotoStmts(Stmt *S);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000499 void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
500 void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
501 void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
502
503 bool IsDeclStmtInForeachHeader(DeclStmt *DS);
504 void CollectBlockDeclRefInfo(BlockExpr *Exp);
505 void GetBlockDeclRefExprs(Stmt *S);
Craig Topper5603df42013-07-05 19:34:19 +0000506 void GetInnerBlockDeclRefExprs(Stmt *S,
507 SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs,
Fariborz Jahanian11671902012-02-07 17:11:38 +0000508 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts);
509
510 // We avoid calling Type::isBlockPointerType(), since it operates on the
511 // canonical type. We only care if the top-level type is a closure pointer.
512 bool isTopLevelBlockPointerType(QualType T) {
513 return isa<BlockPointerType>(T);
514 }
515
516 /// convertBlockPointerToFunctionPointer - Converts a block-pointer type
517 /// to a function pointer type and upon success, returns true; false
518 /// otherwise.
519 bool convertBlockPointerToFunctionPointer(QualType &T) {
520 if (isTopLevelBlockPointerType(T)) {
521 const BlockPointerType *BPT = T->getAs<BlockPointerType>();
522 T = Context->getPointerType(BPT->getPointeeType());
523 return true;
524 }
525 return false;
526 }
527
Fariborz Jahanianc3cdc412012-02-13 18:57:49 +0000528 bool convertObjCTypeToCStyleType(QualType &T);
529
Fariborz Jahanian11671902012-02-07 17:11:38 +0000530 bool needToScanForQualifiers(QualType T);
531 QualType getSuperStructType();
532 QualType getConstantStringStructType();
533 QualType convertFunctionTypeOfBlocks(const FunctionType *FT);
534 bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf);
535
536 void convertToUnqualifiedObjCType(QualType &T) {
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +0000537 if (T->isObjCQualifiedIdType()) {
538 bool isConst = T.isConstQualified();
539 T = isConst ? Context->getObjCIdType().withConst()
540 : Context->getObjCIdType();
541 }
Fariborz Jahanian11671902012-02-07 17:11:38 +0000542 else if (T->isObjCQualifiedClassType())
543 T = Context->getObjCClassType();
544 else if (T->isObjCObjectPointerType() &&
545 T->getPointeeType()->isObjCQualifiedInterfaceType()) {
546 if (const ObjCObjectPointerType * OBJPT =
547 T->getAsObjCInterfacePointerType()) {
548 const ObjCInterfaceType *IFaceT = OBJPT->getInterfaceType();
549 T = QualType(IFaceT, 0);
550 T = Context->getPointerType(T);
551 }
552 }
553 }
554
555 // FIXME: This predicate seems like it would be useful to add to ASTContext.
556 bool isObjCType(QualType T) {
557 if (!LangOpts.ObjC1 && !LangOpts.ObjC2)
558 return false;
559
560 QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
561
562 if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
563 OCT == Context->getCanonicalType(Context->getObjCClassType()))
564 return true;
565
566 if (const PointerType *PT = OCT->getAs<PointerType>()) {
567 if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
568 PT->getPointeeType()->isObjCQualifiedIdType())
569 return true;
570 }
571 return false;
572 }
573 bool PointerTypeTakesAnyBlockArguments(QualType QT);
574 bool PointerTypeTakesAnyObjCQualifiedType(QualType QT);
575 void GetExtentOfArgList(const char *Name, const char *&LParen,
576 const char *&RParen);
577
578 void QuoteDoublequotes(std::string &From, std::string &To) {
579 for (unsigned i = 0; i < From.length(); i++) {
580 if (From[i] == '"')
581 To += "\\\"";
582 else
583 To += From[i];
584 }
585 }
586
587 QualType getSimpleFunctionType(QualType result,
Jordan Rose5c382722013-03-08 21:51:21 +0000588 ArrayRef<QualType> args,
Fariborz Jahanian11671902012-02-07 17:11:38 +0000589 bool variadic = false) {
590 if (result == Context->getObjCInstanceType())
591 result = Context->getObjCIdType();
592 FunctionProtoType::ExtProtoInfo fpi;
593 fpi.Variadic = variadic;
Jordan Rose5c382722013-03-08 21:51:21 +0000594 return Context->getFunctionType(result, args, fpi);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000595 }
596
597 // Helper function: create a CStyleCastExpr with trivial type source info.
598 CStyleCastExpr* NoTypeInfoCStyleCastExpr(ASTContext *Ctx, QualType Ty,
599 CastKind Kind, Expr *E) {
600 TypeSourceInfo *TInfo = Ctx->getTrivialTypeSourceInfo(Ty, SourceLocation());
601 return CStyleCastExpr::Create(*Ctx, Ty, VK_RValue, Kind, E, 0, TInfo,
602 SourceLocation(), SourceLocation());
603 }
Fariborz Jahanian07a423d2012-03-14 23:18:19 +0000604
605 bool ImplementationIsNonLazy(const ObjCImplDecl *OD) const {
606 IdentifierInfo* II = &Context->Idents.get("load");
607 Selector LoadSel = Context->Selectors.getSelector(0, &II);
608 return OD->getClassMethod(LoadSel) != 0;
609 }
Fariborz Jahanian11671902012-02-07 17:11:38 +0000610 };
611
612}
613
614void RewriteModernObjC::RewriteBlocksInFunctionProtoType(QualType funcType,
615 NamedDecl *D) {
616 if (const FunctionProtoType *fproto
617 = dyn_cast<FunctionProtoType>(funcType.IgnoreParens())) {
Alp Toker9cacbab2014-01-20 20:26:09 +0000618 for (FunctionProtoType::param_type_iterator I = fproto->param_type_begin(),
619 E = fproto->param_type_end();
620 I && (I != E); ++I)
Fariborz Jahanian11671902012-02-07 17:11:38 +0000621 if (isTopLevelBlockPointerType(*I)) {
622 // All the args are checked/rewritten. Don't call twice!
623 RewriteBlockPointerDecl(D);
624 break;
625 }
626 }
627}
628
629void RewriteModernObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
630 const PointerType *PT = funcType->getAs<PointerType>();
631 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
632 RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND);
633}
634
635static bool IsHeaderFile(const std::string &Filename) {
636 std::string::size_type DotPos = Filename.rfind('.');
637
638 if (DotPos == std::string::npos) {
639 // no file extension
640 return false;
641 }
642
643 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
644 // C header: .h
645 // C++ header: .hh or .H;
646 return Ext == "h" || Ext == "hh" || Ext == "H";
647}
648
649RewriteModernObjC::RewriteModernObjC(std::string inFile, raw_ostream* OS,
650 DiagnosticsEngine &D, const LangOptions &LOpts,
Fariborz Jahaniane4c7e852013-02-08 00:27:34 +0000651 bool silenceMacroWarn,
652 bool LineInfo)
Fariborz Jahanian11671902012-02-07 17:11:38 +0000653 : Diags(D), LangOpts(LOpts), InFileName(inFile), OutFile(OS),
Fariborz Jahaniane4c7e852013-02-08 00:27:34 +0000654 SilenceRewriteMacroWarning(silenceMacroWarn), GenerateLineInfo(LineInfo) {
Fariborz Jahanian11671902012-02-07 17:11:38 +0000655 IsHeader = IsHeaderFile(inFile);
656 RewriteFailedDiag = Diags.getCustomDiagID(DiagnosticsEngine::Warning,
657 "rewriting sub-expression within a macro (may not be correct)");
Fariborz Jahanianbdf975e2012-03-22 19:54:39 +0000658 // FIXME. This should be an error. But if block is not called, it is OK. And it
659 // may break including some headers.
660 GlobalBlockRewriteFailedDiag = Diags.getCustomDiagID(DiagnosticsEngine::Warning,
661 "rewriting block literal declared in global scope is not implemented");
662
Fariborz Jahanian11671902012-02-07 17:11:38 +0000663 TryFinallyContainsReturnDiag = Diags.getCustomDiagID(
664 DiagnosticsEngine::Warning,
665 "rewriter doesn't support user-specified control flow semantics "
666 "for @try/@finally (code may not execute properly)");
667}
668
669ASTConsumer *clang::CreateModernObjCRewriter(const std::string& InFile,
670 raw_ostream* OS,
671 DiagnosticsEngine &Diags,
672 const LangOptions &LOpts,
Fariborz Jahaniane4c7e852013-02-08 00:27:34 +0000673 bool SilenceRewriteMacroWarning,
674 bool LineInfo) {
675 return new RewriteModernObjC(InFile, OS, Diags, LOpts,
676 SilenceRewriteMacroWarning, LineInfo);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000677}
678
679void RewriteModernObjC::InitializeCommon(ASTContext &context) {
680 Context = &context;
681 SM = &Context->getSourceManager();
682 TUDecl = Context->getTranslationUnitDecl();
683 MsgSendFunctionDecl = 0;
684 MsgSendSuperFunctionDecl = 0;
685 MsgSendStretFunctionDecl = 0;
686 MsgSendSuperStretFunctionDecl = 0;
687 MsgSendFpretFunctionDecl = 0;
688 GetClassFunctionDecl = 0;
689 GetMetaClassFunctionDecl = 0;
690 GetSuperClassFunctionDecl = 0;
691 SelGetUidFunctionDecl = 0;
692 CFStringFunctionDecl = 0;
693 ConstantStringClassReference = 0;
694 NSStringRecord = 0;
695 CurMethodDef = 0;
696 CurFunctionDef = 0;
Fariborz Jahanian11671902012-02-07 17:11:38 +0000697 GlobalVarDecl = 0;
Fariborz Jahaniane0050702012-03-23 00:00:49 +0000698 GlobalConstructionExp = 0;
Fariborz Jahanian11671902012-02-07 17:11:38 +0000699 SuperStructDecl = 0;
700 ProtocolTypeDecl = 0;
701 ConstantStringDecl = 0;
702 BcLabelCount = 0;
Benjamin Kramer60509af2013-09-09 14:48:42 +0000703 SuperConstructorFunctionDecl = 0;
Fariborz Jahanian11671902012-02-07 17:11:38 +0000704 NumObjCStringLiterals = 0;
705 PropParentMap = 0;
706 CurrentBody = 0;
707 DisableReplaceStmt = false;
708 objc_impl_method = false;
709
710 // Get the ID and start/end of the main file.
711 MainFileID = SM->getMainFileID();
712 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
713 MainFileStart = MainBuf->getBufferStart();
714 MainFileEnd = MainBuf->getBufferEnd();
715
David Blaikiebbafb8a2012-03-11 07:00:24 +0000716 Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOpts());
Fariborz Jahanian11671902012-02-07 17:11:38 +0000717}
718
719//===----------------------------------------------------------------------===//
720// Top Level Driver Code
721//===----------------------------------------------------------------------===//
722
723void RewriteModernObjC::HandleTopLevelSingleDecl(Decl *D) {
724 if (Diags.hasErrorOccurred())
725 return;
726
727 // Two cases: either the decl could be in the main file, or it could be in a
728 // #included file. If the former, rewrite it now. If the later, check to see
729 // if we rewrote the #include/#import.
730 SourceLocation Loc = D->getLocation();
731 Loc = SM->getExpansionLoc(Loc);
732
733 // If this is for a builtin, ignore it.
734 if (Loc.isInvalid()) return;
735
736 // Look for built-in declarations that we need to refer during the rewrite.
737 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
738 RewriteFunctionDecl(FD);
739 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
740 // declared in <Foundation/NSString.h>
741 if (FVD->getName() == "_NSConstantStringClassReference") {
742 ConstantStringClassReference = FVD;
743 return;
744 }
Fariborz Jahanian11671902012-02-07 17:11:38 +0000745 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
746 RewriteCategoryDecl(CD);
747 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
748 if (PD->isThisDeclarationADefinition())
749 RewriteProtocolDecl(PD);
750 } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) {
Fariborz Jahanianf264d5d2012-04-04 17:16:15 +0000751 // FIXME. This will not work in all situations and leaving it out
752 // is harmless.
753 // RewriteLinkageSpec(LSD);
754
Fariborz Jahanian11671902012-02-07 17:11:38 +0000755 // Recurse into linkage specifications
756 for (DeclContext::decl_iterator DI = LSD->decls_begin(),
757 DIEnd = LSD->decls_end();
758 DI != DIEnd; ) {
759 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>((*DI))) {
760 if (!IFace->isThisDeclarationADefinition()) {
761 SmallVector<Decl *, 8> DG;
762 SourceLocation StartLoc = IFace->getLocStart();
763 do {
764 if (isa<ObjCInterfaceDecl>(*DI) &&
765 !cast<ObjCInterfaceDecl>(*DI)->isThisDeclarationADefinition() &&
766 StartLoc == (*DI)->getLocStart())
767 DG.push_back(*DI);
768 else
769 break;
770
771 ++DI;
772 } while (DI != DIEnd);
773 RewriteForwardClassDecl(DG);
774 continue;
775 }
Fariborz Jahanian08ed8922012-04-03 17:35:38 +0000776 else {
777 // Keep track of all interface declarations seen.
778 ObjCInterfacesSeen.push_back(IFace);
779 ++DI;
780 continue;
781 }
Fariborz Jahanian11671902012-02-07 17:11:38 +0000782 }
783
784 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>((*DI))) {
785 if (!Proto->isThisDeclarationADefinition()) {
786 SmallVector<Decl *, 8> DG;
787 SourceLocation StartLoc = Proto->getLocStart();
788 do {
789 if (isa<ObjCProtocolDecl>(*DI) &&
790 !cast<ObjCProtocolDecl>(*DI)->isThisDeclarationADefinition() &&
791 StartLoc == (*DI)->getLocStart())
792 DG.push_back(*DI);
793 else
794 break;
795
796 ++DI;
797 } while (DI != DIEnd);
798 RewriteForwardProtocolDecl(DG);
799 continue;
800 }
801 }
802
803 HandleTopLevelSingleDecl(*DI);
804 ++DI;
805 }
806 }
807 // If we have a decl in the main file, see if we should rewrite it.
Eli Friedman5ba37d52013-08-22 00:27:10 +0000808 if (SM->isWrittenInMainFile(Loc))
Fariborz Jahanian11671902012-02-07 17:11:38 +0000809 return HandleDeclInMainFile(D);
810}
811
812//===----------------------------------------------------------------------===//
813// Syntactic (non-AST) Rewriting Code
814//===----------------------------------------------------------------------===//
815
816void RewriteModernObjC::RewriteInclude() {
817 SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID);
818 StringRef MainBuf = SM->getBufferData(MainFileID);
819 const char *MainBufStart = MainBuf.begin();
820 const char *MainBufEnd = MainBuf.end();
821 size_t ImportLen = strlen("import");
822
823 // Loop over the whole file, looking for includes.
824 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
825 if (*BufPtr == '#') {
826 if (++BufPtr == MainBufEnd)
827 return;
828 while (*BufPtr == ' ' || *BufPtr == '\t')
829 if (++BufPtr == MainBufEnd)
830 return;
831 if (!strncmp(BufPtr, "import", ImportLen)) {
832 // replace import with include
833 SourceLocation ImportLoc =
834 LocStart.getLocWithOffset(BufPtr-MainBufStart);
835 ReplaceText(ImportLoc, ImportLen, "include");
836 BufPtr += ImportLen;
837 }
838 }
839 }
840}
841
Fariborz Jahanian89919cc2012-05-08 23:54:35 +0000842static void WriteInternalIvarName(const ObjCInterfaceDecl *IDecl,
843 ObjCIvarDecl *IvarDecl, std::string &Result) {
844 Result += "OBJC_IVAR_$_";
845 Result += IDecl->getName();
846 Result += "$";
847 Result += IvarDecl->getName();
848}
849
850std::string
851RewriteModernObjC::getIvarAccessString(ObjCIvarDecl *D) {
852 const ObjCInterfaceDecl *ClassDecl = D->getContainingInterface();
853
854 // Build name of symbol holding ivar offset.
855 std::string IvarOffsetName;
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +0000856 if (D->isBitField())
857 ObjCIvarBitfieldGroupOffset(D, IvarOffsetName);
858 else
859 WriteInternalIvarName(ClassDecl, D, IvarOffsetName);
Fariborz Jahanian89919cc2012-05-08 23:54:35 +0000860
861
862 std::string S = "(*(";
863 QualType IvarT = D->getType();
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +0000864 if (D->isBitField())
865 IvarT = GetGroupRecordTypeForObjCIvarBitfield(D);
Fariborz Jahanian89919cc2012-05-08 23:54:35 +0000866
867 if (!isa<TypedefType>(IvarT) && IvarT->isRecordType()) {
868 RecordDecl *RD = IvarT->getAs<RecordType>()->getDecl();
869 RD = RD->getDefinition();
870 if (RD && !RD->getDeclName().getAsIdentifierInfo()) {
871 // decltype(((Foo_IMPL*)0)->bar) *
872 ObjCContainerDecl *CDecl =
873 dyn_cast<ObjCContainerDecl>(D->getDeclContext());
874 // ivar in class extensions requires special treatment.
875 if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(CDecl))
876 CDecl = CatDecl->getClassInterface();
877 std::string RecName = CDecl->getName();
878 RecName += "_IMPL";
879 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
880 SourceLocation(), SourceLocation(),
881 &Context->Idents.get(RecName.c_str()));
882 QualType PtrStructIMPL = Context->getPointerType(Context->getTagDeclType(RD));
883 unsigned UnsignedIntSize =
884 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
885 Expr *Zero = IntegerLiteral::Create(*Context,
886 llvm::APInt(UnsignedIntSize, 0),
887 Context->UnsignedIntTy, SourceLocation());
888 Zero = NoTypeInfoCStyleCastExpr(Context, PtrStructIMPL, CK_BitCast, Zero);
889 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
890 Zero);
891 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
892 SourceLocation(),
893 &Context->Idents.get(D->getNameAsString()),
894 IvarT, 0,
895 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smith2b013182012-06-10 03:12:00 +0000896 ICIS_NoInit);
Fariborz Jahanian89919cc2012-05-08 23:54:35 +0000897 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
898 FD->getType(), VK_LValue,
899 OK_Ordinary);
900 IvarT = Context->getDecltypeType(ME, ME->getType());
901 }
902 }
903 convertObjCTypeToCStyleType(IvarT);
904 QualType castT = Context->getPointerType(IvarT);
905 std::string TypeString(castT.getAsString(Context->getPrintingPolicy()));
906 S += TypeString;
907 S += ")";
908
909 // ((char *)self + IVAR_OFFSET_SYMBOL_NAME)
910 S += "((char *)self + ";
911 S += IvarOffsetName;
912 S += "))";
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +0000913 if (D->isBitField()) {
914 S += ".";
915 S += D->getNameAsString();
916 }
Fariborz Jahanian89919cc2012-05-08 23:54:35 +0000917 ReferencedIvars[const_cast<ObjCInterfaceDecl *>(ClassDecl)].insert(D);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000918 return S;
919}
920
Fariborz Jahanianf687e7b2012-05-03 22:52:13 +0000921/// mustSynthesizeSetterGetterMethod - returns true if setter or getter has not
922/// been found in the class implementation. In this case, it must be synthesized.
923static bool mustSynthesizeSetterGetterMethod(ObjCImplementationDecl *IMP,
924 ObjCPropertyDecl *PD,
925 bool getter) {
926 return getter ? !IMP->getInstanceMethod(PD->getGetterName())
927 : !IMP->getInstanceMethod(PD->getSetterName());
928
929}
930
Fariborz Jahanian11671902012-02-07 17:11:38 +0000931void RewriteModernObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
932 ObjCImplementationDecl *IMD,
933 ObjCCategoryImplDecl *CID) {
934 static bool objcGetPropertyDefined = false;
935 static bool objcSetPropertyDefined = false;
Fariborz Jahanianf687e7b2012-05-03 22:52:13 +0000936 SourceLocation startGetterSetterLoc;
937
938 if (PID->getLocStart().isValid()) {
939 SourceLocation startLoc = PID->getLocStart();
940 InsertText(startLoc, "// ");
941 const char *startBuf = SM->getCharacterData(startLoc);
942 assert((*startBuf == '@') && "bogus @synthesize location");
943 const char *semiBuf = strchr(startBuf, ';');
944 assert((*semiBuf == ';') && "@synthesize: can't find ';'");
945 startGetterSetterLoc = startLoc.getLocWithOffset(semiBuf-startBuf+1);
946 }
947 else
948 startGetterSetterLoc = IMD ? IMD->getLocEnd() : CID->getLocEnd();
Fariborz Jahanian11671902012-02-07 17:11:38 +0000949
950 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
951 return; // FIXME: is this correct?
952
953 // Generate the 'getter' function.
954 ObjCPropertyDecl *PD = PID->getPropertyDecl();
955 ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
Jordan Rose755a2ff2013-03-15 21:41:35 +0000956 assert(IMD && OID && "Synthesized ivars must be attached to @implementation");
Fariborz Jahanian11671902012-02-07 17:11:38 +0000957
Bill Wendling44426052012-12-20 19:22:21 +0000958 unsigned Attributes = PD->getPropertyAttributes();
Fariborz Jahanianf687e7b2012-05-03 22:52:13 +0000959 if (mustSynthesizeSetterGetterMethod(IMD, PD, true /*getter*/)) {
Bill Wendling44426052012-12-20 19:22:21 +0000960 bool GenGetProperty = !(Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic) &&
961 (Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
Fariborz Jahanian11671902012-02-07 17:11:38 +0000962 ObjCPropertyDecl::OBJC_PR_copy));
963 std::string Getr;
964 if (GenGetProperty && !objcGetPropertyDefined) {
965 objcGetPropertyDefined = true;
966 // FIXME. Is this attribute correct in all cases?
967 Getr = "\nextern \"C\" __declspec(dllimport) "
968 "id objc_getProperty(id, SEL, long, bool);\n";
969 }
970 RewriteObjCMethodDecl(OID->getContainingInterface(),
971 PD->getGetterMethodDecl(), Getr);
972 Getr += "{ ";
973 // Synthesize an explicit cast to gain access to the ivar.
974 // See objc-act.c:objc_synthesize_new_getter() for details.
975 if (GenGetProperty) {
976 // return objc_getProperty(self, _cmd, offsetof(ClassDecl, OID), 1)
977 Getr += "typedef ";
978 const FunctionType *FPRetType = 0;
979 RewriteTypeIntoString(PD->getGetterMethodDecl()->getResultType(), Getr,
980 FPRetType);
981 Getr += " _TYPE";
982 if (FPRetType) {
983 Getr += ")"; // close the precedence "scope" for "*".
984
985 // Now, emit the argument types (if any).
986 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)){
987 Getr += "(";
Alp Toker9cacbab2014-01-20 20:26:09 +0000988 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
Fariborz Jahanian11671902012-02-07 17:11:38 +0000989 if (i) Getr += ", ";
Alp Toker9cacbab2014-01-20 20:26:09 +0000990 std::string ParamStr =
991 FT->getParamType(i).getAsString(Context->getPrintingPolicy());
Fariborz Jahanian11671902012-02-07 17:11:38 +0000992 Getr += ParamStr;
993 }
994 if (FT->isVariadic()) {
Alp Toker9cacbab2014-01-20 20:26:09 +0000995 if (FT->getNumParams())
996 Getr += ", ";
Fariborz Jahanian11671902012-02-07 17:11:38 +0000997 Getr += "...";
998 }
999 Getr += ")";
1000 } else
1001 Getr += "()";
1002 }
1003 Getr += ";\n";
1004 Getr += "return (_TYPE)";
1005 Getr += "objc_getProperty(self, _cmd, ";
1006 RewriteIvarOffsetComputation(OID, Getr);
1007 Getr += ", 1)";
1008 }
1009 else
1010 Getr += "return " + getIvarAccessString(OID);
1011 Getr += "; }";
Fariborz Jahanianf687e7b2012-05-03 22:52:13 +00001012 InsertText(startGetterSetterLoc, Getr);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001013 }
1014
Fariborz Jahanianf687e7b2012-05-03 22:52:13 +00001015 if (PD->isReadOnly() ||
1016 !mustSynthesizeSetterGetterMethod(IMD, PD, false /*setter*/))
Fariborz Jahanian11671902012-02-07 17:11:38 +00001017 return;
1018
1019 // Generate the 'setter' function.
1020 std::string Setr;
Bill Wendling44426052012-12-20 19:22:21 +00001021 bool GenSetProperty = Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
Fariborz Jahanian11671902012-02-07 17:11:38 +00001022 ObjCPropertyDecl::OBJC_PR_copy);
1023 if (GenSetProperty && !objcSetPropertyDefined) {
1024 objcSetPropertyDefined = true;
1025 // FIXME. Is this attribute correct in all cases?
1026 Setr = "\nextern \"C\" __declspec(dllimport) "
1027 "void objc_setProperty (id, SEL, long, id, bool, bool);\n";
1028 }
1029
1030 RewriteObjCMethodDecl(OID->getContainingInterface(),
1031 PD->getSetterMethodDecl(), Setr);
1032 Setr += "{ ";
1033 // Synthesize an explicit cast to initialize the ivar.
1034 // See objc-act.c:objc_synthesize_new_setter() for details.
1035 if (GenSetProperty) {
1036 Setr += "objc_setProperty (self, _cmd, ";
1037 RewriteIvarOffsetComputation(OID, Setr);
1038 Setr += ", (id)";
1039 Setr += PD->getName();
1040 Setr += ", ";
Bill Wendling44426052012-12-20 19:22:21 +00001041 if (Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic)
Fariborz Jahanian11671902012-02-07 17:11:38 +00001042 Setr += "0, ";
1043 else
1044 Setr += "1, ";
Bill Wendling44426052012-12-20 19:22:21 +00001045 if (Attributes & ObjCPropertyDecl::OBJC_PR_copy)
Fariborz Jahanian11671902012-02-07 17:11:38 +00001046 Setr += "1)";
1047 else
1048 Setr += "0)";
1049 }
1050 else {
1051 Setr += getIvarAccessString(OID) + " = ";
1052 Setr += PD->getName();
1053 }
Fariborz Jahanianf687e7b2012-05-03 22:52:13 +00001054 Setr += "; }\n";
1055 InsertText(startGetterSetterLoc, Setr);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001056}
1057
1058static void RewriteOneForwardClassDecl(ObjCInterfaceDecl *ForwardDecl,
1059 std::string &typedefString) {
Fariborz Jahaniane8730a32013-02-08 17:15:07 +00001060 typedefString += "\n#ifndef _REWRITER_typedef_";
Fariborz Jahanian11671902012-02-07 17:11:38 +00001061 typedefString += ForwardDecl->getNameAsString();
1062 typedefString += "\n";
1063 typedefString += "#define _REWRITER_typedef_";
1064 typedefString += ForwardDecl->getNameAsString();
1065 typedefString += "\n";
1066 typedefString += "typedef struct objc_object ";
1067 typedefString += ForwardDecl->getNameAsString();
Fariborz Jahanian2cc29af2012-03-12 23:58:28 +00001068 // typedef struct { } _objc_exc_Classname;
1069 typedefString += ";\ntypedef struct {} _objc_exc_";
1070 typedefString += ForwardDecl->getNameAsString();
Fariborz Jahanian11671902012-02-07 17:11:38 +00001071 typedefString += ";\n#endif\n";
1072}
1073
1074void RewriteModernObjC::RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
1075 const std::string &typedefString) {
1076 SourceLocation startLoc = ClassDecl->getLocStart();
1077 const char *startBuf = SM->getCharacterData(startLoc);
1078 const char *semiPtr = strchr(startBuf, ';');
1079 // Replace the @class with typedefs corresponding to the classes.
1080 ReplaceText(startLoc, semiPtr-startBuf+1, typedefString);
1081}
1082
1083void RewriteModernObjC::RewriteForwardClassDecl(DeclGroupRef D) {
1084 std::string typedefString;
1085 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
Fariborz Jahanian0dded8a2013-09-24 17:03:07 +00001086 if (ObjCInterfaceDecl *ForwardDecl = dyn_cast<ObjCInterfaceDecl>(*I)) {
1087 if (I == D.begin()) {
1088 // Translate to typedef's that forward reference structs with the same name
1089 // as the class. As a convenience, we include the original declaration
1090 // as a comment.
1091 typedefString += "// @class ";
1092 typedefString += ForwardDecl->getNameAsString();
1093 typedefString += ";";
1094 }
1095 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001096 }
Fariborz Jahanian0dded8a2013-09-24 17:03:07 +00001097 else
1098 HandleTopLevelSingleDecl(*I);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001099 }
1100 DeclGroupRef::iterator I = D.begin();
1101 RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(*I), typedefString);
1102}
1103
1104void RewriteModernObjC::RewriteForwardClassDecl(
Craig Topper5603df42013-07-05 19:34:19 +00001105 const SmallVectorImpl<Decl *> &D) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00001106 std::string typedefString;
1107 for (unsigned i = 0; i < D.size(); i++) {
1108 ObjCInterfaceDecl *ForwardDecl = cast<ObjCInterfaceDecl>(D[i]);
1109 if (i == 0) {
1110 typedefString += "// @class ";
1111 typedefString += ForwardDecl->getNameAsString();
Fariborz Jahaniane8730a32013-02-08 17:15:07 +00001112 typedefString += ";";
Fariborz Jahanian11671902012-02-07 17:11:38 +00001113 }
1114 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
1115 }
1116 RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(D[0]), typedefString);
1117}
1118
1119void RewriteModernObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
1120 // When method is a synthesized one, such as a getter/setter there is
1121 // nothing to rewrite.
1122 if (Method->isImplicit())
1123 return;
1124 SourceLocation LocStart = Method->getLocStart();
1125 SourceLocation LocEnd = Method->getLocEnd();
1126
1127 if (SM->getExpansionLineNumber(LocEnd) >
1128 SM->getExpansionLineNumber(LocStart)) {
1129 InsertText(LocStart, "#if 0\n");
1130 ReplaceText(LocEnd, 1, ";\n#endif\n");
1131 } else {
1132 InsertText(LocStart, "// ");
1133 }
1134}
1135
1136void RewriteModernObjC::RewriteProperty(ObjCPropertyDecl *prop) {
1137 SourceLocation Loc = prop->getAtLoc();
1138
1139 ReplaceText(Loc, 0, "// ");
1140 // FIXME: handle properties that are declared across multiple lines.
1141}
1142
1143void RewriteModernObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
1144 SourceLocation LocStart = CatDecl->getLocStart();
1145
1146 // FIXME: handle category headers that are declared across multiple lines.
Fariborz Jahanian144b7222012-05-01 17:46:45 +00001147 if (CatDecl->getIvarRBraceLoc().isValid()) {
1148 ReplaceText(LocStart, 1, "/** ");
1149 ReplaceText(CatDecl->getIvarRBraceLoc(), 1, "**/ ");
1150 }
1151 else {
Fariborz Jahanian2b383d212012-02-19 19:00:05 +00001152 ReplaceText(LocStart, 0, "// ");
Fariborz Jahanian144b7222012-05-01 17:46:45 +00001153 }
Fariborz Jahaniana7765fe2012-02-20 20:09:20 +00001154
Fariborz Jahanian11671902012-02-07 17:11:38 +00001155 for (ObjCCategoryDecl::prop_iterator I = CatDecl->prop_begin(),
1156 E = CatDecl->prop_end(); I != E; ++I)
David Blaikie40ed2972012-06-06 20:45:41 +00001157 RewriteProperty(*I);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001158
1159 for (ObjCCategoryDecl::instmeth_iterator
1160 I = CatDecl->instmeth_begin(), E = CatDecl->instmeth_end();
1161 I != E; ++I)
1162 RewriteMethodDeclaration(*I);
1163 for (ObjCCategoryDecl::classmeth_iterator
1164 I = CatDecl->classmeth_begin(), E = CatDecl->classmeth_end();
1165 I != E; ++I)
1166 RewriteMethodDeclaration(*I);
1167
1168 // Lastly, comment out the @end.
1169 ReplaceText(CatDecl->getAtEndRange().getBegin(),
Fariborz Jahanian3a65ce32013-04-03 19:11:21 +00001170 strlen("@end"), "/* @end */\n");
Fariborz Jahanian11671902012-02-07 17:11:38 +00001171}
1172
1173void RewriteModernObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
1174 SourceLocation LocStart = PDecl->getLocStart();
1175 assert(PDecl->isThisDeclarationADefinition());
1176
1177 // FIXME: handle protocol headers that are declared across multiple lines.
1178 ReplaceText(LocStart, 0, "// ");
1179
1180 for (ObjCProtocolDecl::instmeth_iterator
1181 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
1182 I != E; ++I)
1183 RewriteMethodDeclaration(*I);
1184 for (ObjCProtocolDecl::classmeth_iterator
1185 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
1186 I != E; ++I)
1187 RewriteMethodDeclaration(*I);
1188
1189 for (ObjCInterfaceDecl::prop_iterator I = PDecl->prop_begin(),
1190 E = PDecl->prop_end(); I != E; ++I)
David Blaikie40ed2972012-06-06 20:45:41 +00001191 RewriteProperty(*I);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001192
1193 // Lastly, comment out the @end.
1194 SourceLocation LocEnd = PDecl->getAtEndRange().getBegin();
Fariborz Jahanian3a65ce32013-04-03 19:11:21 +00001195 ReplaceText(LocEnd, strlen("@end"), "/* @end */\n");
Fariborz Jahanian11671902012-02-07 17:11:38 +00001196
1197 // Must comment out @optional/@required
1198 const char *startBuf = SM->getCharacterData(LocStart);
1199 const char *endBuf = SM->getCharacterData(LocEnd);
1200 for (const char *p = startBuf; p < endBuf; p++) {
1201 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
1202 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
1203 ReplaceText(OptionalLoc, strlen("@optional"), "/* @optional */");
1204
1205 }
1206 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
1207 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
1208 ReplaceText(OptionalLoc, strlen("@required"), "/* @required */");
1209
1210 }
1211 }
1212}
1213
1214void RewriteModernObjC::RewriteForwardProtocolDecl(DeclGroupRef D) {
1215 SourceLocation LocStart = (*D.begin())->getLocStart();
1216 if (LocStart.isInvalid())
1217 llvm_unreachable("Invalid SourceLocation");
1218 // FIXME: handle forward protocol that are declared across multiple lines.
1219 ReplaceText(LocStart, 0, "// ");
1220}
1221
1222void
Craig Topper5603df42013-07-05 19:34:19 +00001223RewriteModernObjC::RewriteForwardProtocolDecl(const SmallVectorImpl<Decl *> &DG) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00001224 SourceLocation LocStart = DG[0]->getLocStart();
1225 if (LocStart.isInvalid())
1226 llvm_unreachable("Invalid SourceLocation");
1227 // FIXME: handle forward protocol that are declared across multiple lines.
1228 ReplaceText(LocStart, 0, "// ");
1229}
1230
Fariborz Jahanian08ed8922012-04-03 17:35:38 +00001231void
1232RewriteModernObjC::RewriteLinkageSpec(LinkageSpecDecl *LSD) {
1233 SourceLocation LocStart = LSD->getExternLoc();
1234 if (LocStart.isInvalid())
1235 llvm_unreachable("Invalid extern SourceLocation");
1236
1237 ReplaceText(LocStart, 0, "// ");
1238 if (!LSD->hasBraces())
1239 return;
1240 // FIXME. We don't rewrite well if '{' is not on same line as 'extern'.
1241 SourceLocation LocRBrace = LSD->getRBraceLoc();
1242 if (LocRBrace.isInvalid())
1243 llvm_unreachable("Invalid rbrace SourceLocation");
1244 ReplaceText(LocRBrace, 0, "// ");
1245}
1246
Fariborz Jahanian11671902012-02-07 17:11:38 +00001247void RewriteModernObjC::RewriteTypeIntoString(QualType T, std::string &ResultStr,
1248 const FunctionType *&FPRetType) {
1249 if (T->isObjCQualifiedIdType())
1250 ResultStr += "id";
1251 else if (T->isFunctionPointerType() ||
1252 T->isBlockPointerType()) {
1253 // needs special handling, since pointer-to-functions have special
1254 // syntax (where a decaration models use).
1255 QualType retType = T;
1256 QualType PointeeTy;
1257 if (const PointerType* PT = retType->getAs<PointerType>())
1258 PointeeTy = PT->getPointeeType();
1259 else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>())
1260 PointeeTy = BPT->getPointeeType();
1261 if ((FPRetType = PointeeTy->getAs<FunctionType>())) {
1262 ResultStr += FPRetType->getResultType().getAsString(
1263 Context->getPrintingPolicy());
1264 ResultStr += "(*";
1265 }
1266 } else
1267 ResultStr += T.getAsString(Context->getPrintingPolicy());
1268}
1269
1270void RewriteModernObjC::RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
1271 ObjCMethodDecl *OMD,
1272 std::string &ResultStr) {
1273 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
1274 const FunctionType *FPRetType = 0;
1275 ResultStr += "\nstatic ";
1276 RewriteTypeIntoString(OMD->getResultType(), ResultStr, FPRetType);
1277 ResultStr += " ";
1278
1279 // Unique method name
1280 std::string NameStr;
1281
1282 if (OMD->isInstanceMethod())
1283 NameStr += "_I_";
1284 else
1285 NameStr += "_C_";
1286
1287 NameStr += IDecl->getNameAsString();
1288 NameStr += "_";
1289
1290 if (ObjCCategoryImplDecl *CID =
1291 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
1292 NameStr += CID->getNameAsString();
1293 NameStr += "_";
1294 }
1295 // Append selector names, replacing ':' with '_'
1296 {
1297 std::string selString = OMD->getSelector().getAsString();
1298 int len = selString.size();
1299 for (int i = 0; i < len; i++)
1300 if (selString[i] == ':')
1301 selString[i] = '_';
1302 NameStr += selString;
1303 }
1304 // Remember this name for metadata emission
1305 MethodInternalNames[OMD] = NameStr;
1306 ResultStr += NameStr;
1307
1308 // Rewrite arguments
1309 ResultStr += "(";
1310
1311 // invisible arguments
1312 if (OMD->isInstanceMethod()) {
1313 QualType selfTy = Context->getObjCInterfaceType(IDecl);
1314 selfTy = Context->getPointerType(selfTy);
1315 if (!LangOpts.MicrosoftExt) {
1316 if (ObjCSynthesizedStructs.count(const_cast<ObjCInterfaceDecl*>(IDecl)))
1317 ResultStr += "struct ";
1318 }
1319 // When rewriting for Microsoft, explicitly omit the structure name.
1320 ResultStr += IDecl->getNameAsString();
1321 ResultStr += " *";
1322 }
1323 else
1324 ResultStr += Context->getObjCClassType().getAsString(
1325 Context->getPrintingPolicy());
1326
1327 ResultStr += " self, ";
1328 ResultStr += Context->getObjCSelType().getAsString(Context->getPrintingPolicy());
1329 ResultStr += " _cmd";
1330
1331 // Method arguments.
1332 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
1333 E = OMD->param_end(); PI != E; ++PI) {
1334 ParmVarDecl *PDecl = *PI;
1335 ResultStr += ", ";
1336 if (PDecl->getType()->isObjCQualifiedIdType()) {
1337 ResultStr += "id ";
1338 ResultStr += PDecl->getNameAsString();
1339 } else {
1340 std::string Name = PDecl->getNameAsString();
1341 QualType QT = PDecl->getType();
1342 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian835cabe2012-03-27 16:42:20 +00001343 (void)convertBlockPointerToFunctionPointer(QT);
1344 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
Fariborz Jahanian11671902012-02-07 17:11:38 +00001345 ResultStr += Name;
1346 }
1347 }
1348 if (OMD->isVariadic())
1349 ResultStr += ", ...";
1350 ResultStr += ") ";
1351
1352 if (FPRetType) {
1353 ResultStr += ")"; // close the precedence "scope" for "*".
1354
1355 // Now, emit the argument types (if any).
1356 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
1357 ResultStr += "(";
Alp Toker9cacbab2014-01-20 20:26:09 +00001358 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00001359 if (i) ResultStr += ", ";
Alp Toker9cacbab2014-01-20 20:26:09 +00001360 std::string ParamStr =
1361 FT->getParamType(i).getAsString(Context->getPrintingPolicy());
Fariborz Jahanian11671902012-02-07 17:11:38 +00001362 ResultStr += ParamStr;
1363 }
1364 if (FT->isVariadic()) {
Alp Toker9cacbab2014-01-20 20:26:09 +00001365 if (FT->getNumParams())
1366 ResultStr += ", ";
Fariborz Jahanian11671902012-02-07 17:11:38 +00001367 ResultStr += "...";
1368 }
1369 ResultStr += ")";
1370 } else {
1371 ResultStr += "()";
1372 }
1373 }
1374}
1375void RewriteModernObjC::RewriteImplementationDecl(Decl *OID) {
1376 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
1377 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
1378
Fariborz Jahanian2b383d212012-02-19 19:00:05 +00001379 if (IMD) {
Fariborz Jahanian144b7222012-05-01 17:46:45 +00001380 if (IMD->getIvarRBraceLoc().isValid()) {
1381 ReplaceText(IMD->getLocStart(), 1, "/** ");
1382 ReplaceText(IMD->getIvarRBraceLoc(), 1, "**/ ");
Fariborz Jahanian2b383d212012-02-19 19:00:05 +00001383 }
Fariborz Jahanian144b7222012-05-01 17:46:45 +00001384 else {
1385 InsertText(IMD->getLocStart(), "// ");
1386 }
Fariborz Jahanian2b383d212012-02-19 19:00:05 +00001387 }
1388 else
1389 InsertText(CID->getLocStart(), "// ");
Fariborz Jahanian11671902012-02-07 17:11:38 +00001390
1391 for (ObjCCategoryImplDecl::instmeth_iterator
1392 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
1393 E = IMD ? IMD->instmeth_end() : CID->instmeth_end();
1394 I != E; ++I) {
1395 std::string ResultStr;
1396 ObjCMethodDecl *OMD = *I;
1397 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
1398 SourceLocation LocStart = OMD->getLocStart();
1399 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
1400
1401 const char *startBuf = SM->getCharacterData(LocStart);
1402 const char *endBuf = SM->getCharacterData(LocEnd);
1403 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
1404 }
1405
1406 for (ObjCCategoryImplDecl::classmeth_iterator
1407 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
1408 E = IMD ? IMD->classmeth_end() : CID->classmeth_end();
1409 I != E; ++I) {
1410 std::string ResultStr;
1411 ObjCMethodDecl *OMD = *I;
1412 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
1413 SourceLocation LocStart = OMD->getLocStart();
1414 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
1415
1416 const char *startBuf = SM->getCharacterData(LocStart);
1417 const char *endBuf = SM->getCharacterData(LocEnd);
1418 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
1419 }
1420 for (ObjCCategoryImplDecl::propimpl_iterator
1421 I = IMD ? IMD->propimpl_begin() : CID->propimpl_begin(),
1422 E = IMD ? IMD->propimpl_end() : CID->propimpl_end();
1423 I != E; ++I) {
David Blaikie40ed2972012-06-06 20:45:41 +00001424 RewritePropertyImplDecl(*I, IMD, CID);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001425 }
1426
1427 InsertText(IMD ? IMD->getLocEnd() : CID->getLocEnd(), "// ");
1428}
1429
1430void RewriteModernObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Fariborz Jahanian088959a2012-02-11 20:10:52 +00001431 // Do not synthesize more than once.
1432 if (ObjCSynthesizedStructs.count(ClassDecl))
1433 return;
1434 // Make sure super class's are written before current class is written.
1435 ObjCInterfaceDecl *SuperClass = ClassDecl->getSuperClass();
1436 while (SuperClass) {
1437 RewriteInterfaceDecl(SuperClass);
1438 SuperClass = SuperClass->getSuperClass();
1439 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00001440 std::string ResultStr;
Fariborz Jahaniand268b0c2012-02-17 22:20:12 +00001441 if (!ObjCWrittenInterfaces.count(ClassDecl->getCanonicalDecl())) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00001442 // we haven't seen a forward decl - generate a typedef.
Fariborz Jahanian2cc29af2012-03-12 23:58:28 +00001443 RewriteOneForwardClassDecl(ClassDecl, ResultStr);
Fariborz Jahanian5e49eb92012-02-22 18:13:25 +00001444 RewriteIvarOffsetSymbols(ClassDecl, ResultStr);
1445
Fariborz Jahanianff513382012-02-15 22:01:47 +00001446 RewriteObjCInternalStruct(ClassDecl, ResultStr);
Fariborz Jahaniand268b0c2012-02-17 22:20:12 +00001447 // Mark this typedef as having been written into its c++ equivalent.
1448 ObjCWrittenInterfaces.insert(ClassDecl->getCanonicalDecl());
Fariborz Jahanianff513382012-02-15 22:01:47 +00001449
1450 for (ObjCInterfaceDecl::prop_iterator I = ClassDecl->prop_begin(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00001451 E = ClassDecl->prop_end(); I != E; ++I)
David Blaikie40ed2972012-06-06 20:45:41 +00001452 RewriteProperty(*I);
Fariborz Jahanianff513382012-02-15 22:01:47 +00001453 for (ObjCInterfaceDecl::instmeth_iterator
Fariborz Jahanian11671902012-02-07 17:11:38 +00001454 I = ClassDecl->instmeth_begin(), E = ClassDecl->instmeth_end();
Fariborz Jahanianff513382012-02-15 22:01:47 +00001455 I != E; ++I)
1456 RewriteMethodDeclaration(*I);
1457 for (ObjCInterfaceDecl::classmeth_iterator
Fariborz Jahanian11671902012-02-07 17:11:38 +00001458 I = ClassDecl->classmeth_begin(), E = ClassDecl->classmeth_end();
Fariborz Jahanianff513382012-02-15 22:01:47 +00001459 I != E; ++I)
1460 RewriteMethodDeclaration(*I);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001461
Fariborz Jahanianff513382012-02-15 22:01:47 +00001462 // Lastly, comment out the @end.
1463 ReplaceText(ClassDecl->getAtEndRange().getBegin(), strlen("@end"),
Fariborz Jahanian3a65ce32013-04-03 19:11:21 +00001464 "/* @end */\n");
Fariborz Jahanianff513382012-02-15 22:01:47 +00001465 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00001466}
1467
1468Stmt *RewriteModernObjC::RewritePropertyOrImplicitSetter(PseudoObjectExpr *PseudoOp) {
1469 SourceRange OldRange = PseudoOp->getSourceRange();
1470
1471 // We just magically know some things about the structure of this
1472 // expression.
1473 ObjCMessageExpr *OldMsg =
1474 cast<ObjCMessageExpr>(PseudoOp->getSemanticExpr(
1475 PseudoOp->getNumSemanticExprs() - 1));
1476
1477 // Because the rewriter doesn't allow us to rewrite rewritten code,
1478 // we need to suppress rewriting the sub-statements.
Fariborz Jahanian31176b12012-04-10 22:06:54 +00001479 Expr *Base;
1480 SmallVector<Expr*, 2> Args;
Fariborz Jahanian11671902012-02-07 17:11:38 +00001481 {
1482 DisableReplaceStmtScope S(*this);
1483
1484 // Rebuild the base expression if we have one.
1485 Base = 0;
1486 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1487 Base = OldMsg->getInstanceReceiver();
1488 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1489 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1490 }
Fariborz Jahanian31176b12012-04-10 22:06:54 +00001491
1492 unsigned numArgs = OldMsg->getNumArgs();
1493 for (unsigned i = 0; i < numArgs; i++) {
1494 Expr *Arg = OldMsg->getArg(i);
1495 if (isa<OpaqueValueExpr>(Arg))
1496 Arg = cast<OpaqueValueExpr>(Arg)->getSourceExpr();
1497 Arg = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Arg));
1498 Args.push_back(Arg);
1499 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00001500 }
1501
1502 // TODO: avoid this copy.
1503 SmallVector<SourceLocation, 1> SelLocs;
1504 OldMsg->getSelectorLocs(SelLocs);
1505
1506 ObjCMessageExpr *NewMsg = 0;
1507 switch (OldMsg->getReceiverKind()) {
1508 case ObjCMessageExpr::Class:
1509 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1510 OldMsg->getValueKind(),
1511 OldMsg->getLeftLoc(),
1512 OldMsg->getClassReceiverTypeInfo(),
1513 OldMsg->getSelector(),
1514 SelLocs,
1515 OldMsg->getMethodDecl(),
Fariborz Jahanian31176b12012-04-10 22:06:54 +00001516 Args,
Fariborz Jahanian11671902012-02-07 17:11:38 +00001517 OldMsg->getRightLoc(),
1518 OldMsg->isImplicit());
1519 break;
1520
1521 case ObjCMessageExpr::Instance:
1522 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1523 OldMsg->getValueKind(),
1524 OldMsg->getLeftLoc(),
1525 Base,
1526 OldMsg->getSelector(),
1527 SelLocs,
1528 OldMsg->getMethodDecl(),
Fariborz Jahanian31176b12012-04-10 22:06:54 +00001529 Args,
Fariborz Jahanian11671902012-02-07 17:11:38 +00001530 OldMsg->getRightLoc(),
1531 OldMsg->isImplicit());
1532 break;
1533
1534 case ObjCMessageExpr::SuperClass:
1535 case ObjCMessageExpr::SuperInstance:
1536 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1537 OldMsg->getValueKind(),
1538 OldMsg->getLeftLoc(),
1539 OldMsg->getSuperLoc(),
1540 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1541 OldMsg->getSuperType(),
1542 OldMsg->getSelector(),
1543 SelLocs,
1544 OldMsg->getMethodDecl(),
Fariborz Jahanian31176b12012-04-10 22:06:54 +00001545 Args,
Fariborz Jahanian11671902012-02-07 17:11:38 +00001546 OldMsg->getRightLoc(),
1547 OldMsg->isImplicit());
1548 break;
1549 }
1550
1551 Stmt *Replacement = SynthMessageExpr(NewMsg);
1552 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1553 return Replacement;
1554}
1555
1556Stmt *RewriteModernObjC::RewritePropertyOrImplicitGetter(PseudoObjectExpr *PseudoOp) {
1557 SourceRange OldRange = PseudoOp->getSourceRange();
1558
1559 // We just magically know some things about the structure of this
1560 // expression.
1561 ObjCMessageExpr *OldMsg =
1562 cast<ObjCMessageExpr>(PseudoOp->getResultExpr()->IgnoreImplicit());
1563
1564 // Because the rewriter doesn't allow us to rewrite rewritten code,
1565 // we need to suppress rewriting the sub-statements.
1566 Expr *Base = 0;
Fariborz Jahanian31176b12012-04-10 22:06:54 +00001567 SmallVector<Expr*, 1> Args;
Fariborz Jahanian11671902012-02-07 17:11:38 +00001568 {
1569 DisableReplaceStmtScope S(*this);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001570 // Rebuild the base expression if we have one.
1571 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1572 Base = OldMsg->getInstanceReceiver();
1573 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1574 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1575 }
Fariborz Jahanian31176b12012-04-10 22:06:54 +00001576 unsigned numArgs = OldMsg->getNumArgs();
1577 for (unsigned i = 0; i < numArgs; i++) {
1578 Expr *Arg = OldMsg->getArg(i);
1579 if (isa<OpaqueValueExpr>(Arg))
1580 Arg = cast<OpaqueValueExpr>(Arg)->getSourceExpr();
1581 Arg = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Arg));
1582 Args.push_back(Arg);
1583 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00001584 }
1585
1586 // Intentionally empty.
1587 SmallVector<SourceLocation, 1> SelLocs;
Fariborz Jahanian11671902012-02-07 17:11:38 +00001588
1589 ObjCMessageExpr *NewMsg = 0;
1590 switch (OldMsg->getReceiverKind()) {
1591 case ObjCMessageExpr::Class:
1592 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1593 OldMsg->getValueKind(),
1594 OldMsg->getLeftLoc(),
1595 OldMsg->getClassReceiverTypeInfo(),
1596 OldMsg->getSelector(),
1597 SelLocs,
1598 OldMsg->getMethodDecl(),
1599 Args,
1600 OldMsg->getRightLoc(),
1601 OldMsg->isImplicit());
1602 break;
1603
1604 case ObjCMessageExpr::Instance:
1605 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1606 OldMsg->getValueKind(),
1607 OldMsg->getLeftLoc(),
1608 Base,
1609 OldMsg->getSelector(),
1610 SelLocs,
1611 OldMsg->getMethodDecl(),
1612 Args,
1613 OldMsg->getRightLoc(),
1614 OldMsg->isImplicit());
1615 break;
1616
1617 case ObjCMessageExpr::SuperClass:
1618 case ObjCMessageExpr::SuperInstance:
1619 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1620 OldMsg->getValueKind(),
1621 OldMsg->getLeftLoc(),
1622 OldMsg->getSuperLoc(),
1623 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1624 OldMsg->getSuperType(),
1625 OldMsg->getSelector(),
1626 SelLocs,
1627 OldMsg->getMethodDecl(),
1628 Args,
1629 OldMsg->getRightLoc(),
1630 OldMsg->isImplicit());
1631 break;
1632 }
1633
1634 Stmt *Replacement = SynthMessageExpr(NewMsg);
1635 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1636 return Replacement;
1637}
1638
1639/// SynthCountByEnumWithState - To print:
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001640/// ((NSUInteger (*)
1641/// (id, SEL, struct __objcFastEnumerationState *, id *, NSUInteger))
Fariborz Jahanian11671902012-02-07 17:11:38 +00001642/// (void *)objc_msgSend)((id)l_collection,
1643/// sel_registerName(
1644/// "countByEnumeratingWithState:objects:count:"),
1645/// &enumState,
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001646/// (id *)__rw_items, (NSUInteger)16)
Fariborz Jahanian11671902012-02-07 17:11:38 +00001647///
1648void RewriteModernObjC::SynthCountByEnumWithState(std::string &buf) {
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001649 buf += "((_WIN_NSUInteger (*) (id, SEL, struct __objcFastEnumerationState *, "
1650 "id *, _WIN_NSUInteger))(void *)objc_msgSend)";
Fariborz Jahanian11671902012-02-07 17:11:38 +00001651 buf += "\n\t\t";
1652 buf += "((id)l_collection,\n\t\t";
1653 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1654 buf += "\n\t\t";
1655 buf += "&enumState, "
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001656 "(id *)__rw_items, (_WIN_NSUInteger)16)";
Fariborz Jahanian11671902012-02-07 17:11:38 +00001657}
1658
1659/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1660/// statement to exit to its outer synthesized loop.
1661///
1662Stmt *RewriteModernObjC::RewriteBreakStmt(BreakStmt *S) {
1663 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1664 return S;
1665 // replace break with goto __break_label
1666 std::string buf;
1667
1668 SourceLocation startLoc = S->getLocStart();
1669 buf = "goto __break_label_";
1670 buf += utostr(ObjCBcLabelNo.back());
1671 ReplaceText(startLoc, strlen("break"), buf);
1672
1673 return 0;
1674}
1675
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00001676void RewriteModernObjC::ConvertSourceLocationToLineDirective(
1677 SourceLocation Loc,
1678 std::string &LineString) {
Fariborz Jahaniane4c7e852013-02-08 00:27:34 +00001679 if (Loc.isFileID() && GenerateLineInfo) {
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00001680 LineString += "\n#line ";
1681 PresumedLoc PLoc = SM->getPresumedLoc(Loc);
1682 LineString += utostr(PLoc.getLine());
1683 LineString += " \"";
1684 LineString += Lexer::Stringify(PLoc.getFilename());
1685 LineString += "\"\n";
1686 }
1687}
1688
Fariborz Jahanian11671902012-02-07 17:11:38 +00001689/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1690/// statement to continue with its inner synthesized loop.
1691///
1692Stmt *RewriteModernObjC::RewriteContinueStmt(ContinueStmt *S) {
1693 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1694 return S;
1695 // replace continue with goto __continue_label
1696 std::string buf;
1697
1698 SourceLocation startLoc = S->getLocStart();
1699 buf = "goto __continue_label_";
1700 buf += utostr(ObjCBcLabelNo.back());
1701 ReplaceText(startLoc, strlen("continue"), buf);
1702
1703 return 0;
1704}
1705
1706/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
1707/// It rewrites:
1708/// for ( type elem in collection) { stmts; }
1709
1710/// Into:
1711/// {
1712/// type elem;
1713/// struct __objcFastEnumerationState enumState = { 0 };
1714/// id __rw_items[16];
1715/// id l_collection = (id)collection;
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001716/// NSUInteger limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian11671902012-02-07 17:11:38 +00001717/// objects:__rw_items count:16];
1718/// if (limit) {
1719/// unsigned long startMutations = *enumState.mutationsPtr;
1720/// do {
1721/// unsigned long counter = 0;
1722/// do {
1723/// if (startMutations != *enumState.mutationsPtr)
1724/// objc_enumerationMutation(l_collection);
1725/// elem = (type)enumState.itemsPtr[counter++];
1726/// stmts;
1727/// __continue_label: ;
1728/// } while (counter < limit);
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001729/// } while ((limit = [l_collection countByEnumeratingWithState:&enumState
1730/// objects:__rw_items count:16]));
Fariborz Jahanian11671902012-02-07 17:11:38 +00001731/// elem = nil;
1732/// __break_label: ;
1733/// }
1734/// else
1735/// elem = nil;
1736/// }
1737///
1738Stmt *RewriteModernObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
1739 SourceLocation OrigEnd) {
1740 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
1741 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
1742 "ObjCForCollectionStmt Statement stack mismatch");
1743 assert(!ObjCBcLabelNo.empty() &&
1744 "ObjCForCollectionStmt - Label No stack empty");
1745
1746 SourceLocation startLoc = S->getLocStart();
1747 const char *startBuf = SM->getCharacterData(startLoc);
1748 StringRef elementName;
1749 std::string elementTypeAsString;
1750 std::string buf;
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00001751 // line directive first.
1752 SourceLocation ForEachLoc = S->getForLoc();
1753 ConvertSourceLocationToLineDirective(ForEachLoc, buf);
1754 buf += "{\n\t";
Fariborz Jahanian11671902012-02-07 17:11:38 +00001755 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1756 // type elem;
1757 NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
1758 QualType ElementType = cast<ValueDecl>(D)->getType();
1759 if (ElementType->isObjCQualifiedIdType() ||
1760 ElementType->isObjCQualifiedInterfaceType())
1761 // Simply use 'id' for all qualified types.
1762 elementTypeAsString = "id";
1763 else
1764 elementTypeAsString = ElementType.getAsString(Context->getPrintingPolicy());
1765 buf += elementTypeAsString;
1766 buf += " ";
1767 elementName = D->getName();
1768 buf += elementName;
1769 buf += ";\n\t";
1770 }
1771 else {
1772 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
1773 elementName = DR->getDecl()->getName();
1774 ValueDecl *VD = cast<ValueDecl>(DR->getDecl());
1775 if (VD->getType()->isObjCQualifiedIdType() ||
1776 VD->getType()->isObjCQualifiedInterfaceType())
1777 // Simply use 'id' for all qualified types.
1778 elementTypeAsString = "id";
1779 else
1780 elementTypeAsString = VD->getType().getAsString(Context->getPrintingPolicy());
1781 }
1782
1783 // struct __objcFastEnumerationState enumState = { 0 };
1784 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1785 // id __rw_items[16];
1786 buf += "id __rw_items[16];\n\t";
1787 // id l_collection = (id)
1788 buf += "id l_collection = (id)";
1789 // Find start location of 'collection' the hard way!
1790 const char *startCollectionBuf = startBuf;
1791 startCollectionBuf += 3; // skip 'for'
1792 startCollectionBuf = strchr(startCollectionBuf, '(');
1793 startCollectionBuf++; // skip '('
1794 // find 'in' and skip it.
1795 while (*startCollectionBuf != ' ' ||
1796 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1797 (*(startCollectionBuf+3) != ' ' &&
1798 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1799 startCollectionBuf++;
1800 startCollectionBuf += 3;
1801
1802 // Replace: "for (type element in" with string constructed thus far.
1803 ReplaceText(startLoc, startCollectionBuf - startBuf, buf);
1804 // Replace ')' in for '(' type elem in collection ')' with ';'
1805 SourceLocation rightParenLoc = S->getRParenLoc();
1806 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1807 SourceLocation lparenLoc = startLoc.getLocWithOffset(rparenBuf-startBuf);
1808 buf = ";\n\t";
1809
1810 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1811 // objects:__rw_items count:16];
1812 // which is synthesized into:
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001813 // NSUInteger limit =
1814 // ((NSUInteger (*)
1815 // (id, SEL, struct __objcFastEnumerationState *, id *, NSUInteger))
Fariborz Jahanian11671902012-02-07 17:11:38 +00001816 // (void *)objc_msgSend)((id)l_collection,
1817 // sel_registerName(
1818 // "countByEnumeratingWithState:objects:count:"),
1819 // (struct __objcFastEnumerationState *)&state,
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001820 // (id *)__rw_items, (NSUInteger)16);
1821 buf += "_WIN_NSUInteger limit =\n\t\t";
Fariborz Jahanian11671902012-02-07 17:11:38 +00001822 SynthCountByEnumWithState(buf);
1823 buf += ";\n\t";
1824 /// if (limit) {
1825 /// unsigned long startMutations = *enumState.mutationsPtr;
1826 /// do {
1827 /// unsigned long counter = 0;
1828 /// do {
1829 /// if (startMutations != *enumState.mutationsPtr)
1830 /// objc_enumerationMutation(l_collection);
1831 /// elem = (type)enumState.itemsPtr[counter++];
1832 buf += "if (limit) {\n\t";
1833 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1834 buf += "do {\n\t\t";
1835 buf += "unsigned long counter = 0;\n\t\t";
1836 buf += "do {\n\t\t\t";
1837 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1838 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1839 buf += elementName;
1840 buf += " = (";
1841 buf += elementTypeAsString;
1842 buf += ")enumState.itemsPtr[counter++];";
1843 // Replace ')' in for '(' type elem in collection ')' with all of these.
1844 ReplaceText(lparenLoc, 1, buf);
1845
1846 /// __continue_label: ;
1847 /// } while (counter < limit);
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001848 /// } while ((limit = [l_collection countByEnumeratingWithState:&enumState
1849 /// objects:__rw_items count:16]));
Fariborz Jahanian11671902012-02-07 17:11:38 +00001850 /// elem = nil;
1851 /// __break_label: ;
1852 /// }
1853 /// else
1854 /// elem = nil;
1855 /// }
1856 ///
1857 buf = ";\n\t";
1858 buf += "__continue_label_";
1859 buf += utostr(ObjCBcLabelNo.back());
1860 buf += ": ;";
1861 buf += "\n\t\t";
1862 buf += "} while (counter < limit);\n\t";
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001863 buf += "} while ((limit = ";
Fariborz Jahanian11671902012-02-07 17:11:38 +00001864 SynthCountByEnumWithState(buf);
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001865 buf += "));\n\t";
Fariborz Jahanian11671902012-02-07 17:11:38 +00001866 buf += elementName;
1867 buf += " = ((";
1868 buf += elementTypeAsString;
1869 buf += ")0);\n\t";
1870 buf += "__break_label_";
1871 buf += utostr(ObjCBcLabelNo.back());
1872 buf += ": ;\n\t";
1873 buf += "}\n\t";
1874 buf += "else\n\t\t";
1875 buf += elementName;
1876 buf += " = ((";
1877 buf += elementTypeAsString;
1878 buf += ")0);\n\t";
1879 buf += "}\n";
1880
1881 // Insert all these *after* the statement body.
1882 // FIXME: If this should support Obj-C++, support CXXTryStmt
1883 if (isa<CompoundStmt>(S->getBody())) {
1884 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(1);
1885 InsertText(endBodyLoc, buf);
1886 } else {
1887 /* Need to treat single statements specially. For example:
1888 *
1889 * for (A *a in b) if (stuff()) break;
1890 * for (A *a in b) xxxyy;
1891 *
1892 * The following code simply scans ahead to the semi to find the actual end.
1893 */
1894 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1895 const char *semiBuf = strchr(stmtBuf, ';');
1896 assert(semiBuf && "Can't find ';'");
1897 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(semiBuf-stmtBuf+1);
1898 InsertText(endBodyLoc, buf);
1899 }
1900 Stmts.pop_back();
1901 ObjCBcLabelNo.pop_back();
1902 return 0;
1903}
1904
Fariborz Jahanianfe6268e2012-03-16 21:33:16 +00001905static void Write_RethrowObject(std::string &buf) {
1906 buf += "{ struct _FIN { _FIN(id reth) : rethrow(reth) {}\n";
1907 buf += "\t~_FIN() { if (rethrow) objc_exception_throw(rethrow); }\n";
1908 buf += "\tid rethrow;\n";
1909 buf += "\t} _fin_force_rethow(_rethrow);";
1910}
1911
Fariborz Jahanian11671902012-02-07 17:11:38 +00001912/// RewriteObjCSynchronizedStmt -
1913/// This routine rewrites @synchronized(expr) stmt;
1914/// into:
1915/// objc_sync_enter(expr);
1916/// @try stmt @finally { objc_sync_exit(expr); }
1917///
1918Stmt *RewriteModernObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
1919 // Get the start location and compute the semi location.
1920 SourceLocation startLoc = S->getLocStart();
1921 const char *startBuf = SM->getCharacterData(startLoc);
1922
1923 assert((*startBuf == '@') && "bogus @synchronized location");
1924
1925 std::string buf;
Fariborz Jahaniane030a632012-11-07 00:43:05 +00001926 SourceLocation SynchLoc = S->getAtSynchronizedLoc();
1927 ConvertSourceLocationToLineDirective(SynchLoc, buf);
Fariborz Jahanianff0c4602013-09-17 17:51:48 +00001928 buf += "{ id _rethrow = 0; id _sync_obj = (id)";
Fariborz Jahanianfe6268e2012-03-16 21:33:16 +00001929
Fariborz Jahanian11671902012-02-07 17:11:38 +00001930 const char *lparenBuf = startBuf;
1931 while (*lparenBuf != '(') lparenBuf++;
1932 ReplaceText(startLoc, lparenBuf-startBuf+1, buf);
Fariborz Jahaniane8810762012-03-17 17:46:02 +00001933
1934 buf = "; objc_sync_enter(_sync_obj);\n";
1935 buf += "try {\n\tstruct _SYNC_EXIT { _SYNC_EXIT(id arg) : sync_exit(arg) {}";
1936 buf += "\n\t~_SYNC_EXIT() {objc_sync_exit(sync_exit);}";
1937 buf += "\n\tid sync_exit;";
1938 buf += "\n\t} _sync_exit(_sync_obj);\n";
1939
1940 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1941 // the sync expression is typically a message expression that's already
1942 // been rewritten! (which implies the SourceLocation's are invalid).
1943 SourceLocation RParenExprLoc = S->getSynchBody()->getLocStart();
1944 const char *RParenExprLocBuf = SM->getCharacterData(RParenExprLoc);
1945 while (*RParenExprLocBuf != ')') RParenExprLocBuf--;
1946 RParenExprLoc = startLoc.getLocWithOffset(RParenExprLocBuf-startBuf);
1947
1948 SourceLocation LBranceLoc = S->getSynchBody()->getLocStart();
1949 const char *LBraceLocBuf = SM->getCharacterData(LBranceLoc);
1950 assert (*LBraceLocBuf == '{');
1951 ReplaceText(RParenExprLoc, (LBraceLocBuf - SM->getCharacterData(RParenExprLoc) + 1), buf);
Fariborz Jahanianfe6268e2012-03-16 21:33:16 +00001952
Fariborz Jahanian1d24a0252012-03-16 21:43:45 +00001953 SourceLocation startRBraceLoc = S->getSynchBody()->getLocEnd();
Matt Beaumont-Gay6e177d32012-03-16 22:20:39 +00001954 assert((*SM->getCharacterData(startRBraceLoc) == '}') &&
1955 "bogus @synchronized block");
Fariborz Jahanianfe6268e2012-03-16 21:33:16 +00001956
1957 buf = "} catch (id e) {_rethrow = e;}\n";
1958 Write_RethrowObject(buf);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001959 buf += "}\n";
Fariborz Jahanianfe6268e2012-03-16 21:33:16 +00001960 buf += "}\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00001961
Fariborz Jahanian1d24a0252012-03-16 21:43:45 +00001962 ReplaceText(startRBraceLoc, 1, buf);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001963
Fariborz Jahanian11671902012-02-07 17:11:38 +00001964 return 0;
1965}
1966
1967void RewriteModernObjC::WarnAboutReturnGotoStmts(Stmt *S)
1968{
1969 // Perform a bottom up traversal of all children.
1970 for (Stmt::child_range CI = S->children(); CI; ++CI)
1971 if (*CI)
1972 WarnAboutReturnGotoStmts(*CI);
1973
1974 if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
1975 Diags.Report(Context->getFullLoc(S->getLocStart()),
1976 TryFinallyContainsReturnDiag);
1977 }
1978 return;
1979}
1980
Fariborz Jahanian9b43c3f2012-05-23 23:47:20 +00001981Stmt *RewriteModernObjC::RewriteObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S) {
1982 SourceLocation startLoc = S->getAtLoc();
1983 ReplaceText(startLoc, strlen("@autoreleasepool"), "/* @autoreleasepool */");
Fariborz Jahanianc37a1d62012-05-24 22:59:56 +00001984 ReplaceText(S->getSubStmt()->getLocStart(), 1,
1985 "{ __AtAutoreleasePool __autoreleasepool; ");
Fariborz Jahanian9b43c3f2012-05-23 23:47:20 +00001986
1987 return 0;
1988}
1989
Fariborz Jahanian11671902012-02-07 17:11:38 +00001990Stmt *RewriteModernObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Fariborz Jahanian3b71b172012-03-15 22:42:15 +00001991 ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt();
Fariborz Jahanianb960db42012-03-15 23:50:33 +00001992 bool noCatch = S->getNumCatchStmts() == 0;
Fariborz Jahanian3b71b172012-03-15 22:42:15 +00001993 std::string buf;
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00001994 SourceLocation TryLocation = S->getAtTryLoc();
1995 ConvertSourceLocationToLineDirective(TryLocation, buf);
Fariborz Jahanian3b71b172012-03-15 22:42:15 +00001996
1997 if (finalStmt) {
Fariborz Jahanianb960db42012-03-15 23:50:33 +00001998 if (noCatch)
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00001999 buf += "{ id volatile _rethrow = 0;\n";
Fariborz Jahanianb960db42012-03-15 23:50:33 +00002000 else {
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00002001 buf += "{ id volatile _rethrow = 0;\ntry {\n";
Fariborz Jahanianb960db42012-03-15 23:50:33 +00002002 }
Fariborz Jahanian3b71b172012-03-15 22:42:15 +00002003 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00002004 // Get the start location and compute the semi location.
2005 SourceLocation startLoc = S->getLocStart();
2006 const char *startBuf = SM->getCharacterData(startLoc);
2007
2008 assert((*startBuf == '@') && "bogus @try location");
Fariborz Jahanian3b71b172012-03-15 22:42:15 +00002009 if (finalStmt)
2010 ReplaceText(startLoc, 1, buf);
2011 else
2012 // @try -> try
2013 ReplaceText(startLoc, 1, "");
2014
Fariborz Jahanian11671902012-02-07 17:11:38 +00002015 for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I) {
2016 ObjCAtCatchStmt *Catch = S->getCatchStmt(I);
Fariborz Jahanianf232bb42012-03-15 20:11:10 +00002017 VarDecl *catchDecl = Catch->getCatchParamDecl();
Fariborz Jahanian2cc29af2012-03-12 23:58:28 +00002018
Fariborz Jahanian11671902012-02-07 17:11:38 +00002019 startLoc = Catch->getLocStart();
Fariborz Jahanianf232bb42012-03-15 20:11:10 +00002020 bool AtRemoved = false;
2021 if (catchDecl) {
2022 QualType t = catchDecl->getType();
2023 if (const ObjCObjectPointerType *Ptr = t->getAs<ObjCObjectPointerType>()) {
2024 // Should be a pointer to a class.
2025 ObjCInterfaceDecl *IDecl = Ptr->getObjectType()->getInterface();
2026 if (IDecl) {
2027 std::string Result;
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00002028 ConvertSourceLocationToLineDirective(Catch->getLocStart(), Result);
2029
Fariborz Jahanianf232bb42012-03-15 20:11:10 +00002030 startBuf = SM->getCharacterData(startLoc);
2031 assert((*startBuf == '@') && "bogus @catch location");
2032 SourceLocation rParenLoc = Catch->getRParenLoc();
2033 const char *rParenBuf = SM->getCharacterData(rParenLoc);
2034
2035 // _objc_exc_Foo *_e as argument to catch.
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00002036 Result += "catch (_objc_exc_"; Result += IDecl->getNameAsString();
Fariborz Jahanianf232bb42012-03-15 20:11:10 +00002037 Result += " *_"; Result += catchDecl->getNameAsString();
2038 Result += ")";
2039 ReplaceText(startLoc, rParenBuf-startBuf+1, Result);
2040 // Foo *e = (Foo *)_e;
2041 Result.clear();
2042 Result = "{ ";
2043 Result += IDecl->getNameAsString();
2044 Result += " *"; Result += catchDecl->getNameAsString();
2045 Result += " = ("; Result += IDecl->getNameAsString(); Result += "*)";
2046 Result += "_"; Result += catchDecl->getNameAsString();
2047
2048 Result += "; ";
2049 SourceLocation lBraceLoc = Catch->getCatchBody()->getLocStart();
2050 ReplaceText(lBraceLoc, 1, Result);
2051 AtRemoved = true;
2052 }
2053 }
2054 }
2055 if (!AtRemoved)
2056 // @catch -> catch
2057 ReplaceText(startLoc, 1, "");
Fariborz Jahanian2cc29af2012-03-12 23:58:28 +00002058
Fariborz Jahanian11671902012-02-07 17:11:38 +00002059 }
Fariborz Jahanianb960db42012-03-15 23:50:33 +00002060 if (finalStmt) {
2061 buf.clear();
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00002062 SourceLocation FinallyLoc = finalStmt->getLocStart();
2063
2064 if (noCatch) {
2065 ConvertSourceLocationToLineDirective(FinallyLoc, buf);
2066 buf += "catch (id e) {_rethrow = e;}\n";
2067 }
2068 else {
2069 buf += "}\n";
2070 ConvertSourceLocationToLineDirective(FinallyLoc, buf);
2071 buf += "catch (id e) {_rethrow = e;}\n";
2072 }
2073
Fariborz Jahanianb960db42012-03-15 23:50:33 +00002074 SourceLocation startFinalLoc = finalStmt->getLocStart();
2075 ReplaceText(startFinalLoc, 8, buf);
2076 Stmt *body = finalStmt->getFinallyBody();
2077 SourceLocation startFinalBodyLoc = body->getLocStart();
2078 buf.clear();
Fariborz Jahanianfe6268e2012-03-16 21:33:16 +00002079 Write_RethrowObject(buf);
Fariborz Jahanianb960db42012-03-15 23:50:33 +00002080 ReplaceText(startFinalBodyLoc, 1, buf);
2081
2082 SourceLocation endFinalBodyLoc = body->getLocEnd();
2083 ReplaceText(endFinalBodyLoc, 1, "}\n}");
Fariborz Jahaniane8810762012-03-17 17:46:02 +00002084 // Now check for any return/continue/go statements within the @try.
2085 WarnAboutReturnGotoStmts(S->getTryBody());
Fariborz Jahanianb960db42012-03-15 23:50:33 +00002086 }
2087
Fariborz Jahanian11671902012-02-07 17:11:38 +00002088 return 0;
2089}
2090
2091// This can't be done with ReplaceStmt(S, ThrowExpr), since
2092// the throw expression is typically a message expression that's already
2093// been rewritten! (which implies the SourceLocation's are invalid).
2094Stmt *RewriteModernObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
2095 // Get the start location and compute the semi location.
2096 SourceLocation startLoc = S->getLocStart();
2097 const char *startBuf = SM->getCharacterData(startLoc);
2098
2099 assert((*startBuf == '@') && "bogus @throw location");
2100
2101 std::string buf;
2102 /* void objc_exception_throw(id) __attribute__((noreturn)); */
2103 if (S->getThrowExpr())
2104 buf = "objc_exception_throw(";
Fariborz Jahanian52fe6a02012-03-16 16:52:06 +00002105 else
2106 buf = "throw";
Fariborz Jahanian11671902012-02-07 17:11:38 +00002107
2108 // handle "@ throw" correctly.
2109 const char *wBuf = strchr(startBuf, 'w');
2110 assert((*wBuf == 'w') && "@throw: can't find 'w'");
2111 ReplaceText(startLoc, wBuf-startBuf+1, buf);
2112
Fariborz Jahanianb0fdab22013-02-11 19:30:33 +00002113 SourceLocation endLoc = S->getLocEnd();
2114 const char *endBuf = SM->getCharacterData(endLoc);
2115 const char *semiBuf = strchr(endBuf, ';');
Fariborz Jahanian11671902012-02-07 17:11:38 +00002116 assert((*semiBuf == ';') && "@throw: can't find ';'");
2117 SourceLocation semiLoc = startLoc.getLocWithOffset(semiBuf-startBuf);
Fariborz Jahanian52fe6a02012-03-16 16:52:06 +00002118 if (S->getThrowExpr())
2119 ReplaceText(semiLoc, 1, ");");
Fariborz Jahanian11671902012-02-07 17:11:38 +00002120 return 0;
2121}
2122
2123Stmt *RewriteModernObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
2124 // Create a new string expression.
2125 QualType StrType = Context->getPointerType(Context->CharTy);
2126 std::string StrEncoding;
2127 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
2128 Expr *Replacement = StringLiteral::Create(*Context, StrEncoding,
2129 StringLiteral::Ascii, false,
2130 StrType, SourceLocation());
2131 ReplaceStmt(Exp, Replacement);
2132
2133 // Replace this subexpr in the parent.
2134 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2135 return Replacement;
2136}
2137
2138Stmt *RewriteModernObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
2139 if (!SelGetUidFunctionDecl)
2140 SynthSelGetUidFunctionDecl();
2141 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
2142 // Create a call to sel_registerName("selName").
2143 SmallVector<Expr*, 8> SelExprs;
2144 QualType argType = Context->getPointerType(Context->CharTy);
2145 SelExprs.push_back(StringLiteral::Create(*Context,
2146 Exp->getSelector().getAsString(),
2147 StringLiteral::Ascii, false,
2148 argType, SourceLocation()));
2149 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2150 &SelExprs[0], SelExprs.size());
2151 ReplaceStmt(Exp, SelExp);
2152 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2153 return SelExp;
2154}
2155
2156CallExpr *RewriteModernObjC::SynthesizeCallToFunctionDecl(
2157 FunctionDecl *FD, Expr **args, unsigned nargs, SourceLocation StartLoc,
2158 SourceLocation EndLoc) {
2159 // Get the type, we will need to reference it in a couple spots.
2160 QualType msgSendType = FD->getType();
2161
2162 // Create a reference to the objc_msgSend() declaration.
2163 DeclRefExpr *DRE =
John McCall113bee02012-03-10 09:33:50 +00002164 new (Context) DeclRefExpr(FD, false, msgSendType, VK_LValue, SourceLocation());
Fariborz Jahanian11671902012-02-07 17:11:38 +00002165
2166 // Now, we cast the reference to a pointer to the objc_msgSend type.
2167 QualType pToFunc = Context->getPointerType(msgSendType);
2168 ImplicitCastExpr *ICE =
2169 ImplicitCastExpr::Create(*Context, pToFunc, CK_FunctionToPointerDecay,
2170 DRE, 0, VK_RValue);
2171
2172 const FunctionType *FT = msgSendType->getAs<FunctionType>();
2173
2174 CallExpr *Exp =
Benjamin Kramerc215e762012-08-24 11:54:20 +00002175 new (Context) CallExpr(*Context, ICE, llvm::makeArrayRef(args, nargs),
Fariborz Jahanian11671902012-02-07 17:11:38 +00002176 FT->getCallResultType(*Context),
2177 VK_RValue, EndLoc);
2178 return Exp;
2179}
2180
2181static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
2182 const char *&startRef, const char *&endRef) {
2183 while (startBuf < endBuf) {
2184 if (*startBuf == '<')
2185 startRef = startBuf; // mark the start.
2186 if (*startBuf == '>') {
2187 if (startRef && *startRef == '<') {
2188 endRef = startBuf; // mark the end.
2189 return true;
2190 }
2191 return false;
2192 }
2193 startBuf++;
2194 }
2195 return false;
2196}
2197
2198static void scanToNextArgument(const char *&argRef) {
2199 int angle = 0;
2200 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
2201 if (*argRef == '<')
2202 angle++;
2203 else if (*argRef == '>')
2204 angle--;
2205 argRef++;
2206 }
2207 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
2208}
2209
2210bool RewriteModernObjC::needToScanForQualifiers(QualType T) {
2211 if (T->isObjCQualifiedIdType())
2212 return true;
2213 if (const PointerType *PT = T->getAs<PointerType>()) {
2214 if (PT->getPointeeType()->isObjCQualifiedIdType())
2215 return true;
2216 }
2217 if (T->isObjCObjectPointerType()) {
2218 T = T->getPointeeType();
2219 return T->isObjCQualifiedInterfaceType();
2220 }
2221 if (T->isArrayType()) {
2222 QualType ElemTy = Context->getBaseElementType(T);
2223 return needToScanForQualifiers(ElemTy);
2224 }
2225 return false;
2226}
2227
2228void RewriteModernObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
2229 QualType Type = E->getType();
2230 if (needToScanForQualifiers(Type)) {
2231 SourceLocation Loc, EndLoc;
2232
2233 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
2234 Loc = ECE->getLParenLoc();
2235 EndLoc = ECE->getRParenLoc();
2236 } else {
2237 Loc = E->getLocStart();
2238 EndLoc = E->getLocEnd();
2239 }
2240 // This will defend against trying to rewrite synthesized expressions.
2241 if (Loc.isInvalid() || EndLoc.isInvalid())
2242 return;
2243
2244 const char *startBuf = SM->getCharacterData(Loc);
2245 const char *endBuf = SM->getCharacterData(EndLoc);
2246 const char *startRef = 0, *endRef = 0;
2247 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2248 // Get the locations of the startRef, endRef.
2249 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-startBuf);
2250 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-startBuf+1);
2251 // Comment out the protocol references.
2252 InsertText(LessLoc, "/*");
2253 InsertText(GreaterLoc, "*/");
2254 }
2255 }
2256}
2257
2258void RewriteModernObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
2259 SourceLocation Loc;
2260 QualType Type;
2261 const FunctionProtoType *proto = 0;
2262 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
2263 Loc = VD->getLocation();
2264 Type = VD->getType();
2265 }
2266 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
2267 Loc = FD->getLocation();
2268 // Check for ObjC 'id' and class types that have been adorned with protocol
2269 // information (id<p>, C<p>*). The protocol references need to be rewritten!
2270 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2271 assert(funcType && "missing function type");
2272 proto = dyn_cast<FunctionProtoType>(funcType);
2273 if (!proto)
2274 return;
2275 Type = proto->getResultType();
2276 }
2277 else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
2278 Loc = FD->getLocation();
2279 Type = FD->getType();
2280 }
Fariborz Jahanian3a65ce32013-04-03 19:11:21 +00002281 else if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(Dcl)) {
2282 Loc = TD->getLocation();
2283 Type = TD->getUnderlyingType();
2284 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00002285 else
2286 return;
2287
2288 if (needToScanForQualifiers(Type)) {
2289 // Since types are unique, we need to scan the buffer.
2290
2291 const char *endBuf = SM->getCharacterData(Loc);
2292 const char *startBuf = endBuf;
2293 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
2294 startBuf--; // scan backward (from the decl location) for return type.
2295 const char *startRef = 0, *endRef = 0;
2296 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2297 // Get the locations of the startRef, endRef.
2298 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-endBuf);
2299 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-endBuf+1);
2300 // Comment out the protocol references.
2301 InsertText(LessLoc, "/*");
2302 InsertText(GreaterLoc, "*/");
2303 }
2304 }
2305 if (!proto)
2306 return; // most likely, was a variable
2307 // Now check arguments.
2308 const char *startBuf = SM->getCharacterData(Loc);
2309 const char *startFuncBuf = startBuf;
Alp Toker9cacbab2014-01-20 20:26:09 +00002310 for (unsigned i = 0; i < proto->getNumParams(); i++) {
2311 if (needToScanForQualifiers(proto->getParamType(i))) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00002312 // Since types are unique, we need to scan the buffer.
2313
2314 const char *endBuf = startBuf;
2315 // scan forward (from the decl location) for argument types.
2316 scanToNextArgument(endBuf);
2317 const char *startRef = 0, *endRef = 0;
2318 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2319 // Get the locations of the startRef, endRef.
2320 SourceLocation LessLoc =
2321 Loc.getLocWithOffset(startRef-startFuncBuf);
2322 SourceLocation GreaterLoc =
2323 Loc.getLocWithOffset(endRef-startFuncBuf+1);
2324 // Comment out the protocol references.
2325 InsertText(LessLoc, "/*");
2326 InsertText(GreaterLoc, "*/");
2327 }
2328 startBuf = ++endBuf;
2329 }
2330 else {
2331 // If the function name is derived from a macro expansion, then the
2332 // argument buffer will not follow the name. Need to speak with Chris.
2333 while (*startBuf && *startBuf != ')' && *startBuf != ',')
2334 startBuf++; // scan forward (from the decl location) for argument types.
2335 startBuf++;
2336 }
2337 }
2338}
2339
2340void RewriteModernObjC::RewriteTypeOfDecl(VarDecl *ND) {
2341 QualType QT = ND->getType();
2342 const Type* TypePtr = QT->getAs<Type>();
2343 if (!isa<TypeOfExprType>(TypePtr))
2344 return;
2345 while (isa<TypeOfExprType>(TypePtr)) {
2346 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
2347 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
2348 TypePtr = QT->getAs<Type>();
2349 }
2350 // FIXME. This will not work for multiple declarators; as in:
2351 // __typeof__(a) b,c,d;
2352 std::string TypeAsString(QT.getAsString(Context->getPrintingPolicy()));
2353 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
2354 const char *startBuf = SM->getCharacterData(DeclLoc);
2355 if (ND->getInit()) {
2356 std::string Name(ND->getNameAsString());
2357 TypeAsString += " " + Name + " = ";
2358 Expr *E = ND->getInit();
2359 SourceLocation startLoc;
2360 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
2361 startLoc = ECE->getLParenLoc();
2362 else
2363 startLoc = E->getLocStart();
2364 startLoc = SM->getExpansionLoc(startLoc);
2365 const char *endBuf = SM->getCharacterData(startLoc);
2366 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
2367 }
2368 else {
2369 SourceLocation X = ND->getLocEnd();
2370 X = SM->getExpansionLoc(X);
2371 const char *endBuf = SM->getCharacterData(X);
2372 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
2373 }
2374}
2375
2376// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
2377void RewriteModernObjC::SynthSelGetUidFunctionDecl() {
2378 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
2379 SmallVector<QualType, 16> ArgTys;
2380 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2381 QualType getFuncType =
Jordan Rose5c382722013-03-08 21:51:21 +00002382 getSimpleFunctionType(Context->getObjCSelType(), ArgTys);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002383 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002384 SourceLocation(),
2385 SourceLocation(),
2386 SelGetUidIdent, getFuncType, 0,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002387 SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002388}
2389
2390void RewriteModernObjC::RewriteFunctionDecl(FunctionDecl *FD) {
2391 // declared in <objc/objc.h>
2392 if (FD->getIdentifier() &&
2393 FD->getName() == "sel_registerName") {
2394 SelGetUidFunctionDecl = FD;
2395 return;
2396 }
2397 RewriteObjCQualifiedInterfaceTypes(FD);
2398}
2399
2400void RewriteModernObjC::RewriteBlockPointerType(std::string& Str, QualType Type) {
2401 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
2402 const char *argPtr = TypeString.c_str();
2403 if (!strchr(argPtr, '^')) {
2404 Str += TypeString;
2405 return;
2406 }
2407 while (*argPtr) {
2408 Str += (*argPtr == '^' ? '*' : *argPtr);
2409 argPtr++;
2410 }
2411}
2412
2413// FIXME. Consolidate this routine with RewriteBlockPointerType.
2414void RewriteModernObjC::RewriteBlockPointerTypeVariable(std::string& Str,
2415 ValueDecl *VD) {
2416 QualType Type = VD->getType();
2417 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
2418 const char *argPtr = TypeString.c_str();
2419 int paren = 0;
2420 while (*argPtr) {
2421 switch (*argPtr) {
2422 case '(':
2423 Str += *argPtr;
2424 paren++;
2425 break;
2426 case ')':
2427 Str += *argPtr;
2428 paren--;
2429 break;
2430 case '^':
2431 Str += '*';
2432 if (paren == 1)
2433 Str += VD->getNameAsString();
2434 break;
2435 default:
2436 Str += *argPtr;
2437 break;
2438 }
2439 argPtr++;
2440 }
2441}
2442
Fariborz Jahanianca357d92012-04-19 00:50:01 +00002443void RewriteModernObjC::RewriteBlockLiteralFunctionDecl(FunctionDecl *FD) {
2444 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
2445 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2446 const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(funcType);
2447 if (!proto)
2448 return;
2449 QualType Type = proto->getResultType();
2450 std::string FdStr = Type.getAsString(Context->getPrintingPolicy());
2451 FdStr += " ";
2452 FdStr += FD->getName();
2453 FdStr += "(";
Alp Toker9cacbab2014-01-20 20:26:09 +00002454 unsigned numArgs = proto->getNumParams();
Fariborz Jahanianca357d92012-04-19 00:50:01 +00002455 for (unsigned i = 0; i < numArgs; i++) {
Alp Toker9cacbab2014-01-20 20:26:09 +00002456 QualType ArgType = proto->getParamType(i);
Fariborz Jahanianca357d92012-04-19 00:50:01 +00002457 RewriteBlockPointerType(FdStr, ArgType);
2458 if (i+1 < numArgs)
2459 FdStr += ", ";
2460 }
Fariborz Jahaniandf0577d2012-04-19 16:30:28 +00002461 if (FD->isVariadic()) {
2462 FdStr += (numArgs > 0) ? ", ...);\n" : "...);\n";
2463 }
2464 else
2465 FdStr += ");\n";
Fariborz Jahanianca357d92012-04-19 00:50:01 +00002466 InsertText(FunLocStart, FdStr);
2467}
2468
Benjamin Kramer60509af2013-09-09 14:48:42 +00002469// SynthSuperConstructorFunctionDecl - id __rw_objc_super(id obj, id super);
2470void RewriteModernObjC::SynthSuperConstructorFunctionDecl() {
2471 if (SuperConstructorFunctionDecl)
Fariborz Jahanian11671902012-02-07 17:11:38 +00002472 return;
2473 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
2474 SmallVector<QualType, 16> ArgTys;
2475 QualType argT = Context->getObjCIdType();
2476 assert(!argT.isNull() && "Can't find 'id' type");
2477 ArgTys.push_back(argT);
2478 ArgTys.push_back(argT);
2479 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002480 ArgTys);
Benjamin Kramer60509af2013-09-09 14:48:42 +00002481 SuperConstructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002482 SourceLocation(),
2483 SourceLocation(),
2484 msgSendIdent, msgSendType,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002485 0, SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002486}
2487
2488// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
2489void RewriteModernObjC::SynthMsgSendFunctionDecl() {
2490 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
2491 SmallVector<QualType, 16> ArgTys;
2492 QualType argT = Context->getObjCIdType();
2493 assert(!argT.isNull() && "Can't find 'id' type");
2494 ArgTys.push_back(argT);
2495 argT = Context->getObjCSelType();
2496 assert(!argT.isNull() && "Can't find 'SEL' type");
2497 ArgTys.push_back(argT);
2498 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002499 ArgTys, /*isVariadic=*/true);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002500 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002501 SourceLocation(),
2502 SourceLocation(),
2503 msgSendIdent, msgSendType, 0,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002504 SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002505}
2506
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00002507// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(void);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002508void RewriteModernObjC::SynthMsgSendSuperFunctionDecl() {
2509 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00002510 SmallVector<QualType, 2> ArgTys;
2511 ArgTys.push_back(Context->VoidTy);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002512 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002513 ArgTys, /*isVariadic=*/true);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002514 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002515 SourceLocation(),
2516 SourceLocation(),
2517 msgSendIdent, msgSendType, 0,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002518 SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002519}
2520
2521// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
2522void RewriteModernObjC::SynthMsgSendStretFunctionDecl() {
2523 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
2524 SmallVector<QualType, 16> ArgTys;
2525 QualType argT = Context->getObjCIdType();
2526 assert(!argT.isNull() && "Can't find 'id' type");
2527 ArgTys.push_back(argT);
2528 argT = Context->getObjCSelType();
2529 assert(!argT.isNull() && "Can't find 'SEL' type");
2530 ArgTys.push_back(argT);
2531 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002532 ArgTys, /*isVariadic=*/true);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002533 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002534 SourceLocation(),
2535 SourceLocation(),
2536 msgSendIdent, msgSendType, 0,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002537 SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002538}
2539
2540// SynthMsgSendSuperStretFunctionDecl -
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00002541// id objc_msgSendSuper_stret(void);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002542void RewriteModernObjC::SynthMsgSendSuperStretFunctionDecl() {
2543 IdentifierInfo *msgSendIdent =
2544 &Context->Idents.get("objc_msgSendSuper_stret");
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00002545 SmallVector<QualType, 2> ArgTys;
2546 ArgTys.push_back(Context->VoidTy);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002547 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002548 ArgTys, /*isVariadic=*/true);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002549 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2550 SourceLocation(),
2551 SourceLocation(),
Chad Rosierac00fbc2013-01-04 22:40:33 +00002552 msgSendIdent,
2553 msgSendType, 0,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002554 SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002555}
2556
2557// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
2558void RewriteModernObjC::SynthMsgSendFpretFunctionDecl() {
2559 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
2560 SmallVector<QualType, 16> ArgTys;
2561 QualType argT = Context->getObjCIdType();
2562 assert(!argT.isNull() && "Can't find 'id' type");
2563 ArgTys.push_back(argT);
2564 argT = Context->getObjCSelType();
2565 assert(!argT.isNull() && "Can't find 'SEL' type");
2566 ArgTys.push_back(argT);
2567 QualType msgSendType = getSimpleFunctionType(Context->DoubleTy,
Jordan Rose5c382722013-03-08 21:51:21 +00002568 ArgTys, /*isVariadic=*/true);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002569 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002570 SourceLocation(),
2571 SourceLocation(),
2572 msgSendIdent, msgSendType, 0,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002573 SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002574}
2575
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00002576// SynthGetClassFunctionDecl - Class objc_getClass(const char *name);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002577void RewriteModernObjC::SynthGetClassFunctionDecl() {
2578 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
2579 SmallVector<QualType, 16> ArgTys;
2580 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00002581 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002582 ArgTys);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002583 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002584 SourceLocation(),
2585 SourceLocation(),
2586 getClassIdent, getClassType, 0,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002587 SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002588}
2589
2590// SynthGetSuperClassFunctionDecl - Class class_getSuperclass(Class cls);
2591void RewriteModernObjC::SynthGetSuperClassFunctionDecl() {
2592 IdentifierInfo *getSuperClassIdent =
2593 &Context->Idents.get("class_getSuperclass");
2594 SmallVector<QualType, 16> ArgTys;
2595 ArgTys.push_back(Context->getObjCClassType());
2596 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002597 ArgTys);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002598 GetSuperClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2599 SourceLocation(),
2600 SourceLocation(),
2601 getSuperClassIdent,
2602 getClassType, 0,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002603 SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002604}
2605
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00002606// SynthGetMetaClassFunctionDecl - Class objc_getMetaClass(const char *name);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002607void RewriteModernObjC::SynthGetMetaClassFunctionDecl() {
2608 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
2609 SmallVector<QualType, 16> ArgTys;
2610 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00002611 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002612 ArgTys);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002613 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002614 SourceLocation(),
2615 SourceLocation(),
2616 getClassIdent, getClassType,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002617 0, SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002618}
2619
2620Stmt *RewriteModernObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
2621 QualType strType = getConstantStringStructType();
2622
2623 std::string S = "__NSConstantStringImpl_";
2624
2625 std::string tmpName = InFileName;
2626 unsigned i;
2627 for (i=0; i < tmpName.length(); i++) {
2628 char c = tmpName.at(i);
Alp Tokerd4733632013-12-05 04:47:09 +00002629 // replace any non-alphanumeric characters with '_'.
Jordan Rosea7d03842013-02-08 22:30:41 +00002630 if (!isAlphanumeric(c))
Fariborz Jahanian11671902012-02-07 17:11:38 +00002631 tmpName[i] = '_';
2632 }
2633 S += tmpName;
2634 S += "_";
2635 S += utostr(NumObjCStringLiterals++);
2636
2637 Preamble += "static __NSConstantStringImpl " + S;
2638 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2639 Preamble += "0x000007c8,"; // utf8_str
2640 // The pretty printer for StringLiteral handles escape characters properly.
2641 std::string prettyBufS;
2642 llvm::raw_string_ostream prettyBuf(prettyBufS);
Richard Smith235341b2012-08-16 03:56:14 +00002643 Exp->getString()->printPretty(prettyBuf, 0, PrintingPolicy(LangOpts));
Fariborz Jahanian11671902012-02-07 17:11:38 +00002644 Preamble += prettyBuf.str();
2645 Preamble += ",";
2646 Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
2647
2648 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
2649 SourceLocation(), &Context->Idents.get(S),
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002650 strType, 0, SC_Static);
John McCall113bee02012-03-10 09:33:50 +00002651 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, false, strType, VK_LValue,
Fariborz Jahanian11671902012-02-07 17:11:38 +00002652 SourceLocation());
2653 Expr *Unop = new (Context) UnaryOperator(DRE, UO_AddrOf,
2654 Context->getPointerType(DRE->getType()),
2655 VK_RValue, OK_Ordinary,
2656 SourceLocation());
2657 // cast to NSConstantString *
2658 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Exp->getType(),
2659 CK_CPointerToObjCPointerCast, Unop);
2660 ReplaceStmt(Exp, cast);
2661 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2662 return cast;
2663}
2664
Fariborz Jahanian307b7ad2012-03-27 20:17:30 +00002665Stmt *RewriteModernObjC::RewriteObjCBoolLiteralExpr(ObjCBoolLiteralExpr *Exp) {
2666 unsigned IntSize =
2667 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
2668
2669 Expr *FlagExp = IntegerLiteral::Create(*Context,
2670 llvm::APInt(IntSize, Exp->getValue()),
2671 Context->IntTy, Exp->getLocation());
2672 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Context->ObjCBuiltinBoolTy,
2673 CK_BitCast, FlagExp);
2674 ParenExpr *PE = new (Context) ParenExpr(Exp->getLocation(), Exp->getExprLoc(),
2675 cast);
2676 ReplaceStmt(Exp, PE);
2677 return PE;
2678}
2679
Patrick Beard0caa3942012-04-19 00:25:12 +00002680Stmt *RewriteModernObjC::RewriteObjCBoxedExpr(ObjCBoxedExpr *Exp) {
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002681 // synthesize declaration of helper functions needed in this routine.
2682 if (!SelGetUidFunctionDecl)
2683 SynthSelGetUidFunctionDecl();
2684 // use objc_msgSend() for all.
2685 if (!MsgSendFunctionDecl)
2686 SynthMsgSendFunctionDecl();
2687 if (!GetClassFunctionDecl)
2688 SynthGetClassFunctionDecl();
2689
2690 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2691 SourceLocation StartLoc = Exp->getLocStart();
2692 SourceLocation EndLoc = Exp->getLocEnd();
2693
2694 // Synthesize a call to objc_msgSend().
2695 SmallVector<Expr*, 4> MsgExprs;
2696 SmallVector<Expr*, 4> ClsExprs;
2697 QualType argType = Context->getPointerType(Context->CharTy);
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002698
Patrick Beard0caa3942012-04-19 00:25:12 +00002699 // Create a call to objc_getClass("<BoxingClass>"). It will be the 1st argument.
2700 ObjCMethodDecl *BoxingMethod = Exp->getBoxingMethod();
2701 ObjCInterfaceDecl *BoxingClass = BoxingMethod->getClassInterface();
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002702
Patrick Beard0caa3942012-04-19 00:25:12 +00002703 IdentifierInfo *clsName = BoxingClass->getIdentifier();
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002704 ClsExprs.push_back(StringLiteral::Create(*Context,
2705 clsName->getName(),
2706 StringLiteral::Ascii, false,
2707 argType, SourceLocation()));
2708 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2709 &ClsExprs[0],
2710 ClsExprs.size(),
2711 StartLoc, EndLoc);
2712 MsgExprs.push_back(Cls);
2713
Patrick Beard0caa3942012-04-19 00:25:12 +00002714 // Create a call to sel_registerName("<BoxingMethod>:"), etc.
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002715 // it will be the 2nd argument.
2716 SmallVector<Expr*, 4> SelExprs;
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002717 SelExprs.push_back(StringLiteral::Create(*Context,
Patrick Beard0caa3942012-04-19 00:25:12 +00002718 BoxingMethod->getSelector().getAsString(),
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002719 StringLiteral::Ascii, false,
2720 argType, SourceLocation()));
2721 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2722 &SelExprs[0], SelExprs.size(),
2723 StartLoc, EndLoc);
2724 MsgExprs.push_back(SelExp);
2725
Patrick Beard0caa3942012-04-19 00:25:12 +00002726 // User provided sub-expression is the 3rd, and last, argument.
2727 Expr *subExpr = Exp->getSubExpr();
2728 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(subExpr)) {
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002729 QualType type = ICE->getType();
2730 const Expr *SubExpr = ICE->IgnoreParenImpCasts();
2731 CastKind CK = CK_BitCast;
2732 if (SubExpr->getType()->isIntegralType(*Context) && type->isBooleanType())
2733 CK = CK_IntegralToBoolean;
Patrick Beard0caa3942012-04-19 00:25:12 +00002734 subExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, subExpr);
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002735 }
Patrick Beard0caa3942012-04-19 00:25:12 +00002736 MsgExprs.push_back(subExpr);
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002737
2738 SmallVector<QualType, 4> ArgTypes;
2739 ArgTypes.push_back(Context->getObjCIdType());
2740 ArgTypes.push_back(Context->getObjCSelType());
Patrick Beard0caa3942012-04-19 00:25:12 +00002741 for (ObjCMethodDecl::param_iterator PI = BoxingMethod->param_begin(),
2742 E = BoxingMethod->param_end(); PI != E; ++PI)
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002743 ArgTypes.push_back((*PI)->getType());
Patrick Beard0caa3942012-04-19 00:25:12 +00002744
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002745 QualType returnType = Exp->getType();
2746 // Get the type, we will need to reference it in a couple spots.
2747 QualType msgSendType = MsgSendFlavor->getType();
2748
2749 // Create a reference to the objc_msgSend() declaration.
2750 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
2751 VK_LValue, SourceLocation());
2752
2753 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
Patrick Beard0caa3942012-04-19 00:25:12 +00002754 Context->getPointerType(Context->VoidTy),
2755 CK_BitCast, DRE);
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002756
2757 // Now do the "normal" pointer to function cast.
2758 QualType castType =
Jordan Rose5c382722013-03-08 21:51:21 +00002759 getSimpleFunctionType(returnType, ArgTypes, BoxingMethod->isVariadic());
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002760 castType = Context->getPointerType(castType);
2761 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2762 cast);
2763
2764 // Don't forget the parens to enforce the proper binding.
2765 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
2766
2767 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Benjamin Kramerc215e762012-08-24 11:54:20 +00002768 CallExpr *CE = new (Context) CallExpr(*Context, PE, MsgExprs,
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002769 FT->getResultType(), VK_RValue,
2770 EndLoc);
2771 ReplaceStmt(Exp, CE);
2772 return CE;
2773}
2774
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002775Stmt *RewriteModernObjC::RewriteObjCArrayLiteralExpr(ObjCArrayLiteral *Exp) {
2776 // synthesize declaration of helper functions needed in this routine.
2777 if (!SelGetUidFunctionDecl)
2778 SynthSelGetUidFunctionDecl();
2779 // use objc_msgSend() for all.
2780 if (!MsgSendFunctionDecl)
2781 SynthMsgSendFunctionDecl();
2782 if (!GetClassFunctionDecl)
2783 SynthGetClassFunctionDecl();
2784
2785 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2786 SourceLocation StartLoc = Exp->getLocStart();
2787 SourceLocation EndLoc = Exp->getLocEnd();
2788
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002789 // Build the expression: __NSContainer_literal(int, ...).arr
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00002790 QualType IntQT = Context->IntTy;
2791 QualType NSArrayFType =
Jordan Rose5c382722013-03-08 21:51:21 +00002792 getSimpleFunctionType(Context->VoidTy, IntQT, true);
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002793 std::string NSArrayFName("__NSContainer_literal");
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00002794 FunctionDecl *NSArrayFD = SynthBlockInitFunctionDecl(NSArrayFName);
2795 DeclRefExpr *NSArrayDRE =
2796 new (Context) DeclRefExpr(NSArrayFD, false, NSArrayFType, VK_RValue,
2797 SourceLocation());
2798
2799 SmallVector<Expr*, 16> InitExprs;
2800 unsigned NumElements = Exp->getNumElements();
2801 unsigned UnsignedIntSize =
2802 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
2803 Expr *count = IntegerLiteral::Create(*Context,
2804 llvm::APInt(UnsignedIntSize, NumElements),
2805 Context->UnsignedIntTy, SourceLocation());
2806 InitExprs.push_back(count);
2807 for (unsigned i = 0; i < NumElements; i++)
2808 InitExprs.push_back(Exp->getElement(i));
2809 Expr *NSArrayCallExpr =
Benjamin Kramerc215e762012-08-24 11:54:20 +00002810 new (Context) CallExpr(*Context, NSArrayDRE, InitExprs,
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00002811 NSArrayFType, VK_LValue, SourceLocation());
2812
2813 FieldDecl *ARRFD = FieldDecl::Create(*Context, 0, SourceLocation(),
2814 SourceLocation(),
2815 &Context->Idents.get("arr"),
2816 Context->getPointerType(Context->VoidPtrTy), 0,
2817 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smith2b013182012-06-10 03:12:00 +00002818 ICIS_NoInit);
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00002819 MemberExpr *ArrayLiteralME =
2820 new (Context) MemberExpr(NSArrayCallExpr, false, ARRFD,
2821 SourceLocation(),
2822 ARRFD->getType(), VK_LValue,
2823 OK_Ordinary);
2824 QualType ConstIdT = Context->getObjCIdType().withConst();
2825 CStyleCastExpr * ArrayLiteralObjects =
2826 NoTypeInfoCStyleCastExpr(Context,
2827 Context->getPointerType(ConstIdT),
2828 CK_BitCast,
2829 ArrayLiteralME);
2830
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002831 // Synthesize a call to objc_msgSend().
2832 SmallVector<Expr*, 32> MsgExprs;
2833 SmallVector<Expr*, 4> ClsExprs;
2834 QualType argType = Context->getPointerType(Context->CharTy);
2835 QualType expType = Exp->getType();
2836
2837 // Create a call to objc_getClass("NSArray"). It will be th 1st argument.
2838 ObjCInterfaceDecl *Class =
2839 expType->getPointeeType()->getAs<ObjCObjectType>()->getInterface();
2840
2841 IdentifierInfo *clsName = Class->getIdentifier();
2842 ClsExprs.push_back(StringLiteral::Create(*Context,
2843 clsName->getName(),
2844 StringLiteral::Ascii, false,
2845 argType, SourceLocation()));
2846 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2847 &ClsExprs[0],
2848 ClsExprs.size(),
2849 StartLoc, EndLoc);
2850 MsgExprs.push_back(Cls);
2851
2852 // Create a call to sel_registerName("arrayWithObjects:count:").
2853 // it will be the 2nd argument.
2854 SmallVector<Expr*, 4> SelExprs;
2855 ObjCMethodDecl *ArrayMethod = Exp->getArrayWithObjectsMethod();
2856 SelExprs.push_back(StringLiteral::Create(*Context,
2857 ArrayMethod->getSelector().getAsString(),
2858 StringLiteral::Ascii, false,
2859 argType, SourceLocation()));
2860 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2861 &SelExprs[0], SelExprs.size(),
2862 StartLoc, EndLoc);
2863 MsgExprs.push_back(SelExp);
2864
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00002865 // (const id [])objects
2866 MsgExprs.push_back(ArrayLiteralObjects);
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002867
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00002868 // (NSUInteger)cnt
2869 Expr *cnt = IntegerLiteral::Create(*Context,
2870 llvm::APInt(UnsignedIntSize, NumElements),
2871 Context->UnsignedIntTy, SourceLocation());
2872 MsgExprs.push_back(cnt);
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002873
2874
2875 SmallVector<QualType, 4> ArgTypes;
2876 ArgTypes.push_back(Context->getObjCIdType());
2877 ArgTypes.push_back(Context->getObjCSelType());
2878 for (ObjCMethodDecl::param_iterator PI = ArrayMethod->param_begin(),
2879 E = ArrayMethod->param_end(); PI != E; ++PI)
2880 ArgTypes.push_back((*PI)->getType());
2881
2882 QualType returnType = Exp->getType();
2883 // Get the type, we will need to reference it in a couple spots.
2884 QualType msgSendType = MsgSendFlavor->getType();
2885
2886 // Create a reference to the objc_msgSend() declaration.
2887 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
2888 VK_LValue, SourceLocation());
2889
2890 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
2891 Context->getPointerType(Context->VoidTy),
2892 CK_BitCast, DRE);
2893
2894 // Now do the "normal" pointer to function cast.
2895 QualType castType =
Jordan Rose5c382722013-03-08 21:51:21 +00002896 getSimpleFunctionType(returnType, ArgTypes, ArrayMethod->isVariadic());
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002897 castType = Context->getPointerType(castType);
2898 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2899 cast);
2900
2901 // Don't forget the parens to enforce the proper binding.
2902 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
2903
2904 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Benjamin Kramerc215e762012-08-24 11:54:20 +00002905 CallExpr *CE = new (Context) CallExpr(*Context, PE, MsgExprs,
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002906 FT->getResultType(), VK_RValue,
2907 EndLoc);
2908 ReplaceStmt(Exp, CE);
2909 return CE;
2910}
2911
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002912Stmt *RewriteModernObjC::RewriteObjCDictionaryLiteralExpr(ObjCDictionaryLiteral *Exp) {
2913 // synthesize declaration of helper functions needed in this routine.
2914 if (!SelGetUidFunctionDecl)
2915 SynthSelGetUidFunctionDecl();
2916 // use objc_msgSend() for all.
2917 if (!MsgSendFunctionDecl)
2918 SynthMsgSendFunctionDecl();
2919 if (!GetClassFunctionDecl)
2920 SynthGetClassFunctionDecl();
2921
2922 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2923 SourceLocation StartLoc = Exp->getLocStart();
2924 SourceLocation EndLoc = Exp->getLocEnd();
2925
2926 // Build the expression: __NSContainer_literal(int, ...).arr
2927 QualType IntQT = Context->IntTy;
2928 QualType NSDictFType =
Jordan Rose5c382722013-03-08 21:51:21 +00002929 getSimpleFunctionType(Context->VoidTy, IntQT, true);
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002930 std::string NSDictFName("__NSContainer_literal");
2931 FunctionDecl *NSDictFD = SynthBlockInitFunctionDecl(NSDictFName);
2932 DeclRefExpr *NSDictDRE =
2933 new (Context) DeclRefExpr(NSDictFD, false, NSDictFType, VK_RValue,
2934 SourceLocation());
2935
2936 SmallVector<Expr*, 16> KeyExprs;
2937 SmallVector<Expr*, 16> ValueExprs;
2938
2939 unsigned NumElements = Exp->getNumElements();
2940 unsigned UnsignedIntSize =
2941 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
2942 Expr *count = IntegerLiteral::Create(*Context,
2943 llvm::APInt(UnsignedIntSize, NumElements),
2944 Context->UnsignedIntTy, SourceLocation());
2945 KeyExprs.push_back(count);
2946 ValueExprs.push_back(count);
2947 for (unsigned i = 0; i < NumElements; i++) {
2948 ObjCDictionaryElement Element = Exp->getKeyValueElement(i);
2949 KeyExprs.push_back(Element.Key);
2950 ValueExprs.push_back(Element.Value);
2951 }
2952
2953 // (const id [])objects
2954 Expr *NSValueCallExpr =
Benjamin Kramerc215e762012-08-24 11:54:20 +00002955 new (Context) CallExpr(*Context, NSDictDRE, ValueExprs,
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002956 NSDictFType, VK_LValue, SourceLocation());
2957
2958 FieldDecl *ARRFD = FieldDecl::Create(*Context, 0, SourceLocation(),
2959 SourceLocation(),
2960 &Context->Idents.get("arr"),
2961 Context->getPointerType(Context->VoidPtrTy), 0,
2962 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smith2b013182012-06-10 03:12:00 +00002963 ICIS_NoInit);
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002964 MemberExpr *DictLiteralValueME =
2965 new (Context) MemberExpr(NSValueCallExpr, false, ARRFD,
2966 SourceLocation(),
2967 ARRFD->getType(), VK_LValue,
2968 OK_Ordinary);
2969 QualType ConstIdT = Context->getObjCIdType().withConst();
2970 CStyleCastExpr * DictValueObjects =
2971 NoTypeInfoCStyleCastExpr(Context,
2972 Context->getPointerType(ConstIdT),
2973 CK_BitCast,
2974 DictLiteralValueME);
2975 // (const id <NSCopying> [])keys
2976 Expr *NSKeyCallExpr =
Benjamin Kramerc215e762012-08-24 11:54:20 +00002977 new (Context) CallExpr(*Context, NSDictDRE, KeyExprs,
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002978 NSDictFType, VK_LValue, SourceLocation());
2979
2980 MemberExpr *DictLiteralKeyME =
2981 new (Context) MemberExpr(NSKeyCallExpr, false, ARRFD,
2982 SourceLocation(),
2983 ARRFD->getType(), VK_LValue,
2984 OK_Ordinary);
2985
2986 CStyleCastExpr * DictKeyObjects =
2987 NoTypeInfoCStyleCastExpr(Context,
2988 Context->getPointerType(ConstIdT),
2989 CK_BitCast,
2990 DictLiteralKeyME);
2991
2992
2993
2994 // Synthesize a call to objc_msgSend().
2995 SmallVector<Expr*, 32> MsgExprs;
2996 SmallVector<Expr*, 4> ClsExprs;
2997 QualType argType = Context->getPointerType(Context->CharTy);
2998 QualType expType = Exp->getType();
2999
3000 // Create a call to objc_getClass("NSArray"). It will be th 1st argument.
3001 ObjCInterfaceDecl *Class =
3002 expType->getPointeeType()->getAs<ObjCObjectType>()->getInterface();
3003
3004 IdentifierInfo *clsName = Class->getIdentifier();
3005 ClsExprs.push_back(StringLiteral::Create(*Context,
3006 clsName->getName(),
3007 StringLiteral::Ascii, false,
3008 argType, SourceLocation()));
3009 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
3010 &ClsExprs[0],
3011 ClsExprs.size(),
3012 StartLoc, EndLoc);
3013 MsgExprs.push_back(Cls);
3014
3015 // Create a call to sel_registerName("arrayWithObjects:count:").
3016 // it will be the 2nd argument.
3017 SmallVector<Expr*, 4> SelExprs;
3018 ObjCMethodDecl *DictMethod = Exp->getDictWithObjectsMethod();
3019 SelExprs.push_back(StringLiteral::Create(*Context,
3020 DictMethod->getSelector().getAsString(),
3021 StringLiteral::Ascii, false,
3022 argType, SourceLocation()));
3023 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
3024 &SelExprs[0], SelExprs.size(),
3025 StartLoc, EndLoc);
3026 MsgExprs.push_back(SelExp);
3027
3028 // (const id [])objects
3029 MsgExprs.push_back(DictValueObjects);
3030
3031 // (const id <NSCopying> [])keys
3032 MsgExprs.push_back(DictKeyObjects);
3033
3034 // (NSUInteger)cnt
3035 Expr *cnt = IntegerLiteral::Create(*Context,
3036 llvm::APInt(UnsignedIntSize, NumElements),
3037 Context->UnsignedIntTy, SourceLocation());
3038 MsgExprs.push_back(cnt);
3039
3040
3041 SmallVector<QualType, 8> ArgTypes;
3042 ArgTypes.push_back(Context->getObjCIdType());
3043 ArgTypes.push_back(Context->getObjCSelType());
3044 for (ObjCMethodDecl::param_iterator PI = DictMethod->param_begin(),
3045 E = DictMethod->param_end(); PI != E; ++PI) {
3046 QualType T = (*PI)->getType();
3047 if (const PointerType* PT = T->getAs<PointerType>()) {
3048 QualType PointeeTy = PT->getPointeeType();
3049 convertToUnqualifiedObjCType(PointeeTy);
3050 T = Context->getPointerType(PointeeTy);
3051 }
3052 ArgTypes.push_back(T);
3053 }
3054
3055 QualType returnType = Exp->getType();
3056 // Get the type, we will need to reference it in a couple spots.
3057 QualType msgSendType = MsgSendFlavor->getType();
3058
3059 // Create a reference to the objc_msgSend() declaration.
3060 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
3061 VK_LValue, SourceLocation());
3062
3063 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
3064 Context->getPointerType(Context->VoidTy),
3065 CK_BitCast, DRE);
3066
3067 // Now do the "normal" pointer to function cast.
3068 QualType castType =
Jordan Rose5c382722013-03-08 21:51:21 +00003069 getSimpleFunctionType(returnType, ArgTypes, DictMethod->isVariadic());
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00003070 castType = Context->getPointerType(castType);
3071 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
3072 cast);
3073
3074 // Don't forget the parens to enforce the proper binding.
3075 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
3076
3077 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Benjamin Kramerc215e762012-08-24 11:54:20 +00003078 CallExpr *CE = new (Context) CallExpr(*Context, PE, MsgExprs,
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00003079 FT->getResultType(), VK_RValue,
3080 EndLoc);
3081 ReplaceStmt(Exp, CE);
3082 return CE;
3083}
3084
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003085// struct __rw_objc_super {
3086// struct objc_object *object; struct objc_object *superClass;
3087// };
Fariborz Jahanian11671902012-02-07 17:11:38 +00003088QualType RewriteModernObjC::getSuperStructType() {
3089 if (!SuperStructDecl) {
3090 SuperStructDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
3091 SourceLocation(), SourceLocation(),
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003092 &Context->Idents.get("__rw_objc_super"));
Fariborz Jahanian11671902012-02-07 17:11:38 +00003093 QualType FieldTypes[2];
3094
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003095 // struct objc_object *object;
Fariborz Jahanian11671902012-02-07 17:11:38 +00003096 FieldTypes[0] = Context->getObjCIdType();
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003097 // struct objc_object *superClass;
3098 FieldTypes[1] = Context->getObjCIdType();
Fariborz Jahanian11671902012-02-07 17:11:38 +00003099
3100 // Create fields
3101 for (unsigned i = 0; i < 2; ++i) {
3102 SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
3103 SourceLocation(),
3104 SourceLocation(), 0,
3105 FieldTypes[i], 0,
3106 /*BitWidth=*/0,
3107 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00003108 ICIS_NoInit));
Fariborz Jahanian11671902012-02-07 17:11:38 +00003109 }
3110
3111 SuperStructDecl->completeDefinition();
3112 }
3113 return Context->getTagDeclType(SuperStructDecl);
3114}
3115
3116QualType RewriteModernObjC::getConstantStringStructType() {
3117 if (!ConstantStringDecl) {
3118 ConstantStringDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
3119 SourceLocation(), SourceLocation(),
3120 &Context->Idents.get("__NSConstantStringImpl"));
3121 QualType FieldTypes[4];
3122
3123 // struct objc_object *receiver;
3124 FieldTypes[0] = Context->getObjCIdType();
3125 // int flags;
3126 FieldTypes[1] = Context->IntTy;
3127 // char *str;
3128 FieldTypes[2] = Context->getPointerType(Context->CharTy);
3129 // long length;
3130 FieldTypes[3] = Context->LongTy;
3131
3132 // Create fields
3133 for (unsigned i = 0; i < 4; ++i) {
3134 ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
3135 ConstantStringDecl,
3136 SourceLocation(),
3137 SourceLocation(), 0,
3138 FieldTypes[i], 0,
3139 /*BitWidth=*/0,
3140 /*Mutable=*/true,
Richard Smith2b013182012-06-10 03:12:00 +00003141 ICIS_NoInit));
Fariborz Jahanian11671902012-02-07 17:11:38 +00003142 }
3143
3144 ConstantStringDecl->completeDefinition();
3145 }
3146 return Context->getTagDeclType(ConstantStringDecl);
3147}
3148
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003149/// getFunctionSourceLocation - returns start location of a function
3150/// definition. Complication arises when function has declared as
3151/// extern "C" or extern "C" {...}
3152static SourceLocation getFunctionSourceLocation (RewriteModernObjC &R,
3153 FunctionDecl *FD) {
3154 if (FD->isExternC() && !FD->isMain()) {
3155 const DeclContext *DC = FD->getDeclContext();
3156 if (const LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(DC))
3157 // if it is extern "C" {...}, return function decl's own location.
3158 if (!LSD->getRBraceLoc().isValid())
3159 return LSD->getExternLoc();
3160 }
Rafael Espindola6ae7e502013-04-03 19:27:57 +00003161 if (FD->getStorageClass() != SC_None)
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003162 R.RewriteBlockLiteralFunctionDecl(FD);
3163 return FD->getTypeSpecStartLoc();
3164}
3165
Fariborz Jahanianaa4a2422012-11-06 17:30:23 +00003166void RewriteModernObjC::RewriteLineDirective(const Decl *D) {
3167
3168 SourceLocation Location = D->getLocation();
3169
Fariborz Jahaniane4c7e852013-02-08 00:27:34 +00003170 if (Location.isFileID() && GenerateLineInfo) {
Fariborz Jahanian83dadc72012-11-07 18:15:53 +00003171 std::string LineString("\n#line ");
Fariborz Jahanianaa4a2422012-11-06 17:30:23 +00003172 PresumedLoc PLoc = SM->getPresumedLoc(Location);
3173 LineString += utostr(PLoc.getLine());
3174 LineString += " \"";
NAKAMURA Takumib46a05c2012-11-06 22:45:31 +00003175 LineString += Lexer::Stringify(PLoc.getFilename());
Fariborz Jahanianaa4a2422012-11-06 17:30:23 +00003176 if (isa<ObjCMethodDecl>(D))
3177 LineString += "\"";
3178 else LineString += "\"\n";
3179
3180 Location = D->getLocStart();
3181 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
3182 if (FD->isExternC() && !FD->isMain()) {
3183 const DeclContext *DC = FD->getDeclContext();
3184 if (const LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(DC))
3185 // if it is extern "C" {...}, return function decl's own location.
3186 if (!LSD->getRBraceLoc().isValid())
3187 Location = LSD->getExternLoc();
3188 }
3189 }
3190 InsertText(Location, LineString);
3191 }
3192}
3193
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003194/// SynthMsgSendStretCallExpr - This routine translates message expression
3195/// into a call to objc_msgSend_stret() entry point. Tricky part is that
3196/// nil check on receiver must be performed before calling objc_msgSend_stret.
3197/// MsgSendStretFlavor - function declaration objc_msgSend_stret(...)
3198/// msgSendType - function type of objc_msgSend_stret(...)
3199/// returnType - Result type of the method being synthesized.
3200/// ArgTypes - type of the arguments passed to objc_msgSend_stret, starting with receiver type.
3201/// MsgExprs - list of argument expressions being passed to objc_msgSend_stret,
3202/// starting with receiver.
3203/// Method - Method being rewritten.
3204Expr *RewriteModernObjC::SynthMsgSendStretCallExpr(FunctionDecl *MsgSendStretFlavor,
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003205 QualType returnType,
3206 SmallVectorImpl<QualType> &ArgTypes,
3207 SmallVectorImpl<Expr*> &MsgExprs,
3208 ObjCMethodDecl *Method) {
3209 // Now do the "normal" pointer to function cast.
Jordan Rose5c382722013-03-08 21:51:21 +00003210 QualType castType = getSimpleFunctionType(returnType, ArgTypes,
3211 Method ? Method->isVariadic()
3212 : false);
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003213 castType = Context->getPointerType(castType);
3214
3215 // build type for containing the objc_msgSend_stret object.
3216 static unsigned stretCount=0;
3217 std::string name = "__Stret"; name += utostr(stretCount);
Fariborz Jahanian1a112522012-07-25 21:48:36 +00003218 std::string str =
3219 "extern \"C\" void * __cdecl memset(void *_Dst, int _Val, size_t _Size);\n";
Fariborz Jahanianb1a21242013-09-09 19:59:59 +00003220 str += "namespace {\n";
Fariborz Jahanian1a112522012-07-25 21:48:36 +00003221 str += "struct "; str += name;
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003222 str += " {\n\t";
3223 str += name;
3224 str += "(id receiver, SEL sel";
3225 for (unsigned i = 2; i < ArgTypes.size(); i++) {
Fariborz Jahanian2794ad52012-06-29 19:55:46 +00003226 std::string ArgName = "arg"; ArgName += utostr(i);
3227 ArgTypes[i].getAsStringInternal(ArgName, Context->getPrintingPolicy());
3228 str += ", "; str += ArgName;
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003229 }
3230 // could be vararg.
3231 for (unsigned i = ArgTypes.size(); i < MsgExprs.size(); i++) {
Fariborz Jahanian2794ad52012-06-29 19:55:46 +00003232 std::string ArgName = "arg"; ArgName += utostr(i);
3233 MsgExprs[i]->getType().getAsStringInternal(ArgName,
3234 Context->getPrintingPolicy());
3235 str += ", "; str += ArgName;
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003236 }
3237
3238 str += ") {\n";
Fariborz Jahanianb1a21242013-09-09 19:59:59 +00003239 str += "\t unsigned size = sizeof(";
3240 str += returnType.getAsString(Context->getPrintingPolicy()); str += ");\n";
3241
3242 str += "\t if (size == 1 || size == 2 || size == 4 || size == 8)\n";
3243
3244 str += "\t s = (("; str += castType.getAsString(Context->getPrintingPolicy());
3245 str += ")(void *)objc_msgSend)(receiver, sel";
3246 for (unsigned i = 2; i < ArgTypes.size(); i++) {
3247 str += ", arg"; str += utostr(i);
3248 }
3249 // could be vararg.
3250 for (unsigned i = ArgTypes.size(); i < MsgExprs.size(); i++) {
3251 str += ", arg"; str += utostr(i);
3252 }
3253 str+= ");\n";
3254
3255 str += "\t else if (receiver == 0)\n";
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003256 str += "\t memset((void*)&s, 0, sizeof(s));\n";
3257 str += "\t else\n";
Fariborz Jahanianb1a21242013-09-09 19:59:59 +00003258
3259
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003260 str += "\t s = (("; str += castType.getAsString(Context->getPrintingPolicy());
3261 str += ")(void *)objc_msgSend_stret)(receiver, sel";
3262 for (unsigned i = 2; i < ArgTypes.size(); i++) {
3263 str += ", arg"; str += utostr(i);
3264 }
3265 // could be vararg.
3266 for (unsigned i = ArgTypes.size(); i < MsgExprs.size(); i++) {
3267 str += ", arg"; str += utostr(i);
3268 }
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003269 str += ");\n";
Fariborz Jahanianb1a21242013-09-09 19:59:59 +00003270
3271
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003272 str += "\t}\n";
3273 str += "\t"; str += returnType.getAsString(Context->getPrintingPolicy());
3274 str += " s;\n";
Fariborz Jahanianb1a21242013-09-09 19:59:59 +00003275 str += "};\n};\n\n";
Fariborz Jahanianf1f36c62012-08-21 18:56:50 +00003276 SourceLocation FunLocStart;
3277 if (CurFunctionDef)
3278 FunLocStart = getFunctionSourceLocation(*this, CurFunctionDef);
3279 else {
3280 assert(CurMethodDef && "SynthMsgSendStretCallExpr - CurMethodDef is null");
3281 FunLocStart = CurMethodDef->getLocStart();
3282 }
3283
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003284 InsertText(FunLocStart, str);
3285 ++stretCount;
3286
3287 // AST for __Stretn(receiver, args).s;
3288 IdentifierInfo *ID = &Context->Idents.get(name);
3289 FunctionDecl *FD = FunctionDecl::Create(*Context, TUDecl, SourceLocation(),
Chad Rosierac00fbc2013-01-04 22:40:33 +00003290 SourceLocation(), ID, castType, 0,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00003291 SC_Extern, false, false);
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003292 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, false, castType, VK_RValue,
3293 SourceLocation());
Benjamin Kramerc215e762012-08-24 11:54:20 +00003294 CallExpr *STCE = new (Context) CallExpr(*Context, DRE, MsgExprs,
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003295 castType, VK_LValue, SourceLocation());
3296
3297 FieldDecl *FieldD = FieldDecl::Create(*Context, 0, SourceLocation(),
3298 SourceLocation(),
3299 &Context->Idents.get("s"),
3300 returnType, 0,
3301 /*BitWidth=*/0, /*Mutable=*/true,
3302 ICIS_NoInit);
3303 MemberExpr *ME = new (Context) MemberExpr(STCE, false, FieldD, SourceLocation(),
3304 FieldD->getType(), VK_LValue,
3305 OK_Ordinary);
3306
3307 return ME;
3308}
3309
Fariborz Jahanian11671902012-02-07 17:11:38 +00003310Stmt *RewriteModernObjC::SynthMessageExpr(ObjCMessageExpr *Exp,
3311 SourceLocation StartLoc,
3312 SourceLocation EndLoc) {
3313 if (!SelGetUidFunctionDecl)
3314 SynthSelGetUidFunctionDecl();
3315 if (!MsgSendFunctionDecl)
3316 SynthMsgSendFunctionDecl();
3317 if (!MsgSendSuperFunctionDecl)
3318 SynthMsgSendSuperFunctionDecl();
3319 if (!MsgSendStretFunctionDecl)
3320 SynthMsgSendStretFunctionDecl();
3321 if (!MsgSendSuperStretFunctionDecl)
3322 SynthMsgSendSuperStretFunctionDecl();
3323 if (!MsgSendFpretFunctionDecl)
3324 SynthMsgSendFpretFunctionDecl();
3325 if (!GetClassFunctionDecl)
3326 SynthGetClassFunctionDecl();
3327 if (!GetSuperClassFunctionDecl)
3328 SynthGetSuperClassFunctionDecl();
3329 if (!GetMetaClassFunctionDecl)
3330 SynthGetMetaClassFunctionDecl();
3331
3332 // default to objc_msgSend().
3333 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
3334 // May need to use objc_msgSend_stret() as well.
3335 FunctionDecl *MsgSendStretFlavor = 0;
3336 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
3337 QualType resultType = mDecl->getResultType();
3338 if (resultType->isRecordType())
3339 MsgSendStretFlavor = MsgSendStretFunctionDecl;
3340 else if (resultType->isRealFloatingType())
3341 MsgSendFlavor = MsgSendFpretFunctionDecl;
3342 }
3343
3344 // Synthesize a call to objc_msgSend().
3345 SmallVector<Expr*, 8> MsgExprs;
3346 switch (Exp->getReceiverKind()) {
3347 case ObjCMessageExpr::SuperClass: {
3348 MsgSendFlavor = MsgSendSuperFunctionDecl;
3349 if (MsgSendStretFlavor)
3350 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
3351 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
3352
3353 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
3354
3355 SmallVector<Expr*, 4> InitExprs;
3356
3357 // set the receiver to self, the first argument to all methods.
3358 InitExprs.push_back(
3359 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3360 CK_BitCast,
3361 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCall113bee02012-03-10 09:33:50 +00003362 false,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003363 Context->getObjCIdType(),
3364 VK_RValue,
3365 SourceLocation()))
3366 ); // set the 'receiver'.
3367
3368 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3369 SmallVector<Expr*, 8> ClsExprs;
3370 QualType argType = Context->getPointerType(Context->CharTy);
3371 ClsExprs.push_back(StringLiteral::Create(*Context,
3372 ClassDecl->getIdentifier()->getName(),
3373 StringLiteral::Ascii, false,
3374 argType, SourceLocation()));
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00003375 // (Class)objc_getClass("CurrentClass")
Fariborz Jahanian11671902012-02-07 17:11:38 +00003376 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
3377 &ClsExprs[0],
3378 ClsExprs.size(),
3379 StartLoc,
3380 EndLoc);
Fariborz Jahanian11671902012-02-07 17:11:38 +00003381 ClsExprs.clear();
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00003382 ClsExprs.push_back(Cls);
Fariborz Jahanian11671902012-02-07 17:11:38 +00003383 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
3384 &ClsExprs[0], ClsExprs.size(),
3385 StartLoc, EndLoc);
3386
3387 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3388 // To turn off a warning, type-cast to 'id'
3389 InitExprs.push_back( // set 'super class', using class_getSuperclass().
3390 NoTypeInfoCStyleCastExpr(Context,
3391 Context->getObjCIdType(),
3392 CK_BitCast, Cls));
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003393 // struct __rw_objc_super
Fariborz Jahanian11671902012-02-07 17:11:38 +00003394 QualType superType = getSuperStructType();
3395 Expr *SuperRep;
3396
3397 if (LangOpts.MicrosoftExt) {
Benjamin Kramer60509af2013-09-09 14:48:42 +00003398 SynthSuperConstructorFunctionDecl();
3399 // Simulate a constructor call...
3400 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperConstructorFunctionDecl,
John McCall113bee02012-03-10 09:33:50 +00003401 false, superType, VK_LValue,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003402 SourceLocation());
Benjamin Kramerc215e762012-08-24 11:54:20 +00003403 SuperRep = new (Context) CallExpr(*Context, DRE, InitExprs,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003404 superType, VK_LValue,
3405 SourceLocation());
3406 // The code for super is a little tricky to prevent collision with
3407 // the structure definition in the header. The rewriter has it's own
3408 // internal definition (__rw_objc_super) that is uses. This is why
3409 // we need the cast below. For example:
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003410 // (struct __rw_objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
Fariborz Jahanian11671902012-02-07 17:11:38 +00003411 //
3412 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
3413 Context->getPointerType(SuperRep->getType()),
3414 VK_RValue, OK_Ordinary,
3415 SourceLocation());
3416 SuperRep = NoTypeInfoCStyleCastExpr(Context,
3417 Context->getPointerType(superType),
3418 CK_BitCast, SuperRep);
3419 } else {
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003420 // (struct __rw_objc_super) { <exprs from above> }
Fariborz Jahanian11671902012-02-07 17:11:38 +00003421 InitListExpr *ILE =
Benjamin Kramerc215e762012-08-24 11:54:20 +00003422 new (Context) InitListExpr(*Context, SourceLocation(), InitExprs,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003423 SourceLocation());
3424 TypeSourceInfo *superTInfo
3425 = Context->getTrivialTypeSourceInfo(superType);
3426 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
3427 superType, VK_LValue,
3428 ILE, false);
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003429 // struct __rw_objc_super *
Fariborz Jahanian11671902012-02-07 17:11:38 +00003430 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
3431 Context->getPointerType(SuperRep->getType()),
3432 VK_RValue, OK_Ordinary,
3433 SourceLocation());
3434 }
3435 MsgExprs.push_back(SuperRep);
3436 break;
3437 }
3438
3439 case ObjCMessageExpr::Class: {
3440 SmallVector<Expr*, 8> ClsExprs;
3441 QualType argType = Context->getPointerType(Context->CharTy);
3442 ObjCInterfaceDecl *Class
3443 = Exp->getClassReceiver()->getAs<ObjCObjectType>()->getInterface();
3444 IdentifierInfo *clsName = Class->getIdentifier();
3445 ClsExprs.push_back(StringLiteral::Create(*Context,
3446 clsName->getName(),
3447 StringLiteral::Ascii, false,
3448 argType, SourceLocation()));
3449 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
3450 &ClsExprs[0],
3451 ClsExprs.size(),
3452 StartLoc, EndLoc);
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00003453 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
3454 Context->getObjCIdType(),
3455 CK_BitCast, Cls);
3456 MsgExprs.push_back(ArgExpr);
Fariborz Jahanian11671902012-02-07 17:11:38 +00003457 break;
3458 }
3459
3460 case ObjCMessageExpr::SuperInstance:{
3461 MsgSendFlavor = MsgSendSuperFunctionDecl;
3462 if (MsgSendStretFlavor)
3463 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
3464 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
3465 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
3466 SmallVector<Expr*, 4> InitExprs;
3467
3468 InitExprs.push_back(
3469 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3470 CK_BitCast,
3471 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCall113bee02012-03-10 09:33:50 +00003472 false,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003473 Context->getObjCIdType(),
3474 VK_RValue, SourceLocation()))
3475 ); // set the 'receiver'.
3476
3477 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3478 SmallVector<Expr*, 8> ClsExprs;
3479 QualType argType = Context->getPointerType(Context->CharTy);
3480 ClsExprs.push_back(StringLiteral::Create(*Context,
3481 ClassDecl->getIdentifier()->getName(),
3482 StringLiteral::Ascii, false, argType,
3483 SourceLocation()));
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00003484 // (Class)objc_getClass("CurrentClass")
Fariborz Jahanian11671902012-02-07 17:11:38 +00003485 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
3486 &ClsExprs[0],
3487 ClsExprs.size(),
3488 StartLoc, EndLoc);
Fariborz Jahanian11671902012-02-07 17:11:38 +00003489 ClsExprs.clear();
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00003490 ClsExprs.push_back(Cls);
Fariborz Jahanian11671902012-02-07 17:11:38 +00003491 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
3492 &ClsExprs[0], ClsExprs.size(),
3493 StartLoc, EndLoc);
3494
3495 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3496 // To turn off a warning, type-cast to 'id'
3497 InitExprs.push_back(
3498 // set 'super class', using class_getSuperclass().
3499 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3500 CK_BitCast, Cls));
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003501 // struct __rw_objc_super
Fariborz Jahanian11671902012-02-07 17:11:38 +00003502 QualType superType = getSuperStructType();
3503 Expr *SuperRep;
3504
3505 if (LangOpts.MicrosoftExt) {
Benjamin Kramer60509af2013-09-09 14:48:42 +00003506 SynthSuperConstructorFunctionDecl();
3507 // Simulate a constructor call...
3508 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperConstructorFunctionDecl,
John McCall113bee02012-03-10 09:33:50 +00003509 false, superType, VK_LValue,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003510 SourceLocation());
Benjamin Kramerc215e762012-08-24 11:54:20 +00003511 SuperRep = new (Context) CallExpr(*Context, DRE, InitExprs,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003512 superType, VK_LValue, SourceLocation());
3513 // The code for super is a little tricky to prevent collision with
3514 // the structure definition in the header. The rewriter has it's own
3515 // internal definition (__rw_objc_super) that is uses. This is why
3516 // we need the cast below. For example:
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003517 // (struct __rw_objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
Fariborz Jahanian11671902012-02-07 17:11:38 +00003518 //
3519 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
3520 Context->getPointerType(SuperRep->getType()),
3521 VK_RValue, OK_Ordinary,
3522 SourceLocation());
3523 SuperRep = NoTypeInfoCStyleCastExpr(Context,
3524 Context->getPointerType(superType),
3525 CK_BitCast, SuperRep);
3526 } else {
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003527 // (struct __rw_objc_super) { <exprs from above> }
Fariborz Jahanian11671902012-02-07 17:11:38 +00003528 InitListExpr *ILE =
Benjamin Kramerc215e762012-08-24 11:54:20 +00003529 new (Context) InitListExpr(*Context, SourceLocation(), InitExprs,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003530 SourceLocation());
3531 TypeSourceInfo *superTInfo
3532 = Context->getTrivialTypeSourceInfo(superType);
3533 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
3534 superType, VK_RValue, ILE,
3535 false);
3536 }
3537 MsgExprs.push_back(SuperRep);
3538 break;
3539 }
3540
3541 case ObjCMessageExpr::Instance: {
3542 // Remove all type-casts because it may contain objc-style types; e.g.
3543 // Foo<Proto> *.
3544 Expr *recExpr = Exp->getInstanceReceiver();
3545 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
3546 recExpr = CE->getSubExpr();
3547 CastKind CK = recExpr->getType()->isObjCObjectPointerType()
3548 ? CK_BitCast : recExpr->getType()->isBlockPointerType()
3549 ? CK_BlockPointerToObjCPointerCast
3550 : CK_CPointerToObjCPointerCast;
3551
3552 recExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3553 CK, recExpr);
3554 MsgExprs.push_back(recExpr);
3555 break;
3556 }
3557 }
3558
3559 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
3560 SmallVector<Expr*, 8> SelExprs;
3561 QualType argType = Context->getPointerType(Context->CharTy);
3562 SelExprs.push_back(StringLiteral::Create(*Context,
3563 Exp->getSelector().getAsString(),
3564 StringLiteral::Ascii, false,
3565 argType, SourceLocation()));
3566 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
3567 &SelExprs[0], SelExprs.size(),
3568 StartLoc,
3569 EndLoc);
3570 MsgExprs.push_back(SelExp);
3571
3572 // Now push any user supplied arguments.
3573 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
3574 Expr *userExpr = Exp->getArg(i);
3575 // Make all implicit casts explicit...ICE comes in handy:-)
3576 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
3577 // Reuse the ICE type, it is exactly what the doctor ordered.
3578 QualType type = ICE->getType();
3579 if (needToScanForQualifiers(type))
3580 type = Context->getObjCIdType();
3581 // Make sure we convert "type (^)(...)" to "type (*)(...)".
3582 (void)convertBlockPointerToFunctionPointer(type);
3583 const Expr *SubExpr = ICE->IgnoreParenImpCasts();
3584 CastKind CK;
3585 if (SubExpr->getType()->isIntegralType(*Context) &&
3586 type->isBooleanType()) {
3587 CK = CK_IntegralToBoolean;
3588 } else if (type->isObjCObjectPointerType()) {
3589 if (SubExpr->getType()->isBlockPointerType()) {
3590 CK = CK_BlockPointerToObjCPointerCast;
3591 } else if (SubExpr->getType()->isPointerType()) {
3592 CK = CK_CPointerToObjCPointerCast;
3593 } else {
3594 CK = CK_BitCast;
3595 }
3596 } else {
3597 CK = CK_BitCast;
3598 }
3599
3600 userExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, userExpr);
3601 }
3602 // Make id<P...> cast into an 'id' cast.
3603 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
3604 if (CE->getType()->isObjCQualifiedIdType()) {
3605 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
3606 userExpr = CE->getSubExpr();
3607 CastKind CK;
3608 if (userExpr->getType()->isIntegralType(*Context)) {
3609 CK = CK_IntegralToPointer;
3610 } else if (userExpr->getType()->isBlockPointerType()) {
3611 CK = CK_BlockPointerToObjCPointerCast;
3612 } else if (userExpr->getType()->isPointerType()) {
3613 CK = CK_CPointerToObjCPointerCast;
3614 } else {
3615 CK = CK_BitCast;
3616 }
3617 userExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3618 CK, userExpr);
3619 }
3620 }
3621 MsgExprs.push_back(userExpr);
3622 // We've transferred the ownership to MsgExprs. For now, we *don't* null
3623 // out the argument in the original expression (since we aren't deleting
3624 // the ObjCMessageExpr). See RewritePropertyOrImplicitSetter() usage for more info.
3625 //Exp->setArg(i, 0);
3626 }
3627 // Generate the funky cast.
3628 CastExpr *cast;
3629 SmallVector<QualType, 8> ArgTypes;
3630 QualType returnType;
3631
3632 // Push 'id' and 'SEL', the 2 implicit arguments.
3633 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
3634 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
3635 else
3636 ArgTypes.push_back(Context->getObjCIdType());
3637 ArgTypes.push_back(Context->getObjCSelType());
3638 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
3639 // Push any user argument types.
3640 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
3641 E = OMD->param_end(); PI != E; ++PI) {
3642 QualType t = (*PI)->getType()->isObjCQualifiedIdType()
3643 ? Context->getObjCIdType()
3644 : (*PI)->getType();
3645 // Make sure we convert "t (^)(...)" to "t (*)(...)".
3646 (void)convertBlockPointerToFunctionPointer(t);
3647 ArgTypes.push_back(t);
3648 }
3649 returnType = Exp->getType();
3650 convertToUnqualifiedObjCType(returnType);
3651 (void)convertBlockPointerToFunctionPointer(returnType);
3652 } else {
3653 returnType = Context->getObjCIdType();
3654 }
3655 // Get the type, we will need to reference it in a couple spots.
3656 QualType msgSendType = MsgSendFlavor->getType();
3657
3658 // Create a reference to the objc_msgSend() declaration.
John McCall113bee02012-03-10 09:33:50 +00003659 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003660 VK_LValue, SourceLocation());
3661
3662 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
3663 // If we don't do this cast, we get the following bizarre warning/note:
3664 // xx.m:13: warning: function called through a non-compatible type
3665 // xx.m:13: note: if this code is reached, the program will abort
3666 cast = NoTypeInfoCStyleCastExpr(Context,
3667 Context->getPointerType(Context->VoidTy),
3668 CK_BitCast, DRE);
3669
3670 // Now do the "normal" pointer to function cast.
Jordan Rose5c382722013-03-08 21:51:21 +00003671 // If we don't have a method decl, force a variadic cast.
3672 const ObjCMethodDecl *MD = Exp->getMethodDecl();
Fariborz Jahanian11671902012-02-07 17:11:38 +00003673 QualType castType =
Jordan Rose5c382722013-03-08 21:51:21 +00003674 getSimpleFunctionType(returnType, ArgTypes, MD ? MD->isVariadic() : true);
Fariborz Jahanian11671902012-02-07 17:11:38 +00003675 castType = Context->getPointerType(castType);
3676 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
3677 cast);
3678
3679 // Don't forget the parens to enforce the proper binding.
3680 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
3681
3682 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Benjamin Kramerc215e762012-08-24 11:54:20 +00003683 CallExpr *CE = new (Context) CallExpr(*Context, PE, MsgExprs,
3684 FT->getResultType(), VK_RValue, EndLoc);
Fariborz Jahanian11671902012-02-07 17:11:38 +00003685 Stmt *ReplacingStmt = CE;
3686 if (MsgSendStretFlavor) {
3687 // We have the method which returns a struct/union. Must also generate
3688 // call to objc_msgSend_stret and hang both varieties on a conditional
3689 // expression which dictate which one to envoke depending on size of
3690 // method's return type.
3691
Fariborz Jahanianb1a21242013-09-09 19:59:59 +00003692 Expr *STCE = SynthMsgSendStretCallExpr(MsgSendStretFlavor,
3693 returnType,
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003694 ArgTypes, MsgExprs,
3695 Exp->getMethodDecl());
Fariborz Jahanianb1a21242013-09-09 19:59:59 +00003696 ReplacingStmt = STCE;
Fariborz Jahanian11671902012-02-07 17:11:38 +00003697 }
3698 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3699 return ReplacingStmt;
3700}
3701
3702Stmt *RewriteModernObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
3703 Stmt *ReplacingStmt = SynthMessageExpr(Exp, Exp->getLocStart(),
3704 Exp->getLocEnd());
3705
3706 // Now do the actual rewrite.
3707 ReplaceStmt(Exp, ReplacingStmt);
3708
3709 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3710 return ReplacingStmt;
3711}
3712
3713// typedef struct objc_object Protocol;
3714QualType RewriteModernObjC::getProtocolType() {
3715 if (!ProtocolTypeDecl) {
3716 TypeSourceInfo *TInfo
3717 = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
3718 ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
3719 SourceLocation(), SourceLocation(),
3720 &Context->Idents.get("Protocol"),
3721 TInfo);
3722 }
3723 return Context->getTypeDeclType(ProtocolTypeDecl);
3724}
3725
3726/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
3727/// a synthesized/forward data reference (to the protocol's metadata).
3728/// The forward references (and metadata) are generated in
3729/// RewriteModernObjC::HandleTranslationUnit().
3730Stmt *RewriteModernObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Fariborz Jahanianb31e3af2012-03-15 17:05:33 +00003731 std::string Name = "_OBJC_PROTOCOL_REFERENCE_$_" +
3732 Exp->getProtocol()->getNameAsString();
Fariborz Jahanian11671902012-02-07 17:11:38 +00003733 IdentifierInfo *ID = &Context->Idents.get(Name);
3734 VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
3735 SourceLocation(), ID, getProtocolType(), 0,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00003736 SC_Extern);
John McCall113bee02012-03-10 09:33:50 +00003737 DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, false, getProtocolType(),
3738 VK_LValue, SourceLocation());
Fariborz Jahaniand38951a2013-11-22 18:43:41 +00003739 CastExpr *castExpr =
3740 NoTypeInfoCStyleCastExpr(
3741 Context, Context->getPointerType(DRE->getType()), CK_BitCast, DRE);
Fariborz Jahanian11671902012-02-07 17:11:38 +00003742 ReplaceStmt(Exp, castExpr);
3743 ProtocolExprDecls.insert(Exp->getProtocol()->getCanonicalDecl());
3744 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3745 return castExpr;
3746
3747}
3748
3749bool RewriteModernObjC::BufferContainsPPDirectives(const char *startBuf,
3750 const char *endBuf) {
3751 while (startBuf < endBuf) {
3752 if (*startBuf == '#') {
3753 // Skip whitespace.
3754 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
3755 ;
3756 if (!strncmp(startBuf, "if", strlen("if")) ||
3757 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
3758 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
3759 !strncmp(startBuf, "define", strlen("define")) ||
3760 !strncmp(startBuf, "undef", strlen("undef")) ||
3761 !strncmp(startBuf, "else", strlen("else")) ||
3762 !strncmp(startBuf, "elif", strlen("elif")) ||
3763 !strncmp(startBuf, "endif", strlen("endif")) ||
3764 !strncmp(startBuf, "pragma", strlen("pragma")) ||
3765 !strncmp(startBuf, "include", strlen("include")) ||
3766 !strncmp(startBuf, "import", strlen("import")) ||
3767 !strncmp(startBuf, "include_next", strlen("include_next")))
3768 return true;
3769 }
3770 startBuf++;
3771 }
3772 return false;
3773}
3774
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003775/// IsTagDefinedInsideClass - This routine checks that a named tagged type
3776/// is defined inside an objective-c class. If so, it returns true.
Fariborz Jahanian144b7222012-05-01 17:46:45 +00003777bool RewriteModernObjC::IsTagDefinedInsideClass(ObjCContainerDecl *IDecl,
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003778 TagDecl *Tag,
3779 bool &IsNamedDefinition) {
Fariborz Jahanian5979c312012-04-30 19:46:53 +00003780 if (!IDecl)
3781 return false;
3782 SourceLocation TagLocation;
3783 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) {
3784 RD = RD->getDefinition();
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003785 if (!RD || !RD->getDeclName().getAsIdentifierInfo())
Fariborz Jahanian5979c312012-04-30 19:46:53 +00003786 return false;
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003787 IsNamedDefinition = true;
Fariborz Jahanian5979c312012-04-30 19:46:53 +00003788 TagLocation = RD->getLocation();
3789 return Context->getSourceManager().isBeforeInTranslationUnit(
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003790 IDecl->getLocation(), TagLocation);
3791 }
3792 if (EnumDecl *ED = dyn_cast<EnumDecl>(Tag)) {
3793 if (!ED || !ED->getDeclName().getAsIdentifierInfo())
3794 return false;
3795 IsNamedDefinition = true;
3796 TagLocation = ED->getLocation();
3797 return Context->getSourceManager().isBeforeInTranslationUnit(
3798 IDecl->getLocation(), TagLocation);
3799
Fariborz Jahanian5979c312012-04-30 19:46:53 +00003800 }
3801 return false;
3802}
3803
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003804/// RewriteObjCFieldDeclType - This routine rewrites a type into the buffer.
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003805/// It handles elaborated types, as well as enum types in the process.
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003806bool RewriteModernObjC::RewriteObjCFieldDeclType(QualType &Type,
3807 std::string &Result) {
Fariborz Jahaniand7c67772012-05-02 17:34:59 +00003808 if (isa<TypedefType>(Type)) {
3809 Result += "\t";
3810 return false;
3811 }
3812
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003813 if (Type->isArrayType()) {
3814 QualType ElemTy = Context->getBaseElementType(Type);
3815 return RewriteObjCFieldDeclType(ElemTy, Result);
3816 }
3817 else if (Type->isRecordType()) {
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003818 RecordDecl *RD = Type->getAs<RecordType>()->getDecl();
3819 if (RD->isCompleteDefinition()) {
3820 if (RD->isStruct())
3821 Result += "\n\tstruct ";
3822 else if (RD->isUnion())
3823 Result += "\n\tunion ";
3824 else
3825 assert(false && "class not allowed as an ivar type");
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003826
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003827 Result += RD->getName();
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003828 if (GlobalDefinedTags.count(RD)) {
3829 // struct/union is defined globally, use it.
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003830 Result += " ";
3831 return true;
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003832 }
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003833 Result += " {\n";
3834 for (RecordDecl::field_iterator i = RD->field_begin(),
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003835 e = RD->field_end(); i != e; ++i) {
David Blaikie40ed2972012-06-06 20:45:41 +00003836 FieldDecl *FD = *i;
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003837 RewriteObjCFieldDecl(FD, Result);
3838 }
3839 Result += "\t} ";
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003840 return true;
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003841 }
3842 }
3843 else if (Type->isEnumeralType()) {
3844 EnumDecl *ED = Type->getAs<EnumType>()->getDecl();
3845 if (ED->isCompleteDefinition()) {
3846 Result += "\n\tenum ";
3847 Result += ED->getName();
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003848 if (GlobalDefinedTags.count(ED)) {
3849 // Enum is globall defined, use it.
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003850 Result += " ";
3851 return true;
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003852 }
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003853
3854 Result += " {\n";
3855 for (EnumDecl::enumerator_iterator EC = ED->enumerator_begin(),
3856 ECEnd = ED->enumerator_end(); EC != ECEnd; ++EC) {
3857 Result += "\t"; Result += EC->getName(); Result += " = ";
3858 llvm::APSInt Val = EC->getInitVal();
3859 Result += Val.toString(10);
3860 Result += ",\n";
3861 }
3862 Result += "\t} ";
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003863 return true;
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003864 }
3865 }
3866
3867 Result += "\t";
3868 convertObjCTypeToCStyleType(Type);
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003869 return false;
3870}
3871
3872
3873/// RewriteObjCFieldDecl - This routine rewrites a field into the buffer.
3874/// It handles elaborated types, as well as enum types in the process.
3875void RewriteModernObjC::RewriteObjCFieldDecl(FieldDecl *fieldDecl,
3876 std::string &Result) {
3877 QualType Type = fieldDecl->getType();
3878 std::string Name = fieldDecl->getNameAsString();
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003879
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003880 bool EleboratedType = RewriteObjCFieldDeclType(Type, Result);
3881 if (!EleboratedType)
3882 Type.getAsStringInternal(Name, Context->getPrintingPolicy());
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003883 Result += Name;
3884 if (fieldDecl->isBitField()) {
3885 Result += " : "; Result += utostr(fieldDecl->getBitWidthValue(*Context));
3886 }
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003887 else if (EleboratedType && Type->isArrayType()) {
Eli Friedman07bab732012-12-13 01:43:21 +00003888 const ArrayType *AT = Context->getAsArrayType(Type);
3889 do {
3890 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003891 Result += "[";
3892 llvm::APInt Dim = CAT->getSize();
3893 Result += utostr(Dim.getZExtValue());
3894 Result += "]";
3895 }
Eli Friedman07bab732012-12-13 01:43:21 +00003896 AT = Context->getAsArrayType(AT->getElementType());
3897 } while (AT);
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003898 }
3899
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003900 Result += ";\n";
3901}
3902
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003903/// RewriteLocallyDefinedNamedAggregates - This routine rewrites locally defined
3904/// named aggregate types into the input buffer.
3905void RewriteModernObjC::RewriteLocallyDefinedNamedAggregates(FieldDecl *fieldDecl,
3906 std::string &Result) {
3907 QualType Type = fieldDecl->getType();
Fariborz Jahaniand7c67772012-05-02 17:34:59 +00003908 if (isa<TypedefType>(Type))
3909 return;
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003910 if (Type->isArrayType())
3911 Type = Context->getBaseElementType(Type);
Fariborz Jahanian144b7222012-05-01 17:46:45 +00003912 ObjCContainerDecl *IDecl =
3913 dyn_cast<ObjCContainerDecl>(fieldDecl->getDeclContext());
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003914
3915 TagDecl *TD = 0;
3916 if (Type->isRecordType()) {
3917 TD = Type->getAs<RecordType>()->getDecl();
3918 }
3919 else if (Type->isEnumeralType()) {
3920 TD = Type->getAs<EnumType>()->getDecl();
3921 }
3922
3923 if (TD) {
3924 if (GlobalDefinedTags.count(TD))
3925 return;
3926
3927 bool IsNamedDefinition = false;
3928 if (IsTagDefinedInsideClass(IDecl, TD, IsNamedDefinition)) {
3929 RewriteObjCFieldDeclType(Type, Result);
3930 Result += ";";
3931 }
3932 if (IsNamedDefinition)
3933 GlobalDefinedTags.insert(TD);
3934 }
3935
3936}
3937
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00003938unsigned RewriteModernObjC::ObjCIvarBitfieldGroupNo(ObjCIvarDecl *IV) {
3939 const ObjCInterfaceDecl *CDecl = IV->getContainingInterface();
3940 if (ObjCInterefaceHasBitfieldGroups.count(CDecl)) {
3941 return IvarGroupNumber[IV];
3942 }
3943 unsigned GroupNo = 0;
3944 SmallVector<const ObjCIvarDecl *, 8> IVars;
3945 for (const ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
3946 IVD; IVD = IVD->getNextIvar())
3947 IVars.push_back(IVD);
3948
3949 for (unsigned i = 0, e = IVars.size(); i < e; i++)
3950 if (IVars[i]->isBitField()) {
3951 IvarGroupNumber[IVars[i++]] = ++GroupNo;
3952 while (i < e && IVars[i]->isBitField())
3953 IvarGroupNumber[IVars[i++]] = GroupNo;
3954 if (i < e)
3955 --i;
3956 }
3957
3958 ObjCInterefaceHasBitfieldGroups.insert(CDecl);
3959 return IvarGroupNumber[IV];
3960}
3961
3962QualType RewriteModernObjC::SynthesizeBitfieldGroupStructType(
3963 ObjCIvarDecl *IV,
3964 SmallVectorImpl<ObjCIvarDecl *> &IVars) {
3965 std::string StructTagName;
3966 ObjCIvarBitfieldGroupType(IV, StructTagName);
3967 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct,
3968 Context->getTranslationUnitDecl(),
3969 SourceLocation(), SourceLocation(),
3970 &Context->Idents.get(StructTagName));
3971 for (unsigned i=0, e = IVars.size(); i < e; i++) {
3972 ObjCIvarDecl *Ivar = IVars[i];
3973 RD->addDecl(FieldDecl::Create(*Context, RD, SourceLocation(), SourceLocation(),
3974 &Context->Idents.get(Ivar->getName()),
3975 Ivar->getType(),
3976 0, /*Expr *BW */Ivar->getBitWidth(), false,
3977 ICIS_NoInit));
3978 }
3979 RD->completeDefinition();
3980 return Context->getTagDeclType(RD);
3981}
3982
3983QualType RewriteModernObjC::GetGroupRecordTypeForObjCIvarBitfield(ObjCIvarDecl *IV) {
3984 const ObjCInterfaceDecl *CDecl = IV->getContainingInterface();
3985 unsigned GroupNo = ObjCIvarBitfieldGroupNo(IV);
3986 std::pair<const ObjCInterfaceDecl*, unsigned> tuple = std::make_pair(CDecl, GroupNo);
3987 if (GroupRecordType.count(tuple))
3988 return GroupRecordType[tuple];
3989
3990 SmallVector<ObjCIvarDecl *, 8> IVars;
3991 for (const ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
3992 IVD; IVD = IVD->getNextIvar()) {
3993 if (IVD->isBitField())
3994 IVars.push_back(const_cast<ObjCIvarDecl *>(IVD));
3995 else {
3996 if (!IVars.empty()) {
3997 unsigned GroupNo = ObjCIvarBitfieldGroupNo(IVars[0]);
3998 // Generate the struct type for this group of bitfield ivars.
3999 GroupRecordType[std::make_pair(CDecl, GroupNo)] =
4000 SynthesizeBitfieldGroupStructType(IVars[0], IVars);
4001 IVars.clear();
4002 }
4003 }
4004 }
4005 if (!IVars.empty()) {
4006 // Do the last one.
4007 unsigned GroupNo = ObjCIvarBitfieldGroupNo(IVars[0]);
4008 GroupRecordType[std::make_pair(CDecl, GroupNo)] =
4009 SynthesizeBitfieldGroupStructType(IVars[0], IVars);
4010 }
4011 QualType RetQT = GroupRecordType[tuple];
4012 assert(!RetQT.isNull() && "GetGroupRecordTypeForObjCIvarBitfield struct type is NULL");
4013
4014 return RetQT;
4015}
4016
4017/// ObjCIvarBitfieldGroupDecl - Names field decl. for ivar bitfield group.
4018/// Name would be: classname__GRBF_n where n is the group number for this ivar.
4019void RewriteModernObjC::ObjCIvarBitfieldGroupDecl(ObjCIvarDecl *IV,
4020 std::string &Result) {
4021 const ObjCInterfaceDecl *CDecl = IV->getContainingInterface();
4022 Result += CDecl->getName();
4023 Result += "__GRBF_";
4024 unsigned GroupNo = ObjCIvarBitfieldGroupNo(IV);
4025 Result += utostr(GroupNo);
4026 return;
4027}
4028
4029/// ObjCIvarBitfieldGroupType - Names struct type for ivar bitfield group.
4030/// Name of the struct would be: classname__T_n where n is the group number for
4031/// this ivar.
4032void RewriteModernObjC::ObjCIvarBitfieldGroupType(ObjCIvarDecl *IV,
4033 std::string &Result) {
4034 const ObjCInterfaceDecl *CDecl = IV->getContainingInterface();
4035 Result += CDecl->getName();
4036 Result += "__T_";
4037 unsigned GroupNo = ObjCIvarBitfieldGroupNo(IV);
4038 Result += utostr(GroupNo);
4039 return;
4040}
4041
4042/// ObjCIvarBitfieldGroupOffset - Names symbol for ivar bitfield group field offset.
4043/// Name would be: OBJC_IVAR_$_classname__GRBF_n where n is the group number for
4044/// this ivar.
4045void RewriteModernObjC::ObjCIvarBitfieldGroupOffset(ObjCIvarDecl *IV,
4046 std::string &Result) {
4047 Result += "OBJC_IVAR_$_";
4048 ObjCIvarBitfieldGroupDecl(IV, Result);
4049}
4050
4051#define SKIP_BITFIELDS(IX, ENDIX, VEC) { \
4052 while ((IX < ENDIX) && VEC[IX]->isBitField()) \
4053 ++IX; \
4054 if (IX < ENDIX) \
4055 --IX; \
4056}
4057
Fariborz Jahanian11671902012-02-07 17:11:38 +00004058/// RewriteObjCInternalStruct - Rewrite one internal struct corresponding to
4059/// an objective-c class with ivars.
4060void RewriteModernObjC::RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
4061 std::string &Result) {
4062 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
4063 assert(CDecl->getName() != "" &&
4064 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanian11671902012-02-07 17:11:38 +00004065 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Fariborz Jahaniancb1d9f32012-02-10 23:18:24 +00004066 SmallVector<ObjCIvarDecl *, 8> IVars;
4067 for (ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
Fariborz Jahaniand7a32612012-03-06 17:16:27 +00004068 IVD; IVD = IVD->getNextIvar())
Fariborz Jahaniancb1d9f32012-02-10 23:18:24 +00004069 IVars.push_back(IVD);
Fariborz Jahaniand7a32612012-03-06 17:16:27 +00004070
Fariborz Jahanian11671902012-02-07 17:11:38 +00004071 SourceLocation LocStart = CDecl->getLocStart();
4072 SourceLocation LocEnd = CDecl->getEndOfDefinitionLoc();
Fariborz Jahaniancb1d9f32012-02-10 23:18:24 +00004073
Fariborz Jahanian11671902012-02-07 17:11:38 +00004074 const char *startBuf = SM->getCharacterData(LocStart);
4075 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahaniancb1d9f32012-02-10 23:18:24 +00004076
Fariborz Jahanian11671902012-02-07 17:11:38 +00004077 // If no ivars and no root or if its root, directly or indirectly,
4078 // have no ivars (thus not synthesized) then no need to synthesize this class.
Fariborz Jahaniancb1d9f32012-02-10 23:18:24 +00004079 if ((!CDecl->isThisDeclarationADefinition() || IVars.size() == 0) &&
Fariborz Jahanian11671902012-02-07 17:11:38 +00004080 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
4081 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
4082 ReplaceText(LocStart, endBuf-startBuf, Result);
4083 return;
4084 }
Fariborz Jahaniancb1d9f32012-02-10 23:18:24 +00004085
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00004086 // Insert named struct/union definitions inside class to
4087 // outer scope. This follows semantics of locally defined
4088 // struct/unions in objective-c classes.
4089 for (unsigned i = 0, e = IVars.size(); i < e; i++)
4090 RewriteLocallyDefinedNamedAggregates(IVars[i], Result);
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00004091
4092 // Insert named structs which are syntheized to group ivar bitfields
4093 // to outer scope as well.
4094 for (unsigned i = 0, e = IVars.size(); i < e; i++)
4095 if (IVars[i]->isBitField()) {
4096 ObjCIvarDecl *IV = IVars[i];
4097 QualType QT = GetGroupRecordTypeForObjCIvarBitfield(IV);
4098 RewriteObjCFieldDeclType(QT, Result);
4099 Result += ";";
4100 // skip over ivar bitfields in this group.
4101 SKIP_BITFIELDS(i , e, IVars);
4102 }
4103
Fariborz Jahanian11671902012-02-07 17:11:38 +00004104 Result += "\nstruct ";
4105 Result += CDecl->getNameAsString();
Fariborz Jahaniancb1d9f32012-02-10 23:18:24 +00004106 Result += "_IMPL {\n";
4107
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00004108 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Fariborz Jahaniancb1d9f32012-02-10 23:18:24 +00004109 Result += "\tstruct "; Result += RCDecl->getNameAsString();
4110 Result += "_IMPL "; Result += RCDecl->getNameAsString();
4111 Result += "_IVARS;\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00004112 }
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00004113
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00004114 for (unsigned i = 0, e = IVars.size(); i < e; i++) {
4115 if (IVars[i]->isBitField()) {
4116 ObjCIvarDecl *IV = IVars[i];
4117 Result += "\tstruct ";
4118 ObjCIvarBitfieldGroupType(IV, Result); Result += " ";
4119 ObjCIvarBitfieldGroupDecl(IV, Result); Result += ";\n";
4120 // skip over ivar bitfields in this group.
4121 SKIP_BITFIELDS(i , e, IVars);
4122 }
4123 else
4124 RewriteObjCFieldDecl(IVars[i], Result);
4125 }
Fariborz Jahanian245534d2012-02-12 21:36:23 +00004126
Fariborz Jahaniancb1d9f32012-02-10 23:18:24 +00004127 Result += "};\n";
4128 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
4129 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00004130 // Mark this struct as having been generated.
4131 if (!ObjCSynthesizedStructs.insert(CDecl))
4132 llvm_unreachable("struct already synthesize- RewriteObjCInternalStruct");
Fariborz Jahanian11671902012-02-07 17:11:38 +00004133}
4134
Fariborz Jahanian5e49eb92012-02-22 18:13:25 +00004135/// RewriteIvarOffsetSymbols - Rewrite ivar offset symbols of those ivars which
4136/// have been referenced in an ivar access expression.
4137void RewriteModernObjC::RewriteIvarOffsetSymbols(ObjCInterfaceDecl *CDecl,
4138 std::string &Result) {
4139 // write out ivar offset symbols which have been referenced in an ivar
4140 // access expression.
4141 llvm::SmallPtrSet<ObjCIvarDecl *, 8> Ivars = ReferencedIvars[CDecl];
4142 if (Ivars.empty())
4143 return;
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00004144
4145 llvm::DenseSet<std::pair<const ObjCInterfaceDecl*, unsigned> > GroupSymbolOutput;
Fariborz Jahanian5e49eb92012-02-22 18:13:25 +00004146 for (llvm::SmallPtrSet<ObjCIvarDecl *, 8>::iterator i = Ivars.begin(),
4147 e = Ivars.end(); i != e; i++) {
4148 ObjCIvarDecl *IvarDecl = (*i);
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00004149 const ObjCInterfaceDecl *IDecl = IvarDecl->getContainingInterface();
4150 unsigned GroupNo = 0;
4151 if (IvarDecl->isBitField()) {
4152 GroupNo = ObjCIvarBitfieldGroupNo(IvarDecl);
4153 if (GroupSymbolOutput.count(std::make_pair(IDecl, GroupNo)))
4154 continue;
4155 }
Fariborz Jahaniane47bf2b2012-03-12 16:46:58 +00004156 Result += "\n";
4157 if (LangOpts.MicrosoftExt)
4158 Result += "__declspec(allocate(\".objc_ivar$B\")) ";
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00004159 Result += "extern \"C\" ";
Fariborz Jahaniane47bf2b2012-03-12 16:46:58 +00004160 if (LangOpts.MicrosoftExt &&
4161 IvarDecl->getAccessControl() != ObjCIvarDecl::Private &&
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00004162 IvarDecl->getAccessControl() != ObjCIvarDecl::Package)
4163 Result += "__declspec(dllimport) ";
4164
Fariborz Jahanian38c59102012-03-27 16:21:30 +00004165 Result += "unsigned long ";
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00004166 if (IvarDecl->isBitField()) {
4167 ObjCIvarBitfieldGroupOffset(IvarDecl, Result);
4168 GroupSymbolOutput.insert(std::make_pair(IDecl, GroupNo));
4169 }
4170 else
4171 WriteInternalIvarName(CDecl, IvarDecl, Result);
Fariborz Jahaniana854174a2012-03-20 17:13:39 +00004172 Result += ";";
Fariborz Jahanian5e49eb92012-02-22 18:13:25 +00004173 }
4174}
4175
Fariborz Jahanian11671902012-02-07 17:11:38 +00004176//===----------------------------------------------------------------------===//
4177// Meta Data Emission
4178//===----------------------------------------------------------------------===//
4179
4180
4181/// RewriteImplementations - This routine rewrites all method implementations
4182/// and emits meta-data.
4183
4184void RewriteModernObjC::RewriteImplementations() {
4185 int ClsDefCount = ClassImplementation.size();
4186 int CatDefCount = CategoryImplementation.size();
4187
4188 // Rewrite implemented methods
Fariborz Jahanian088959a2012-02-11 20:10:52 +00004189 for (int i = 0; i < ClsDefCount; i++) {
4190 ObjCImplementationDecl *OIMP = ClassImplementation[i];
4191 ObjCInterfaceDecl *CDecl = OIMP->getClassInterface();
4192 if (CDecl->isImplicitInterfaceDecl())
Fariborz Jahaniand268b0c2012-02-17 22:20:12 +00004193 assert(false &&
4194 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian088959a2012-02-11 20:10:52 +00004195 RewriteImplementationDecl(OIMP);
4196 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00004197
Fariborz Jahanian320c88a2012-02-17 20:33:00 +00004198 for (int i = 0; i < CatDefCount; i++) {
4199 ObjCCategoryImplDecl *CIMP = CategoryImplementation[i];
4200 ObjCInterfaceDecl *CDecl = CIMP->getClassInterface();
4201 if (CDecl->isImplicitInterfaceDecl())
4202 assert(false &&
4203 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian320c88a2012-02-17 20:33:00 +00004204 RewriteImplementationDecl(CIMP);
4205 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00004206}
4207
4208void RewriteModernObjC::RewriteByRefString(std::string &ResultStr,
4209 const std::string &Name,
4210 ValueDecl *VD, bool def) {
4211 assert(BlockByRefDeclNo.count(VD) &&
4212 "RewriteByRefString: ByRef decl missing");
4213 if (def)
4214 ResultStr += "struct ";
4215 ResultStr += "__Block_byref_" + Name +
4216 "_" + utostr(BlockByRefDeclNo[VD]) ;
4217}
4218
4219static bool HasLocalVariableExternalStorage(ValueDecl *VD) {
4220 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4221 return (Var->isFunctionOrMethodVarDecl() && !Var->hasLocalStorage());
4222 return false;
4223}
4224
4225std::string RewriteModernObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
4226 StringRef funcName,
4227 std::string Tag) {
4228 const FunctionType *AFT = CE->getFunctionType();
4229 QualType RT = AFT->getResultType();
4230 std::string StructRef = "struct " + Tag;
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00004231 SourceLocation BlockLoc = CE->getExprLoc();
4232 std::string S;
4233 ConvertSourceLocationToLineDirective(BlockLoc, S);
4234
4235 S += "static " + RT.getAsString(Context->getPrintingPolicy()) + " __" +
4236 funcName.str() + "_block_func_" + utostr(i);
Fariborz Jahanian11671902012-02-07 17:11:38 +00004237
4238 BlockDecl *BD = CE->getBlockDecl();
4239
4240 if (isa<FunctionNoProtoType>(AFT)) {
4241 // No user-supplied arguments. Still need to pass in a pointer to the
4242 // block (to reference imported block decl refs).
4243 S += "(" + StructRef + " *__cself)";
4244 } else if (BD->param_empty()) {
4245 S += "(" + StructRef + " *__cself)";
4246 } else {
4247 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
4248 assert(FT && "SynthesizeBlockFunc: No function proto");
4249 S += '(';
4250 // first add the implicit argument.
4251 S += StructRef + " *__cself, ";
4252 std::string ParamStr;
4253 for (BlockDecl::param_iterator AI = BD->param_begin(),
4254 E = BD->param_end(); AI != E; ++AI) {
4255 if (AI != BD->param_begin()) S += ", ";
4256 ParamStr = (*AI)->getNameAsString();
4257 QualType QT = (*AI)->getType();
Fariborz Jahanian835cabe2012-03-27 16:42:20 +00004258 (void)convertBlockPointerToFunctionPointer(QT);
4259 QT.getAsStringInternal(ParamStr, Context->getPrintingPolicy());
Fariborz Jahanian11671902012-02-07 17:11:38 +00004260 S += ParamStr;
4261 }
4262 if (FT->isVariadic()) {
4263 if (!BD->param_empty()) S += ", ";
4264 S += "...";
4265 }
4266 S += ')';
4267 }
4268 S += " {\n";
4269
4270 // Create local declarations to avoid rewriting all closure decl ref exprs.
4271 // First, emit a declaration for all "by ref" decls.
Craig Topper2341c0d2013-07-04 03:08:24 +00004272 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00004273 E = BlockByRefDecls.end(); I != E; ++I) {
4274 S += " ";
4275 std::string Name = (*I)->getNameAsString();
4276 std::string TypeString;
4277 RewriteByRefString(TypeString, Name, (*I));
4278 TypeString += " *";
4279 Name = TypeString + Name;
4280 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
4281 }
4282 // Next, emit a declaration for all "by copy" declarations.
Craig Topper2341c0d2013-07-04 03:08:24 +00004283 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00004284 E = BlockByCopyDecls.end(); I != E; ++I) {
4285 S += " ";
4286 // Handle nested closure invocation. For example:
4287 //
4288 // void (^myImportedClosure)(void);
4289 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
4290 //
4291 // void (^anotherClosure)(void);
4292 // anotherClosure = ^(void) {
4293 // myImportedClosure(); // import and invoke the closure
4294 // };
4295 //
4296 if (isTopLevelBlockPointerType((*I)->getType())) {
4297 RewriteBlockPointerTypeVariable(S, (*I));
4298 S += " = (";
4299 RewriteBlockPointerType(S, (*I)->getType());
4300 S += ")";
4301 S += "__cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
4302 }
4303 else {
4304 std::string Name = (*I)->getNameAsString();
4305 QualType QT = (*I)->getType();
4306 if (HasLocalVariableExternalStorage(*I))
4307 QT = Context->getPointerType(QT);
4308 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
4309 S += Name + " = __cself->" +
4310 (*I)->getNameAsString() + "; // bound by copy\n";
4311 }
4312 }
4313 std::string RewrittenStr = RewrittenBlockExprs[CE];
4314 const char *cstr = RewrittenStr.c_str();
4315 while (*cstr++ != '{') ;
4316 S += cstr;
4317 S += "\n";
4318 return S;
4319}
4320
4321std::string RewriteModernObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
4322 StringRef funcName,
4323 std::string Tag) {
4324 std::string StructRef = "struct " + Tag;
4325 std::string S = "static void __";
4326
4327 S += funcName;
4328 S += "_block_copy_" + utostr(i);
4329 S += "(" + StructRef;
4330 S += "*dst, " + StructRef;
4331 S += "*src) {";
4332 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
4333 E = ImportedBlockDecls.end(); I != E; ++I) {
4334 ValueDecl *VD = (*I);
4335 S += "_Block_object_assign((void*)&dst->";
4336 S += (*I)->getNameAsString();
4337 S += ", (void*)src->";
4338 S += (*I)->getNameAsString();
4339 if (BlockByRefDeclsPtrSet.count((*I)))
4340 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
4341 else if (VD->getType()->isBlockPointerType())
4342 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
4343 else
4344 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
4345 }
4346 S += "}\n";
4347
4348 S += "\nstatic void __";
4349 S += funcName;
4350 S += "_block_dispose_" + utostr(i);
4351 S += "(" + StructRef;
4352 S += "*src) {";
4353 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
4354 E = ImportedBlockDecls.end(); I != E; ++I) {
4355 ValueDecl *VD = (*I);
4356 S += "_Block_object_dispose((void*)src->";
4357 S += (*I)->getNameAsString();
4358 if (BlockByRefDeclsPtrSet.count((*I)))
4359 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
4360 else if (VD->getType()->isBlockPointerType())
4361 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
4362 else
4363 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
4364 }
4365 S += "}\n";
4366 return S;
4367}
4368
4369std::string RewriteModernObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
4370 std::string Desc) {
4371 std::string S = "\nstruct " + Tag;
4372 std::string Constructor = " " + Tag;
4373
4374 S += " {\n struct __block_impl impl;\n";
4375 S += " struct " + Desc;
4376 S += "* Desc;\n";
4377
4378 Constructor += "(void *fp, "; // Invoke function pointer.
4379 Constructor += "struct " + Desc; // Descriptor pointer.
4380 Constructor += " *desc";
4381
4382 if (BlockDeclRefs.size()) {
4383 // Output all "by copy" declarations.
Craig Topper2341c0d2013-07-04 03:08:24 +00004384 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00004385 E = BlockByCopyDecls.end(); I != E; ++I) {
4386 S += " ";
4387 std::string FieldName = (*I)->getNameAsString();
4388 std::string ArgName = "_" + FieldName;
4389 // Handle nested closure invocation. For example:
4390 //
4391 // void (^myImportedBlock)(void);
4392 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
4393 //
4394 // void (^anotherBlock)(void);
4395 // anotherBlock = ^(void) {
4396 // myImportedBlock(); // import and invoke the closure
4397 // };
4398 //
4399 if (isTopLevelBlockPointerType((*I)->getType())) {
4400 S += "struct __block_impl *";
4401 Constructor += ", void *" + ArgName;
4402 } else {
4403 QualType QT = (*I)->getType();
4404 if (HasLocalVariableExternalStorage(*I))
4405 QT = Context->getPointerType(QT);
4406 QT.getAsStringInternal(FieldName, Context->getPrintingPolicy());
4407 QT.getAsStringInternal(ArgName, Context->getPrintingPolicy());
4408 Constructor += ", " + ArgName;
4409 }
4410 S += FieldName + ";\n";
4411 }
4412 // Output all "by ref" declarations.
Craig Topper2341c0d2013-07-04 03:08:24 +00004413 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00004414 E = BlockByRefDecls.end(); I != E; ++I) {
4415 S += " ";
4416 std::string FieldName = (*I)->getNameAsString();
4417 std::string ArgName = "_" + FieldName;
4418 {
4419 std::string TypeString;
4420 RewriteByRefString(TypeString, FieldName, (*I));
4421 TypeString += " *";
4422 FieldName = TypeString + FieldName;
4423 ArgName = TypeString + ArgName;
4424 Constructor += ", " + ArgName;
4425 }
4426 S += FieldName + "; // by ref\n";
4427 }
4428 // Finish writing the constructor.
4429 Constructor += ", int flags=0)";
4430 // Initialize all "by copy" arguments.
4431 bool firsTime = true;
Craig Topper2341c0d2013-07-04 03:08:24 +00004432 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00004433 E = BlockByCopyDecls.end(); I != E; ++I) {
4434 std::string Name = (*I)->getNameAsString();
4435 if (firsTime) {
4436 Constructor += " : ";
4437 firsTime = false;
4438 }
4439 else
4440 Constructor += ", ";
4441 if (isTopLevelBlockPointerType((*I)->getType()))
4442 Constructor += Name + "((struct __block_impl *)_" + Name + ")";
4443 else
4444 Constructor += Name + "(_" + Name + ")";
4445 }
4446 // Initialize all "by ref" arguments.
Craig Topper2341c0d2013-07-04 03:08:24 +00004447 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00004448 E = BlockByRefDecls.end(); I != E; ++I) {
4449 std::string Name = (*I)->getNameAsString();
4450 if (firsTime) {
4451 Constructor += " : ";
4452 firsTime = false;
4453 }
4454 else
4455 Constructor += ", ";
4456 Constructor += Name + "(_" + Name + "->__forwarding)";
4457 }
4458
4459 Constructor += " {\n";
4460 if (GlobalVarDecl)
4461 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4462 else
4463 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
4464 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
4465
4466 Constructor += " Desc = desc;\n";
4467 } else {
4468 // Finish writing the constructor.
4469 Constructor += ", int flags=0) {\n";
4470 if (GlobalVarDecl)
4471 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4472 else
4473 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
4474 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
4475 Constructor += " Desc = desc;\n";
4476 }
4477 Constructor += " ";
4478 Constructor += "}\n";
4479 S += Constructor;
4480 S += "};\n";
4481 return S;
4482}
4483
4484std::string RewriteModernObjC::SynthesizeBlockDescriptor(std::string DescTag,
4485 std::string ImplTag, int i,
4486 StringRef FunName,
4487 unsigned hasCopy) {
4488 std::string S = "\nstatic struct " + DescTag;
4489
Fariborz Jahanian2e7f6382012-05-03 21:44:12 +00004490 S += " {\n size_t reserved;\n";
4491 S += " size_t Block_size;\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00004492 if (hasCopy) {
4493 S += " void (*copy)(struct ";
4494 S += ImplTag; S += "*, struct ";
4495 S += ImplTag; S += "*);\n";
4496
4497 S += " void (*dispose)(struct ";
4498 S += ImplTag; S += "*);\n";
4499 }
4500 S += "} ";
4501
4502 S += DescTag + "_DATA = { 0, sizeof(struct ";
4503 S += ImplTag + ")";
4504 if (hasCopy) {
4505 S += ", __" + FunName.str() + "_block_copy_" + utostr(i);
4506 S += ", __" + FunName.str() + "_block_dispose_" + utostr(i);
4507 }
4508 S += "};\n";
4509 return S;
4510}
4511
4512void RewriteModernObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
4513 StringRef FunName) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00004514 bool RewriteSC = (GlobalVarDecl &&
4515 !Blocks.empty() &&
4516 GlobalVarDecl->getStorageClass() == SC_Static &&
4517 GlobalVarDecl->getType().getCVRQualifiers());
4518 if (RewriteSC) {
4519 std::string SC(" void __");
4520 SC += GlobalVarDecl->getNameAsString();
4521 SC += "() {}";
4522 InsertText(FunLocStart, SC);
4523 }
4524
4525 // Insert closures that were part of the function.
4526 for (unsigned i = 0, count=0; i < Blocks.size(); i++) {
4527 CollectBlockDeclRefInfo(Blocks[i]);
4528 // Need to copy-in the inner copied-in variables not actually used in this
4529 // block.
4530 for (int j = 0; j < InnerDeclRefsCount[i]; j++) {
John McCall113bee02012-03-10 09:33:50 +00004531 DeclRefExpr *Exp = InnerDeclRefs[count++];
Fariborz Jahanian11671902012-02-07 17:11:38 +00004532 ValueDecl *VD = Exp->getDecl();
4533 BlockDeclRefs.push_back(Exp);
John McCall113bee02012-03-10 09:33:50 +00004534 if (!VD->hasAttr<BlocksAttr>()) {
4535 if (!BlockByCopyDeclsPtrSet.count(VD)) {
4536 BlockByCopyDeclsPtrSet.insert(VD);
4537 BlockByCopyDecls.push_back(VD);
4538 }
4539 continue;
Fariborz Jahanian11671902012-02-07 17:11:38 +00004540 }
John McCall113bee02012-03-10 09:33:50 +00004541
4542 if (!BlockByRefDeclsPtrSet.count(VD)) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00004543 BlockByRefDeclsPtrSet.insert(VD);
4544 BlockByRefDecls.push_back(VD);
4545 }
John McCall113bee02012-03-10 09:33:50 +00004546
Fariborz Jahanian11671902012-02-07 17:11:38 +00004547 // imported objects in the inner blocks not used in the outer
4548 // blocks must be copied/disposed in the outer block as well.
John McCall113bee02012-03-10 09:33:50 +00004549 if (VD->getType()->isObjCObjectPointerType() ||
Fariborz Jahanian11671902012-02-07 17:11:38 +00004550 VD->getType()->isBlockPointerType())
4551 ImportedBlockDecls.insert(VD);
4552 }
4553
4554 std::string ImplTag = "__" + FunName.str() + "_block_impl_" + utostr(i);
4555 std::string DescTag = "__" + FunName.str() + "_block_desc_" + utostr(i);
4556
4557 std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
4558
4559 InsertText(FunLocStart, CI);
4560
4561 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
4562
4563 InsertText(FunLocStart, CF);
4564
4565 if (ImportedBlockDecls.size()) {
4566 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
4567 InsertText(FunLocStart, HF);
4568 }
4569 std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
4570 ImportedBlockDecls.size() > 0);
4571 InsertText(FunLocStart, BD);
4572
4573 BlockDeclRefs.clear();
4574 BlockByRefDecls.clear();
4575 BlockByRefDeclsPtrSet.clear();
4576 BlockByCopyDecls.clear();
4577 BlockByCopyDeclsPtrSet.clear();
4578 ImportedBlockDecls.clear();
4579 }
4580 if (RewriteSC) {
4581 // Must insert any 'const/volatile/static here. Since it has been
4582 // removed as result of rewriting of block literals.
4583 std::string SC;
4584 if (GlobalVarDecl->getStorageClass() == SC_Static)
4585 SC = "static ";
4586 if (GlobalVarDecl->getType().isConstQualified())
4587 SC += "const ";
4588 if (GlobalVarDecl->getType().isVolatileQualified())
4589 SC += "volatile ";
4590 if (GlobalVarDecl->getType().isRestrictQualified())
4591 SC += "restrict ";
4592 InsertText(FunLocStart, SC);
4593 }
Fariborz Jahaniane0050702012-03-23 00:00:49 +00004594 if (GlobalConstructionExp) {
4595 // extra fancy dance for global literal expression.
4596
4597 // Always the latest block expression on the block stack.
4598 std::string Tag = "__";
4599 Tag += FunName;
4600 Tag += "_block_impl_";
4601 Tag += utostr(Blocks.size()-1);
4602 std::string globalBuf = "static ";
4603 globalBuf += Tag; globalBuf += " ";
4604 std::string SStr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00004605
Fariborz Jahaniane0050702012-03-23 00:00:49 +00004606 llvm::raw_string_ostream constructorExprBuf(SStr);
Richard Smith235341b2012-08-16 03:56:14 +00004607 GlobalConstructionExp->printPretty(constructorExprBuf, 0,
Fariborz Jahaniane0050702012-03-23 00:00:49 +00004608 PrintingPolicy(LangOpts));
4609 globalBuf += constructorExprBuf.str();
4610 globalBuf += ";\n";
4611 InsertText(FunLocStart, globalBuf);
4612 GlobalConstructionExp = 0;
4613 }
4614
Fariborz Jahanian11671902012-02-07 17:11:38 +00004615 Blocks.clear();
4616 InnerDeclRefsCount.clear();
4617 InnerDeclRefs.clear();
4618 RewrittenBlockExprs.clear();
4619}
4620
4621void RewriteModernObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
Fariborz Jahaniane49a42c2012-04-25 17:56:48 +00004622 SourceLocation FunLocStart =
4623 (!Blocks.empty()) ? getFunctionSourceLocation(*this, FD)
4624 : FD->getTypeSpecStartLoc();
Fariborz Jahanian11671902012-02-07 17:11:38 +00004625 StringRef FuncName = FD->getName();
4626
4627 SynthesizeBlockLiterals(FunLocStart, FuncName);
4628}
4629
4630static void BuildUniqueMethodName(std::string &Name,
4631 ObjCMethodDecl *MD) {
4632 ObjCInterfaceDecl *IFace = MD->getClassInterface();
4633 Name = IFace->getName();
4634 Name += "__" + MD->getSelector().getAsString();
4635 // Convert colons to underscores.
4636 std::string::size_type loc = 0;
4637 while ((loc = Name.find(":", loc)) != std::string::npos)
4638 Name.replace(loc, 1, "_");
4639}
4640
4641void RewriteModernObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
4642 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
4643 //SourceLocation FunLocStart = MD->getLocStart();
4644 SourceLocation FunLocStart = MD->getLocStart();
4645 std::string FuncName;
4646 BuildUniqueMethodName(FuncName, MD);
4647 SynthesizeBlockLiterals(FunLocStart, FuncName);
4648}
4649
4650void RewriteModernObjC::GetBlockDeclRefExprs(Stmt *S) {
4651 for (Stmt::child_range CI = S->children(); CI; ++CI)
4652 if (*CI) {
4653 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
4654 GetBlockDeclRefExprs(CBE->getBody());
4655 else
4656 GetBlockDeclRefExprs(*CI);
4657 }
4658 // Handle specific things.
Fariborz Jahanian35f6e122012-04-16 23:00:57 +00004659 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4660 if (DRE->refersToEnclosingLocal()) {
4661 // FIXME: Handle enums.
4662 if (!isa<FunctionDecl>(DRE->getDecl()))
4663 BlockDeclRefs.push_back(DRE);
4664 if (HasLocalVariableExternalStorage(DRE->getDecl()))
4665 BlockDeclRefs.push_back(DRE);
Fariborz Jahanian11671902012-02-07 17:11:38 +00004666 }
Fariborz Jahanian35f6e122012-04-16 23:00:57 +00004667 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00004668
4669 return;
4670}
4671
Craig Topper5603df42013-07-05 19:34:19 +00004672void RewriteModernObjC::GetInnerBlockDeclRefExprs(Stmt *S,
4673 SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs,
Fariborz Jahanian11671902012-02-07 17:11:38 +00004674 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts) {
4675 for (Stmt::child_range CI = S->children(); CI; ++CI)
4676 if (*CI) {
4677 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI)) {
4678 InnerContexts.insert(cast<DeclContext>(CBE->getBlockDecl()));
4679 GetInnerBlockDeclRefExprs(CBE->getBody(),
4680 InnerBlockDeclRefs,
4681 InnerContexts);
4682 }
4683 else
4684 GetInnerBlockDeclRefExprs(*CI,
4685 InnerBlockDeclRefs,
4686 InnerContexts);
4687
4688 }
4689 // Handle specific things.
John McCall113bee02012-03-10 09:33:50 +00004690 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4691 if (DRE->refersToEnclosingLocal()) {
4692 if (!isa<FunctionDecl>(DRE->getDecl()) &&
4693 !InnerContexts.count(DRE->getDecl()->getDeclContext()))
4694 InnerBlockDeclRefs.push_back(DRE);
4695 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl()))
4696 if (Var->isFunctionOrMethodVarDecl())
4697 ImportedLocalExternalDecls.insert(Var);
4698 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00004699 }
4700
4701 return;
4702}
4703
Fariborz Jahanianc3cdc412012-02-13 18:57:49 +00004704/// convertObjCTypeToCStyleType - This routine converts such objc types
4705/// as qualified objects, and blocks to their closest c/c++ types that
4706/// it can. It returns true if input type was modified.
4707bool RewriteModernObjC::convertObjCTypeToCStyleType(QualType &T) {
4708 QualType oldT = T;
4709 convertBlockPointerToFunctionPointer(T);
4710 if (T->isFunctionPointerType()) {
4711 QualType PointeeTy;
4712 if (const PointerType* PT = T->getAs<PointerType>()) {
4713 PointeeTy = PT->getPointeeType();
4714 if (const FunctionType *FT = PointeeTy->getAs<FunctionType>()) {
4715 T = convertFunctionTypeOfBlocks(FT);
4716 T = Context->getPointerType(T);
4717 }
4718 }
4719 }
4720
4721 convertToUnqualifiedObjCType(T);
4722 return T != oldT;
4723}
4724
Fariborz Jahanian11671902012-02-07 17:11:38 +00004725/// convertFunctionTypeOfBlocks - This routine converts a function type
4726/// whose result type may be a block pointer or whose argument type(s)
4727/// might be block pointers to an equivalent function type replacing
4728/// all block pointers to function pointers.
4729QualType RewriteModernObjC::convertFunctionTypeOfBlocks(const FunctionType *FT) {
4730 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
4731 // FTP will be null for closures that don't take arguments.
4732 // Generate a funky cast.
4733 SmallVector<QualType, 8> ArgTypes;
4734 QualType Res = FT->getResultType();
Fariborz Jahanianc3cdc412012-02-13 18:57:49 +00004735 bool modified = convertObjCTypeToCStyleType(Res);
Fariborz Jahanian11671902012-02-07 17:11:38 +00004736
4737 if (FTP) {
Alp Toker9cacbab2014-01-20 20:26:09 +00004738 for (FunctionProtoType::param_type_iterator I = FTP->param_type_begin(),
4739 E = FTP->param_type_end();
4740 I && (I != E); ++I) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00004741 QualType t = *I;
4742 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanianc3cdc412012-02-13 18:57:49 +00004743 if (convertObjCTypeToCStyleType(t))
4744 modified = true;
Fariborz Jahanian11671902012-02-07 17:11:38 +00004745 ArgTypes.push_back(t);
4746 }
4747 }
4748 QualType FuncType;
Fariborz Jahanianc3cdc412012-02-13 18:57:49 +00004749 if (modified)
Jordan Rose5c382722013-03-08 21:51:21 +00004750 FuncType = getSimpleFunctionType(Res, ArgTypes);
Fariborz Jahanian11671902012-02-07 17:11:38 +00004751 else FuncType = QualType(FT, 0);
4752 return FuncType;
4753}
4754
4755Stmt *RewriteModernObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
4756 // Navigate to relevant type information.
4757 const BlockPointerType *CPT = 0;
4758
4759 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
4760 CPT = DRE->getType()->getAs<BlockPointerType>();
Fariborz Jahanian11671902012-02-07 17:11:38 +00004761 } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
4762 CPT = MExpr->getType()->getAs<BlockPointerType>();
4763 }
4764 else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
4765 return SynthesizeBlockCall(Exp, PRE->getSubExpr());
4766 }
4767 else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
4768 CPT = IEXPR->getType()->getAs<BlockPointerType>();
4769 else if (const ConditionalOperator *CEXPR =
4770 dyn_cast<ConditionalOperator>(BlockExp)) {
4771 Expr *LHSExp = CEXPR->getLHS();
4772 Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
4773 Expr *RHSExp = CEXPR->getRHS();
4774 Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
4775 Expr *CONDExp = CEXPR->getCond();
4776 ConditionalOperator *CondExpr =
4777 new (Context) ConditionalOperator(CONDExp,
4778 SourceLocation(), cast<Expr>(LHSStmt),
4779 SourceLocation(), cast<Expr>(RHSStmt),
4780 Exp->getType(), VK_RValue, OK_Ordinary);
4781 return CondExpr;
4782 } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
4783 CPT = IRE->getType()->getAs<BlockPointerType>();
4784 } else if (const PseudoObjectExpr *POE
4785 = dyn_cast<PseudoObjectExpr>(BlockExp)) {
4786 CPT = POE->getType()->castAs<BlockPointerType>();
4787 } else {
4788 assert(1 && "RewriteBlockClass: Bad type");
4789 }
4790 assert(CPT && "RewriteBlockClass: Bad type");
4791 const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
4792 assert(FT && "RewriteBlockClass: Bad type");
4793 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
4794 // FTP will be null for closures that don't take arguments.
4795
4796 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
4797 SourceLocation(), SourceLocation(),
4798 &Context->Idents.get("__block_impl"));
4799 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
4800
4801 // Generate a funky cast.
4802 SmallVector<QualType, 8> ArgTypes;
4803
4804 // Push the block argument type.
4805 ArgTypes.push_back(PtrBlock);
4806 if (FTP) {
Alp Toker9cacbab2014-01-20 20:26:09 +00004807 for (FunctionProtoType::param_type_iterator I = FTP->param_type_begin(),
4808 E = FTP->param_type_end();
4809 I && (I != E); ++I) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00004810 QualType t = *I;
4811 // Make sure we convert "t (^)(...)" to "t (*)(...)".
4812 if (!convertBlockPointerToFunctionPointer(t))
4813 convertToUnqualifiedObjCType(t);
4814 ArgTypes.push_back(t);
4815 }
4816 }
4817 // Now do the pointer to function cast.
Jordan Rose5c382722013-03-08 21:51:21 +00004818 QualType PtrToFuncCastType = getSimpleFunctionType(Exp->getType(), ArgTypes);
Fariborz Jahanian11671902012-02-07 17:11:38 +00004819
4820 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
4821
4822 CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock,
4823 CK_BitCast,
4824 const_cast<Expr*>(BlockExp));
4825 // Don't forget the parens to enforce the proper binding.
4826 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4827 BlkCast);
4828 //PE->dump();
4829
4830 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4831 SourceLocation(),
4832 &Context->Idents.get("FuncPtr"),
4833 Context->VoidPtrTy, 0,
4834 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smith2b013182012-06-10 03:12:00 +00004835 ICIS_NoInit);
Fariborz Jahanian11671902012-02-07 17:11:38 +00004836 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
4837 FD->getType(), VK_LValue,
4838 OK_Ordinary);
4839
4840
4841 CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType,
4842 CK_BitCast, ME);
4843 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
4844
4845 SmallVector<Expr*, 8> BlkExprs;
4846 // Add the implicit argument.
4847 BlkExprs.push_back(BlkCast);
4848 // Add the user arguments.
4849 for (CallExpr::arg_iterator I = Exp->arg_begin(),
4850 E = Exp->arg_end(); I != E; ++I) {
4851 BlkExprs.push_back(*I);
4852 }
Benjamin Kramerc215e762012-08-24 11:54:20 +00004853 CallExpr *CE = new (Context) CallExpr(*Context, PE, BlkExprs,
Fariborz Jahanian11671902012-02-07 17:11:38 +00004854 Exp->getType(), VK_RValue,
4855 SourceLocation());
4856 return CE;
4857}
4858
4859// We need to return the rewritten expression to handle cases where the
John McCall113bee02012-03-10 09:33:50 +00004860// DeclRefExpr is embedded in another expression being rewritten.
Fariborz Jahanian11671902012-02-07 17:11:38 +00004861// For example:
4862//
4863// int main() {
4864// __block Foo *f;
4865// __block int i;
4866//
4867// void (^myblock)() = ^() {
John McCall113bee02012-03-10 09:33:50 +00004868// [f test]; // f is a DeclRefExpr embedded in a message (which is being rewritten).
Fariborz Jahanian11671902012-02-07 17:11:38 +00004869// i = 77;
4870// };
4871//}
John McCall113bee02012-03-10 09:33:50 +00004872Stmt *RewriteModernObjC::RewriteBlockDeclRefExpr(DeclRefExpr *DeclRefExp) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00004873 // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
4874 // for each DeclRefExp where BYREFVAR is name of the variable.
John McCall113bee02012-03-10 09:33:50 +00004875 ValueDecl *VD = DeclRefExp->getDecl();
4876 bool isArrow = DeclRefExp->refersToEnclosingLocal();
Fariborz Jahanian11671902012-02-07 17:11:38 +00004877
4878 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4879 SourceLocation(),
4880 &Context->Idents.get("__forwarding"),
4881 Context->VoidPtrTy, 0,
4882 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smith2b013182012-06-10 03:12:00 +00004883 ICIS_NoInit);
Fariborz Jahanian11671902012-02-07 17:11:38 +00004884 MemberExpr *ME = new (Context) MemberExpr(DeclRefExp, isArrow,
4885 FD, SourceLocation(),
4886 FD->getType(), VK_LValue,
4887 OK_Ordinary);
4888
4889 StringRef Name = VD->getName();
4890 FD = FieldDecl::Create(*Context, 0, SourceLocation(), SourceLocation(),
4891 &Context->Idents.get(Name),
4892 Context->VoidPtrTy, 0,
4893 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smith2b013182012-06-10 03:12:00 +00004894 ICIS_NoInit);
Fariborz Jahanian11671902012-02-07 17:11:38 +00004895 ME = new (Context) MemberExpr(ME, true, FD, SourceLocation(),
4896 DeclRefExp->getType(), VK_LValue, OK_Ordinary);
4897
4898
4899
4900 // Need parens to enforce precedence.
4901 ParenExpr *PE = new (Context) ParenExpr(DeclRefExp->getExprLoc(),
4902 DeclRefExp->getExprLoc(),
4903 ME);
4904 ReplaceStmt(DeclRefExp, PE);
4905 return PE;
4906}
4907
4908// Rewrites the imported local variable V with external storage
4909// (static, extern, etc.) as *V
4910//
4911Stmt *RewriteModernObjC::RewriteLocalVariableExternalStorage(DeclRefExpr *DRE) {
4912 ValueDecl *VD = DRE->getDecl();
4913 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4914 if (!ImportedLocalExternalDecls.count(Var))
4915 return DRE;
4916 Expr *Exp = new (Context) UnaryOperator(DRE, UO_Deref, DRE->getType(),
4917 VK_LValue, OK_Ordinary,
4918 DRE->getLocation());
4919 // Need parens to enforce precedence.
4920 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4921 Exp);
4922 ReplaceStmt(DRE, PE);
4923 return PE;
4924}
4925
4926void RewriteModernObjC::RewriteCastExpr(CStyleCastExpr *CE) {
4927 SourceLocation LocStart = CE->getLParenLoc();
4928 SourceLocation LocEnd = CE->getRParenLoc();
4929
4930 // Need to avoid trying to rewrite synthesized casts.
4931 if (LocStart.isInvalid())
4932 return;
4933 // Need to avoid trying to rewrite casts contained in macros.
4934 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
4935 return;
4936
4937 const char *startBuf = SM->getCharacterData(LocStart);
4938 const char *endBuf = SM->getCharacterData(LocEnd);
4939 QualType QT = CE->getType();
4940 const Type* TypePtr = QT->getAs<Type>();
4941 if (isa<TypeOfExprType>(TypePtr)) {
4942 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
4943 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
4944 std::string TypeAsString = "(";
4945 RewriteBlockPointerType(TypeAsString, QT);
4946 TypeAsString += ")";
4947 ReplaceText(LocStart, endBuf-startBuf+1, TypeAsString);
4948 return;
4949 }
4950 // advance the location to startArgList.
4951 const char *argPtr = startBuf;
4952
4953 while (*argPtr++ && (argPtr < endBuf)) {
4954 switch (*argPtr) {
4955 case '^':
4956 // Replace the '^' with '*'.
4957 LocStart = LocStart.getLocWithOffset(argPtr-startBuf);
4958 ReplaceText(LocStart, 1, "*");
4959 break;
4960 }
4961 }
4962 return;
4963}
4964
Fariborz Jahanian2c00acd2012-04-10 00:08:18 +00004965void RewriteModernObjC::RewriteImplicitCastObjCExpr(CastExpr *IC) {
4966 CastKind CastKind = IC->getCastKind();
Fariborz Jahaniancc172282012-04-16 22:14:01 +00004967 if (CastKind != CK_BlockPointerToObjCPointerCast &&
4968 CastKind != CK_AnyPointerToBlockPointerCast)
4969 return;
Fariborz Jahanian2c00acd2012-04-10 00:08:18 +00004970
Fariborz Jahaniancc172282012-04-16 22:14:01 +00004971 QualType QT = IC->getType();
4972 (void)convertBlockPointerToFunctionPointer(QT);
4973 std::string TypeString(QT.getAsString(Context->getPrintingPolicy()));
4974 std::string Str = "(";
4975 Str += TypeString;
4976 Str += ")";
4977 InsertText(IC->getSubExpr()->getLocStart(), &Str[0], Str.size());
4978
Fariborz Jahanian2c00acd2012-04-10 00:08:18 +00004979 return;
4980}
4981
Fariborz Jahanian11671902012-02-07 17:11:38 +00004982void RewriteModernObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
4983 SourceLocation DeclLoc = FD->getLocation();
4984 unsigned parenCount = 0;
4985
4986 // We have 1 or more arguments that have closure pointers.
4987 const char *startBuf = SM->getCharacterData(DeclLoc);
4988 const char *startArgList = strchr(startBuf, '(');
4989
4990 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
4991
4992 parenCount++;
4993 // advance the location to startArgList.
4994 DeclLoc = DeclLoc.getLocWithOffset(startArgList-startBuf);
4995 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
4996
4997 const char *argPtr = startArgList;
4998
4999 while (*argPtr++ && parenCount) {
5000 switch (*argPtr) {
5001 case '^':
5002 // Replace the '^' with '*'.
5003 DeclLoc = DeclLoc.getLocWithOffset(argPtr-startArgList);
5004 ReplaceText(DeclLoc, 1, "*");
5005 break;
5006 case '(':
5007 parenCount++;
5008 break;
5009 case ')':
5010 parenCount--;
5011 break;
5012 }
5013 }
5014 return;
5015}
5016
5017bool RewriteModernObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
5018 const FunctionProtoType *FTP;
5019 const PointerType *PT = QT->getAs<PointerType>();
5020 if (PT) {
5021 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
5022 } else {
5023 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
5024 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
5025 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
5026 }
5027 if (FTP) {
Alp Toker9cacbab2014-01-20 20:26:09 +00005028 for (FunctionProtoType::param_type_iterator I = FTP->param_type_begin(),
5029 E = FTP->param_type_end();
5030 I != E; ++I)
Fariborz Jahanian11671902012-02-07 17:11:38 +00005031 if (isTopLevelBlockPointerType(*I))
5032 return true;
5033 }
5034 return false;
5035}
5036
5037bool RewriteModernObjC::PointerTypeTakesAnyObjCQualifiedType(QualType QT) {
5038 const FunctionProtoType *FTP;
5039 const PointerType *PT = QT->getAs<PointerType>();
5040 if (PT) {
5041 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
5042 } else {
5043 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
5044 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
5045 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
5046 }
5047 if (FTP) {
Alp Toker9cacbab2014-01-20 20:26:09 +00005048 for (FunctionProtoType::param_type_iterator I = FTP->param_type_begin(),
5049 E = FTP->param_type_end();
5050 I != E; ++I) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00005051 if ((*I)->isObjCQualifiedIdType())
5052 return true;
5053 if ((*I)->isObjCObjectPointerType() &&
5054 (*I)->getPointeeType()->isObjCQualifiedInterfaceType())
5055 return true;
5056 }
5057
5058 }
5059 return false;
5060}
5061
5062void RewriteModernObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
5063 const char *&RParen) {
5064 const char *argPtr = strchr(Name, '(');
5065 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
5066
5067 LParen = argPtr; // output the start.
5068 argPtr++; // skip past the left paren.
5069 unsigned parenCount = 1;
5070
5071 while (*argPtr && parenCount) {
5072 switch (*argPtr) {
5073 case '(': parenCount++; break;
5074 case ')': parenCount--; break;
5075 default: break;
5076 }
5077 if (parenCount) argPtr++;
5078 }
5079 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
5080 RParen = argPtr; // output the end
5081}
5082
5083void RewriteModernObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
5084 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
5085 RewriteBlockPointerFunctionArgs(FD);
5086 return;
5087 }
5088 // Handle Variables and Typedefs.
5089 SourceLocation DeclLoc = ND->getLocation();
5090 QualType DeclT;
5091 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
5092 DeclT = VD->getType();
5093 else if (TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(ND))
5094 DeclT = TDD->getUnderlyingType();
5095 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
5096 DeclT = FD->getType();
5097 else
5098 llvm_unreachable("RewriteBlockPointerDecl(): Decl type not yet handled");
5099
5100 const char *startBuf = SM->getCharacterData(DeclLoc);
5101 const char *endBuf = startBuf;
5102 // scan backward (from the decl location) for the end of the previous decl.
5103 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
5104 startBuf--;
5105 SourceLocation Start = DeclLoc.getLocWithOffset(startBuf-endBuf);
5106 std::string buf;
5107 unsigned OrigLength=0;
5108 // *startBuf != '^' if we are dealing with a pointer to function that
5109 // may take block argument types (which will be handled below).
5110 if (*startBuf == '^') {
5111 // Replace the '^' with '*', computing a negative offset.
5112 buf = '*';
5113 startBuf++;
5114 OrigLength++;
5115 }
5116 while (*startBuf != ')') {
5117 buf += *startBuf;
5118 startBuf++;
5119 OrigLength++;
5120 }
5121 buf += ')';
5122 OrigLength++;
5123
5124 if (PointerTypeTakesAnyBlockArguments(DeclT) ||
5125 PointerTypeTakesAnyObjCQualifiedType(DeclT)) {
5126 // Replace the '^' with '*' for arguments.
5127 // Replace id<P> with id/*<>*/
5128 DeclLoc = ND->getLocation();
5129 startBuf = SM->getCharacterData(DeclLoc);
5130 const char *argListBegin, *argListEnd;
5131 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
5132 while (argListBegin < argListEnd) {
5133 if (*argListBegin == '^')
5134 buf += '*';
5135 else if (*argListBegin == '<') {
5136 buf += "/*";
5137 buf += *argListBegin++;
Dmitri Gribenko76bb5cabfa2012-09-10 21:20:09 +00005138 OrigLength++;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005139 while (*argListBegin != '>') {
5140 buf += *argListBegin++;
5141 OrigLength++;
5142 }
5143 buf += *argListBegin;
5144 buf += "*/";
5145 }
5146 else
5147 buf += *argListBegin;
5148 argListBegin++;
5149 OrigLength++;
5150 }
5151 buf += ')';
5152 OrigLength++;
5153 }
5154 ReplaceText(Start, OrigLength, buf);
5155
5156 return;
5157}
5158
5159
5160/// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
5161/// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
5162/// struct Block_byref_id_object *src) {
5163/// _Block_object_assign (&_dest->object, _src->object,
5164/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
5165/// [|BLOCK_FIELD_IS_WEAK]) // object
5166/// _Block_object_assign(&_dest->object, _src->object,
5167/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
5168/// [|BLOCK_FIELD_IS_WEAK]) // block
5169/// }
5170/// And:
5171/// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
5172/// _Block_object_dispose(_src->object,
5173/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
5174/// [|BLOCK_FIELD_IS_WEAK]) // object
5175/// _Block_object_dispose(_src->object,
5176/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
5177/// [|BLOCK_FIELD_IS_WEAK]) // block
5178/// }
5179
5180std::string RewriteModernObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
5181 int flag) {
5182 std::string S;
5183 if (CopyDestroyCache.count(flag))
5184 return S;
5185 CopyDestroyCache.insert(flag);
5186 S = "static void __Block_byref_id_object_copy_";
5187 S += utostr(flag);
5188 S += "(void *dst, void *src) {\n";
5189
5190 // offset into the object pointer is computed as:
5191 // void * + void* + int + int + void* + void *
5192 unsigned IntSize =
5193 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
5194 unsigned VoidPtrSize =
5195 static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
5196
5197 unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/Context->getCharWidth();
5198 S += " _Block_object_assign((char*)dst + ";
5199 S += utostr(offset);
5200 S += ", *(void * *) ((char*)src + ";
5201 S += utostr(offset);
5202 S += "), ";
5203 S += utostr(flag);
5204 S += ");\n}\n";
5205
5206 S += "static void __Block_byref_id_object_dispose_";
5207 S += utostr(flag);
5208 S += "(void *src) {\n";
5209 S += " _Block_object_dispose(*(void * *) ((char*)src + ";
5210 S += utostr(offset);
5211 S += "), ";
5212 S += utostr(flag);
5213 S += ");\n}\n";
5214 return S;
5215}
5216
5217/// RewriteByRefVar - For each __block typex ND variable this routine transforms
5218/// the declaration into:
5219/// struct __Block_byref_ND {
5220/// void *__isa; // NULL for everything except __weak pointers
5221/// struct __Block_byref_ND *__forwarding;
5222/// int32_t __flags;
5223/// int32_t __size;
5224/// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
5225/// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
5226/// typex ND;
5227/// };
5228///
5229/// It then replaces declaration of ND variable with:
5230/// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
5231/// __size=sizeof(struct __Block_byref_ND),
5232/// ND=initializer-if-any};
5233///
5234///
Fariborz Jahanian847713a2012-04-24 19:38:45 +00005235void RewriteModernObjC::RewriteByRefVar(VarDecl *ND, bool firstDecl,
5236 bool lastDecl) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00005237 int flag = 0;
5238 int isa = 0;
5239 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
5240 if (DeclLoc.isInvalid())
5241 // If type location is missing, it is because of missing type (a warning).
5242 // Use variable's location which is good for this case.
5243 DeclLoc = ND->getLocation();
5244 const char *startBuf = SM->getCharacterData(DeclLoc);
5245 SourceLocation X = ND->getLocEnd();
5246 X = SM->getExpansionLoc(X);
5247 const char *endBuf = SM->getCharacterData(X);
5248 std::string Name(ND->getNameAsString());
5249 std::string ByrefType;
5250 RewriteByRefString(ByrefType, Name, ND, true);
5251 ByrefType += " {\n";
5252 ByrefType += " void *__isa;\n";
5253 RewriteByRefString(ByrefType, Name, ND);
5254 ByrefType += " *__forwarding;\n";
5255 ByrefType += " int __flags;\n";
5256 ByrefType += " int __size;\n";
5257 // Add void *__Block_byref_id_object_copy;
5258 // void *__Block_byref_id_object_dispose; if needed.
5259 QualType Ty = ND->getType();
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00005260 bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty, ND);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005261 if (HasCopyAndDispose) {
5262 ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
5263 ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
5264 }
5265
5266 QualType T = Ty;
5267 (void)convertBlockPointerToFunctionPointer(T);
5268 T.getAsStringInternal(Name, Context->getPrintingPolicy());
5269
5270 ByrefType += " " + Name + ";\n";
5271 ByrefType += "};\n";
5272 // Insert this type in global scope. It is needed by helper function.
5273 SourceLocation FunLocStart;
5274 if (CurFunctionDef)
Fariborz Jahanianca357d92012-04-19 00:50:01 +00005275 FunLocStart = getFunctionSourceLocation(*this, CurFunctionDef);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005276 else {
5277 assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null");
5278 FunLocStart = CurMethodDef->getLocStart();
5279 }
5280 InsertText(FunLocStart, ByrefType);
Fariborz Jahanian3fd9bbd2012-04-24 16:45:27 +00005281
Fariborz Jahanian11671902012-02-07 17:11:38 +00005282 if (Ty.isObjCGCWeak()) {
5283 flag |= BLOCK_FIELD_IS_WEAK;
5284 isa = 1;
5285 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00005286 if (HasCopyAndDispose) {
5287 flag = BLOCK_BYREF_CALLER;
5288 QualType Ty = ND->getType();
5289 // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
5290 if (Ty->isBlockPointerType())
5291 flag |= BLOCK_FIELD_IS_BLOCK;
5292 else
5293 flag |= BLOCK_FIELD_IS_OBJECT;
5294 std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
5295 if (!HF.empty())
Fariborz Jahaniane4996132013-02-07 22:50:40 +00005296 Preamble += HF;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005297 }
5298
5299 // struct __Block_byref_ND ND =
5300 // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
5301 // initializer-if-any};
5302 bool hasInit = (ND->getInit() != 0);
Fariborz Jahanian5811fd62012-04-11 23:57:12 +00005303 // FIXME. rewriter does not support __block c++ objects which
5304 // require construction.
Fariborz Jahanian16d0d6c2012-04-26 23:20:25 +00005305 if (hasInit)
5306 if (CXXConstructExpr *CExp = dyn_cast<CXXConstructExpr>(ND->getInit())) {
5307 CXXConstructorDecl *CXXDecl = CExp->getConstructor();
5308 if (CXXDecl && CXXDecl->isDefaultConstructor())
5309 hasInit = false;
5310 }
5311
Fariborz Jahanian11671902012-02-07 17:11:38 +00005312 unsigned flags = 0;
5313 if (HasCopyAndDispose)
5314 flags |= BLOCK_HAS_COPY_DISPOSE;
5315 Name = ND->getNameAsString();
5316 ByrefType.clear();
5317 RewriteByRefString(ByrefType, Name, ND);
5318 std::string ForwardingCastType("(");
5319 ForwardingCastType += ByrefType + " *)";
Fariborz Jahanian3fd9bbd2012-04-24 16:45:27 +00005320 ByrefType += " " + Name + " = {(void*)";
5321 ByrefType += utostr(isa);
5322 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
5323 ByrefType += utostr(flags);
5324 ByrefType += ", ";
5325 ByrefType += "sizeof(";
5326 RewriteByRefString(ByrefType, Name, ND);
5327 ByrefType += ")";
5328 if (HasCopyAndDispose) {
5329 ByrefType += ", __Block_byref_id_object_copy_";
5330 ByrefType += utostr(flag);
5331 ByrefType += ", __Block_byref_id_object_dispose_";
5332 ByrefType += utostr(flag);
5333 }
5334
Fariborz Jahanian847713a2012-04-24 19:38:45 +00005335 if (!firstDecl) {
5336 // In multiple __block declarations, and for all but 1st declaration,
5337 // find location of the separating comma. This would be start location
5338 // where new text is to be inserted.
5339 DeclLoc = ND->getLocation();
5340 const char *startDeclBuf = SM->getCharacterData(DeclLoc);
5341 const char *commaBuf = startDeclBuf;
5342 while (*commaBuf != ',')
5343 commaBuf--;
5344 assert((*commaBuf == ',') && "RewriteByRefVar: can't find ','");
5345 DeclLoc = DeclLoc.getLocWithOffset(commaBuf - startDeclBuf);
5346 startBuf = commaBuf;
5347 }
5348
Fariborz Jahanian11671902012-02-07 17:11:38 +00005349 if (!hasInit) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00005350 ByrefType += "};\n";
5351 unsigned nameSize = Name.size();
5352 // for block or function pointer declaration. Name is aleady
5353 // part of the declaration.
5354 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType())
5355 nameSize = 1;
5356 ReplaceText(DeclLoc, endBuf-startBuf+nameSize, ByrefType);
5357 }
5358 else {
Fariborz Jahanian3fd9bbd2012-04-24 16:45:27 +00005359 ByrefType += ", ";
Fariborz Jahanian11671902012-02-07 17:11:38 +00005360 SourceLocation startLoc;
5361 Expr *E = ND->getInit();
5362 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
5363 startLoc = ECE->getLParenLoc();
5364 else
5365 startLoc = E->getLocStart();
5366 startLoc = SM->getExpansionLoc(startLoc);
5367 endBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005368 ReplaceText(DeclLoc, endBuf-startBuf, ByrefType);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005369
Fariborz Jahanian847713a2012-04-24 19:38:45 +00005370 const char separator = lastDecl ? ';' : ',';
5371 const char *startInitializerBuf = SM->getCharacterData(startLoc);
5372 const char *separatorBuf = strchr(startInitializerBuf, separator);
5373 assert((*separatorBuf == separator) &&
5374 "RewriteByRefVar: can't find ';' or ','");
5375 SourceLocation separatorLoc =
5376 startLoc.getLocWithOffset(separatorBuf-startInitializerBuf);
5377
5378 InsertText(separatorLoc, lastDecl ? "}" : "};\n");
Fariborz Jahanian11671902012-02-07 17:11:38 +00005379 }
5380 return;
5381}
5382
5383void RewriteModernObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
5384 // Add initializers for any closure decl refs.
5385 GetBlockDeclRefExprs(Exp->getBody());
5386 if (BlockDeclRefs.size()) {
5387 // Unique all "by copy" declarations.
5388 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCall113bee02012-03-10 09:33:50 +00005389 if (!BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00005390 if (!BlockByCopyDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
5391 BlockByCopyDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
5392 BlockByCopyDecls.push_back(BlockDeclRefs[i]->getDecl());
5393 }
5394 }
5395 // Unique all "by ref" declarations.
5396 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCall113bee02012-03-10 09:33:50 +00005397 if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00005398 if (!BlockByRefDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
5399 BlockByRefDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
5400 BlockByRefDecls.push_back(BlockDeclRefs[i]->getDecl());
5401 }
5402 }
5403 // Find any imported blocks...they will need special attention.
5404 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCall113bee02012-03-10 09:33:50 +00005405 if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
Fariborz Jahanian11671902012-02-07 17:11:38 +00005406 BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
5407 BlockDeclRefs[i]->getType()->isBlockPointerType())
5408 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
5409 }
5410}
5411
5412FunctionDecl *RewriteModernObjC::SynthBlockInitFunctionDecl(StringRef name) {
5413 IdentifierInfo *ID = &Context->Idents.get(name);
5414 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
5415 return FunctionDecl::Create(*Context, TUDecl, SourceLocation(),
5416 SourceLocation(), ID, FType, 0, SC_Extern,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00005417 false, false);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005418}
5419
5420Stmt *RewriteModernObjC::SynthBlockInitExpr(BlockExpr *Exp,
Craig Topper5603df42013-07-05 19:34:19 +00005421 const SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs) {
Fariborz Jahanianbdf975e2012-03-22 19:54:39 +00005422
Fariborz Jahanian11671902012-02-07 17:11:38 +00005423 const BlockDecl *block = Exp->getBlockDecl();
Fariborz Jahanianbdf975e2012-03-22 19:54:39 +00005424
Fariborz Jahanian11671902012-02-07 17:11:38 +00005425 Blocks.push_back(Exp);
5426
5427 CollectBlockDeclRefInfo(Exp);
5428
5429 // Add inner imported variables now used in current block.
5430 int countOfInnerDecls = 0;
5431 if (!InnerBlockDeclRefs.empty()) {
5432 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++) {
John McCall113bee02012-03-10 09:33:50 +00005433 DeclRefExpr *Exp = InnerBlockDeclRefs[i];
Fariborz Jahanian11671902012-02-07 17:11:38 +00005434 ValueDecl *VD = Exp->getDecl();
John McCall113bee02012-03-10 09:33:50 +00005435 if (!VD->hasAttr<BlocksAttr>() && !BlockByCopyDeclsPtrSet.count(VD)) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00005436 // We need to save the copied-in variables in nested
5437 // blocks because it is needed at the end for some of the API generations.
5438 // See SynthesizeBlockLiterals routine.
5439 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5440 BlockDeclRefs.push_back(Exp);
5441 BlockByCopyDeclsPtrSet.insert(VD);
5442 BlockByCopyDecls.push_back(VD);
5443 }
John McCall113bee02012-03-10 09:33:50 +00005444 if (VD->hasAttr<BlocksAttr>() && !BlockByRefDeclsPtrSet.count(VD)) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00005445 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5446 BlockDeclRefs.push_back(Exp);
5447 BlockByRefDeclsPtrSet.insert(VD);
5448 BlockByRefDecls.push_back(VD);
5449 }
5450 }
5451 // Find any imported blocks...they will need special attention.
5452 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++)
John McCall113bee02012-03-10 09:33:50 +00005453 if (InnerBlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
Fariborz Jahanian11671902012-02-07 17:11:38 +00005454 InnerBlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
5455 InnerBlockDeclRefs[i]->getType()->isBlockPointerType())
5456 ImportedBlockDecls.insert(InnerBlockDeclRefs[i]->getDecl());
5457 }
5458 InnerDeclRefsCount.push_back(countOfInnerDecls);
5459
5460 std::string FuncName;
5461
5462 if (CurFunctionDef)
5463 FuncName = CurFunctionDef->getNameAsString();
5464 else if (CurMethodDef)
5465 BuildUniqueMethodName(FuncName, CurMethodDef);
5466 else if (GlobalVarDecl)
5467 FuncName = std::string(GlobalVarDecl->getNameAsString());
5468
Fariborz Jahaniane0050702012-03-23 00:00:49 +00005469 bool GlobalBlockExpr =
5470 block->getDeclContext()->getRedeclContext()->isFileContext();
5471
5472 if (GlobalBlockExpr && !GlobalVarDecl) {
5473 Diags.Report(block->getLocation(), GlobalBlockRewriteFailedDiag);
5474 GlobalBlockExpr = false;
5475 }
5476
Fariborz Jahanian11671902012-02-07 17:11:38 +00005477 std::string BlockNumber = utostr(Blocks.size()-1);
5478
Fariborz Jahanian11671902012-02-07 17:11:38 +00005479 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
5480
5481 // Get a pointer to the function type so we can cast appropriately.
5482 QualType BFT = convertFunctionTypeOfBlocks(Exp->getFunctionType());
5483 QualType FType = Context->getPointerType(BFT);
5484
5485 FunctionDecl *FD;
5486 Expr *NewRep;
5487
Benjamin Kramer60509af2013-09-09 14:48:42 +00005488 // Simulate a constructor call...
Fariborz Jahaniane0050702012-03-23 00:00:49 +00005489 std::string Tag;
5490
5491 if (GlobalBlockExpr)
5492 Tag = "__global_";
5493 else
5494 Tag = "__";
5495 Tag += FuncName + "_block_impl_" + BlockNumber;
5496
Fariborz Jahanian11671902012-02-07 17:11:38 +00005497 FD = SynthBlockInitFunctionDecl(Tag);
John McCall113bee02012-03-10 09:33:50 +00005498 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, false, FType, VK_RValue,
Fariborz Jahanian11671902012-02-07 17:11:38 +00005499 SourceLocation());
5500
5501 SmallVector<Expr*, 4> InitExprs;
5502
5503 // Initialize the block function.
5504 FD = SynthBlockInitFunctionDecl(Func);
John McCall113bee02012-03-10 09:33:50 +00005505 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, false, FD->getType(),
5506 VK_LValue, SourceLocation());
Fariborz Jahanian11671902012-02-07 17:11:38 +00005507 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
5508 CK_BitCast, Arg);
5509 InitExprs.push_back(castExpr);
5510
5511 // Initialize the block descriptor.
5512 std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
5513
5514 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl,
5515 SourceLocation(), SourceLocation(),
5516 &Context->Idents.get(DescData.c_str()),
5517 Context->VoidPtrTy, 0,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00005518 SC_Static);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005519 UnaryOperator *DescRefExpr =
John McCall113bee02012-03-10 09:33:50 +00005520 new (Context) UnaryOperator(new (Context) DeclRefExpr(NewVD, false,
Fariborz Jahanian11671902012-02-07 17:11:38 +00005521 Context->VoidPtrTy,
5522 VK_LValue,
5523 SourceLocation()),
5524 UO_AddrOf,
5525 Context->getPointerType(Context->VoidPtrTy),
5526 VK_RValue, OK_Ordinary,
5527 SourceLocation());
5528 InitExprs.push_back(DescRefExpr);
5529
5530 // Add initializers for any closure decl refs.
5531 if (BlockDeclRefs.size()) {
5532 Expr *Exp;
5533 // Output all "by copy" declarations.
Craig Topper2341c0d2013-07-04 03:08:24 +00005534 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00005535 E = BlockByCopyDecls.end(); I != E; ++I) {
5536 if (isObjCType((*I)->getType())) {
5537 // FIXME: Conform to ABI ([[obj retain] autorelease]).
5538 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCall113bee02012-03-10 09:33:50 +00005539 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(),
5540 VK_LValue, SourceLocation());
Fariborz Jahanian11671902012-02-07 17:11:38 +00005541 if (HasLocalVariableExternalStorage(*I)) {
5542 QualType QT = (*I)->getType();
5543 QT = Context->getPointerType(QT);
5544 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
5545 OK_Ordinary, SourceLocation());
5546 }
5547 } else if (isTopLevelBlockPointerType((*I)->getType())) {
5548 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCall113bee02012-03-10 09:33:50 +00005549 Arg = new (Context) DeclRefExpr(FD, false, FD->getType(),
5550 VK_LValue, SourceLocation());
Fariborz Jahanian11671902012-02-07 17:11:38 +00005551 Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
5552 CK_BitCast, Arg);
5553 } else {
5554 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCall113bee02012-03-10 09:33:50 +00005555 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(),
5556 VK_LValue, SourceLocation());
Fariborz Jahanian11671902012-02-07 17:11:38 +00005557 if (HasLocalVariableExternalStorage(*I)) {
5558 QualType QT = (*I)->getType();
5559 QT = Context->getPointerType(QT);
5560 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
5561 OK_Ordinary, SourceLocation());
5562 }
5563
5564 }
5565 InitExprs.push_back(Exp);
5566 }
5567 // Output all "by ref" declarations.
Craig Topper2341c0d2013-07-04 03:08:24 +00005568 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00005569 E = BlockByRefDecls.end(); I != E; ++I) {
5570 ValueDecl *ND = (*I);
5571 std::string Name(ND->getNameAsString());
5572 std::string RecName;
5573 RewriteByRefString(RecName, Name, ND, true);
5574 IdentifierInfo *II = &Context->Idents.get(RecName.c_str()
5575 + sizeof("struct"));
5576 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
5577 SourceLocation(), SourceLocation(),
5578 II);
5579 assert(RD && "SynthBlockInitExpr(): Can't find RecordDecl");
5580 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
5581
5582 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCall113bee02012-03-10 09:33:50 +00005583 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(), VK_LValue,
Fariborz Jahanian11671902012-02-07 17:11:38 +00005584 SourceLocation());
5585 bool isNestedCapturedVar = false;
5586 if (block)
5587 for (BlockDecl::capture_const_iterator ci = block->capture_begin(),
5588 ce = block->capture_end(); ci != ce; ++ci) {
5589 const VarDecl *variable = ci->getVariable();
5590 if (variable == ND && ci->isNested()) {
5591 assert (ci->isByRef() &&
5592 "SynthBlockInitExpr - captured block variable is not byref");
5593 isNestedCapturedVar = true;
5594 break;
5595 }
5596 }
5597 // captured nested byref variable has its address passed. Do not take
5598 // its address again.
5599 if (!isNestedCapturedVar)
5600 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf,
5601 Context->getPointerType(Exp->getType()),
5602 VK_RValue, OK_Ordinary, SourceLocation());
5603 Exp = NoTypeInfoCStyleCastExpr(Context, castT, CK_BitCast, Exp);
5604 InitExprs.push_back(Exp);
5605 }
5606 }
5607 if (ImportedBlockDecls.size()) {
5608 // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
5609 int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
5610 unsigned IntSize =
5611 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
5612 Expr *FlagExp = IntegerLiteral::Create(*Context, llvm::APInt(IntSize, flag),
5613 Context->IntTy, SourceLocation());
5614 InitExprs.push_back(FlagExp);
5615 }
Benjamin Kramerc215e762012-08-24 11:54:20 +00005616 NewRep = new (Context) CallExpr(*Context, DRE, InitExprs,
Fariborz Jahanian11671902012-02-07 17:11:38 +00005617 FType, VK_LValue, SourceLocation());
Fariborz Jahaniane0050702012-03-23 00:00:49 +00005618
5619 if (GlobalBlockExpr) {
5620 assert (GlobalConstructionExp == 0 &&
5621 "SynthBlockInitExpr - GlobalConstructionExp must be null");
5622 GlobalConstructionExp = NewRep;
5623 NewRep = DRE;
5624 }
5625
Fariborz Jahanian11671902012-02-07 17:11:38 +00005626 NewRep = new (Context) UnaryOperator(NewRep, UO_AddrOf,
5627 Context->getPointerType(NewRep->getType()),
5628 VK_RValue, OK_Ordinary, SourceLocation());
5629 NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CK_BitCast,
5630 NewRep);
5631 BlockDeclRefs.clear();
5632 BlockByRefDecls.clear();
5633 BlockByRefDeclsPtrSet.clear();
5634 BlockByCopyDecls.clear();
5635 BlockByCopyDeclsPtrSet.clear();
5636 ImportedBlockDecls.clear();
5637 return NewRep;
5638}
5639
5640bool RewriteModernObjC::IsDeclStmtInForeachHeader(DeclStmt *DS) {
5641 if (const ObjCForCollectionStmt * CS =
5642 dyn_cast<ObjCForCollectionStmt>(Stmts.back()))
5643 return CS->getElement() == DS;
5644 return false;
5645}
5646
5647//===----------------------------------------------------------------------===//
5648// Function Body / Expression rewriting
5649//===----------------------------------------------------------------------===//
5650
5651Stmt *RewriteModernObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
5652 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
5653 isa<DoStmt>(S) || isa<ForStmt>(S))
5654 Stmts.push_back(S);
5655 else if (isa<ObjCForCollectionStmt>(S)) {
5656 Stmts.push_back(S);
5657 ObjCBcLabelNo.push_back(++BcLabelCount);
5658 }
5659
5660 // Pseudo-object operations and ivar references need special
5661 // treatment because we're going to recursively rewrite them.
5662 if (PseudoObjectExpr *PseudoOp = dyn_cast<PseudoObjectExpr>(S)) {
5663 if (isa<BinaryOperator>(PseudoOp->getSyntacticForm())) {
5664 return RewritePropertyOrImplicitSetter(PseudoOp);
5665 } else {
5666 return RewritePropertyOrImplicitGetter(PseudoOp);
5667 }
5668 } else if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
5669 return RewriteObjCIvarRefExpr(IvarRefExpr);
5670 }
Fariborz Jahanian4254cdb2013-02-08 18:57:50 +00005671 else if (isa<OpaqueValueExpr>(S))
5672 S = cast<OpaqueValueExpr>(S)->getSourceExpr();
Fariborz Jahanian11671902012-02-07 17:11:38 +00005673
5674 SourceRange OrigStmtRange = S->getSourceRange();
5675
5676 // Perform a bottom up rewrite of all children.
5677 for (Stmt::child_range CI = S->children(); CI; ++CI)
5678 if (*CI) {
5679 Stmt *childStmt = (*CI);
5680 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(childStmt);
5681 if (newStmt) {
5682 *CI = newStmt;
5683 }
5684 }
5685
5686 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
John McCall113bee02012-03-10 09:33:50 +00005687 SmallVector<DeclRefExpr *, 8> InnerBlockDeclRefs;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005688 llvm::SmallPtrSet<const DeclContext *, 8> InnerContexts;
5689 InnerContexts.insert(BE->getBlockDecl());
5690 ImportedLocalExternalDecls.clear();
5691 GetInnerBlockDeclRefExprs(BE->getBody(),
5692 InnerBlockDeclRefs, InnerContexts);
5693 // Rewrite the block body in place.
5694 Stmt *SaveCurrentBody = CurrentBody;
5695 CurrentBody = BE->getBody();
5696 PropParentMap = 0;
5697 // block literal on rhs of a property-dot-sytax assignment
5698 // must be replaced by its synthesize ast so getRewrittenText
5699 // works as expected. In this case, what actually ends up on RHS
5700 // is the blockTranscribed which is the helper function for the
5701 // block literal; as in: self.c = ^() {[ace ARR];};
5702 bool saveDisableReplaceStmt = DisableReplaceStmt;
5703 DisableReplaceStmt = false;
5704 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
5705 DisableReplaceStmt = saveDisableReplaceStmt;
5706 CurrentBody = SaveCurrentBody;
5707 PropParentMap = 0;
5708 ImportedLocalExternalDecls.clear();
5709 // Now we snarf the rewritten text and stash it away for later use.
5710 std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
5711 RewrittenBlockExprs[BE] = Str;
5712
5713 Stmt *blockTranscribed = SynthBlockInitExpr(BE, InnerBlockDeclRefs);
5714
5715 //blockTranscribed->dump();
5716 ReplaceStmt(S, blockTranscribed);
5717 return blockTranscribed;
5718 }
5719 // Handle specific things.
5720 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
5721 return RewriteAtEncode(AtEncode);
5722
5723 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
5724 return RewriteAtSelector(AtSelector);
5725
5726 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
5727 return RewriteObjCStringLiteral(AtString);
Fariborz Jahanian307b7ad2012-03-27 20:17:30 +00005728
5729 if (ObjCBoolLiteralExpr *BoolLitExpr = dyn_cast<ObjCBoolLiteralExpr>(S))
5730 return RewriteObjCBoolLiteralExpr(BoolLitExpr);
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00005731
Patrick Beard0caa3942012-04-19 00:25:12 +00005732 if (ObjCBoxedExpr *BoxedExpr = dyn_cast<ObjCBoxedExpr>(S))
5733 return RewriteObjCBoxedExpr(BoxedExpr);
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00005734
5735 if (ObjCArrayLiteral *ArrayLitExpr = dyn_cast<ObjCArrayLiteral>(S))
5736 return RewriteObjCArrayLiteralExpr(ArrayLitExpr);
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00005737
5738 if (ObjCDictionaryLiteral *DictionaryLitExpr =
5739 dyn_cast<ObjCDictionaryLiteral>(S))
5740 return RewriteObjCDictionaryLiteralExpr(DictionaryLitExpr);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005741
5742 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
5743#if 0
5744 // Before we rewrite it, put the original message expression in a comment.
5745 SourceLocation startLoc = MessExpr->getLocStart();
5746 SourceLocation endLoc = MessExpr->getLocEnd();
5747
5748 const char *startBuf = SM->getCharacterData(startLoc);
5749 const char *endBuf = SM->getCharacterData(endLoc);
5750
5751 std::string messString;
5752 messString += "// ";
5753 messString.append(startBuf, endBuf-startBuf+1);
5754 messString += "\n";
5755
5756 // FIXME: Missing definition of
5757 // InsertText(clang::SourceLocation, char const*, unsigned int).
5758 // InsertText(startLoc, messString.c_str(), messString.size());
5759 // Tried this, but it didn't work either...
5760 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
5761#endif
5762 return RewriteMessageExpr(MessExpr);
5763 }
5764
Fariborz Jahanian9b43c3f2012-05-23 23:47:20 +00005765 if (ObjCAutoreleasePoolStmt *StmtAutoRelease =
5766 dyn_cast<ObjCAutoreleasePoolStmt>(S)) {
5767 return RewriteObjCAutoreleasePoolStmt(StmtAutoRelease);
5768 }
5769
Fariborz Jahanian11671902012-02-07 17:11:38 +00005770 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
5771 return RewriteObjCTryStmt(StmtTry);
5772
5773 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
5774 return RewriteObjCSynchronizedStmt(StmtTry);
5775
5776 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
5777 return RewriteObjCThrowStmt(StmtThrow);
5778
5779 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
5780 return RewriteObjCProtocolExpr(ProtocolExp);
5781
5782 if (ObjCForCollectionStmt *StmtForCollection =
5783 dyn_cast<ObjCForCollectionStmt>(S))
5784 return RewriteObjCForCollectionStmt(StmtForCollection,
5785 OrigStmtRange.getEnd());
5786 if (BreakStmt *StmtBreakStmt =
5787 dyn_cast<BreakStmt>(S))
5788 return RewriteBreakStmt(StmtBreakStmt);
5789 if (ContinueStmt *StmtContinueStmt =
5790 dyn_cast<ContinueStmt>(S))
5791 return RewriteContinueStmt(StmtContinueStmt);
5792
5793 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
5794 // and cast exprs.
5795 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
5796 // FIXME: What we're doing here is modifying the type-specifier that
5797 // precedes the first Decl. In the future the DeclGroup should have
5798 // a separate type-specifier that we can rewrite.
5799 // NOTE: We need to avoid rewriting the DeclStmt if it is within
5800 // the context of an ObjCForCollectionStmt. For example:
5801 // NSArray *someArray;
5802 // for (id <FooProtocol> index in someArray) ;
5803 // This is because RewriteObjCForCollectionStmt() does textual rewriting
5804 // and it depends on the original text locations/positions.
5805 if (Stmts.empty() || !IsDeclStmtInForeachHeader(DS))
5806 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
5807
5808 // Blocks rewrite rules.
5809 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
5810 DI != DE; ++DI) {
5811 Decl *SD = *DI;
5812 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
5813 if (isTopLevelBlockPointerType(ND->getType()))
5814 RewriteBlockPointerDecl(ND);
5815 else if (ND->getType()->isFunctionPointerType())
5816 CheckFunctionPointerDecl(ND->getType(), ND);
5817 if (VarDecl *VD = dyn_cast<VarDecl>(SD)) {
5818 if (VD->hasAttr<BlocksAttr>()) {
5819 static unsigned uniqueByrefDeclCount = 0;
5820 assert(!BlockByRefDeclNo.count(ND) &&
5821 "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl");
5822 BlockByRefDeclNo[ND] = uniqueByrefDeclCount++;
Fariborz Jahanian847713a2012-04-24 19:38:45 +00005823 RewriteByRefVar(VD, (DI == DS->decl_begin()), ((DI+1) == DE));
Fariborz Jahanian11671902012-02-07 17:11:38 +00005824 }
5825 else
5826 RewriteTypeOfDecl(VD);
5827 }
5828 }
5829 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(SD)) {
5830 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
5831 RewriteBlockPointerDecl(TD);
5832 else if (TD->getUnderlyingType()->isFunctionPointerType())
5833 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5834 }
5835 }
5836 }
5837
5838 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
5839 RewriteObjCQualifiedInterfaceTypes(CE);
5840
5841 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
5842 isa<DoStmt>(S) || isa<ForStmt>(S)) {
5843 assert(!Stmts.empty() && "Statement stack is empty");
5844 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
5845 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
5846 && "Statement stack mismatch");
5847 Stmts.pop_back();
5848 }
5849 // Handle blocks rewriting.
Fariborz Jahanian11671902012-02-07 17:11:38 +00005850 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
5851 ValueDecl *VD = DRE->getDecl();
5852 if (VD->hasAttr<BlocksAttr>())
5853 return RewriteBlockDeclRefExpr(DRE);
5854 if (HasLocalVariableExternalStorage(VD))
5855 return RewriteLocalVariableExternalStorage(DRE);
5856 }
5857
5858 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
5859 if (CE->getCallee()->getType()->isBlockPointerType()) {
5860 Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
5861 ReplaceStmt(S, BlockCall);
5862 return BlockCall;
5863 }
5864 }
5865 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
5866 RewriteCastExpr(CE);
5867 }
Fariborz Jahanian2c00acd2012-04-10 00:08:18 +00005868 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
5869 RewriteImplicitCastObjCExpr(ICE);
5870 }
Fariborz Jahaniancc172282012-04-16 22:14:01 +00005871#if 0
Fariborz Jahanian3a5d5522012-04-13 18:00:54 +00005872
Fariborz Jahanian11671902012-02-07 17:11:38 +00005873 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
5874 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(),
5875 ICE->getSubExpr(),
5876 SourceLocation());
5877 // Get the new text.
5878 std::string SStr;
5879 llvm::raw_string_ostream Buf(SStr);
Richard Smith235341b2012-08-16 03:56:14 +00005880 Replacement->printPretty(Buf);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005881 const std::string &Str = Buf.str();
5882
5883 printf("CAST = %s\n", &Str[0]);
5884 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
5885 delete S;
5886 return Replacement;
5887 }
5888#endif
5889 // Return this stmt unmodified.
5890 return S;
5891}
5892
5893void RewriteModernObjC::RewriteRecordBody(RecordDecl *RD) {
5894 for (RecordDecl::field_iterator i = RD->field_begin(),
5895 e = RD->field_end(); i != e; ++i) {
David Blaikie40ed2972012-06-06 20:45:41 +00005896 FieldDecl *FD = *i;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005897 if (isTopLevelBlockPointerType(FD->getType()))
5898 RewriteBlockPointerDecl(FD);
5899 if (FD->getType()->isObjCQualifiedIdType() ||
5900 FD->getType()->isObjCQualifiedInterfaceType())
5901 RewriteObjCQualifiedInterfaceTypes(FD);
5902 }
5903}
5904
5905/// HandleDeclInMainFile - This is called for each top-level decl defined in the
5906/// main file of the input.
5907void RewriteModernObjC::HandleDeclInMainFile(Decl *D) {
5908 switch (D->getKind()) {
5909 case Decl::Function: {
5910 FunctionDecl *FD = cast<FunctionDecl>(D);
5911 if (FD->isOverloadedOperator())
5912 return;
5913
5914 // Since function prototypes don't have ParmDecl's, we check the function
5915 // prototype. This enables us to rewrite function declarations and
5916 // definitions using the same code.
5917 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
5918
Argyrios Kyrtzidis75627ad2012-02-12 04:48:45 +00005919 if (!FD->isThisDeclarationADefinition())
5920 break;
5921
Fariborz Jahanian11671902012-02-07 17:11:38 +00005922 // FIXME: If this should support Obj-C++, support CXXTryStmt
5923 if (CompoundStmt *Body = dyn_cast_or_null<CompoundStmt>(FD->getBody())) {
5924 CurFunctionDef = FD;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005925 CurrentBody = Body;
5926 Body =
5927 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5928 FD->setBody(Body);
5929 CurrentBody = 0;
5930 if (PropParentMap) {
5931 delete PropParentMap;
5932 PropParentMap = 0;
5933 }
5934 // This synthesizes and inserts the block "impl" struct, invoke function,
5935 // and any copy/dispose helper functions.
5936 InsertBlockLiteralsWithinFunction(FD);
Fariborz Jahanianaa4a2422012-11-06 17:30:23 +00005937 RewriteLineDirective(D);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005938 CurFunctionDef = 0;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005939 }
5940 break;
5941 }
5942 case Decl::ObjCMethod: {
5943 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(D);
5944 if (CompoundStmt *Body = MD->getCompoundBody()) {
5945 CurMethodDef = MD;
5946 CurrentBody = Body;
5947 Body =
5948 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5949 MD->setBody(Body);
5950 CurrentBody = 0;
5951 if (PropParentMap) {
5952 delete PropParentMap;
5953 PropParentMap = 0;
5954 }
5955 InsertBlockLiteralsWithinMethod(MD);
Fariborz Jahanianaa4a2422012-11-06 17:30:23 +00005956 RewriteLineDirective(D);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005957 CurMethodDef = 0;
5958 }
5959 break;
5960 }
5961 case Decl::ObjCImplementation: {
5962 ObjCImplementationDecl *CI = cast<ObjCImplementationDecl>(D);
5963 ClassImplementation.push_back(CI);
5964 break;
5965 }
5966 case Decl::ObjCCategoryImpl: {
5967 ObjCCategoryImplDecl *CI = cast<ObjCCategoryImplDecl>(D);
5968 CategoryImplementation.push_back(CI);
5969 break;
5970 }
5971 case Decl::Var: {
5972 VarDecl *VD = cast<VarDecl>(D);
5973 RewriteObjCQualifiedInterfaceTypes(VD);
5974 if (isTopLevelBlockPointerType(VD->getType()))
5975 RewriteBlockPointerDecl(VD);
5976 else if (VD->getType()->isFunctionPointerType()) {
5977 CheckFunctionPointerDecl(VD->getType(), VD);
5978 if (VD->getInit()) {
5979 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
5980 RewriteCastExpr(CE);
5981 }
5982 }
5983 } else if (VD->getType()->isRecordType()) {
5984 RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
5985 if (RD->isCompleteDefinition())
5986 RewriteRecordBody(RD);
5987 }
5988 if (VD->getInit()) {
5989 GlobalVarDecl = VD;
5990 CurrentBody = VD->getInit();
5991 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
5992 CurrentBody = 0;
5993 if (PropParentMap) {
5994 delete PropParentMap;
5995 PropParentMap = 0;
5996 }
5997 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(), VD->getName());
5998 GlobalVarDecl = 0;
5999
6000 // This is needed for blocks.
6001 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
6002 RewriteCastExpr(CE);
6003 }
6004 }
6005 break;
6006 }
6007 case Decl::TypeAlias:
6008 case Decl::Typedef: {
6009 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
6010 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
6011 RewriteBlockPointerDecl(TD);
6012 else if (TD->getUnderlyingType()->isFunctionPointerType())
6013 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
Fariborz Jahanian3a65ce32013-04-03 19:11:21 +00006014 else
6015 RewriteObjCQualifiedInterfaceTypes(TD);
Fariborz Jahanian11671902012-02-07 17:11:38 +00006016 }
6017 break;
6018 }
6019 case Decl::CXXRecord:
6020 case Decl::Record: {
6021 RecordDecl *RD = cast<RecordDecl>(D);
6022 if (RD->isCompleteDefinition())
6023 RewriteRecordBody(RD);
6024 break;
6025 }
6026 default:
6027 break;
6028 }
6029 // Nothing yet.
6030}
6031
Fariborz Jahanianb31e3af2012-03-15 17:05:33 +00006032/// Write_ProtocolExprReferencedMetadata - This routine writer out the
6033/// protocol reference symbols in the for of:
6034/// struct _protocol_t *PROTOCOL_REF = &PROTOCOL_METADATA.
6035static void Write_ProtocolExprReferencedMetadata(ASTContext *Context,
6036 ObjCProtocolDecl *PDecl,
6037 std::string &Result) {
6038 // Also output .objc_protorefs$B section and its meta-data.
6039 if (Context->getLangOpts().MicrosoftExt)
Fariborz Jahanian75f2e3c2012-04-27 21:39:49 +00006040 Result += "static ";
Fariborz Jahanianb31e3af2012-03-15 17:05:33 +00006041 Result += "struct _protocol_t *";
6042 Result += "_OBJC_PROTOCOL_REFERENCE_$_";
6043 Result += PDecl->getNameAsString();
6044 Result += " = &";
6045 Result += "_OBJC_PROTOCOL_"; Result += PDecl->getNameAsString();
6046 Result += ";\n";
6047}
6048
Fariborz Jahanian11671902012-02-07 17:11:38 +00006049void RewriteModernObjC::HandleTranslationUnit(ASTContext &C) {
6050 if (Diags.hasErrorOccurred())
6051 return;
6052
6053 RewriteInclude();
6054
Fariborz Jahaniane4996132013-02-07 22:50:40 +00006055 for (unsigned i = 0, e = FunctionDefinitionsSeen.size(); i < e; i++) {
Alp Tokerf6a24ce2013-12-05 16:25:25 +00006056 // translation of function bodies were postponed until all class and
Fariborz Jahaniane4996132013-02-07 22:50:40 +00006057 // their extensions and implementations are seen. This is because, we
Alp Tokerf6a24ce2013-12-05 16:25:25 +00006058 // cannot build grouping structs for bitfields until they are all seen.
Fariborz Jahaniane4996132013-02-07 22:50:40 +00006059 FunctionDecl *FDecl = FunctionDefinitionsSeen[i];
6060 HandleTopLevelSingleDecl(FDecl);
6061 }
6062
Fariborz Jahanian11671902012-02-07 17:11:38 +00006063 // Here's a great place to add any extra declarations that may be needed.
6064 // Write out meta data for each @protocol(<expr>).
6065 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Fariborz Jahanianb31e3af2012-03-15 17:05:33 +00006066 E = ProtocolExprDecls.end(); I != E; ++I) {
Fariborz Jahaniane18961b2012-02-08 19:53:58 +00006067 RewriteObjCProtocolMetaData(*I, Preamble);
Fariborz Jahanianb31e3af2012-03-15 17:05:33 +00006068 Write_ProtocolExprReferencedMetadata(Context, (*I), Preamble);
6069 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00006070
6071 InsertText(SM->getLocForStartOfFile(MainFileID), Preamble, false);
Fariborz Jahanian89919cc2012-05-08 23:54:35 +00006072
6073 if (ClassImplementation.size() || CategoryImplementation.size())
6074 RewriteImplementations();
6075
Fariborz Jahanian8e1118cbd2012-02-21 23:58:41 +00006076 for (unsigned i = 0, e = ObjCInterfacesSeen.size(); i < e; i++) {
6077 ObjCInterfaceDecl *CDecl = ObjCInterfacesSeen[i];
6078 // Write struct declaration for the class matching its ivar declarations.
6079 // Note that for modern abi, this is postponed until the end of TU
6080 // because class extensions and the implementation might declare their own
6081 // private ivars.
6082 RewriteInterfaceDecl(CDecl);
6083 }
Fariborz Jahaniane4996132013-02-07 22:50:40 +00006084
Fariborz Jahanian11671902012-02-07 17:11:38 +00006085 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
6086 // we are done.
6087 if (const RewriteBuffer *RewriteBuf =
6088 Rewrite.getRewriteBufferFor(MainFileID)) {
6089 //printf("Changed:\n");
6090 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
6091 } else {
6092 llvm::errs() << "No changes\n";
6093 }
6094
6095 if (ClassImplementation.size() || CategoryImplementation.size() ||
6096 ProtocolExprDecls.size()) {
6097 // Rewrite Objective-c meta data*
6098 std::string ResultStr;
6099 RewriteMetaDataIntoBuffer(ResultStr);
6100 // Emit metadata.
6101 *OutFile << ResultStr;
6102 }
Fariborz Jahanianddddca32012-03-14 21:44:09 +00006103 // Emit ImageInfo;
6104 {
6105 std::string ResultStr;
6106 WriteImageInfo(ResultStr);
6107 *OutFile << ResultStr;
6108 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00006109 OutFile->flush();
6110}
6111
6112void RewriteModernObjC::Initialize(ASTContext &context) {
6113 InitializeCommon(context);
6114
Fariborz Jahanianb52221e2012-03-10 17:45:38 +00006115 Preamble += "#ifndef __OBJC2__\n";
6116 Preamble += "#define __OBJC2__\n";
6117 Preamble += "#endif\n";
6118
Fariborz Jahanian11671902012-02-07 17:11:38 +00006119 // declaring objc_selector outside the parameter list removes a silly
6120 // scope related warning...
6121 if (IsHeader)
6122 Preamble = "#pragma once\n";
6123 Preamble += "struct objc_selector; struct objc_class;\n";
Fariborz Jahanian27db0b32012-04-12 23:52:52 +00006124 Preamble += "struct __rw_objc_super { \n\tstruct objc_object *object; ";
6125 Preamble += "\n\tstruct objc_object *superClass; ";
6126 // Add a constructor for creating temporary objects.
6127 Preamble += "\n\t__rw_objc_super(struct objc_object *o, struct objc_object *s) ";
6128 Preamble += ": object(o), superClass(s) {} ";
6129 Preamble += "\n};\n";
6130
Fariborz Jahanian11671902012-02-07 17:11:38 +00006131 if (LangOpts.MicrosoftExt) {
Fariborz Jahanian008dfe22012-03-11 19:41:56 +00006132 // Define all sections using syntax that makes sense.
Fariborz Jahanianddddca32012-03-14 21:44:09 +00006133 // These are currently generated.
6134 Preamble += "\n#pragma section(\".objc_classlist$B\", long, read, write)\n";
Fariborz Jahanian008dfe22012-03-11 19:41:56 +00006135 Preamble += "#pragma section(\".objc_catlist$B\", long, read, write)\n";
Fariborz Jahanianddddca32012-03-14 21:44:09 +00006136 Preamble += "#pragma section(\".objc_imageinfo$B\", long, read, write)\n";
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00006137 Preamble += "#pragma section(\".objc_nlclslist$B\", long, read, write)\n";
6138 Preamble += "#pragma section(\".objc_nlcatlist$B\", long, read, write)\n";
Fariborz Jahanianddddca32012-03-14 21:44:09 +00006139 // These are generated but not necessary for functionality.
Fariborz Jahanianddddca32012-03-14 21:44:09 +00006140 Preamble += "#pragma section(\".cat_cls_meth$B\", long, read, write)\n";
Fariborz Jahanian008dfe22012-03-11 19:41:56 +00006141 Preamble += "#pragma section(\".inst_meth$B\", long, read, write)\n";
6142 Preamble += "#pragma section(\".cls_meth$B\", long, read, write)\n";
Fariborz Jahaniane47bf2b2012-03-12 16:46:58 +00006143 Preamble += "#pragma section(\".objc_ivar$B\", long, read, write)\n";
Fariborz Jahanian45489622012-03-14 18:09:23 +00006144
Fariborz Jahanianb31e3af2012-03-15 17:05:33 +00006145 // These need be generated for performance. Currently they are not,
6146 // using API calls instead.
6147 Preamble += "#pragma section(\".objc_selrefs$B\", long, read, write)\n";
6148 Preamble += "#pragma section(\".objc_classrefs$B\", long, read, write)\n";
6149 Preamble += "#pragma section(\".objc_superrefs$B\", long, read, write)\n";
6150
Fariborz Jahanian11671902012-02-07 17:11:38 +00006151 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00006152 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
6153 Preamble += "typedef struct objc_object Protocol;\n";
6154 Preamble += "#define _REWRITER_typedef_Protocol\n";
6155 Preamble += "#endif\n";
6156 if (LangOpts.MicrosoftExt) {
6157 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
6158 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
Fariborz Jahanian167384d2012-03-21 23:41:04 +00006159 }
6160 else
Fariborz Jahanian11671902012-02-07 17:11:38 +00006161 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
Fariborz Jahanian167384d2012-03-21 23:41:04 +00006162
6163 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend(void);\n";
6164 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSendSuper(void);\n";
6165 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend_stret(void);\n";
6166 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSendSuper_stret(void);\n";
6167 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend_fpret(void);\n";
6168
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00006169 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *objc_getClass";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006170 Preamble += "(const char *);\n";
6171 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *class_getSuperclass";
6172 Preamble += "(struct objc_class *);\n";
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00006173 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *objc_getMetaClass";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006174 Preamble += "(const char *);\n";
Fariborz Jahanian34660592012-03-19 18:11:32 +00006175 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw( struct objc_object *);\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006176 // @synchronized hooks.
Aaron Ballman9c004462012-09-06 16:44:16 +00006177 Preamble += "__OBJC_RW_DLLIMPORT int objc_sync_enter( struct objc_object *);\n";
6178 Preamble += "__OBJC_RW_DLLIMPORT int objc_sync_exit( struct objc_object *);\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006179 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00006180 Preamble += "#ifdef _WIN64\n";
6181 Preamble += "typedef unsigned long long _WIN_NSUInteger;\n";
6182 Preamble += "#else\n";
6183 Preamble += "typedef unsigned int _WIN_NSUInteger;\n";
6184 Preamble += "#endif\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006185 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
6186 Preamble += "struct __objcFastEnumerationState {\n\t";
6187 Preamble += "unsigned long state;\n\t";
6188 Preamble += "void **itemsPtr;\n\t";
6189 Preamble += "unsigned long *mutationsPtr;\n\t";
6190 Preamble += "unsigned long extra[5];\n};\n";
6191 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
6192 Preamble += "#define __FASTENUMERATIONSTATE\n";
6193 Preamble += "#endif\n";
6194 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
6195 Preamble += "struct __NSConstantStringImpl {\n";
6196 Preamble += " int *isa;\n";
6197 Preamble += " int flags;\n";
6198 Preamble += " char *str;\n";
6199 Preamble += " long length;\n";
6200 Preamble += "};\n";
6201 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
6202 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
6203 Preamble += "#else\n";
6204 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
6205 Preamble += "#endif\n";
6206 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
6207 Preamble += "#endif\n";
6208 // Blocks preamble.
6209 Preamble += "#ifndef BLOCK_IMPL\n";
6210 Preamble += "#define BLOCK_IMPL\n";
6211 Preamble += "struct __block_impl {\n";
6212 Preamble += " void *isa;\n";
6213 Preamble += " int Flags;\n";
6214 Preamble += " int Reserved;\n";
6215 Preamble += " void *FuncPtr;\n";
6216 Preamble += "};\n";
6217 Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
6218 Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n";
6219 Preamble += "extern \"C\" __declspec(dllexport) "
6220 "void _Block_object_assign(void *, const void *, const int);\n";
6221 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
6222 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
6223 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
6224 Preamble += "#else\n";
6225 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n";
6226 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n";
6227 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
6228 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
6229 Preamble += "#endif\n";
6230 Preamble += "#endif\n";
6231 if (LangOpts.MicrosoftExt) {
6232 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
6233 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
6234 Preamble += "#ifndef KEEP_ATTRIBUTES\n"; // We use this for clang tests.
6235 Preamble += "#define __attribute__(X)\n";
6236 Preamble += "#endif\n";
Fariborz Jahaniane1240fe2012-04-12 16:33:31 +00006237 Preamble += "#ifndef __weak\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006238 Preamble += "#define __weak\n";
Fariborz Jahaniane1240fe2012-04-12 16:33:31 +00006239 Preamble += "#endif\n";
6240 Preamble += "#ifndef __block\n";
6241 Preamble += "#define __block\n";
6242 Preamble += "#endif\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006243 }
6244 else {
6245 Preamble += "#define __block\n";
6246 Preamble += "#define __weak\n";
6247 }
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00006248
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00006249 // Declarations required for modern objective-c array and dictionary literals.
6250 Preamble += "\n#include <stdarg.h>\n";
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00006251 Preamble += "struct __NSContainer_literal {\n";
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00006252 Preamble += " void * *arr;\n";
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00006253 Preamble += " __NSContainer_literal (unsigned int count, ...) {\n";
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00006254 Preamble += "\tva_list marker;\n";
6255 Preamble += "\tva_start(marker, count);\n";
6256 Preamble += "\tarr = new void *[count];\n";
6257 Preamble += "\tfor (unsigned i = 0; i < count; i++)\n";
6258 Preamble += "\t arr[i] = va_arg(marker, void *);\n";
6259 Preamble += "\tva_end( marker );\n";
6260 Preamble += " };\n";
Fariborz Jahanian70ef9292012-05-02 23:53:46 +00006261 Preamble += " ~__NSContainer_literal() {\n";
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00006262 Preamble += "\tdelete[] arr;\n";
6263 Preamble += " }\n";
6264 Preamble += "};\n";
6265
Fariborz Jahanian9b43c3f2012-05-23 23:47:20 +00006266 // Declaration required for implementation of @autoreleasepool statement.
6267 Preamble += "extern \"C\" __declspec(dllimport) void * objc_autoreleasePoolPush(void);\n";
6268 Preamble += "extern \"C\" __declspec(dllimport) void objc_autoreleasePoolPop(void *);\n\n";
6269 Preamble += "struct __AtAutoreleasePool {\n";
6270 Preamble += " __AtAutoreleasePool() {atautoreleasepoolobj = objc_autoreleasePoolPush();}\n";
6271 Preamble += " ~__AtAutoreleasePool() {objc_autoreleasePoolPop(atautoreleasepoolobj);}\n";
6272 Preamble += " void * atautoreleasepoolobj;\n";
6273 Preamble += "};\n";
6274
Fariborz Jahanian11671902012-02-07 17:11:38 +00006275 // NOTE! Windows uses LLP64 for 64bit mode. So, cast pointer to long long
6276 // as this avoids warning in any 64bit/32bit compilation model.
6277 Preamble += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long long) &((TYPE *)0)->MEMBER)\n";
6278}
6279
6280/// RewriteIvarOffsetComputation - This rutine synthesizes computation of
6281/// ivar offset.
6282void RewriteModernObjC::RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
6283 std::string &Result) {
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006284 Result += "__OFFSETOFIVAR__(struct ";
6285 Result += ivar->getContainingInterface()->getNameAsString();
6286 if (LangOpts.MicrosoftExt)
6287 Result += "_IMPL";
6288 Result += ", ";
6289 if (ivar->isBitField())
6290 ObjCIvarBitfieldGroupDecl(ivar, Result);
6291 else
Fariborz Jahanian11671902012-02-07 17:11:38 +00006292 Result += ivar->getNameAsString();
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006293 Result += ")";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006294}
6295
6296/// WriteModernMetadataDeclarations - Writes out metadata declarations for modern ABI.
6297/// struct _prop_t {
Fariborz Jahanian67f7c552012-02-07 23:31:52 +00006298/// const char *name;
Fariborz Jahanian11671902012-02-07 17:11:38 +00006299/// char *attributes;
6300/// }
6301
6302/// struct _prop_list_t {
6303/// uint32_t entsize; // sizeof(struct _prop_t)
6304/// uint32_t count_of_properties;
6305/// struct _prop_t prop_list[count_of_properties];
6306/// }
6307
6308/// struct _protocol_t;
6309
6310/// struct _protocol_list_t {
6311/// long protocol_count; // Note, this is 32/64 bit
6312/// struct _protocol_t * protocol_list[protocol_count];
6313/// }
6314
6315/// struct _objc_method {
6316/// SEL _cmd;
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006317/// const char *method_type;
Fariborz Jahanian11671902012-02-07 17:11:38 +00006318/// char *_imp;
6319/// }
6320
6321/// struct _method_list_t {
6322/// uint32_t entsize; // sizeof(struct _objc_method)
6323/// uint32_t method_count;
6324/// struct _objc_method method_list[method_count];
6325/// }
6326
6327/// struct _protocol_t {
6328/// id isa; // NULL
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006329/// const char *protocol_name;
Fariborz Jahanian11671902012-02-07 17:11:38 +00006330/// const struct _protocol_list_t * protocol_list; // super protocols
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006331/// const struct method_list_t *instance_methods;
6332/// const struct method_list_t *class_methods;
Fariborz Jahanian11671902012-02-07 17:11:38 +00006333/// const struct method_list_t *optionalInstanceMethods;
6334/// const struct method_list_t *optionalClassMethods;
6335/// const struct _prop_list_t * properties;
6336/// const uint32_t size; // sizeof(struct _protocol_t)
6337/// const uint32_t flags; // = 0
6338/// const char ** extendedMethodTypes;
6339/// }
6340
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006341/// struct _ivar_t {
6342/// unsigned long int *offset; // pointer to ivar offset location
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006343/// const char *name;
6344/// const char *type;
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006345/// uint32_t alignment;
6346/// uint32_t size;
6347/// }
6348
6349/// struct _ivar_list_t {
6350/// uint32 entsize; // sizeof(struct _ivar_t)
6351/// uint32 count;
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006352/// struct _ivar_t list[count];
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006353/// }
6354
6355/// struct _class_ro_t {
Fariborz Jahanian34134812012-03-24 16:53:16 +00006356/// uint32_t flags;
6357/// uint32_t instanceStart;
6358/// uint32_t instanceSize;
6359/// uint32_t reserved; // only when building for 64bit targets
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006360/// const uint8_t *ivarLayout;
6361/// const char *name;
6362/// const struct _method_list_t *baseMethods;
6363/// const struct _protocol_list_t *baseProtocols;
6364/// const struct _ivar_list_t *ivars;
6365/// const uint8_t *weakIvarLayout;
6366/// const struct _prop_list_t *properties;
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006367/// }
6368
6369/// struct _class_t {
6370/// struct _class_t *isa;
Fariborz Jahanian6e60c132012-03-20 17:34:50 +00006371/// struct _class_t *superclass;
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006372/// void *cache;
6373/// IMP *vtable;
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006374/// struct _class_ro_t *ro;
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006375/// }
6376
6377/// struct _category_t {
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006378/// const char *name;
Fariborz Jahaniancd79a492012-03-20 21:41:28 +00006379/// struct _class_t *cls;
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006380/// const struct _method_list_t *instance_methods;
6381/// const struct _method_list_t *class_methods;
6382/// const struct _protocol_list_t *protocols;
6383/// const struct _prop_list_t *properties;
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006384/// }
6385
6386/// MessageRefTy - LLVM for:
6387/// struct _message_ref_t {
6388/// IMP messenger;
6389/// SEL name;
6390/// };
6391
6392/// SuperMessageRefTy - LLVM for:
6393/// struct _super_message_ref_t {
6394/// SUPER_IMP messenger;
6395/// SEL name;
6396/// };
6397
Fariborz Jahanian45489622012-03-14 18:09:23 +00006398static void WriteModernMetadataDeclarations(ASTContext *Context, std::string &Result) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00006399 static bool meta_data_declared = false;
6400 if (meta_data_declared)
6401 return;
6402
6403 Result += "\nstruct _prop_t {\n";
Fariborz Jahanian67f7c552012-02-07 23:31:52 +00006404 Result += "\tconst char *name;\n";
6405 Result += "\tconst char *attributes;\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006406 Result += "};\n";
6407
6408 Result += "\nstruct _protocol_t;\n";
6409
Fariborz Jahanian11671902012-02-07 17:11:38 +00006410 Result += "\nstruct _objc_method {\n";
6411 Result += "\tstruct objc_selector * _cmd;\n";
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006412 Result += "\tconst char *method_type;\n";
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006413 Result += "\tvoid *_imp;\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006414 Result += "};\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006415
6416 Result += "\nstruct _protocol_t {\n";
6417 Result += "\tvoid * isa; // NULL\n";
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006418 Result += "\tconst char *protocol_name;\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006419 Result += "\tconst struct _protocol_list_t * protocol_list; // super protocols\n";
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006420 Result += "\tconst struct method_list_t *instance_methods;\n";
6421 Result += "\tconst struct method_list_t *class_methods;\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006422 Result += "\tconst struct method_list_t *optionalInstanceMethods;\n";
6423 Result += "\tconst struct method_list_t *optionalClassMethods;\n";
6424 Result += "\tconst struct _prop_list_t * properties;\n";
6425 Result += "\tconst unsigned int size; // sizeof(struct _protocol_t)\n";
6426 Result += "\tconst unsigned int flags; // = 0\n";
6427 Result += "\tconst char ** extendedMethodTypes;\n";
6428 Result += "};\n";
6429
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006430 Result += "\nstruct _ivar_t {\n";
6431 Result += "\tunsigned long int *offset; // pointer to ivar offset location\n";
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006432 Result += "\tconst char *name;\n";
6433 Result += "\tconst char *type;\n";
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006434 Result += "\tunsigned int alignment;\n";
6435 Result += "\tunsigned int size;\n";
6436 Result += "};\n";
6437
6438 Result += "\nstruct _class_ro_t {\n";
Fariborz Jahanian34134812012-03-24 16:53:16 +00006439 Result += "\tunsigned int flags;\n";
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006440 Result += "\tunsigned int instanceStart;\n";
Fariborz Jahanian34134812012-03-24 16:53:16 +00006441 Result += "\tunsigned int instanceSize;\n";
Fariborz Jahanian45489622012-03-14 18:09:23 +00006442 const llvm::Triple &Triple(Context->getTargetInfo().getTriple());
6443 if (Triple.getArch() == llvm::Triple::x86_64)
Fariborz Jahanian34134812012-03-24 16:53:16 +00006444 Result += "\tunsigned int reserved;\n";
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006445 Result += "\tconst unsigned char *ivarLayout;\n";
6446 Result += "\tconst char *name;\n";
6447 Result += "\tconst struct _method_list_t *baseMethods;\n";
6448 Result += "\tconst struct _objc_protocol_list *baseProtocols;\n";
6449 Result += "\tconst struct _ivar_list_t *ivars;\n";
6450 Result += "\tconst unsigned char *weakIvarLayout;\n";
6451 Result += "\tconst struct _prop_list_t *properties;\n";
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006452 Result += "};\n";
6453
6454 Result += "\nstruct _class_t {\n";
6455 Result += "\tstruct _class_t *isa;\n";
Fariborz Jahanian6e60c132012-03-20 17:34:50 +00006456 Result += "\tstruct _class_t *superclass;\n";
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006457 Result += "\tvoid *cache;\n";
6458 Result += "\tvoid *vtable;\n";
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006459 Result += "\tstruct _class_ro_t *ro;\n";
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006460 Result += "};\n";
6461
6462 Result += "\nstruct _category_t {\n";
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006463 Result += "\tconst char *name;\n";
Fariborz Jahaniancd79a492012-03-20 21:41:28 +00006464 Result += "\tstruct _class_t *cls;\n";
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006465 Result += "\tconst struct _method_list_t *instance_methods;\n";
6466 Result += "\tconst struct _method_list_t *class_methods;\n";
6467 Result += "\tconst struct _protocol_list_t *protocols;\n";
6468 Result += "\tconst struct _prop_list_t *properties;\n";
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006469 Result += "};\n";
6470
Fariborz Jahanian38c59102012-03-27 16:21:30 +00006471 Result += "extern \"C\" __declspec(dllimport) struct objc_cache _objc_empty_cache;\n";
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00006472 Result += "#pragma warning(disable:4273)\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006473 meta_data_declared = true;
6474}
6475
Fariborz Jahaniane18961b2012-02-08 19:53:58 +00006476static void Write_protocol_list_t_TypeDecl(std::string &Result,
6477 long super_protocol_count) {
6478 Result += "struct /*_protocol_list_t*/"; Result += " {\n";
6479 Result += "\tlong protocol_count; // Note, this is 32/64 bit\n";
6480 Result += "\tstruct _protocol_t *super_protocols[";
6481 Result += utostr(super_protocol_count); Result += "];\n";
6482 Result += "}";
6483}
6484
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006485static void Write_method_list_t_TypeDecl(std::string &Result,
6486 unsigned int method_count) {
6487 Result += "struct /*_method_list_t*/"; Result += " {\n";
6488 Result += "\tunsigned int entsize; // sizeof(struct _objc_method)\n";
6489 Result += "\tunsigned int method_count;\n";
6490 Result += "\tstruct _objc_method method_list[";
6491 Result += utostr(method_count); Result += "];\n";
6492 Result += "}";
6493}
6494
Fariborz Jahanian67f7c552012-02-07 23:31:52 +00006495static void Write__prop_list_t_TypeDecl(std::string &Result,
6496 unsigned int property_count) {
6497 Result += "struct /*_prop_list_t*/"; Result += " {\n";
6498 Result += "\tunsigned int entsize; // sizeof(struct _prop_t)\n";
6499 Result += "\tunsigned int count_of_properties;\n";
6500 Result += "\tstruct _prop_t prop_list[";
6501 Result += utostr(property_count); Result += "];\n";
6502 Result += "}";
6503}
6504
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006505static void Write__ivar_list_t_TypeDecl(std::string &Result,
6506 unsigned int ivar_count) {
6507 Result += "struct /*_ivar_list_t*/"; Result += " {\n";
6508 Result += "\tunsigned int entsize; // sizeof(struct _prop_t)\n";
6509 Result += "\tunsigned int count;\n";
6510 Result += "\tstruct _ivar_t ivar_list[";
6511 Result += utostr(ivar_count); Result += "];\n";
6512 Result += "}";
6513}
6514
Fariborz Jahaniane18961b2012-02-08 19:53:58 +00006515static void Write_protocol_list_initializer(ASTContext *Context, std::string &Result,
6516 ArrayRef<ObjCProtocolDecl *> SuperProtocols,
6517 StringRef VarName,
6518 StringRef ProtocolName) {
6519 if (SuperProtocols.size() > 0) {
6520 Result += "\nstatic ";
6521 Write_protocol_list_t_TypeDecl(Result, SuperProtocols.size());
6522 Result += " "; Result += VarName;
6523 Result += ProtocolName;
6524 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6525 Result += "\t"; Result += utostr(SuperProtocols.size()); Result += ",\n";
6526 for (unsigned i = 0, e = SuperProtocols.size(); i < e; i++) {
6527 ObjCProtocolDecl *SuperPD = SuperProtocols[i];
6528 Result += "\t&"; Result += "_OBJC_PROTOCOL_";
6529 Result += SuperPD->getNameAsString();
6530 if (i == e-1)
6531 Result += "\n};\n";
6532 else
6533 Result += ",\n";
6534 }
6535 }
6536}
6537
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006538static void Write_method_list_t_initializer(RewriteModernObjC &RewriteObj,
6539 ASTContext *Context, std::string &Result,
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006540 ArrayRef<ObjCMethodDecl *> Methods,
6541 StringRef VarName,
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006542 StringRef TopLevelDeclName,
6543 bool MethodImpl) {
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006544 if (Methods.size() > 0) {
6545 Result += "\nstatic ";
6546 Write_method_list_t_TypeDecl(Result, Methods.size());
6547 Result += " "; Result += VarName;
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006548 Result += TopLevelDeclName;
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006549 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6550 Result += "\t"; Result += "sizeof(_objc_method)"; Result += ",\n";
6551 Result += "\t"; Result += utostr(Methods.size()); Result += ",\n";
6552 for (unsigned i = 0, e = Methods.size(); i < e; i++) {
6553 ObjCMethodDecl *MD = Methods[i];
6554 if (i == 0)
6555 Result += "\t{{(struct objc_selector *)\"";
6556 else
6557 Result += "\t{(struct objc_selector *)\"";
6558 Result += (MD)->getSelector().getAsString(); Result += "\"";
6559 Result += ", ";
6560 std::string MethodTypeString;
6561 Context->getObjCEncodingForMethodDecl(MD, MethodTypeString);
6562 Result += "\""; Result += MethodTypeString; Result += "\"";
6563 Result += ", ";
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006564 if (!MethodImpl)
6565 Result += "0";
6566 else {
6567 Result += "(void *)";
6568 Result += RewriteObj.MethodInternalNames[MD];
6569 }
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006570 if (i == e-1)
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006571 Result += "}}\n";
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006572 else
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006573 Result += "},\n";
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006574 }
6575 Result += "};\n";
6576 }
6577}
6578
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006579static void Write_prop_list_t_initializer(RewriteModernObjC &RewriteObj,
Fariborz Jahanian67f7c552012-02-07 23:31:52 +00006580 ASTContext *Context, std::string &Result,
6581 ArrayRef<ObjCPropertyDecl *> Properties,
6582 const Decl *Container,
6583 StringRef VarName,
6584 StringRef ProtocolName) {
6585 if (Properties.size() > 0) {
6586 Result += "\nstatic ";
6587 Write__prop_list_t_TypeDecl(Result, Properties.size());
6588 Result += " "; Result += VarName;
6589 Result += ProtocolName;
6590 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6591 Result += "\t"; Result += "sizeof(_prop_t)"; Result += ",\n";
6592 Result += "\t"; Result += utostr(Properties.size()); Result += ",\n";
6593 for (unsigned i = 0, e = Properties.size(); i < e; i++) {
6594 ObjCPropertyDecl *PropDecl = Properties[i];
6595 if (i == 0)
6596 Result += "\t{{\"";
6597 else
6598 Result += "\t{\"";
6599 Result += PropDecl->getName(); Result += "\",";
6600 std::string PropertyTypeString, QuotePropertyTypeString;
6601 Context->getObjCEncodingForPropertyDecl(PropDecl, Container, PropertyTypeString);
6602 RewriteObj.QuoteDoublequotes(PropertyTypeString, QuotePropertyTypeString);
6603 Result += "\""; Result += QuotePropertyTypeString; Result += "\"";
6604 if (i == e-1)
6605 Result += "}}\n";
6606 else
6607 Result += "},\n";
6608 }
6609 Result += "};\n";
6610 }
6611}
6612
Fariborz Jahanian0a256882012-02-16 18:54:09 +00006613// Metadata flags
6614enum MetaDataDlags {
6615 CLS = 0x0,
6616 CLS_META = 0x1,
6617 CLS_ROOT = 0x2,
6618 OBJC2_CLS_HIDDEN = 0x10,
6619 CLS_EXCEPTION = 0x20,
6620
6621 /// (Obsolete) ARC-specific: this class has a .release_ivars method
6622 CLS_HAS_IVAR_RELEASER = 0x40,
6623 /// class was compiled with -fobjc-arr
6624 CLS_COMPILED_BY_ARC = 0x80 // (1<<7)
6625};
6626
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006627static void Write__class_ro_t_initializer(ASTContext *Context, std::string &Result,
6628 unsigned int flags,
6629 const std::string &InstanceStart,
6630 const std::string &InstanceSize,
6631 ArrayRef<ObjCMethodDecl *>baseMethods,
6632 ArrayRef<ObjCProtocolDecl *>baseProtocols,
6633 ArrayRef<ObjCIvarDecl *>ivars,
6634 ArrayRef<ObjCPropertyDecl *>Properties,
6635 StringRef VarName,
6636 StringRef ClassName) {
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006637 Result += "\nstatic struct _class_ro_t ";
6638 Result += VarName; Result += ClassName;
6639 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6640 Result += "\t";
6641 Result += llvm::utostr(flags); Result += ", ";
6642 Result += InstanceStart; Result += ", ";
6643 Result += InstanceSize; Result += ", \n";
6644 Result += "\t";
Fariborz Jahanian45489622012-03-14 18:09:23 +00006645 const llvm::Triple &Triple(Context->getTargetInfo().getTriple());
6646 if (Triple.getArch() == llvm::Triple::x86_64)
6647 // uint32_t const reserved; // only when building for 64bit targets
6648 Result += "(unsigned int)0, \n\t";
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006649 // const uint8_t * const ivarLayout;
6650 Result += "0, \n\t";
6651 Result += "\""; Result += ClassName; Result += "\",\n\t";
Fariborz Jahanian0a256882012-02-16 18:54:09 +00006652 bool metaclass = ((flags & CLS_META) != 0);
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006653 if (baseMethods.size() > 0) {
6654 Result += "(const struct _method_list_t *)&";
Fariborz Jahanian0a256882012-02-16 18:54:09 +00006655 if (metaclass)
6656 Result += "_OBJC_$_CLASS_METHODS_";
6657 else
6658 Result += "_OBJC_$_INSTANCE_METHODS_";
6659 Result += ClassName;
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006660 Result += ",\n\t";
6661 }
6662 else
6663 Result += "0, \n\t";
6664
Fariborz Jahanian0a256882012-02-16 18:54:09 +00006665 if (!metaclass && baseProtocols.size() > 0) {
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006666 Result += "(const struct _objc_protocol_list *)&";
6667 Result += "_OBJC_CLASS_PROTOCOLS_$_"; Result += ClassName;
6668 Result += ",\n\t";
6669 }
6670 else
6671 Result += "0, \n\t";
6672
Fariborz Jahanian0a256882012-02-16 18:54:09 +00006673 if (!metaclass && ivars.size() > 0) {
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006674 Result += "(const struct _ivar_list_t *)&";
6675 Result += "_OBJC_$_INSTANCE_VARIABLES_"; Result += ClassName;
6676 Result += ",\n\t";
6677 }
6678 else
6679 Result += "0, \n\t";
6680
6681 // weakIvarLayout
6682 Result += "0, \n\t";
Fariborz Jahanian0a256882012-02-16 18:54:09 +00006683 if (!metaclass && Properties.size() > 0) {
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006684 Result += "(const struct _prop_list_t *)&";
Fariborz Jahanianc41d8282012-02-16 21:57:59 +00006685 Result += "_OBJC_$_PROP_LIST_"; Result += ClassName;
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006686 Result += ",\n";
6687 }
6688 else
6689 Result += "0, \n";
6690
6691 Result += "};\n";
6692}
6693
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006694static void Write_class_t(ASTContext *Context, std::string &Result,
6695 StringRef VarName,
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006696 const ObjCInterfaceDecl *CDecl, bool metaclass) {
6697 bool rootClass = (!CDecl->getSuperClass());
6698 const ObjCInterfaceDecl *RootClass = CDecl;
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006699
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006700 if (!rootClass) {
6701 // Find the Root class
6702 RootClass = CDecl->getSuperClass();
6703 while (RootClass->getSuperClass()) {
6704 RootClass = RootClass->getSuperClass();
6705 }
6706 }
6707
6708 if (metaclass && rootClass) {
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006709 // Need to handle a case of use of forward declaration.
Fariborz Jahanianfca65102012-03-10 18:25:06 +00006710 Result += "\n";
Fariborz Jahanian38c59102012-03-27 16:21:30 +00006711 Result += "extern \"C\" ";
Fariborz Jahanianfca65102012-03-10 18:25:06 +00006712 if (CDecl->getImplementation())
6713 Result += "__declspec(dllexport) ";
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00006714 else
6715 Result += "__declspec(dllimport) ";
6716
Fariborz Jahanian38c59102012-03-27 16:21:30 +00006717 Result += "struct _class_t OBJC_CLASS_$_";
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006718 Result += CDecl->getNameAsString();
6719 Result += ";\n";
6720 }
6721 // Also, for possibility of 'super' metadata class not having been defined yet.
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006722 if (!rootClass) {
Fariborz Jahanian064b5382012-03-29 19:04:10 +00006723 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahanianfca65102012-03-10 18:25:06 +00006724 Result += "\n";
Fariborz Jahanian38c59102012-03-27 16:21:30 +00006725 Result += "extern \"C\" ";
Fariborz Jahanian064b5382012-03-29 19:04:10 +00006726 if (SuperClass->getImplementation())
Fariborz Jahanianfca65102012-03-10 18:25:06 +00006727 Result += "__declspec(dllexport) ";
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00006728 else
6729 Result += "__declspec(dllimport) ";
6730
Fariborz Jahanian38c59102012-03-27 16:21:30 +00006731 Result += "struct _class_t ";
Fariborz Jahanianfca65102012-03-10 18:25:06 +00006732 Result += VarName;
Fariborz Jahanian064b5382012-03-29 19:04:10 +00006733 Result += SuperClass->getNameAsString();
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006734 Result += ";\n";
Fariborz Jahanian35465592012-03-20 21:09:58 +00006735
Fariborz Jahanian064b5382012-03-29 19:04:10 +00006736 if (metaclass && RootClass != SuperClass) {
Fariborz Jahanian38c59102012-03-27 16:21:30 +00006737 Result += "extern \"C\" ";
Fariborz Jahanian35465592012-03-20 21:09:58 +00006738 if (RootClass->getImplementation())
6739 Result += "__declspec(dllexport) ";
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00006740 else
6741 Result += "__declspec(dllimport) ";
6742
Fariborz Jahanian38c59102012-03-27 16:21:30 +00006743 Result += "struct _class_t ";
Fariborz Jahanian35465592012-03-20 21:09:58 +00006744 Result += VarName;
6745 Result += RootClass->getNameAsString();
6746 Result += ";\n";
6747 }
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006748 }
6749
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00006750 Result += "\nextern \"C\" __declspec(dllexport) struct _class_t ";
6751 Result += VarName; Result += CDecl->getNameAsString();
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006752 Result += " __attribute__ ((used, section (\"__DATA,__objc_data\"))) = {\n";
6753 Result += "\t";
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006754 if (metaclass) {
6755 if (!rootClass) {
6756 Result += "0, // &"; Result += VarName;
6757 Result += RootClass->getNameAsString();
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006758 Result += ",\n\t";
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006759 Result += "0, // &"; Result += VarName;
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006760 Result += CDecl->getSuperClass()->getNameAsString();
6761 Result += ",\n\t";
6762 }
6763 else {
Fariborz Jahanian35465592012-03-20 21:09:58 +00006764 Result += "0, // &"; Result += VarName;
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006765 Result += CDecl->getNameAsString();
6766 Result += ",\n\t";
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006767 Result += "0, // &OBJC_CLASS_$_"; Result += CDecl->getNameAsString();
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006768 Result += ",\n\t";
6769 }
6770 }
6771 else {
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006772 Result += "0, // &OBJC_METACLASS_$_";
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006773 Result += CDecl->getNameAsString();
6774 Result += ",\n\t";
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006775 if (!rootClass) {
6776 Result += "0, // &"; Result += VarName;
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006777 Result += CDecl->getSuperClass()->getNameAsString();
6778 Result += ",\n\t";
6779 }
6780 else
6781 Result += "0,\n\t";
6782 }
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006783 Result += "0, // (void *)&_objc_empty_cache,\n\t";
6784 Result += "0, // unused, was (void *)&_objc_empty_vtable,\n\t";
6785 if (metaclass)
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006786 Result += "&_OBJC_METACLASS_RO_$_";
6787 else
6788 Result += "&_OBJC_CLASS_RO_$_";
6789 Result += CDecl->getNameAsString();
6790 Result += ",\n};\n";
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006791
6792 // Add static function to initialize some of the meta-data fields.
6793 // avoid doing it twice.
6794 if (metaclass)
6795 return;
6796
6797 const ObjCInterfaceDecl *SuperClass =
6798 rootClass ? CDecl : CDecl->getSuperClass();
6799
6800 Result += "static void OBJC_CLASS_SETUP_$_";
6801 Result += CDecl->getNameAsString();
6802 Result += "(void ) {\n";
6803 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
6804 Result += ".isa = "; Result += "&OBJC_METACLASS_$_";
Fariborz Jahanian35465592012-03-20 21:09:58 +00006805 Result += RootClass->getNameAsString(); Result += ";\n";
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006806
6807 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
Fariborz Jahanian35465592012-03-20 21:09:58 +00006808 Result += ".superclass = ";
6809 if (rootClass)
6810 Result += "&OBJC_CLASS_$_";
6811 else
6812 Result += "&OBJC_METACLASS_$_";
6813
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006814 Result += SuperClass->getNameAsString(); Result += ";\n";
6815
6816 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
6817 Result += ".cache = "; Result += "&_objc_empty_cache"; Result += ";\n";
6818
6819 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6820 Result += ".isa = "; Result += "&OBJC_METACLASS_$_";
6821 Result += CDecl->getNameAsString(); Result += ";\n";
6822
6823 if (!rootClass) {
6824 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6825 Result += ".superclass = "; Result += "&OBJC_CLASS_$_";
6826 Result += SuperClass->getNameAsString(); Result += ";\n";
6827 }
6828
6829 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6830 Result += ".cache = "; Result += "&_objc_empty_cache"; Result += ";\n";
6831 Result += "}\n";
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006832}
6833
Fariborz Jahanianf2055052012-02-17 18:40:41 +00006834static void Write_category_t(RewriteModernObjC &RewriteObj, ASTContext *Context,
6835 std::string &Result,
Fariborz Jahanian5ed21c32012-03-27 18:41:05 +00006836 ObjCCategoryDecl *CatDecl,
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00006837 ObjCInterfaceDecl *ClassDecl,
Fariborz Jahanianf2055052012-02-17 18:40:41 +00006838 ArrayRef<ObjCMethodDecl *> InstanceMethods,
6839 ArrayRef<ObjCMethodDecl *> ClassMethods,
6840 ArrayRef<ObjCProtocolDecl *> RefedProtocols,
6841 ArrayRef<ObjCPropertyDecl *> ClassProperties) {
Fariborz Jahanian5ed21c32012-03-27 18:41:05 +00006842 StringRef CatName = CatDecl->getName();
NAKAMURA Takumi3eb0edd2012-03-21 03:21:46 +00006843 StringRef ClassName = ClassDecl->getName();
Fariborz Jahanian320c88a2012-02-17 20:33:00 +00006844 // must declare an extern class object in case this class is not implemented
6845 // in this TU.
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00006846 Result += "\n";
Fariborz Jahanian38c59102012-03-27 16:21:30 +00006847 Result += "extern \"C\" ";
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00006848 if (ClassDecl->getImplementation())
6849 Result += "__declspec(dllexport) ";
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00006850 else
6851 Result += "__declspec(dllimport) ";
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00006852
Fariborz Jahanian38c59102012-03-27 16:21:30 +00006853 Result += "struct _class_t ";
Fariborz Jahanian320c88a2012-02-17 20:33:00 +00006854 Result += "OBJC_CLASS_$_"; Result += ClassName;
6855 Result += ";\n";
6856
Fariborz Jahanianf2055052012-02-17 18:40:41 +00006857 Result += "\nstatic struct _category_t ";
6858 Result += "_OBJC_$_CATEGORY_";
6859 Result += ClassName; Result += "_$_"; Result += CatName;
6860 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = \n";
6861 Result += "{\n";
6862 Result += "\t\""; Result += ClassName; Result += "\",\n";
Fariborz Jahaniancd79a492012-03-20 21:41:28 +00006863 Result += "\t0, // &"; Result += "OBJC_CLASS_$_"; Result += ClassName;
Fariborz Jahanianf2055052012-02-17 18:40:41 +00006864 Result += ",\n";
6865 if (InstanceMethods.size() > 0) {
6866 Result += "\t(const struct _method_list_t *)&";
6867 Result += "_OBJC_$_CATEGORY_INSTANCE_METHODS_";
6868 Result += ClassName; Result += "_$_"; Result += CatName;
6869 Result += ",\n";
6870 }
6871 else
6872 Result += "\t0,\n";
6873
6874 if (ClassMethods.size() > 0) {
6875 Result += "\t(const struct _method_list_t *)&";
6876 Result += "_OBJC_$_CATEGORY_CLASS_METHODS_";
6877 Result += ClassName; Result += "_$_"; Result += CatName;
6878 Result += ",\n";
6879 }
6880 else
6881 Result += "\t0,\n";
6882
6883 if (RefedProtocols.size() > 0) {
6884 Result += "\t(const struct _protocol_list_t *)&";
6885 Result += "_OBJC_CATEGORY_PROTOCOLS_$_";
6886 Result += ClassName; Result += "_$_"; Result += CatName;
6887 Result += ",\n";
6888 }
6889 else
6890 Result += "\t0,\n";
6891
6892 if (ClassProperties.size() > 0) {
6893 Result += "\t(const struct _prop_list_t *)&"; Result += "_OBJC_$_PROP_LIST_";
6894 Result += ClassName; Result += "_$_"; Result += CatName;
6895 Result += ",\n";
6896 }
6897 else
6898 Result += "\t0,\n";
6899
6900 Result += "};\n";
Fariborz Jahaniancd79a492012-03-20 21:41:28 +00006901
6902 // Add static function to initialize the class pointer in the category structure.
6903 Result += "static void OBJC_CATEGORY_SETUP_$_";
6904 Result += ClassDecl->getNameAsString();
6905 Result += "_$_";
6906 Result += CatName;
6907 Result += "(void ) {\n";
6908 Result += "\t_OBJC_$_CATEGORY_";
6909 Result += ClassDecl->getNameAsString();
6910 Result += "_$_";
6911 Result += CatName;
6912 Result += ".cls = "; Result += "&OBJC_CLASS_$_"; Result += ClassName;
6913 Result += ";\n}\n";
Fariborz Jahanianf2055052012-02-17 18:40:41 +00006914}
6915
Fariborz Jahaniana8395a62012-02-08 22:23:26 +00006916static void Write__extendedMethodTypes_initializer(RewriteModernObjC &RewriteObj,
6917 ASTContext *Context, std::string &Result,
6918 ArrayRef<ObjCMethodDecl *> Methods,
6919 StringRef VarName,
6920 StringRef ProtocolName) {
6921 if (Methods.size() == 0)
6922 return;
6923
6924 Result += "\nstatic const char *";
6925 Result += VarName; Result += ProtocolName;
6926 Result += " [] __attribute__ ((used, section (\"__DATA,__objc_const\"))) = \n";
6927 Result += "{\n";
6928 for (unsigned i = 0, e = Methods.size(); i < e; i++) {
6929 ObjCMethodDecl *MD = Methods[i];
6930 std::string MethodTypeString, QuoteMethodTypeString;
6931 Context->getObjCEncodingForMethodDecl(MD, MethodTypeString, true);
6932 RewriteObj.QuoteDoublequotes(MethodTypeString, QuoteMethodTypeString);
6933 Result += "\t\""; Result += QuoteMethodTypeString; Result += "\"";
6934 if (i == e-1)
6935 Result += "\n};\n";
6936 else {
6937 Result += ",\n";
6938 }
6939 }
6940}
6941
Fariborz Jahanianaaf4d692012-04-11 21:12:36 +00006942static void Write_IvarOffsetVar(RewriteModernObjC &RewriteObj,
6943 ASTContext *Context,
Fariborz Jahaniane47bf2b2012-03-12 16:46:58 +00006944 std::string &Result,
Fariborz Jahanian75e71b92012-02-13 20:59:02 +00006945 ArrayRef<ObjCIvarDecl *> Ivars,
Fariborz Jahaniana854174a2012-03-20 17:13:39 +00006946 ObjCInterfaceDecl *CDecl) {
Fariborz Jahanian75e71b92012-02-13 20:59:02 +00006947 // FIXME. visibilty of offset symbols may have to be set; for Darwin
6948 // this is what happens:
6949 /**
6950 if (Ivar->getAccessControl() == ObjCIvarDecl::Private ||
6951 Ivar->getAccessControl() == ObjCIvarDecl::Package ||
6952 Class->getVisibility() == HiddenVisibility)
6953 Visibility shoud be: HiddenVisibility;
6954 else
6955 Visibility shoud be: DefaultVisibility;
6956 */
6957
Fariborz Jahanian1c1da172012-02-13 21:34:45 +00006958 Result += "\n";
6959 for (unsigned i =0, e = Ivars.size(); i < e; i++) {
6960 ObjCIvarDecl *IvarDecl = Ivars[i];
Fariborz Jahaniane47bf2b2012-03-12 16:46:58 +00006961 if (Context->getLangOpts().MicrosoftExt)
6962 Result += "__declspec(allocate(\".objc_ivar$B\")) ";
6963
6964 if (!Context->getLangOpts().MicrosoftExt ||
6965 IvarDecl->getAccessControl() == ObjCIvarDecl::Private ||
Fariborz Jahanianc9295ec2012-03-10 01:34:42 +00006966 IvarDecl->getAccessControl() == ObjCIvarDecl::Package)
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00006967 Result += "extern \"C\" unsigned long int ";
Fariborz Jahanian2677ded2012-03-10 00:53:02 +00006968 else
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00006969 Result += "extern \"C\" __declspec(dllexport) unsigned long int ";
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006970 if (Ivars[i]->isBitField())
6971 RewriteObj.ObjCIvarBitfieldGroupOffset(IvarDecl, Result);
6972 else
6973 WriteInternalIvarName(CDecl, IvarDecl, Result);
Fariborz Jahanian1c1da172012-02-13 21:34:45 +00006974 Result += " __attribute__ ((used, section (\"__DATA,__objc_ivar\")))";
6975 Result += " = ";
Fariborz Jahanianaaf4d692012-04-11 21:12:36 +00006976 RewriteObj.RewriteIvarOffsetComputation(IvarDecl, Result);
6977 Result += ";\n";
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006978 if (Ivars[i]->isBitField()) {
6979 // skip over rest of the ivar bitfields.
6980 SKIP_BITFIELDS(i , e, Ivars);
6981 }
Fariborz Jahanian75e71b92012-02-13 20:59:02 +00006982 }
6983}
6984
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006985static void Write__ivar_list_t_initializer(RewriteModernObjC &RewriteObj,
6986 ASTContext *Context, std::string &Result,
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006987 ArrayRef<ObjCIvarDecl *> OriginalIvars,
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006988 StringRef VarName,
Fariborz Jahaniana854174a2012-03-20 17:13:39 +00006989 ObjCInterfaceDecl *CDecl) {
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006990 if (OriginalIvars.size() > 0) {
6991 Write_IvarOffsetVar(RewriteObj, Context, Result, OriginalIvars, CDecl);
6992 SmallVector<ObjCIvarDecl *, 8> Ivars;
6993 // strip off all but the first ivar bitfield from each group of ivars.
6994 // Such ivars in the ivar list table will be replaced by their grouping struct
6995 // 'ivar'.
6996 for (unsigned i = 0, e = OriginalIvars.size(); i < e; i++) {
6997 if (OriginalIvars[i]->isBitField()) {
6998 Ivars.push_back(OriginalIvars[i]);
6999 // skip over rest of the ivar bitfields.
7000 SKIP_BITFIELDS(i , e, OriginalIvars);
7001 }
7002 else
7003 Ivars.push_back(OriginalIvars[i]);
7004 }
Fariborz Jahanian1c1da172012-02-13 21:34:45 +00007005
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00007006 Result += "\nstatic ";
7007 Write__ivar_list_t_TypeDecl(Result, Ivars.size());
7008 Result += " "; Result += VarName;
Fariborz Jahaniana854174a2012-03-20 17:13:39 +00007009 Result += CDecl->getNameAsString();
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00007010 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
7011 Result += "\t"; Result += "sizeof(_ivar_t)"; Result += ",\n";
7012 Result += "\t"; Result += utostr(Ivars.size()); Result += ",\n";
7013 for (unsigned i =0, e = Ivars.size(); i < e; i++) {
7014 ObjCIvarDecl *IvarDecl = Ivars[i];
7015 if (i == 0)
7016 Result += "\t{{";
7017 else
7018 Result += "\t {";
Fariborz Jahaniana854174a2012-03-20 17:13:39 +00007019 Result += "(unsigned long int *)&";
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00007020 if (Ivars[i]->isBitField())
7021 RewriteObj.ObjCIvarBitfieldGroupOffset(IvarDecl, Result);
7022 else
7023 WriteInternalIvarName(CDecl, IvarDecl, Result);
Fariborz Jahanian75e71b92012-02-13 20:59:02 +00007024 Result += ", ";
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00007025
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00007026 Result += "\"";
7027 if (Ivars[i]->isBitField())
7028 RewriteObj.ObjCIvarBitfieldGroupDecl(Ivars[i], Result);
7029 else
7030 Result += IvarDecl->getName();
7031 Result += "\", ";
7032
7033 QualType IVQT = IvarDecl->getType();
7034 if (IvarDecl->isBitField())
7035 IVQT = RewriteObj.GetGroupRecordTypeForObjCIvarBitfield(IvarDecl);
7036
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00007037 std::string IvarTypeString, QuoteIvarTypeString;
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00007038 Context->getObjCEncodingForType(IVQT, IvarTypeString,
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00007039 IvarDecl);
7040 RewriteObj.QuoteDoublequotes(IvarTypeString, QuoteIvarTypeString);
7041 Result += "\""; Result += QuoteIvarTypeString; Result += "\", ";
7042
Fariborz Jahanian088959a2012-02-11 20:10:52 +00007043 // FIXME. this alignment represents the host alignment and need be changed to
7044 // represent the target alignment.
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00007045 unsigned Align = Context->getTypeAlign(IVQT)/8;
Fariborz Jahanian088959a2012-02-11 20:10:52 +00007046 Align = llvm::Log2_32(Align);
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00007047 Result += llvm::utostr(Align); Result += ", ";
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00007048 CharUnits Size = Context->getTypeSizeInChars(IVQT);
Fariborz Jahaniancb1d9f32012-02-10 23:18:24 +00007049 Result += llvm::utostr(Size.getQuantity());
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00007050 if (i == e-1)
7051 Result += "}}\n";
7052 else
7053 Result += "},\n";
7054 }
7055 Result += "};\n";
7056 }
7057}
7058
Fariborz Jahanian11671902012-02-07 17:11:38 +00007059/// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
Fariborz Jahaniane18961b2012-02-08 19:53:58 +00007060void RewriteModernObjC::RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl,
7061 std::string &Result) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00007062
Fariborz Jahanian11671902012-02-07 17:11:38 +00007063 // Do not synthesize the protocol more than once.
7064 if (ObjCSynthesizedProtocols.count(PDecl->getCanonicalDecl()))
7065 return;
Fariborz Jahanian45489622012-03-14 18:09:23 +00007066 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanian11671902012-02-07 17:11:38 +00007067
7068 if (ObjCProtocolDecl *Def = PDecl->getDefinition())
7069 PDecl = Def;
Fariborz Jahaniane18961b2012-02-08 19:53:58 +00007070 // Must write out all protocol definitions in current qualifier list,
7071 // and in their nested qualifiers before writing out current definition.
7072 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
7073 E = PDecl->protocol_end(); I != E; ++I)
7074 RewriteObjCProtocolMetaData(*I, Result);
Fariborz Jahanian11671902012-02-07 17:11:38 +00007075
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00007076 // Construct method lists.
7077 std::vector<ObjCMethodDecl *> InstanceMethods, ClassMethods;
7078 std::vector<ObjCMethodDecl *> OptInstanceMethods, OptClassMethods;
7079 for (ObjCProtocolDecl::instmeth_iterator
7080 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
7081 I != E; ++I) {
7082 ObjCMethodDecl *MD = *I;
7083 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
7084 OptInstanceMethods.push_back(MD);
7085 } else {
7086 InstanceMethods.push_back(MD);
7087 }
7088 }
7089
7090 for (ObjCProtocolDecl::classmeth_iterator
7091 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
7092 I != E; ++I) {
7093 ObjCMethodDecl *MD = *I;
7094 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
7095 OptClassMethods.push_back(MD);
7096 } else {
7097 ClassMethods.push_back(MD);
7098 }
7099 }
Fariborz Jahaniana8395a62012-02-08 22:23:26 +00007100 std::vector<ObjCMethodDecl *> AllMethods;
7101 for (unsigned i = 0, e = InstanceMethods.size(); i < e; i++)
7102 AllMethods.push_back(InstanceMethods[i]);
7103 for (unsigned i = 0, e = ClassMethods.size(); i < e; i++)
7104 AllMethods.push_back(ClassMethods[i]);
7105 for (unsigned i = 0, e = OptInstanceMethods.size(); i < e; i++)
7106 AllMethods.push_back(OptInstanceMethods[i]);
7107 for (unsigned i = 0, e = OptClassMethods.size(); i < e; i++)
7108 AllMethods.push_back(OptClassMethods[i]);
7109
7110 Write__extendedMethodTypes_initializer(*this, Context, Result,
7111 AllMethods,
7112 "_OBJC_PROTOCOL_METHOD_TYPES_",
7113 PDecl->getNameAsString());
Fariborz Jahaniane18961b2012-02-08 19:53:58 +00007114 // Protocol's super protocol list
7115 std::vector<ObjCProtocolDecl *> SuperProtocols;
7116 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
7117 E = PDecl->protocol_end(); I != E; ++I)
7118 SuperProtocols.push_back(*I);
7119
7120 Write_protocol_list_initializer(Context, Result, SuperProtocols,
7121 "_OBJC_PROTOCOL_REFS_",
7122 PDecl->getNameAsString());
7123
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007124 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00007125 "_OBJC_PROTOCOL_INSTANCE_METHODS_",
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007126 PDecl->getNameAsString(), false);
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00007127
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007128 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00007129 "_OBJC_PROTOCOL_CLASS_METHODS_",
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007130 PDecl->getNameAsString(), false);
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00007131
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007132 Write_method_list_t_initializer(*this, Context, Result, OptInstanceMethods,
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00007133 "_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_",
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007134 PDecl->getNameAsString(), false);
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00007135
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007136 Write_method_list_t_initializer(*this, Context, Result, OptClassMethods,
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00007137 "_OBJC_PROTOCOL_OPT_CLASS_METHODS_",
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007138 PDecl->getNameAsString(), false);
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00007139
Fariborz Jahanian67f7c552012-02-07 23:31:52 +00007140 // Protocol's property metadata.
7141 std::vector<ObjCPropertyDecl *> ProtocolProperties;
7142 for (ObjCContainerDecl::prop_iterator I = PDecl->prop_begin(),
7143 E = PDecl->prop_end(); I != E; ++I)
David Blaikie40ed2972012-06-06 20:45:41 +00007144 ProtocolProperties.push_back(*I);
Fariborz Jahanian67f7c552012-02-07 23:31:52 +00007145
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007146 Write_prop_list_t_initializer(*this, Context, Result, ProtocolProperties,
Fariborz Jahanian67f7c552012-02-07 23:31:52 +00007147 /* Container */0,
7148 "_OBJC_PROTOCOL_PROPERTIES_",
7149 PDecl->getNameAsString());
Fariborz Jahanian67f7c552012-02-07 23:31:52 +00007150
Fariborz Jahanian48985802012-02-08 00:50:52 +00007151 // Writer out root metadata for current protocol: struct _protocol_t
Fariborz Jahanian008dfe22012-03-11 19:41:56 +00007152 Result += "\n";
7153 if (LangOpts.MicrosoftExt)
Fariborz Jahanian1b085422012-04-14 17:13:08 +00007154 Result += "static ";
Fariborz Jahanianb31e3af2012-03-15 17:05:33 +00007155 Result += "struct _protocol_t _OBJC_PROTOCOL_";
Fariborz Jahanian11671902012-02-07 17:11:38 +00007156 Result += PDecl->getNameAsString();
Fariborz Jahanian48985802012-02-08 00:50:52 +00007157 Result += " __attribute__ ((used, section (\"__DATA,__datacoal_nt,coalesced\"))) = {\n";
7158 Result += "\t0,\n"; // id is; is null
7159 Result += "\t\""; Result += PDecl->getNameAsString(); Result += "\",\n";
Fariborz Jahaniane18961b2012-02-08 19:53:58 +00007160 if (SuperProtocols.size() > 0) {
7161 Result += "\t(const struct _protocol_list_t *)&"; Result += "_OBJC_PROTOCOL_REFS_";
7162 Result += PDecl->getNameAsString(); Result += ",\n";
7163 }
7164 else
7165 Result += "\t0,\n";
Fariborz Jahanian48985802012-02-08 00:50:52 +00007166 if (InstanceMethods.size() > 0) {
7167 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
7168 Result += PDecl->getNameAsString(); Result += ",\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00007169 }
7170 else
Fariborz Jahanian48985802012-02-08 00:50:52 +00007171 Result += "\t0,\n";
7172
7173 if (ClassMethods.size() > 0) {
7174 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_CLASS_METHODS_";
7175 Result += PDecl->getNameAsString(); Result += ",\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00007176 }
7177 else
Fariborz Jahanian48985802012-02-08 00:50:52 +00007178 Result += "\t0,\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00007179
Fariborz Jahanian48985802012-02-08 00:50:52 +00007180 if (OptInstanceMethods.size() > 0) {
7181 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_";
7182 Result += PDecl->getNameAsString(); Result += ",\n";
7183 }
7184 else
7185 Result += "\t0,\n";
7186
7187 if (OptClassMethods.size() > 0) {
7188 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_CLASS_METHODS_";
7189 Result += PDecl->getNameAsString(); Result += ",\n";
7190 }
7191 else
7192 Result += "\t0,\n";
7193
7194 if (ProtocolProperties.size() > 0) {
7195 Result += "\t(const struct _prop_list_t *)&_OBJC_PROTOCOL_PROPERTIES_";
7196 Result += PDecl->getNameAsString(); Result += ",\n";
7197 }
7198 else
7199 Result += "\t0,\n";
7200
7201 Result += "\t"; Result += "sizeof(_protocol_t)"; Result += ",\n";
7202 Result += "\t0,\n";
7203
Fariborz Jahaniana8395a62012-02-08 22:23:26 +00007204 if (AllMethods.size() > 0) {
7205 Result += "\t(const char **)&"; Result += "_OBJC_PROTOCOL_METHOD_TYPES_";
7206 Result += PDecl->getNameAsString();
7207 Result += "\n};\n";
7208 }
7209 else
7210 Result += "\t0\n};\n";
Fariborz Jahanianddddca32012-03-14 21:44:09 +00007211
Fariborz Jahanianddddca32012-03-14 21:44:09 +00007212 if (LangOpts.MicrosoftExt)
Fariborz Jahanian1b085422012-04-14 17:13:08 +00007213 Result += "static ";
Fariborz Jahanianddddca32012-03-14 21:44:09 +00007214 Result += "struct _protocol_t *";
7215 Result += "_OBJC_LABEL_PROTOCOL_$_"; Result += PDecl->getNameAsString();
7216 Result += " = &_OBJC_PROTOCOL_"; Result += PDecl->getNameAsString();
7217 Result += ";\n";
Fariborz Jahanian48985802012-02-08 00:50:52 +00007218
Fariborz Jahanian11671902012-02-07 17:11:38 +00007219 // Mark this protocol as having been generated.
7220 if (!ObjCSynthesizedProtocols.insert(PDecl->getCanonicalDecl()))
7221 llvm_unreachable("protocol already synthesized");
7222
7223}
7224
7225void RewriteModernObjC::RewriteObjCProtocolListMetaData(
7226 const ObjCList<ObjCProtocolDecl> &Protocols,
7227 StringRef prefix, StringRef ClassName,
7228 std::string &Result) {
7229 if (Protocols.empty()) return;
7230
7231 for (unsigned i = 0; i != Protocols.size(); i++)
Fariborz Jahaniane18961b2012-02-08 19:53:58 +00007232 RewriteObjCProtocolMetaData(Protocols[i], Result);
Fariborz Jahanian11671902012-02-07 17:11:38 +00007233
7234 // Output the top lovel protocol meta-data for the class.
7235 /* struct _objc_protocol_list {
7236 struct _objc_protocol_list *next;
7237 int protocol_count;
7238 struct _objc_protocol *class_protocols[];
7239 }
7240 */
Fariborz Jahanian008dfe22012-03-11 19:41:56 +00007241 Result += "\n";
7242 if (LangOpts.MicrosoftExt)
7243 Result += "__declspec(allocate(\".cat_cls_meth$B\")) ";
7244 Result += "static struct {\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00007245 Result += "\tstruct _objc_protocol_list *next;\n";
7246 Result += "\tint protocol_count;\n";
7247 Result += "\tstruct _objc_protocol *class_protocols[";
7248 Result += utostr(Protocols.size());
7249 Result += "];\n} _OBJC_";
7250 Result += prefix;
7251 Result += "_PROTOCOLS_";
7252 Result += ClassName;
7253 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
7254 "{\n\t0, ";
7255 Result += utostr(Protocols.size());
7256 Result += "\n";
7257
7258 Result += "\t,{&_OBJC_PROTOCOL_";
7259 Result += Protocols[0]->getNameAsString();
7260 Result += " \n";
7261
7262 for (unsigned i = 1; i != Protocols.size(); i++) {
7263 Result += "\t ,&_OBJC_PROTOCOL_";
7264 Result += Protocols[i]->getNameAsString();
7265 Result += "\n";
7266 }
7267 Result += "\t }\n};\n";
7268}
7269
Fariborz Jahanian0a256882012-02-16 18:54:09 +00007270/// hasObjCExceptionAttribute - Return true if this class or any super
7271/// class has the __objc_exception__ attribute.
7272/// FIXME. Move this to ASTContext.cpp as it is also used for IRGen.
7273static bool hasObjCExceptionAttribute(ASTContext &Context,
7274 const ObjCInterfaceDecl *OID) {
7275 if (OID->hasAttr<ObjCExceptionAttr>())
7276 return true;
7277 if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
7278 return hasObjCExceptionAttribute(Context, Super);
7279 return false;
7280}
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007281
Fariborz Jahanian11671902012-02-07 17:11:38 +00007282void RewriteModernObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
7283 std::string &Result) {
7284 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
7285
7286 // Explicitly declared @interface's are already synthesized.
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00007287 if (CDecl->isImplicitInterfaceDecl())
7288 assert(false &&
7289 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian088959a2012-02-11 20:10:52 +00007290
Fariborz Jahanian45489622012-03-14 18:09:23 +00007291 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00007292 SmallVector<ObjCIvarDecl *, 8> IVars;
7293
7294 for (ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
7295 IVD; IVD = IVD->getNextIvar()) {
7296 // Ignore unnamed bit-fields.
7297 if (!IVD->getDeclName())
7298 continue;
7299 IVars.push_back(IVD);
Fariborz Jahanian11671902012-02-07 17:11:38 +00007300 }
7301
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00007302 Write__ivar_list_t_initializer(*this, Context, Result, IVars,
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007303 "_OBJC_$_INSTANCE_VARIABLES_",
Fariborz Jahaniana854174a2012-03-20 17:13:39 +00007304 CDecl);
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007305
7306 // Build _objc_method_list for class's instance methods if needed
7307 SmallVector<ObjCMethodDecl *, 32>
7308 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
7309
7310 // If any of our property implementations have associated getters or
7311 // setters, produce metadata for them as well.
7312 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
7313 PropEnd = IDecl->propimpl_end();
7314 Prop != PropEnd; ++Prop) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00007315 if (Prop->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007316 continue;
David Blaikie2d7c57e2012-04-30 02:36:29 +00007317 if (!Prop->getPropertyIvarDecl())
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007318 continue;
David Blaikie2d7c57e2012-04-30 02:36:29 +00007319 ObjCPropertyDecl *PD = Prop->getPropertyDecl();
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007320 if (!PD)
7321 continue;
7322 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
Fariborz Jahanianf687e7b2012-05-03 22:52:13 +00007323 if (mustSynthesizeSetterGetterMethod(IDecl, PD, true /*getter*/))
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007324 InstanceMethods.push_back(Getter);
7325 if (PD->isReadOnly())
7326 continue;
7327 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
Fariborz Jahanianf687e7b2012-05-03 22:52:13 +00007328 if (mustSynthesizeSetterGetterMethod(IDecl, PD, false /*setter*/))
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007329 InstanceMethods.push_back(Setter);
7330 }
7331
7332 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
7333 "_OBJC_$_INSTANCE_METHODS_",
7334 IDecl->getNameAsString(), true);
7335
7336 SmallVector<ObjCMethodDecl *, 32>
7337 ClassMethods(IDecl->classmeth_begin(), IDecl->classmeth_end());
7338
7339 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
7340 "_OBJC_$_CLASS_METHODS_",
7341 IDecl->getNameAsString(), true);
Fariborz Jahanianbce367742012-02-14 19:31:35 +00007342
7343 // Protocols referenced in class declaration?
7344 // Protocol's super protocol list
7345 std::vector<ObjCProtocolDecl *> RefedProtocols;
7346 const ObjCList<ObjCProtocolDecl> &Protocols = CDecl->getReferencedProtocols();
7347 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
7348 E = Protocols.end();
7349 I != E; ++I) {
7350 RefedProtocols.push_back(*I);
7351 // Must write out all protocol definitions in current qualifier list,
7352 // and in their nested qualifiers before writing out current definition.
7353 RewriteObjCProtocolMetaData(*I, Result);
7354 }
7355
7356 Write_protocol_list_initializer(Context, Result,
7357 RefedProtocols,
7358 "_OBJC_CLASS_PROTOCOLS_$_",
7359 IDecl->getNameAsString());
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007360
7361 // Protocol's property metadata.
7362 std::vector<ObjCPropertyDecl *> ClassProperties;
7363 for (ObjCContainerDecl::prop_iterator I = CDecl->prop_begin(),
7364 E = CDecl->prop_end(); I != E; ++I)
David Blaikie40ed2972012-06-06 20:45:41 +00007365 ClassProperties.push_back(*I);
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007366
7367 Write_prop_list_t_initializer(*this, Context, Result, ClassProperties,
Fariborz Jahanianee1db7a2012-03-22 17:39:35 +00007368 /* Container */IDecl,
Fariborz Jahanianc41d8282012-02-16 21:57:59 +00007369 "_OBJC_$_PROP_LIST_",
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007370 CDecl->getNameAsString());
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007371
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007372
Fariborz Jahanian0a256882012-02-16 18:54:09 +00007373 // Data for initializing _class_ro_t metaclass meta-data
7374 uint32_t flags = CLS_META;
7375 std::string InstanceSize;
7376 std::string InstanceStart;
7377
7378
7379 bool classIsHidden = CDecl->getVisibility() == HiddenVisibility;
7380 if (classIsHidden)
7381 flags |= OBJC2_CLS_HIDDEN;
7382
7383 if (!CDecl->getSuperClass())
7384 // class is root
7385 flags |= CLS_ROOT;
7386 InstanceSize = "sizeof(struct _class_t)";
7387 InstanceStart = InstanceSize;
7388 Write__class_ro_t_initializer(Context, Result, flags,
7389 InstanceStart, InstanceSize,
7390 ClassMethods,
7391 0,
7392 0,
7393 0,
7394 "_OBJC_METACLASS_RO_$_",
7395 CDecl->getNameAsString());
7396
7397
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007398 // Data for initializing _class_ro_t meta-data
Fariborz Jahanian0a256882012-02-16 18:54:09 +00007399 flags = CLS;
7400 if (classIsHidden)
7401 flags |= OBJC2_CLS_HIDDEN;
7402
7403 if (hasObjCExceptionAttribute(*Context, CDecl))
7404 flags |= CLS_EXCEPTION;
7405
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007406 if (!CDecl->getSuperClass())
7407 // class is root
7408 flags |= CLS_ROOT;
7409
Fariborz Jahanian0a256882012-02-16 18:54:09 +00007410 InstanceSize.clear();
7411 InstanceStart.clear();
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007412 if (!ObjCSynthesizedStructs.count(CDecl)) {
7413 InstanceSize = "0";
7414 InstanceStart = "0";
7415 }
7416 else {
7417 InstanceSize = "sizeof(struct ";
7418 InstanceSize += CDecl->getNameAsString();
7419 InstanceSize += "_IMPL)";
7420
7421 ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
7422 if (IVD) {
Fariborz Jahanianaaf4d692012-04-11 21:12:36 +00007423 RewriteIvarOffsetComputation(IVD, InstanceStart);
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007424 }
7425 else
7426 InstanceStart = InstanceSize;
7427 }
7428 Write__class_ro_t_initializer(Context, Result, flags,
7429 InstanceStart, InstanceSize,
7430 InstanceMethods,
7431 RefedProtocols,
7432 IVars,
7433 ClassProperties,
7434 "_OBJC_CLASS_RO_$_",
7435 CDecl->getNameAsString());
Fariborz Jahanian638252f2012-02-16 21:37:05 +00007436
7437 Write_class_t(Context, Result,
7438 "OBJC_METACLASS_$_",
7439 CDecl, /*metaclass*/true);
7440
7441 Write_class_t(Context, Result,
7442 "OBJC_CLASS_$_",
7443 CDecl, /*metaclass*/false);
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00007444
7445 if (ImplementationIsNonLazy(IDecl))
7446 DefinedNonLazyClasses.push_back(CDecl);
Fariborz Jahanian638252f2012-02-16 21:37:05 +00007447
Fariborz Jahanian11671902012-02-07 17:11:38 +00007448}
7449
Fariborz Jahanian5ed21c32012-03-27 18:41:05 +00007450void RewriteModernObjC::RewriteClassSetupInitHook(std::string &Result) {
7451 int ClsDefCount = ClassImplementation.size();
7452 if (!ClsDefCount)
7453 return;
7454 Result += "#pragma section(\".objc_inithooks$B\", long, read, write)\n";
7455 Result += "__declspec(allocate(\".objc_inithooks$B\")) ";
7456 Result += "static void *OBJC_CLASS_SETUP[] = {\n";
7457 for (int i = 0; i < ClsDefCount; i++) {
7458 ObjCImplementationDecl *IDecl = ClassImplementation[i];
7459 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
7460 Result += "\t(void *)&OBJC_CLASS_SETUP_$_";
7461 Result += CDecl->getName(); Result += ",\n";
7462 }
7463 Result += "};\n";
7464}
7465
Fariborz Jahanian11671902012-02-07 17:11:38 +00007466void RewriteModernObjC::RewriteMetaDataIntoBuffer(std::string &Result) {
7467 int ClsDefCount = ClassImplementation.size();
7468 int CatDefCount = CategoryImplementation.size();
7469
7470 // For each implemented class, write out all its meta data.
7471 for (int i = 0; i < ClsDefCount; i++)
7472 RewriteObjCClassMetaData(ClassImplementation[i], Result);
7473
Fariborz Jahanian5ed21c32012-03-27 18:41:05 +00007474 RewriteClassSetupInitHook(Result);
7475
Fariborz Jahanian11671902012-02-07 17:11:38 +00007476 // For each implemented category, write out all its meta data.
7477 for (int i = 0; i < CatDefCount; i++)
7478 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
7479
Fariborz Jahanian5ed21c32012-03-27 18:41:05 +00007480 RewriteCategorySetupInitHook(Result);
7481
Fariborz Jahaniane7a0c932012-02-17 00:06:14 +00007482 if (ClsDefCount > 0) {
Fariborz Jahanian008dfe22012-03-11 19:41:56 +00007483 if (LangOpts.MicrosoftExt)
7484 Result += "__declspec(allocate(\".objc_classlist$B\")) ";
Fariborz Jahaniane7a0c932012-02-17 00:06:14 +00007485 Result += "static struct _class_t *L_OBJC_LABEL_CLASS_$ [";
7486 Result += llvm::utostr(ClsDefCount); Result += "]";
7487 Result +=
7488 " __attribute__((used, section (\"__DATA, __objc_classlist,"
7489 "regular,no_dead_strip\")))= {\n";
7490 for (int i = 0; i < ClsDefCount; i++) {
7491 Result += "\t&OBJC_CLASS_$_";
7492 Result += ClassImplementation[i]->getNameAsString();
7493 Result += ",\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00007494 }
Fariborz Jahaniane7a0c932012-02-17 00:06:14 +00007495 Result += "};\n";
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00007496
7497 if (!DefinedNonLazyClasses.empty()) {
7498 if (LangOpts.MicrosoftExt)
7499 Result += "__declspec(allocate(\".objc_nlclslist$B\")) \n";
7500 Result += "static struct _class_t *_OBJC_LABEL_NONLAZY_CLASS_$[] = {\n\t";
7501 for (unsigned i = 0, e = DefinedNonLazyClasses.size(); i < e; i++) {
7502 Result += "\t&OBJC_CLASS_$_"; Result += DefinedNonLazyClasses[i]->getNameAsString();
7503 Result += ",\n";
7504 }
7505 Result += "};\n";
7506 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00007507 }
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007508
7509 if (CatDefCount > 0) {
Fariborz Jahanian008dfe22012-03-11 19:41:56 +00007510 if (LangOpts.MicrosoftExt)
7511 Result += "__declspec(allocate(\".objc_catlist$B\")) ";
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007512 Result += "static struct _category_t *L_OBJC_LABEL_CATEGORY_$ [";
7513 Result += llvm::utostr(CatDefCount); Result += "]";
7514 Result +=
7515 " __attribute__((used, section (\"__DATA, __objc_catlist,"
7516 "regular,no_dead_strip\")))= {\n";
7517 for (int i = 0; i < CatDefCount; i++) {
7518 Result += "\t&_OBJC_$_CATEGORY_";
7519 Result +=
7520 CategoryImplementation[i]->getClassInterface()->getNameAsString();
7521 Result += "_$_";
7522 Result += CategoryImplementation[i]->getNameAsString();
7523 Result += ",\n";
7524 }
7525 Result += "};\n";
7526 }
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00007527
7528 if (!DefinedNonLazyCategories.empty()) {
7529 if (LangOpts.MicrosoftExt)
7530 Result += "__declspec(allocate(\".objc_nlcatlist$B\")) \n";
7531 Result += "static struct _category_t *_OBJC_LABEL_NONLAZY_CATEGORY_$[] = {\n\t";
7532 for (unsigned i = 0, e = DefinedNonLazyCategories.size(); i < e; i++) {
7533 Result += "\t&_OBJC_$_CATEGORY_";
7534 Result +=
7535 DefinedNonLazyCategories[i]->getClassInterface()->getNameAsString();
7536 Result += "_$_";
7537 Result += DefinedNonLazyCategories[i]->getNameAsString();
7538 Result += ",\n";
7539 }
7540 Result += "};\n";
7541 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00007542}
7543
Fariborz Jahanianddddca32012-03-14 21:44:09 +00007544void RewriteModernObjC::WriteImageInfo(std::string &Result) {
7545 if (LangOpts.MicrosoftExt)
7546 Result += "__declspec(allocate(\".objc_imageinfo$B\")) \n";
7547
7548 Result += "static struct IMAGE_INFO { unsigned version; unsigned flag; } ";
7549 // version 0, ObjCABI is 2
Fariborz Jahanianb31e3af2012-03-15 17:05:33 +00007550 Result += "_OBJC_IMAGE_INFO = { 0, 2 };\n";
Fariborz Jahanianddddca32012-03-14 21:44:09 +00007551}
7552
Fariborz Jahanian11671902012-02-07 17:11:38 +00007553/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
7554/// implementation.
7555void RewriteModernObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
7556 std::string &Result) {
Fariborz Jahanian45489622012-03-14 18:09:23 +00007557 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanian11671902012-02-07 17:11:38 +00007558 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
7559 // Find category declaration for this implementation.
Douglas Gregor048fbfa2013-01-16 23:00:23 +00007560 ObjCCategoryDecl *CDecl
7561 = ClassDecl->FindCategoryDeclaration(IDecl->getIdentifier());
Fariborz Jahanian11671902012-02-07 17:11:38 +00007562
7563 std::string FullCategoryName = ClassDecl->getNameAsString();
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007564 FullCategoryName += "_$_";
7565 FullCategoryName += CDecl->getNameAsString();
Fariborz Jahanian11671902012-02-07 17:11:38 +00007566
7567 // Build _objc_method_list for class's instance methods if needed
7568 SmallVector<ObjCMethodDecl *, 32>
7569 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
7570
7571 // If any of our property implementations have associated getters or
7572 // setters, produce metadata for them as well.
7573 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
7574 PropEnd = IDecl->propimpl_end();
7575 Prop != PropEnd; ++Prop) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00007576 if (Prop->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
Fariborz Jahanian11671902012-02-07 17:11:38 +00007577 continue;
David Blaikie2d7c57e2012-04-30 02:36:29 +00007578 if (!Prop->getPropertyIvarDecl())
Fariborz Jahanian11671902012-02-07 17:11:38 +00007579 continue;
David Blaikie2d7c57e2012-04-30 02:36:29 +00007580 ObjCPropertyDecl *PD = Prop->getPropertyDecl();
Fariborz Jahanian11671902012-02-07 17:11:38 +00007581 if (!PD)
7582 continue;
7583 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
7584 InstanceMethods.push_back(Getter);
7585 if (PD->isReadOnly())
7586 continue;
7587 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
7588 InstanceMethods.push_back(Setter);
7589 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00007590
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007591 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
7592 "_OBJC_$_CATEGORY_INSTANCE_METHODS_",
7593 FullCategoryName, true);
7594
7595 SmallVector<ObjCMethodDecl *, 32>
7596 ClassMethods(IDecl->classmeth_begin(), IDecl->classmeth_end());
7597
7598 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
7599 "_OBJC_$_CATEGORY_CLASS_METHODS_",
7600 FullCategoryName, true);
Fariborz Jahanian11671902012-02-07 17:11:38 +00007601
7602 // Protocols referenced in class declaration?
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007603 // Protocol's super protocol list
7604 std::vector<ObjCProtocolDecl *> RefedProtocols;
Argyrios Kyrtzidise7f3ef32012-03-13 01:09:41 +00007605 for (ObjCInterfaceDecl::protocol_iterator I = CDecl->protocol_begin(),
7606 E = CDecl->protocol_end();
7607
7608 I != E; ++I) {
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007609 RefedProtocols.push_back(*I);
7610 // Must write out all protocol definitions in current qualifier list,
7611 // and in their nested qualifiers before writing out current definition.
7612 RewriteObjCProtocolMetaData(*I, Result);
7613 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00007614
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007615 Write_protocol_list_initializer(Context, Result,
7616 RefedProtocols,
7617 "_OBJC_CATEGORY_PROTOCOLS_$_",
7618 FullCategoryName);
Fariborz Jahanian11671902012-02-07 17:11:38 +00007619
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007620 // Protocol's property metadata.
7621 std::vector<ObjCPropertyDecl *> ClassProperties;
7622 for (ObjCContainerDecl::prop_iterator I = CDecl->prop_begin(),
7623 E = CDecl->prop_end(); I != E; ++I)
David Blaikie40ed2972012-06-06 20:45:41 +00007624 ClassProperties.push_back(*I);
Fariborz Jahanian11671902012-02-07 17:11:38 +00007625
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007626 Write_prop_list_t_initializer(*this, Context, Result, ClassProperties,
Fariborz Jahaniane9863b52012-05-03 23:19:33 +00007627 /* Container */IDecl,
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007628 "_OBJC_$_PROP_LIST_",
7629 FullCategoryName);
7630
7631 Write_category_t(*this, Context, Result,
Fariborz Jahanian5ed21c32012-03-27 18:41:05 +00007632 CDecl,
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00007633 ClassDecl,
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007634 InstanceMethods,
7635 ClassMethods,
7636 RefedProtocols,
7637 ClassProperties);
7638
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00007639 // Determine if this category is also "non-lazy".
7640 if (ImplementationIsNonLazy(IDecl))
7641 DefinedNonLazyCategories.push_back(CDecl);
Fariborz Jahanian5ed21c32012-03-27 18:41:05 +00007642
7643}
7644
7645void RewriteModernObjC::RewriteCategorySetupInitHook(std::string &Result) {
7646 int CatDefCount = CategoryImplementation.size();
7647 if (!CatDefCount)
7648 return;
7649 Result += "#pragma section(\".objc_inithooks$B\", long, read, write)\n";
7650 Result += "__declspec(allocate(\".objc_inithooks$B\")) ";
7651 Result += "static void *OBJC_CATEGORY_SETUP[] = {\n";
7652 for (int i = 0; i < CatDefCount; i++) {
7653 ObjCCategoryImplDecl *IDecl = CategoryImplementation[i];
7654 ObjCCategoryDecl *CatDecl= IDecl->getCategoryDecl();
7655 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
7656 Result += "\t(void *)&OBJC_CATEGORY_SETUP_$_";
7657 Result += ClassDecl->getName();
7658 Result += "_$_";
7659 Result += CatDecl->getName();
7660 Result += ",\n";
7661 }
7662 Result += "};\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00007663}
7664
7665// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
7666/// class methods.
7667template<typename MethodIterator>
7668void RewriteModernObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
7669 MethodIterator MethodEnd,
7670 bool IsInstanceMethod,
7671 StringRef prefix,
7672 StringRef ClassName,
7673 std::string &Result) {
7674 if (MethodBegin == MethodEnd) return;
7675
7676 if (!objc_impl_method) {
7677 /* struct _objc_method {
7678 SEL _cmd;
7679 char *method_types;
7680 void *_imp;
7681 }
7682 */
7683 Result += "\nstruct _objc_method {\n";
7684 Result += "\tSEL _cmd;\n";
7685 Result += "\tchar *method_types;\n";
7686 Result += "\tvoid *_imp;\n";
7687 Result += "};\n";
7688
7689 objc_impl_method = true;
7690 }
7691
7692 // Build _objc_method_list for class's methods if needed
7693
7694 /* struct {
7695 struct _objc_method_list *next_method;
7696 int method_count;
7697 struct _objc_method method_list[];
7698 }
7699 */
7700 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
Fariborz Jahanian008dfe22012-03-11 19:41:56 +00007701 Result += "\n";
7702 if (LangOpts.MicrosoftExt) {
7703 if (IsInstanceMethod)
7704 Result += "__declspec(allocate(\".inst_meth$B\")) ";
7705 else
7706 Result += "__declspec(allocate(\".cls_meth$B\")) ";
7707 }
7708 Result += "static struct {\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00007709 Result += "\tstruct _objc_method_list *next_method;\n";
7710 Result += "\tint method_count;\n";
7711 Result += "\tstruct _objc_method method_list[";
7712 Result += utostr(NumMethods);
7713 Result += "];\n} _OBJC_";
7714 Result += prefix;
7715 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
7716 Result += "_METHODS_";
7717 Result += ClassName;
7718 Result += " __attribute__ ((used, section (\"__OBJC, __";
7719 Result += IsInstanceMethod ? "inst" : "cls";
7720 Result += "_meth\")))= ";
7721 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
7722
7723 Result += "\t,{{(SEL)\"";
7724 Result += (*MethodBegin)->getSelector().getAsString().c_str();
7725 std::string MethodTypeString;
7726 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
7727 Result += "\", \"";
7728 Result += MethodTypeString;
7729 Result += "\", (void *)";
7730 Result += MethodInternalNames[*MethodBegin];
7731 Result += "}\n";
7732 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
7733 Result += "\t ,{(SEL)\"";
7734 Result += (*MethodBegin)->getSelector().getAsString().c_str();
7735 std::string MethodTypeString;
7736 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
7737 Result += "\", \"";
7738 Result += MethodTypeString;
7739 Result += "\", (void *)";
7740 Result += MethodInternalNames[*MethodBegin];
7741 Result += "}\n";
7742 }
7743 Result += "\t }\n};\n";
7744}
7745
7746Stmt *RewriteModernObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) {
7747 SourceRange OldRange = IV->getSourceRange();
7748 Expr *BaseExpr = IV->getBase();
7749
7750 // Rewrite the base, but without actually doing replaces.
7751 {
7752 DisableReplaceStmtScope S(*this);
7753 BaseExpr = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(BaseExpr));
7754 IV->setBase(BaseExpr);
7755 }
7756
7757 ObjCIvarDecl *D = IV->getDecl();
7758
7759 Expr *Replacement = IV;
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007760
Fariborz Jahanian11671902012-02-07 17:11:38 +00007761 if (BaseExpr->getType()->isObjCObjectPointerType()) {
7762 const ObjCInterfaceType *iFaceDecl =
Fariborz Jahanian89919cc2012-05-08 23:54:35 +00007763 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
Fariborz Jahanian11671902012-02-07 17:11:38 +00007764 assert(iFaceDecl && "RewriteObjCIvarRefExpr - iFaceDecl is null");
7765 // lookup which class implements the instance variable.
7766 ObjCInterfaceDecl *clsDeclared = 0;
7767 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
7768 clsDeclared);
7769 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
7770
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007771 // Build name of symbol holding ivar offset.
Fariborz Jahaniana854174a2012-03-20 17:13:39 +00007772 std::string IvarOffsetName;
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00007773 if (D->isBitField())
7774 ObjCIvarBitfieldGroupOffset(D, IvarOffsetName);
7775 else
7776 WriteInternalIvarName(clsDeclared, D, IvarOffsetName);
Fariborz Jahaniana854174a2012-03-20 17:13:39 +00007777
Fariborz Jahanian5e49eb92012-02-22 18:13:25 +00007778 ReferencedIvars[clsDeclared].insert(D);
7779
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007780 // cast offset to "char *".
7781 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context,
7782 Context->getPointerType(Context->CharTy),
Fariborz Jahanian11671902012-02-07 17:11:38 +00007783 CK_BitCast,
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007784 BaseExpr);
7785 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
7786 SourceLocation(), &Context->Idents.get(IvarOffsetName),
Rafael Espindola6ae7e502013-04-03 19:27:57 +00007787 Context->UnsignedLongTy, 0, SC_Extern);
John McCall113bee02012-03-10 09:33:50 +00007788 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, false,
7789 Context->UnsignedLongTy, VK_LValue,
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007790 SourceLocation());
7791 BinaryOperator *addExpr =
7792 new (Context) BinaryOperator(castExpr, DRE, BO_Add,
7793 Context->getPointerType(Context->CharTy),
Lang Hames5de91cc2012-10-02 04:45:10 +00007794 VK_RValue, OK_Ordinary, SourceLocation(), false);
Fariborz Jahanian11671902012-02-07 17:11:38 +00007795 // Don't forget the parens to enforce the proper binding.
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007796 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(),
7797 SourceLocation(),
7798 addExpr);
Fariborz Jahaniandd5a59b2012-02-24 17:35:35 +00007799 QualType IvarT = D->getType();
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00007800 if (D->isBitField())
7801 IvarT = GetGroupRecordTypeForObjCIvarBitfield(D);
Fariborz Jahanianbf217c82012-04-27 22:48:54 +00007802
Fariborz Jahaniand7c67772012-05-02 17:34:59 +00007803 if (!isa<TypedefType>(IvarT) && IvarT->isRecordType()) {
Fariborz Jahanianbf217c82012-04-27 22:48:54 +00007804 RecordDecl *RD = IvarT->getAs<RecordType>()->getDecl();
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00007805 RD = RD->getDefinition();
7806 if (RD && !RD->getDeclName().getAsIdentifierInfo()) {
Fariborz Jahanianbf217c82012-04-27 22:48:54 +00007807 // decltype(((Foo_IMPL*)0)->bar) *
Fariborz Jahaniand7c67772012-05-02 17:34:59 +00007808 ObjCContainerDecl *CDecl =
7809 dyn_cast<ObjCContainerDecl>(D->getDeclContext());
7810 // ivar in class extensions requires special treatment.
7811 if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(CDecl))
7812 CDecl = CatDecl->getClassInterface();
7813 std::string RecName = CDecl->getName();
Fariborz Jahanianbf217c82012-04-27 22:48:54 +00007814 RecName += "_IMPL";
7815 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
7816 SourceLocation(), SourceLocation(),
7817 &Context->Idents.get(RecName.c_str()));
7818 QualType PtrStructIMPL = Context->getPointerType(Context->getTagDeclType(RD));
7819 unsigned UnsignedIntSize =
7820 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
7821 Expr *Zero = IntegerLiteral::Create(*Context,
7822 llvm::APInt(UnsignedIntSize, 0),
7823 Context->UnsignedIntTy, SourceLocation());
7824 Zero = NoTypeInfoCStyleCastExpr(Context, PtrStructIMPL, CK_BitCast, Zero);
7825 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
7826 Zero);
7827 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
7828 SourceLocation(),
7829 &Context->Idents.get(D->getNameAsString()),
7830 IvarT, 0,
7831 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smith2b013182012-06-10 03:12:00 +00007832 ICIS_NoInit);
Fariborz Jahanianbf217c82012-04-27 22:48:54 +00007833 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
7834 FD->getType(), VK_LValue,
7835 OK_Ordinary);
7836 IvarT = Context->getDecltypeType(ME, ME->getType());
7837 }
7838 }
Fariborz Jahanian1dc712f2012-02-29 00:26:20 +00007839 convertObjCTypeToCStyleType(IvarT);
Fariborz Jahaniandd5a59b2012-02-24 17:35:35 +00007840 QualType castT = Context->getPointerType(IvarT);
Fariborz Jahanianbf217c82012-04-27 22:48:54 +00007841
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007842 castExpr = NoTypeInfoCStyleCastExpr(Context,
7843 castT,
7844 CK_BitCast,
7845 PE);
Fariborz Jahanianbf217c82012-04-27 22:48:54 +00007846
7847
Fariborz Jahanian1dc712f2012-02-29 00:26:20 +00007848 Expr *Exp = new (Context) UnaryOperator(castExpr, UO_Deref, IvarT,
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007849 VK_LValue, OK_Ordinary,
7850 SourceLocation());
7851 PE = new (Context) ParenExpr(OldRange.getBegin(),
7852 OldRange.getEnd(),
7853 Exp);
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00007854
7855 if (D->isBitField()) {
7856 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
7857 SourceLocation(),
7858 &Context->Idents.get(D->getNameAsString()),
7859 D->getType(), 0,
7860 /*BitWidth=*/D->getBitWidth(),
7861 /*Mutable=*/true,
7862 ICIS_NoInit);
7863 MemberExpr *ME = new (Context) MemberExpr(PE, /*isArrow*/false, FD, SourceLocation(),
7864 FD->getType(), VK_LValue,
7865 OK_Ordinary);
7866 Replacement = ME;
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007867
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00007868 }
7869 else
7870 Replacement = PE;
Fariborz Jahanian11671902012-02-07 17:11:38 +00007871 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00007872
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007873 ReplaceStmtWithRange(IV, Replacement, OldRange);
7874 return Replacement;
Fariborz Jahanian11671902012-02-07 17:11:38 +00007875}