blob: 93c9a1c02c15b0e4e1d45fb9794d80d8448dbc28 [file] [log] [blame]
Fariborz Jahanian64cb63a2012-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
14#include "clang/Rewrite/ASTConsumers.h"
15#include "clang/Rewrite/Rewriter.h"
16#include "clang/AST/AST.h"
17#include "clang/AST/ASTConsumer.h"
18#include "clang/AST/ParentMap.h"
19#include "clang/Basic/SourceManager.h"
20#include "clang/Basic/IdentifierTable.h"
21#include "clang/Basic/Diagnostic.h"
22#include "clang/Lex/Lexer.h"
23#include "llvm/Support/MemoryBuffer.h"
24#include "llvm/Support/raw_ostream.h"
25#include "llvm/ADT/StringExtras.h"
26#include "llvm/ADT/SmallPtrSet.h"
27#include "llvm/ADT/OwningPtr.h"
28#include "llvm/ADT/DenseSet.h"
29
30using namespace clang;
31using llvm::utostr;
32
33namespace {
34 class RewriteModernObjC : public ASTConsumer {
35 protected:
36
37 enum {
38 BLOCK_FIELD_IS_OBJECT = 3, /* id, NSObject, __attribute__((NSObject)),
39 block, ... */
40 BLOCK_FIELD_IS_BLOCK = 7, /* a block variable */
41 BLOCK_FIELD_IS_BYREF = 8, /* the on stack structure holding the
42 __block variable */
43 BLOCK_FIELD_IS_WEAK = 16, /* declared __weak, only used in byref copy
44 helpers */
45 BLOCK_BYREF_CALLER = 128, /* called from __block (byref) copy/dispose
46 support routines */
47 BLOCK_BYREF_CURRENT_MAX = 256
48 };
49
50 enum {
51 BLOCK_NEEDS_FREE = (1 << 24),
52 BLOCK_HAS_COPY_DISPOSE = (1 << 25),
53 BLOCK_HAS_CXX_OBJ = (1 << 26),
54 BLOCK_IS_GC = (1 << 27),
55 BLOCK_IS_GLOBAL = (1 << 28),
56 BLOCK_HAS_DESCRIPTOR = (1 << 29)
57 };
58 static const int OBJC_ABI_VERSION = 7;
59
60 Rewriter Rewrite;
61 DiagnosticsEngine &Diags;
62 const LangOptions &LangOpts;
63 ASTContext *Context;
64 SourceManager *SM;
65 TranslationUnitDecl *TUDecl;
66 FileID MainFileID;
67 const char *MainFileStart, *MainFileEnd;
68 Stmt *CurrentBody;
69 ParentMap *PropParentMap; // created lazily.
70 std::string InFileName;
71 raw_ostream* OutFile;
72 std::string Preamble;
73
74 TypeDecl *ProtocolTypeDecl;
75 VarDecl *GlobalVarDecl;
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +000076 Expr *GlobalConstructionExp;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +000077 unsigned RewriteFailedDiag;
Fariborz Jahaniand13c2c22012-03-22 19:54:39 +000078 unsigned GlobalBlockRewriteFailedDiag;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +000079 // ObjC string constant support.
80 unsigned NumObjCStringLiterals;
81 VarDecl *ConstantStringClassReference;
82 RecordDecl *NSStringRecord;
83
84 // ObjC foreach break/continue generation support.
85 int BcLabelCount;
86
87 unsigned TryFinallyContainsReturnDiag;
88 // Needed for super.
89 ObjCMethodDecl *CurMethodDef;
90 RecordDecl *SuperStructDecl;
91 RecordDecl *ConstantStringDecl;
92
93 FunctionDecl *MsgSendFunctionDecl;
94 FunctionDecl *MsgSendSuperFunctionDecl;
95 FunctionDecl *MsgSendStretFunctionDecl;
96 FunctionDecl *MsgSendSuperStretFunctionDecl;
97 FunctionDecl *MsgSendFpretFunctionDecl;
98 FunctionDecl *GetClassFunctionDecl;
99 FunctionDecl *GetMetaClassFunctionDecl;
100 FunctionDecl *GetSuperClassFunctionDecl;
101 FunctionDecl *SelGetUidFunctionDecl;
102 FunctionDecl *CFStringFunctionDecl;
103 FunctionDecl *SuperContructorFunctionDecl;
104 FunctionDecl *CurFunctionDef;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000105
106 /* Misc. containers needed for meta-data rewrite. */
107 SmallVector<ObjCImplementationDecl *, 8> ClassImplementation;
108 SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation;
109 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCSynthesizedStructs;
110 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> ObjCSynthesizedProtocols;
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +0000111 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCWrittenInterfaces;
Fariborz Jahanian8fba8942012-04-30 23:20:30 +0000112 llvm::SmallPtrSet<TagDecl*, 32> GlobalDefinedTags;
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +0000113 SmallVector<ObjCInterfaceDecl*, 32> ObjCInterfacesSeen;
Fariborz Jahanian88f7f752012-03-14 23:18:19 +0000114 /// DefinedNonLazyClasses - List of defined "non-lazy" classes.
115 SmallVector<ObjCInterfaceDecl*, 8> DefinedNonLazyClasses;
116
117 /// DefinedNonLazyCategories - List of defined "non-lazy" categories.
118 llvm::SmallVector<ObjCCategoryDecl*, 8> DefinedNonLazyCategories;
119
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000120 SmallVector<Stmt *, 32> Stmts;
121 SmallVector<int, 8> ObjCBcLabelNo;
122 // Remember all the @protocol(<expr>) expressions.
123 llvm::SmallPtrSet<ObjCProtocolDecl *, 32> ProtocolExprDecls;
124
125 llvm::DenseSet<uint64_t> CopyDestroyCache;
126
127 // Block expressions.
128 SmallVector<BlockExpr *, 32> Blocks;
129 SmallVector<int, 32> InnerDeclRefsCount;
John McCallf4b88a42012-03-10 09:33:50 +0000130 SmallVector<DeclRefExpr *, 32> InnerDeclRefs;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000131
John McCallf4b88a42012-03-10 09:33:50 +0000132 SmallVector<DeclRefExpr *, 32> BlockDeclRefs;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000133
134 // Block related declarations.
135 SmallVector<ValueDecl *, 8> BlockByCopyDecls;
136 llvm::SmallPtrSet<ValueDecl *, 8> BlockByCopyDeclsPtrSet;
137 SmallVector<ValueDecl *, 8> BlockByRefDecls;
138 llvm::SmallPtrSet<ValueDecl *, 8> BlockByRefDeclsPtrSet;
139 llvm::DenseMap<ValueDecl *, unsigned> BlockByRefDeclNo;
140 llvm::SmallPtrSet<ValueDecl *, 8> ImportedBlockDecls;
141 llvm::SmallPtrSet<VarDecl *, 8> ImportedLocalExternalDecls;
142
143 llvm::DenseMap<BlockExpr *, std::string> RewrittenBlockExprs;
Fariborz Jahanian72c88f12012-02-22 18:13:25 +0000144 llvm::DenseMap<ObjCInterfaceDecl *,
145 llvm::SmallPtrSet<ObjCIvarDecl *, 8> > ReferencedIvars;
146
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000147 // This maps an original source AST to it's rewritten form. This allows
148 // us to avoid rewriting the same node twice (which is very uncommon).
149 // This is needed to support some of the exotic property rewriting.
150 llvm::DenseMap<Stmt *, Stmt *> ReplacedNodes;
151
152 // Needed for header files being rewritten
153 bool IsHeader;
154 bool SilenceRewriteMacroWarning;
155 bool objc_impl_method;
156
157 bool DisableReplaceStmt;
158 class DisableReplaceStmtScope {
159 RewriteModernObjC &R;
160 bool SavedValue;
161
162 public:
163 DisableReplaceStmtScope(RewriteModernObjC &R)
164 : R(R), SavedValue(R.DisableReplaceStmt) {
165 R.DisableReplaceStmt = true;
166 }
167 ~DisableReplaceStmtScope() {
168 R.DisableReplaceStmt = SavedValue;
169 }
170 };
171 void InitializeCommon(ASTContext &context);
172
173 public:
Fariborz Jahanian90af4e22012-02-14 17:19:02 +0000174 llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000175 // Top Level Driver code.
176 virtual bool HandleTopLevelDecl(DeclGroupRef D) {
177 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
178 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(*I)) {
179 if (!Class->isThisDeclarationADefinition()) {
180 RewriteForwardClassDecl(D);
181 break;
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +0000182 } else {
183 // Keep track of all interface declarations seen.
Fariborz Jahanianf3295272012-02-24 21:42:38 +0000184 ObjCInterfacesSeen.push_back(Class);
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +0000185 break;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000186 }
187 }
188
189 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>(*I)) {
190 if (!Proto->isThisDeclarationADefinition()) {
191 RewriteForwardProtocolDecl(D);
192 break;
193 }
194 }
195
196 HandleTopLevelSingleDecl(*I);
197 }
198 return true;
199 }
200 void HandleTopLevelSingleDecl(Decl *D);
201 void HandleDeclInMainFile(Decl *D);
202 RewriteModernObjC(std::string inFile, raw_ostream *OS,
203 DiagnosticsEngine &D, const LangOptions &LOpts,
204 bool silenceMacroWarn);
205
206 ~RewriteModernObjC() {}
207
208 virtual void HandleTranslationUnit(ASTContext &C);
209
210 void ReplaceStmt(Stmt *Old, Stmt *New) {
211 Stmt *ReplacingStmt = ReplacedNodes[Old];
212
213 if (ReplacingStmt)
214 return; // We can't rewrite the same node twice.
215
216 if (DisableReplaceStmt)
217 return;
218
219 // If replacement succeeded or warning disabled return with no warning.
220 if (!Rewrite.ReplaceStmt(Old, New)) {
221 ReplacedNodes[Old] = New;
222 return;
223 }
224 if (SilenceRewriteMacroWarning)
225 return;
226 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
227 << Old->getSourceRange();
228 }
229
230 void ReplaceStmtWithRange(Stmt *Old, Stmt *New, SourceRange SrcRange) {
231 if (DisableReplaceStmt)
232 return;
233
234 // Measure the old text.
235 int Size = Rewrite.getRangeSize(SrcRange);
236 if (Size == -1) {
237 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
238 << Old->getSourceRange();
239 return;
240 }
241 // Get the new text.
242 std::string SStr;
243 llvm::raw_string_ostream S(SStr);
244 New->printPretty(S, *Context, 0, PrintingPolicy(LangOpts));
245 const std::string &Str = S.str();
246
247 // If replacement succeeded or warning disabled return with no warning.
248 if (!Rewrite.ReplaceText(SrcRange.getBegin(), Size, Str)) {
249 ReplacedNodes[Old] = New;
250 return;
251 }
252 if (SilenceRewriteMacroWarning)
253 return;
254 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
255 << Old->getSourceRange();
256 }
257
258 void InsertText(SourceLocation Loc, StringRef Str,
259 bool InsertAfter = true) {
260 // If insertion succeeded or warning disabled return with no warning.
261 if (!Rewrite.InsertText(Loc, Str, InsertAfter) ||
262 SilenceRewriteMacroWarning)
263 return;
264
265 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
266 }
267
268 void ReplaceText(SourceLocation Start, unsigned OrigLength,
269 StringRef Str) {
270 // If removal succeeded or warning disabled return with no warning.
271 if (!Rewrite.ReplaceText(Start, OrigLength, Str) ||
272 SilenceRewriteMacroWarning)
273 return;
274
275 Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
276 }
277
278 // Syntactic Rewriting.
279 void RewriteRecordBody(RecordDecl *RD);
280 void RewriteInclude();
281 void RewriteForwardClassDecl(DeclGroupRef D);
282 void RewriteForwardClassDecl(const llvm::SmallVector<Decl*, 8> &DG);
283 void RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
284 const std::string &typedefString);
285 void RewriteImplementations();
286 void RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
287 ObjCImplementationDecl *IMD,
288 ObjCCategoryImplDecl *CID);
289 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
290 void RewriteImplementationDecl(Decl *Dcl);
291 void RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
292 ObjCMethodDecl *MDecl, std::string &ResultStr);
293 void RewriteTypeIntoString(QualType T, std::string &ResultStr,
294 const FunctionType *&FPRetType);
295 void RewriteByRefString(std::string &ResultStr, const std::string &Name,
296 ValueDecl *VD, bool def=false);
297 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
298 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
299 void RewriteForwardProtocolDecl(DeclGroupRef D);
300 void RewriteForwardProtocolDecl(const llvm::SmallVector<Decl*, 8> &DG);
301 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
302 void RewriteProperty(ObjCPropertyDecl *prop);
303 void RewriteFunctionDecl(FunctionDecl *FD);
304 void RewriteBlockPointerType(std::string& Str, QualType Type);
305 void RewriteBlockPointerTypeVariable(std::string& Str, ValueDecl *VD);
Fariborz Jahanianb75f8de2012-04-19 00:50:01 +0000306 void RewriteBlockLiteralFunctionDecl(FunctionDecl *FD);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000307 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
308 void RewriteTypeOfDecl(VarDecl *VD);
309 void RewriteObjCQualifiedInterfaceTypes(Expr *E);
Fariborz Jahanian163d3ce2012-05-08 23:54:35 +0000310
311 std::string getIvarAccessString(ObjCIvarDecl *D);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000312
313 // Expression Rewriting.
314 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
315 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
316 Stmt *RewritePropertyOrImplicitGetter(PseudoObjectExpr *Pseudo);
317 Stmt *RewritePropertyOrImplicitSetter(PseudoObjectExpr *Pseudo);
318 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
319 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
320 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian55947042012-03-27 20:17:30 +0000321 Stmt *RewriteObjCBoolLiteralExpr(ObjCBoolLiteralExpr *Exp);
Patrick Beardeb382ec2012-04-19 00:25:12 +0000322 Stmt *RewriteObjCBoxedExpr(ObjCBoxedExpr *Exp);
Fariborz Jahanian86cff602012-03-30 23:35:47 +0000323 Stmt *RewriteObjCArrayLiteralExpr(ObjCArrayLiteral *Exp);
Fariborz Jahaniane35abe12012-04-06 22:29:36 +0000324 Stmt *RewriteObjCDictionaryLiteralExpr(ObjCDictionaryLiteral *Exp);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000325 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000326 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
Fariborz Jahanian042b91d2012-05-23 23:47:20 +0000327 Stmt *RewriteObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000328 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
329 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
330 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
331 SourceLocation OrigEnd);
332 Stmt *RewriteBreakStmt(BreakStmt *S);
333 Stmt *RewriteContinueStmt(ContinueStmt *S);
334 void RewriteCastExpr(CStyleCastExpr *CE);
Fariborz Jahanianf1ee6872012-04-10 00:08:18 +0000335 void RewriteImplicitCastObjCExpr(CastExpr *IE);
Fariborz Jahanianb3f904f2012-04-03 17:35:38 +0000336 void RewriteLinkageSpec(LinkageSpecDecl *LSD);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000337
338 // Block rewriting.
339 void RewriteBlocksInFunctionProtoType(QualType funcType, NamedDecl *D);
340
341 // Block specific rewrite rules.
342 void RewriteBlockPointerDecl(NamedDecl *VD);
Fariborz Jahanian4fe261c2012-04-24 19:38:45 +0000343 void RewriteByRefVar(VarDecl *VD, bool firstDecl, bool lastDecl);
John McCallf4b88a42012-03-10 09:33:50 +0000344 Stmt *RewriteBlockDeclRefExpr(DeclRefExpr *VD);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000345 Stmt *RewriteLocalVariableExternalStorage(DeclRefExpr *DRE);
346 void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
347
348 void RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
349 std::string &Result);
350
Fariborz Jahanian15f87772012-02-28 22:45:07 +0000351 void RewriteObjCFieldDecl(FieldDecl *fieldDecl, std::string &Result);
Fariborz Jahanianb68258f2012-05-01 17:46:45 +0000352 bool IsTagDefinedInsideClass(ObjCContainerDecl *IDecl, TagDecl *Tag,
Fariborz Jahanian8fba8942012-04-30 23:20:30 +0000353 bool &IsNamedDefinition);
354 void RewriteLocallyDefinedNamedAggregates(FieldDecl *fieldDecl,
355 std::string &Result);
Fariborz Jahanian15f87772012-02-28 22:45:07 +0000356
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +0000357 bool RewriteObjCFieldDeclType(QualType &Type, std::string &Result);
358
Fariborz Jahanian72c88f12012-02-22 18:13:25 +0000359 void RewriteIvarOffsetSymbols(ObjCInterfaceDecl *CDecl,
360 std::string &Result);
361
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000362 virtual void Initialize(ASTContext &context);
363
364 // Misc. AST transformation routines. Somtimes they end up calling
365 // rewriting routines on the new ASTs.
366 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
367 Expr **args, unsigned nargs,
368 SourceLocation StartLoc=SourceLocation(),
369 SourceLocation EndLoc=SourceLocation());
370
371 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp,
372 SourceLocation StartLoc=SourceLocation(),
373 SourceLocation EndLoc=SourceLocation());
374
375 void SynthCountByEnumWithState(std::string &buf);
376 void SynthMsgSendFunctionDecl();
377 void SynthMsgSendSuperFunctionDecl();
378 void SynthMsgSendStretFunctionDecl();
379 void SynthMsgSendFpretFunctionDecl();
380 void SynthMsgSendSuperStretFunctionDecl();
381 void SynthGetClassFunctionDecl();
382 void SynthGetMetaClassFunctionDecl();
383 void SynthGetSuperClassFunctionDecl();
384 void SynthSelGetUidFunctionDecl();
385 void SynthSuperContructorFunctionDecl();
386
387 // Rewriting metadata
388 template<typename MethodIterator>
389 void RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
390 MethodIterator MethodEnd,
391 bool IsInstanceMethod,
392 StringRef prefix,
393 StringRef ClassName,
394 std::string &Result);
Fariborz Jahanianda9624a2012-02-08 19:53:58 +0000395 void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
396 std::string &Result);
Fariborz Jahanianb4ee8802012-04-30 16:57:52 +0000397 void RewriteObjCProtocolListMetaData(
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000398 const ObjCList<ObjCProtocolDecl> &Prots,
399 StringRef prefix, StringRef ClassName, std::string &Result);
Fariborz Jahanianb4ee8802012-04-30 16:57:52 +0000400 void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000401 std::string &Result);
Fariborz Jahanianb4ee8802012-04-30 16:57:52 +0000402 void RewriteClassSetupInitHook(std::string &Result);
Fariborz Jahaniane0335782012-03-27 18:41:05 +0000403
Fariborz Jahanianb4ee8802012-04-30 16:57:52 +0000404 void RewriteMetaDataIntoBuffer(std::string &Result);
405 void WriteImageInfo(std::string &Result);
406 void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000407 std::string &Result);
Fariborz Jahanianb4ee8802012-04-30 16:57:52 +0000408 void RewriteCategorySetupInitHook(std::string &Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000409
410 // Rewriting ivar
Fariborz Jahanianb4ee8802012-04-30 16:57:52 +0000411 void RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000412 std::string &Result);
Fariborz Jahanianb4ee8802012-04-30 16:57:52 +0000413 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000414
415
416 std::string SynthesizeByrefCopyDestroyHelper(VarDecl *VD, int flag);
417 std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
418 StringRef funcName, std::string Tag);
419 std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
420 StringRef funcName, std::string Tag);
421 std::string SynthesizeBlockImpl(BlockExpr *CE,
422 std::string Tag, std::string Desc);
423 std::string SynthesizeBlockDescriptor(std::string DescTag,
424 std::string ImplTag,
425 int i, StringRef funcName,
426 unsigned hasCopy);
427 Stmt *SynthesizeBlockCall(CallExpr *Exp, const Expr* BlockExp);
428 void SynthesizeBlockLiterals(SourceLocation FunLocStart,
429 StringRef FunName);
430 FunctionDecl *SynthBlockInitFunctionDecl(StringRef name);
431 Stmt *SynthBlockInitExpr(BlockExpr *Exp,
John McCallf4b88a42012-03-10 09:33:50 +0000432 const SmallVector<DeclRefExpr *, 8> &InnerBlockDeclRefs);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000433
434 // Misc. helper routines.
435 QualType getProtocolType();
436 void WarnAboutReturnGotoStmts(Stmt *S);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000437 void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
438 void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
439 void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
440
441 bool IsDeclStmtInForeachHeader(DeclStmt *DS);
442 void CollectBlockDeclRefInfo(BlockExpr *Exp);
443 void GetBlockDeclRefExprs(Stmt *S);
444 void GetInnerBlockDeclRefExprs(Stmt *S,
John McCallf4b88a42012-03-10 09:33:50 +0000445 SmallVector<DeclRefExpr *, 8> &InnerBlockDeclRefs,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000446 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts);
447
448 // We avoid calling Type::isBlockPointerType(), since it operates on the
449 // canonical type. We only care if the top-level type is a closure pointer.
450 bool isTopLevelBlockPointerType(QualType T) {
451 return isa<BlockPointerType>(T);
452 }
453
454 /// convertBlockPointerToFunctionPointer - Converts a block-pointer type
455 /// to a function pointer type and upon success, returns true; false
456 /// otherwise.
457 bool convertBlockPointerToFunctionPointer(QualType &T) {
458 if (isTopLevelBlockPointerType(T)) {
459 const BlockPointerType *BPT = T->getAs<BlockPointerType>();
460 T = Context->getPointerType(BPT->getPointeeType());
461 return true;
462 }
463 return false;
464 }
465
Fariborz Jahanian164d6f82012-02-13 18:57:49 +0000466 bool convertObjCTypeToCStyleType(QualType &T);
467
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000468 bool needToScanForQualifiers(QualType T);
469 QualType getSuperStructType();
470 QualType getConstantStringStructType();
471 QualType convertFunctionTypeOfBlocks(const FunctionType *FT);
472 bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf);
473
474 void convertToUnqualifiedObjCType(QualType &T) {
Fariborz Jahaniane35abe12012-04-06 22:29:36 +0000475 if (T->isObjCQualifiedIdType()) {
476 bool isConst = T.isConstQualified();
477 T = isConst ? Context->getObjCIdType().withConst()
478 : Context->getObjCIdType();
479 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000480 else if (T->isObjCQualifiedClassType())
481 T = Context->getObjCClassType();
482 else if (T->isObjCObjectPointerType() &&
483 T->getPointeeType()->isObjCQualifiedInterfaceType()) {
484 if (const ObjCObjectPointerType * OBJPT =
485 T->getAsObjCInterfacePointerType()) {
486 const ObjCInterfaceType *IFaceT = OBJPT->getInterfaceType();
487 T = QualType(IFaceT, 0);
488 T = Context->getPointerType(T);
489 }
490 }
491 }
492
493 // FIXME: This predicate seems like it would be useful to add to ASTContext.
494 bool isObjCType(QualType T) {
495 if (!LangOpts.ObjC1 && !LangOpts.ObjC2)
496 return false;
497
498 QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
499
500 if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
501 OCT == Context->getCanonicalType(Context->getObjCClassType()))
502 return true;
503
504 if (const PointerType *PT = OCT->getAs<PointerType>()) {
505 if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
506 PT->getPointeeType()->isObjCQualifiedIdType())
507 return true;
508 }
509 return false;
510 }
511 bool PointerTypeTakesAnyBlockArguments(QualType QT);
512 bool PointerTypeTakesAnyObjCQualifiedType(QualType QT);
513 void GetExtentOfArgList(const char *Name, const char *&LParen,
514 const char *&RParen);
515
516 void QuoteDoublequotes(std::string &From, std::string &To) {
517 for (unsigned i = 0; i < From.length(); i++) {
518 if (From[i] == '"')
519 To += "\\\"";
520 else
521 To += From[i];
522 }
523 }
524
525 QualType getSimpleFunctionType(QualType result,
526 const QualType *args,
527 unsigned numArgs,
528 bool variadic = false) {
529 if (result == Context->getObjCInstanceType())
530 result = Context->getObjCIdType();
531 FunctionProtoType::ExtProtoInfo fpi;
532 fpi.Variadic = variadic;
533 return Context->getFunctionType(result, args, numArgs, fpi);
534 }
535
536 // Helper function: create a CStyleCastExpr with trivial type source info.
537 CStyleCastExpr* NoTypeInfoCStyleCastExpr(ASTContext *Ctx, QualType Ty,
538 CastKind Kind, Expr *E) {
539 TypeSourceInfo *TInfo = Ctx->getTrivialTypeSourceInfo(Ty, SourceLocation());
540 return CStyleCastExpr::Create(*Ctx, Ty, VK_RValue, Kind, E, 0, TInfo,
541 SourceLocation(), SourceLocation());
542 }
Fariborz Jahanian88f7f752012-03-14 23:18:19 +0000543
544 bool ImplementationIsNonLazy(const ObjCImplDecl *OD) const {
545 IdentifierInfo* II = &Context->Idents.get("load");
546 Selector LoadSel = Context->Selectors.getSelector(0, &II);
547 return OD->getClassMethod(LoadSel) != 0;
548 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000549 };
550
551}
552
553void RewriteModernObjC::RewriteBlocksInFunctionProtoType(QualType funcType,
554 NamedDecl *D) {
555 if (const FunctionProtoType *fproto
556 = dyn_cast<FunctionProtoType>(funcType.IgnoreParens())) {
557 for (FunctionProtoType::arg_type_iterator I = fproto->arg_type_begin(),
558 E = fproto->arg_type_end(); I && (I != E); ++I)
559 if (isTopLevelBlockPointerType(*I)) {
560 // All the args are checked/rewritten. Don't call twice!
561 RewriteBlockPointerDecl(D);
562 break;
563 }
564 }
565}
566
567void RewriteModernObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
568 const PointerType *PT = funcType->getAs<PointerType>();
569 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
570 RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND);
571}
572
573static bool IsHeaderFile(const std::string &Filename) {
574 std::string::size_type DotPos = Filename.rfind('.');
575
576 if (DotPos == std::string::npos) {
577 // no file extension
578 return false;
579 }
580
581 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
582 // C header: .h
583 // C++ header: .hh or .H;
584 return Ext == "h" || Ext == "hh" || Ext == "H";
585}
586
587RewriteModernObjC::RewriteModernObjC(std::string inFile, raw_ostream* OS,
588 DiagnosticsEngine &D, const LangOptions &LOpts,
589 bool silenceMacroWarn)
590 : Diags(D), LangOpts(LOpts), InFileName(inFile), OutFile(OS),
591 SilenceRewriteMacroWarning(silenceMacroWarn) {
592 IsHeader = IsHeaderFile(inFile);
593 RewriteFailedDiag = Diags.getCustomDiagID(DiagnosticsEngine::Warning,
594 "rewriting sub-expression within a macro (may not be correct)");
Fariborz Jahaniand13c2c22012-03-22 19:54:39 +0000595 // FIXME. This should be an error. But if block is not called, it is OK. And it
596 // may break including some headers.
597 GlobalBlockRewriteFailedDiag = Diags.getCustomDiagID(DiagnosticsEngine::Warning,
598 "rewriting block literal declared in global scope is not implemented");
599
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000600 TryFinallyContainsReturnDiag = Diags.getCustomDiagID(
601 DiagnosticsEngine::Warning,
602 "rewriter doesn't support user-specified control flow semantics "
603 "for @try/@finally (code may not execute properly)");
604}
605
606ASTConsumer *clang::CreateModernObjCRewriter(const std::string& InFile,
607 raw_ostream* OS,
608 DiagnosticsEngine &Diags,
609 const LangOptions &LOpts,
610 bool SilenceRewriteMacroWarning) {
611 return new RewriteModernObjC(InFile, OS, Diags, LOpts, SilenceRewriteMacroWarning);
612}
613
614void RewriteModernObjC::InitializeCommon(ASTContext &context) {
615 Context = &context;
616 SM = &Context->getSourceManager();
617 TUDecl = Context->getTranslationUnitDecl();
618 MsgSendFunctionDecl = 0;
619 MsgSendSuperFunctionDecl = 0;
620 MsgSendStretFunctionDecl = 0;
621 MsgSendSuperStretFunctionDecl = 0;
622 MsgSendFpretFunctionDecl = 0;
623 GetClassFunctionDecl = 0;
624 GetMetaClassFunctionDecl = 0;
625 GetSuperClassFunctionDecl = 0;
626 SelGetUidFunctionDecl = 0;
627 CFStringFunctionDecl = 0;
628 ConstantStringClassReference = 0;
629 NSStringRecord = 0;
630 CurMethodDef = 0;
631 CurFunctionDef = 0;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000632 GlobalVarDecl = 0;
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +0000633 GlobalConstructionExp = 0;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000634 SuperStructDecl = 0;
635 ProtocolTypeDecl = 0;
636 ConstantStringDecl = 0;
637 BcLabelCount = 0;
638 SuperContructorFunctionDecl = 0;
639 NumObjCStringLiterals = 0;
640 PropParentMap = 0;
641 CurrentBody = 0;
642 DisableReplaceStmt = false;
643 objc_impl_method = false;
644
645 // Get the ID and start/end of the main file.
646 MainFileID = SM->getMainFileID();
647 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
648 MainFileStart = MainBuf->getBufferStart();
649 MainFileEnd = MainBuf->getBufferEnd();
650
David Blaikie4e4d0842012-03-11 07:00:24 +0000651 Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOpts());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000652}
653
654//===----------------------------------------------------------------------===//
655// Top Level Driver Code
656//===----------------------------------------------------------------------===//
657
658void RewriteModernObjC::HandleTopLevelSingleDecl(Decl *D) {
659 if (Diags.hasErrorOccurred())
660 return;
661
662 // Two cases: either the decl could be in the main file, or it could be in a
663 // #included file. If the former, rewrite it now. If the later, check to see
664 // if we rewrote the #include/#import.
665 SourceLocation Loc = D->getLocation();
666 Loc = SM->getExpansionLoc(Loc);
667
668 // If this is for a builtin, ignore it.
669 if (Loc.isInvalid()) return;
670
671 // Look for built-in declarations that we need to refer during the rewrite.
672 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
673 RewriteFunctionDecl(FD);
674 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
675 // declared in <Foundation/NSString.h>
676 if (FVD->getName() == "_NSConstantStringClassReference") {
677 ConstantStringClassReference = FVD;
678 return;
679 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000680 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
681 RewriteCategoryDecl(CD);
682 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
683 if (PD->isThisDeclarationADefinition())
684 RewriteProtocolDecl(PD);
685 } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) {
Fariborz Jahanian8e86b2d2012-04-04 17:16:15 +0000686 // FIXME. This will not work in all situations and leaving it out
687 // is harmless.
688 // RewriteLinkageSpec(LSD);
689
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000690 // Recurse into linkage specifications
691 for (DeclContext::decl_iterator DI = LSD->decls_begin(),
692 DIEnd = LSD->decls_end();
693 DI != DIEnd; ) {
694 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>((*DI))) {
695 if (!IFace->isThisDeclarationADefinition()) {
696 SmallVector<Decl *, 8> DG;
697 SourceLocation StartLoc = IFace->getLocStart();
698 do {
699 if (isa<ObjCInterfaceDecl>(*DI) &&
700 !cast<ObjCInterfaceDecl>(*DI)->isThisDeclarationADefinition() &&
701 StartLoc == (*DI)->getLocStart())
702 DG.push_back(*DI);
703 else
704 break;
705
706 ++DI;
707 } while (DI != DIEnd);
708 RewriteForwardClassDecl(DG);
709 continue;
710 }
Fariborz Jahanianb3f904f2012-04-03 17:35:38 +0000711 else {
712 // Keep track of all interface declarations seen.
713 ObjCInterfacesSeen.push_back(IFace);
714 ++DI;
715 continue;
716 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000717 }
718
719 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>((*DI))) {
720 if (!Proto->isThisDeclarationADefinition()) {
721 SmallVector<Decl *, 8> DG;
722 SourceLocation StartLoc = Proto->getLocStart();
723 do {
724 if (isa<ObjCProtocolDecl>(*DI) &&
725 !cast<ObjCProtocolDecl>(*DI)->isThisDeclarationADefinition() &&
726 StartLoc == (*DI)->getLocStart())
727 DG.push_back(*DI);
728 else
729 break;
730
731 ++DI;
732 } while (DI != DIEnd);
733 RewriteForwardProtocolDecl(DG);
734 continue;
735 }
736 }
737
738 HandleTopLevelSingleDecl(*DI);
739 ++DI;
740 }
741 }
742 // If we have a decl in the main file, see if we should rewrite it.
743 if (SM->isFromMainFile(Loc))
744 return HandleDeclInMainFile(D);
745}
746
747//===----------------------------------------------------------------------===//
748// Syntactic (non-AST) Rewriting Code
749//===----------------------------------------------------------------------===//
750
751void RewriteModernObjC::RewriteInclude() {
752 SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID);
753 StringRef MainBuf = SM->getBufferData(MainFileID);
754 const char *MainBufStart = MainBuf.begin();
755 const char *MainBufEnd = MainBuf.end();
756 size_t ImportLen = strlen("import");
757
758 // Loop over the whole file, looking for includes.
759 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
760 if (*BufPtr == '#') {
761 if (++BufPtr == MainBufEnd)
762 return;
763 while (*BufPtr == ' ' || *BufPtr == '\t')
764 if (++BufPtr == MainBufEnd)
765 return;
766 if (!strncmp(BufPtr, "import", ImportLen)) {
767 // replace import with include
768 SourceLocation ImportLoc =
769 LocStart.getLocWithOffset(BufPtr-MainBufStart);
770 ReplaceText(ImportLoc, ImportLen, "include");
771 BufPtr += ImportLen;
772 }
773 }
774 }
775}
776
Fariborz Jahanian163d3ce2012-05-08 23:54:35 +0000777static void WriteInternalIvarName(const ObjCInterfaceDecl *IDecl,
778 ObjCIvarDecl *IvarDecl, std::string &Result) {
779 Result += "OBJC_IVAR_$_";
780 Result += IDecl->getName();
781 Result += "$";
782 Result += IvarDecl->getName();
783}
784
785std::string
786RewriteModernObjC::getIvarAccessString(ObjCIvarDecl *D) {
787 const ObjCInterfaceDecl *ClassDecl = D->getContainingInterface();
788
789 // Build name of symbol holding ivar offset.
790 std::string IvarOffsetName;
791 WriteInternalIvarName(ClassDecl, D, IvarOffsetName);
792
793
794 std::string S = "(*(";
795 QualType IvarT = D->getType();
796
797 if (!isa<TypedefType>(IvarT) && IvarT->isRecordType()) {
798 RecordDecl *RD = IvarT->getAs<RecordType>()->getDecl();
799 RD = RD->getDefinition();
800 if (RD && !RD->getDeclName().getAsIdentifierInfo()) {
801 // decltype(((Foo_IMPL*)0)->bar) *
802 ObjCContainerDecl *CDecl =
803 dyn_cast<ObjCContainerDecl>(D->getDeclContext());
804 // ivar in class extensions requires special treatment.
805 if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(CDecl))
806 CDecl = CatDecl->getClassInterface();
807 std::string RecName = CDecl->getName();
808 RecName += "_IMPL";
809 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
810 SourceLocation(), SourceLocation(),
811 &Context->Idents.get(RecName.c_str()));
812 QualType PtrStructIMPL = Context->getPointerType(Context->getTagDeclType(RD));
813 unsigned UnsignedIntSize =
814 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
815 Expr *Zero = IntegerLiteral::Create(*Context,
816 llvm::APInt(UnsignedIntSize, 0),
817 Context->UnsignedIntTy, SourceLocation());
818 Zero = NoTypeInfoCStyleCastExpr(Context, PtrStructIMPL, CK_BitCast, Zero);
819 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
820 Zero);
821 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
822 SourceLocation(),
823 &Context->Idents.get(D->getNameAsString()),
824 IvarT, 0,
825 /*BitWidth=*/0, /*Mutable=*/true,
826 /*HasInit=*/false);
827 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
828 FD->getType(), VK_LValue,
829 OK_Ordinary);
830 IvarT = Context->getDecltypeType(ME, ME->getType());
831 }
832 }
833 convertObjCTypeToCStyleType(IvarT);
834 QualType castT = Context->getPointerType(IvarT);
835 std::string TypeString(castT.getAsString(Context->getPrintingPolicy()));
836 S += TypeString;
837 S += ")";
838
839 // ((char *)self + IVAR_OFFSET_SYMBOL_NAME)
840 S += "((char *)self + ";
841 S += IvarOffsetName;
842 S += "))";
843 ReferencedIvars[const_cast<ObjCInterfaceDecl *>(ClassDecl)].insert(D);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000844 return S;
845}
846
Fariborz Jahanian301e2e42012-05-03 22:52:13 +0000847/// mustSynthesizeSetterGetterMethod - returns true if setter or getter has not
848/// been found in the class implementation. In this case, it must be synthesized.
849static bool mustSynthesizeSetterGetterMethod(ObjCImplementationDecl *IMP,
850 ObjCPropertyDecl *PD,
851 bool getter) {
852 return getter ? !IMP->getInstanceMethod(PD->getGetterName())
853 : !IMP->getInstanceMethod(PD->getSetterName());
854
855}
856
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000857void RewriteModernObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
858 ObjCImplementationDecl *IMD,
859 ObjCCategoryImplDecl *CID) {
860 static bool objcGetPropertyDefined = false;
861 static bool objcSetPropertyDefined = false;
Fariborz Jahanian301e2e42012-05-03 22:52:13 +0000862 SourceLocation startGetterSetterLoc;
863
864 if (PID->getLocStart().isValid()) {
865 SourceLocation startLoc = PID->getLocStart();
866 InsertText(startLoc, "// ");
867 const char *startBuf = SM->getCharacterData(startLoc);
868 assert((*startBuf == '@') && "bogus @synthesize location");
869 const char *semiBuf = strchr(startBuf, ';');
870 assert((*semiBuf == ';') && "@synthesize: can't find ';'");
871 startGetterSetterLoc = startLoc.getLocWithOffset(semiBuf-startBuf+1);
872 }
873 else
874 startGetterSetterLoc = IMD ? IMD->getLocEnd() : CID->getLocEnd();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000875
876 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
877 return; // FIXME: is this correct?
878
879 // Generate the 'getter' function.
880 ObjCPropertyDecl *PD = PID->getPropertyDecl();
881 ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
882
883 if (!OID)
884 return;
885 unsigned Attributes = PD->getPropertyAttributes();
Fariborz Jahanian301e2e42012-05-03 22:52:13 +0000886 if (mustSynthesizeSetterGetterMethod(IMD, PD, true /*getter*/)) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000887 bool GenGetProperty = !(Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic) &&
888 (Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
889 ObjCPropertyDecl::OBJC_PR_copy));
890 std::string Getr;
891 if (GenGetProperty && !objcGetPropertyDefined) {
892 objcGetPropertyDefined = true;
893 // FIXME. Is this attribute correct in all cases?
894 Getr = "\nextern \"C\" __declspec(dllimport) "
895 "id objc_getProperty(id, SEL, long, bool);\n";
896 }
897 RewriteObjCMethodDecl(OID->getContainingInterface(),
898 PD->getGetterMethodDecl(), Getr);
899 Getr += "{ ";
900 // Synthesize an explicit cast to gain access to the ivar.
901 // See objc-act.c:objc_synthesize_new_getter() for details.
902 if (GenGetProperty) {
903 // return objc_getProperty(self, _cmd, offsetof(ClassDecl, OID), 1)
904 Getr += "typedef ";
905 const FunctionType *FPRetType = 0;
906 RewriteTypeIntoString(PD->getGetterMethodDecl()->getResultType(), Getr,
907 FPRetType);
908 Getr += " _TYPE";
909 if (FPRetType) {
910 Getr += ")"; // close the precedence "scope" for "*".
911
912 // Now, emit the argument types (if any).
913 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)){
914 Getr += "(";
915 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
916 if (i) Getr += ", ";
917 std::string ParamStr = FT->getArgType(i).getAsString(
918 Context->getPrintingPolicy());
919 Getr += ParamStr;
920 }
921 if (FT->isVariadic()) {
922 if (FT->getNumArgs()) Getr += ", ";
923 Getr += "...";
924 }
925 Getr += ")";
926 } else
927 Getr += "()";
928 }
929 Getr += ";\n";
930 Getr += "return (_TYPE)";
931 Getr += "objc_getProperty(self, _cmd, ";
932 RewriteIvarOffsetComputation(OID, Getr);
933 Getr += ", 1)";
934 }
935 else
936 Getr += "return " + getIvarAccessString(OID);
937 Getr += "; }";
Fariborz Jahanian301e2e42012-05-03 22:52:13 +0000938 InsertText(startGetterSetterLoc, Getr);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000939 }
940
Fariborz Jahanian301e2e42012-05-03 22:52:13 +0000941 if (PD->isReadOnly() ||
942 !mustSynthesizeSetterGetterMethod(IMD, PD, false /*setter*/))
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000943 return;
944
945 // Generate the 'setter' function.
946 std::string Setr;
947 bool GenSetProperty = Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
948 ObjCPropertyDecl::OBJC_PR_copy);
949 if (GenSetProperty && !objcSetPropertyDefined) {
950 objcSetPropertyDefined = true;
951 // FIXME. Is this attribute correct in all cases?
952 Setr = "\nextern \"C\" __declspec(dllimport) "
953 "void objc_setProperty (id, SEL, long, id, bool, bool);\n";
954 }
955
956 RewriteObjCMethodDecl(OID->getContainingInterface(),
957 PD->getSetterMethodDecl(), Setr);
958 Setr += "{ ";
959 // Synthesize an explicit cast to initialize the ivar.
960 // See objc-act.c:objc_synthesize_new_setter() for details.
961 if (GenSetProperty) {
962 Setr += "objc_setProperty (self, _cmd, ";
963 RewriteIvarOffsetComputation(OID, Setr);
964 Setr += ", (id)";
965 Setr += PD->getName();
966 Setr += ", ";
967 if (Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic)
968 Setr += "0, ";
969 else
970 Setr += "1, ";
971 if (Attributes & ObjCPropertyDecl::OBJC_PR_copy)
972 Setr += "1)";
973 else
974 Setr += "0)";
975 }
976 else {
977 Setr += getIvarAccessString(OID) + " = ";
978 Setr += PD->getName();
979 }
Fariborz Jahanian301e2e42012-05-03 22:52:13 +0000980 Setr += "; }\n";
981 InsertText(startGetterSetterLoc, Setr);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000982}
983
984static void RewriteOneForwardClassDecl(ObjCInterfaceDecl *ForwardDecl,
985 std::string &typedefString) {
986 typedefString += "#ifndef _REWRITER_typedef_";
987 typedefString += ForwardDecl->getNameAsString();
988 typedefString += "\n";
989 typedefString += "#define _REWRITER_typedef_";
990 typedefString += ForwardDecl->getNameAsString();
991 typedefString += "\n";
992 typedefString += "typedef struct objc_object ";
993 typedefString += ForwardDecl->getNameAsString();
Fariborz Jahanianc38503b2012-03-12 23:58:28 +0000994 // typedef struct { } _objc_exc_Classname;
995 typedefString += ";\ntypedef struct {} _objc_exc_";
996 typedefString += ForwardDecl->getNameAsString();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000997 typedefString += ";\n#endif\n";
998}
999
1000void RewriteModernObjC::RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
1001 const std::string &typedefString) {
1002 SourceLocation startLoc = ClassDecl->getLocStart();
1003 const char *startBuf = SM->getCharacterData(startLoc);
1004 const char *semiPtr = strchr(startBuf, ';');
1005 // Replace the @class with typedefs corresponding to the classes.
1006 ReplaceText(startLoc, semiPtr-startBuf+1, typedefString);
1007}
1008
1009void RewriteModernObjC::RewriteForwardClassDecl(DeclGroupRef D) {
1010 std::string typedefString;
1011 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
1012 ObjCInterfaceDecl *ForwardDecl = cast<ObjCInterfaceDecl>(*I);
1013 if (I == D.begin()) {
1014 // Translate to typedef's that forward reference structs with the same name
1015 // as the class. As a convenience, we include the original declaration
1016 // as a comment.
1017 typedefString += "// @class ";
1018 typedefString += ForwardDecl->getNameAsString();
1019 typedefString += ";\n";
1020 }
1021 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
1022 }
1023 DeclGroupRef::iterator I = D.begin();
1024 RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(*I), typedefString);
1025}
1026
1027void RewriteModernObjC::RewriteForwardClassDecl(
1028 const llvm::SmallVector<Decl*, 8> &D) {
1029 std::string typedefString;
1030 for (unsigned i = 0; i < D.size(); i++) {
1031 ObjCInterfaceDecl *ForwardDecl = cast<ObjCInterfaceDecl>(D[i]);
1032 if (i == 0) {
1033 typedefString += "// @class ";
1034 typedefString += ForwardDecl->getNameAsString();
1035 typedefString += ";\n";
1036 }
1037 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
1038 }
1039 RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(D[0]), typedefString);
1040}
1041
1042void RewriteModernObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
1043 // When method is a synthesized one, such as a getter/setter there is
1044 // nothing to rewrite.
1045 if (Method->isImplicit())
1046 return;
1047 SourceLocation LocStart = Method->getLocStart();
1048 SourceLocation LocEnd = Method->getLocEnd();
1049
1050 if (SM->getExpansionLineNumber(LocEnd) >
1051 SM->getExpansionLineNumber(LocStart)) {
1052 InsertText(LocStart, "#if 0\n");
1053 ReplaceText(LocEnd, 1, ";\n#endif\n");
1054 } else {
1055 InsertText(LocStart, "// ");
1056 }
1057}
1058
1059void RewriteModernObjC::RewriteProperty(ObjCPropertyDecl *prop) {
1060 SourceLocation Loc = prop->getAtLoc();
1061
1062 ReplaceText(Loc, 0, "// ");
1063 // FIXME: handle properties that are declared across multiple lines.
1064}
1065
1066void RewriteModernObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
1067 SourceLocation LocStart = CatDecl->getLocStart();
1068
1069 // FIXME: handle category headers that are declared across multiple lines.
Fariborz Jahanianb68258f2012-05-01 17:46:45 +00001070 if (CatDecl->getIvarRBraceLoc().isValid()) {
1071 ReplaceText(LocStart, 1, "/** ");
1072 ReplaceText(CatDecl->getIvarRBraceLoc(), 1, "**/ ");
1073 }
1074 else {
Fariborz Jahaniand2aea122012-02-19 19:00:05 +00001075 ReplaceText(LocStart, 0, "// ");
Fariborz Jahanianb68258f2012-05-01 17:46:45 +00001076 }
Fariborz Jahanianaf300292012-02-20 20:09:20 +00001077
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001078 for (ObjCCategoryDecl::prop_iterator I = CatDecl->prop_begin(),
1079 E = CatDecl->prop_end(); I != E; ++I)
David Blaikie262bc182012-04-30 02:36:29 +00001080 RewriteProperty(&*I);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001081
1082 for (ObjCCategoryDecl::instmeth_iterator
1083 I = CatDecl->instmeth_begin(), E = CatDecl->instmeth_end();
1084 I != E; ++I)
1085 RewriteMethodDeclaration(*I);
1086 for (ObjCCategoryDecl::classmeth_iterator
1087 I = CatDecl->classmeth_begin(), E = CatDecl->classmeth_end();
1088 I != E; ++I)
1089 RewriteMethodDeclaration(*I);
1090
1091 // Lastly, comment out the @end.
1092 ReplaceText(CatDecl->getAtEndRange().getBegin(),
1093 strlen("@end"), "/* @end */");
1094}
1095
1096void RewriteModernObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
1097 SourceLocation LocStart = PDecl->getLocStart();
1098 assert(PDecl->isThisDeclarationADefinition());
1099
1100 // FIXME: handle protocol headers that are declared across multiple lines.
1101 ReplaceText(LocStart, 0, "// ");
1102
1103 for (ObjCProtocolDecl::instmeth_iterator
1104 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
1105 I != E; ++I)
1106 RewriteMethodDeclaration(*I);
1107 for (ObjCProtocolDecl::classmeth_iterator
1108 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
1109 I != E; ++I)
1110 RewriteMethodDeclaration(*I);
1111
1112 for (ObjCInterfaceDecl::prop_iterator I = PDecl->prop_begin(),
1113 E = PDecl->prop_end(); I != E; ++I)
David Blaikie262bc182012-04-30 02:36:29 +00001114 RewriteProperty(&*I);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001115
1116 // Lastly, comment out the @end.
1117 SourceLocation LocEnd = PDecl->getAtEndRange().getBegin();
1118 ReplaceText(LocEnd, strlen("@end"), "/* @end */");
1119
1120 // Must comment out @optional/@required
1121 const char *startBuf = SM->getCharacterData(LocStart);
1122 const char *endBuf = SM->getCharacterData(LocEnd);
1123 for (const char *p = startBuf; p < endBuf; p++) {
1124 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
1125 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
1126 ReplaceText(OptionalLoc, strlen("@optional"), "/* @optional */");
1127
1128 }
1129 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
1130 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
1131 ReplaceText(OptionalLoc, strlen("@required"), "/* @required */");
1132
1133 }
1134 }
1135}
1136
1137void RewriteModernObjC::RewriteForwardProtocolDecl(DeclGroupRef D) {
1138 SourceLocation LocStart = (*D.begin())->getLocStart();
1139 if (LocStart.isInvalid())
1140 llvm_unreachable("Invalid SourceLocation");
1141 // FIXME: handle forward protocol that are declared across multiple lines.
1142 ReplaceText(LocStart, 0, "// ");
1143}
1144
1145void
1146RewriteModernObjC::RewriteForwardProtocolDecl(const llvm::SmallVector<Decl*, 8> &DG) {
1147 SourceLocation LocStart = DG[0]->getLocStart();
1148 if (LocStart.isInvalid())
1149 llvm_unreachable("Invalid SourceLocation");
1150 // FIXME: handle forward protocol that are declared across multiple lines.
1151 ReplaceText(LocStart, 0, "// ");
1152}
1153
Fariborz Jahanianb3f904f2012-04-03 17:35:38 +00001154void
1155RewriteModernObjC::RewriteLinkageSpec(LinkageSpecDecl *LSD) {
1156 SourceLocation LocStart = LSD->getExternLoc();
1157 if (LocStart.isInvalid())
1158 llvm_unreachable("Invalid extern SourceLocation");
1159
1160 ReplaceText(LocStart, 0, "// ");
1161 if (!LSD->hasBraces())
1162 return;
1163 // FIXME. We don't rewrite well if '{' is not on same line as 'extern'.
1164 SourceLocation LocRBrace = LSD->getRBraceLoc();
1165 if (LocRBrace.isInvalid())
1166 llvm_unreachable("Invalid rbrace SourceLocation");
1167 ReplaceText(LocRBrace, 0, "// ");
1168}
1169
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001170void RewriteModernObjC::RewriteTypeIntoString(QualType T, std::string &ResultStr,
1171 const FunctionType *&FPRetType) {
1172 if (T->isObjCQualifiedIdType())
1173 ResultStr += "id";
1174 else if (T->isFunctionPointerType() ||
1175 T->isBlockPointerType()) {
1176 // needs special handling, since pointer-to-functions have special
1177 // syntax (where a decaration models use).
1178 QualType retType = T;
1179 QualType PointeeTy;
1180 if (const PointerType* PT = retType->getAs<PointerType>())
1181 PointeeTy = PT->getPointeeType();
1182 else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>())
1183 PointeeTy = BPT->getPointeeType();
1184 if ((FPRetType = PointeeTy->getAs<FunctionType>())) {
1185 ResultStr += FPRetType->getResultType().getAsString(
1186 Context->getPrintingPolicy());
1187 ResultStr += "(*";
1188 }
1189 } else
1190 ResultStr += T.getAsString(Context->getPrintingPolicy());
1191}
1192
1193void RewriteModernObjC::RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
1194 ObjCMethodDecl *OMD,
1195 std::string &ResultStr) {
1196 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
1197 const FunctionType *FPRetType = 0;
1198 ResultStr += "\nstatic ";
1199 RewriteTypeIntoString(OMD->getResultType(), ResultStr, FPRetType);
1200 ResultStr += " ";
1201
1202 // Unique method name
1203 std::string NameStr;
1204
1205 if (OMD->isInstanceMethod())
1206 NameStr += "_I_";
1207 else
1208 NameStr += "_C_";
1209
1210 NameStr += IDecl->getNameAsString();
1211 NameStr += "_";
1212
1213 if (ObjCCategoryImplDecl *CID =
1214 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
1215 NameStr += CID->getNameAsString();
1216 NameStr += "_";
1217 }
1218 // Append selector names, replacing ':' with '_'
1219 {
1220 std::string selString = OMD->getSelector().getAsString();
1221 int len = selString.size();
1222 for (int i = 0; i < len; i++)
1223 if (selString[i] == ':')
1224 selString[i] = '_';
1225 NameStr += selString;
1226 }
1227 // Remember this name for metadata emission
1228 MethodInternalNames[OMD] = NameStr;
1229 ResultStr += NameStr;
1230
1231 // Rewrite arguments
1232 ResultStr += "(";
1233
1234 // invisible arguments
1235 if (OMD->isInstanceMethod()) {
1236 QualType selfTy = Context->getObjCInterfaceType(IDecl);
1237 selfTy = Context->getPointerType(selfTy);
1238 if (!LangOpts.MicrosoftExt) {
1239 if (ObjCSynthesizedStructs.count(const_cast<ObjCInterfaceDecl*>(IDecl)))
1240 ResultStr += "struct ";
1241 }
1242 // When rewriting for Microsoft, explicitly omit the structure name.
1243 ResultStr += IDecl->getNameAsString();
1244 ResultStr += " *";
1245 }
1246 else
1247 ResultStr += Context->getObjCClassType().getAsString(
1248 Context->getPrintingPolicy());
1249
1250 ResultStr += " self, ";
1251 ResultStr += Context->getObjCSelType().getAsString(Context->getPrintingPolicy());
1252 ResultStr += " _cmd";
1253
1254 // Method arguments.
1255 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
1256 E = OMD->param_end(); PI != E; ++PI) {
1257 ParmVarDecl *PDecl = *PI;
1258 ResultStr += ", ";
1259 if (PDecl->getType()->isObjCQualifiedIdType()) {
1260 ResultStr += "id ";
1261 ResultStr += PDecl->getNameAsString();
1262 } else {
1263 std::string Name = PDecl->getNameAsString();
1264 QualType QT = PDecl->getType();
1265 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian2610f902012-03-27 16:42:20 +00001266 (void)convertBlockPointerToFunctionPointer(QT);
1267 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001268 ResultStr += Name;
1269 }
1270 }
1271 if (OMD->isVariadic())
1272 ResultStr += ", ...";
1273 ResultStr += ") ";
1274
1275 if (FPRetType) {
1276 ResultStr += ")"; // close the precedence "scope" for "*".
1277
1278 // Now, emit the argument types (if any).
1279 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
1280 ResultStr += "(";
1281 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
1282 if (i) ResultStr += ", ";
1283 std::string ParamStr = FT->getArgType(i).getAsString(
1284 Context->getPrintingPolicy());
1285 ResultStr += ParamStr;
1286 }
1287 if (FT->isVariadic()) {
1288 if (FT->getNumArgs()) ResultStr += ", ";
1289 ResultStr += "...";
1290 }
1291 ResultStr += ")";
1292 } else {
1293 ResultStr += "()";
1294 }
1295 }
1296}
1297void RewriteModernObjC::RewriteImplementationDecl(Decl *OID) {
1298 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
1299 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
1300
Fariborz Jahaniand2aea122012-02-19 19:00:05 +00001301 if (IMD) {
Fariborz Jahanianb68258f2012-05-01 17:46:45 +00001302 if (IMD->getIvarRBraceLoc().isValid()) {
1303 ReplaceText(IMD->getLocStart(), 1, "/** ");
1304 ReplaceText(IMD->getIvarRBraceLoc(), 1, "**/ ");
Fariborz Jahaniand2aea122012-02-19 19:00:05 +00001305 }
Fariborz Jahanianb68258f2012-05-01 17:46:45 +00001306 else {
1307 InsertText(IMD->getLocStart(), "// ");
1308 }
Fariborz Jahaniand2aea122012-02-19 19:00:05 +00001309 }
1310 else
1311 InsertText(CID->getLocStart(), "// ");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001312
1313 for (ObjCCategoryImplDecl::instmeth_iterator
1314 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
1315 E = IMD ? IMD->instmeth_end() : CID->instmeth_end();
1316 I != E; ++I) {
1317 std::string ResultStr;
1318 ObjCMethodDecl *OMD = *I;
1319 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
1320 SourceLocation LocStart = OMD->getLocStart();
1321 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
1322
1323 const char *startBuf = SM->getCharacterData(LocStart);
1324 const char *endBuf = SM->getCharacterData(LocEnd);
1325 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
1326 }
1327
1328 for (ObjCCategoryImplDecl::classmeth_iterator
1329 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
1330 E = IMD ? IMD->classmeth_end() : CID->classmeth_end();
1331 I != E; ++I) {
1332 std::string ResultStr;
1333 ObjCMethodDecl *OMD = *I;
1334 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
1335 SourceLocation LocStart = OMD->getLocStart();
1336 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
1337
1338 const char *startBuf = SM->getCharacterData(LocStart);
1339 const char *endBuf = SM->getCharacterData(LocEnd);
1340 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
1341 }
1342 for (ObjCCategoryImplDecl::propimpl_iterator
1343 I = IMD ? IMD->propimpl_begin() : CID->propimpl_begin(),
1344 E = IMD ? IMD->propimpl_end() : CID->propimpl_end();
1345 I != E; ++I) {
David Blaikie262bc182012-04-30 02:36:29 +00001346 RewritePropertyImplDecl(&*I, IMD, CID);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001347 }
1348
1349 InsertText(IMD ? IMD->getLocEnd() : CID->getLocEnd(), "// ");
1350}
1351
1352void RewriteModernObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00001353 // Do not synthesize more than once.
1354 if (ObjCSynthesizedStructs.count(ClassDecl))
1355 return;
1356 // Make sure super class's are written before current class is written.
1357 ObjCInterfaceDecl *SuperClass = ClassDecl->getSuperClass();
1358 while (SuperClass) {
1359 RewriteInterfaceDecl(SuperClass);
1360 SuperClass = SuperClass->getSuperClass();
1361 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001362 std::string ResultStr;
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +00001363 if (!ObjCWrittenInterfaces.count(ClassDecl->getCanonicalDecl())) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001364 // we haven't seen a forward decl - generate a typedef.
Fariborz Jahanianc38503b2012-03-12 23:58:28 +00001365 RewriteOneForwardClassDecl(ClassDecl, ResultStr);
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00001366 RewriteIvarOffsetSymbols(ClassDecl, ResultStr);
1367
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001368 RewriteObjCInternalStruct(ClassDecl, ResultStr);
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +00001369 // Mark this typedef as having been written into its c++ equivalent.
1370 ObjCWrittenInterfaces.insert(ClassDecl->getCanonicalDecl());
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001371
1372 for (ObjCInterfaceDecl::prop_iterator I = ClassDecl->prop_begin(),
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001373 E = ClassDecl->prop_end(); I != E; ++I)
David Blaikie262bc182012-04-30 02:36:29 +00001374 RewriteProperty(&*I);
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001375 for (ObjCInterfaceDecl::instmeth_iterator
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001376 I = ClassDecl->instmeth_begin(), E = ClassDecl->instmeth_end();
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001377 I != E; ++I)
1378 RewriteMethodDeclaration(*I);
1379 for (ObjCInterfaceDecl::classmeth_iterator
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001380 I = ClassDecl->classmeth_begin(), E = ClassDecl->classmeth_end();
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001381 I != E; ++I)
1382 RewriteMethodDeclaration(*I);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001383
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001384 // Lastly, comment out the @end.
1385 ReplaceText(ClassDecl->getAtEndRange().getBegin(), strlen("@end"),
1386 "/* @end */");
1387 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001388}
1389
1390Stmt *RewriteModernObjC::RewritePropertyOrImplicitSetter(PseudoObjectExpr *PseudoOp) {
1391 SourceRange OldRange = PseudoOp->getSourceRange();
1392
1393 // We just magically know some things about the structure of this
1394 // expression.
1395 ObjCMessageExpr *OldMsg =
1396 cast<ObjCMessageExpr>(PseudoOp->getSemanticExpr(
1397 PseudoOp->getNumSemanticExprs() - 1));
1398
1399 // Because the rewriter doesn't allow us to rewrite rewritten code,
1400 // we need to suppress rewriting the sub-statements.
Fariborz Jahanian88ec6102012-04-10 22:06:54 +00001401 Expr *Base;
1402 SmallVector<Expr*, 2> Args;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001403 {
1404 DisableReplaceStmtScope S(*this);
1405
1406 // Rebuild the base expression if we have one.
1407 Base = 0;
1408 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1409 Base = OldMsg->getInstanceReceiver();
1410 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1411 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1412 }
Fariborz Jahanian88ec6102012-04-10 22:06:54 +00001413
1414 unsigned numArgs = OldMsg->getNumArgs();
1415 for (unsigned i = 0; i < numArgs; i++) {
1416 Expr *Arg = OldMsg->getArg(i);
1417 if (isa<OpaqueValueExpr>(Arg))
1418 Arg = cast<OpaqueValueExpr>(Arg)->getSourceExpr();
1419 Arg = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Arg));
1420 Args.push_back(Arg);
1421 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001422 }
1423
1424 // TODO: avoid this copy.
1425 SmallVector<SourceLocation, 1> SelLocs;
1426 OldMsg->getSelectorLocs(SelLocs);
1427
1428 ObjCMessageExpr *NewMsg = 0;
1429 switch (OldMsg->getReceiverKind()) {
1430 case ObjCMessageExpr::Class:
1431 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1432 OldMsg->getValueKind(),
1433 OldMsg->getLeftLoc(),
1434 OldMsg->getClassReceiverTypeInfo(),
1435 OldMsg->getSelector(),
1436 SelLocs,
1437 OldMsg->getMethodDecl(),
Fariborz Jahanian88ec6102012-04-10 22:06:54 +00001438 Args,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001439 OldMsg->getRightLoc(),
1440 OldMsg->isImplicit());
1441 break;
1442
1443 case ObjCMessageExpr::Instance:
1444 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1445 OldMsg->getValueKind(),
1446 OldMsg->getLeftLoc(),
1447 Base,
1448 OldMsg->getSelector(),
1449 SelLocs,
1450 OldMsg->getMethodDecl(),
Fariborz Jahanian88ec6102012-04-10 22:06:54 +00001451 Args,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001452 OldMsg->getRightLoc(),
1453 OldMsg->isImplicit());
1454 break;
1455
1456 case ObjCMessageExpr::SuperClass:
1457 case ObjCMessageExpr::SuperInstance:
1458 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1459 OldMsg->getValueKind(),
1460 OldMsg->getLeftLoc(),
1461 OldMsg->getSuperLoc(),
1462 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1463 OldMsg->getSuperType(),
1464 OldMsg->getSelector(),
1465 SelLocs,
1466 OldMsg->getMethodDecl(),
Fariborz Jahanian88ec6102012-04-10 22:06:54 +00001467 Args,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001468 OldMsg->getRightLoc(),
1469 OldMsg->isImplicit());
1470 break;
1471 }
1472
1473 Stmt *Replacement = SynthMessageExpr(NewMsg);
1474 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1475 return Replacement;
1476}
1477
1478Stmt *RewriteModernObjC::RewritePropertyOrImplicitGetter(PseudoObjectExpr *PseudoOp) {
1479 SourceRange OldRange = PseudoOp->getSourceRange();
1480
1481 // We just magically know some things about the structure of this
1482 // expression.
1483 ObjCMessageExpr *OldMsg =
1484 cast<ObjCMessageExpr>(PseudoOp->getResultExpr()->IgnoreImplicit());
1485
1486 // Because the rewriter doesn't allow us to rewrite rewritten code,
1487 // we need to suppress rewriting the sub-statements.
1488 Expr *Base = 0;
Fariborz Jahanian88ec6102012-04-10 22:06:54 +00001489 SmallVector<Expr*, 1> Args;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001490 {
1491 DisableReplaceStmtScope S(*this);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001492 // Rebuild the base expression if we have one.
1493 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1494 Base = OldMsg->getInstanceReceiver();
1495 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1496 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1497 }
Fariborz Jahanian88ec6102012-04-10 22:06:54 +00001498 unsigned numArgs = OldMsg->getNumArgs();
1499 for (unsigned i = 0; i < numArgs; i++) {
1500 Expr *Arg = OldMsg->getArg(i);
1501 if (isa<OpaqueValueExpr>(Arg))
1502 Arg = cast<OpaqueValueExpr>(Arg)->getSourceExpr();
1503 Arg = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Arg));
1504 Args.push_back(Arg);
1505 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001506 }
1507
1508 // Intentionally empty.
1509 SmallVector<SourceLocation, 1> SelLocs;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001510
1511 ObjCMessageExpr *NewMsg = 0;
1512 switch (OldMsg->getReceiverKind()) {
1513 case ObjCMessageExpr::Class:
1514 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1515 OldMsg->getValueKind(),
1516 OldMsg->getLeftLoc(),
1517 OldMsg->getClassReceiverTypeInfo(),
1518 OldMsg->getSelector(),
1519 SelLocs,
1520 OldMsg->getMethodDecl(),
1521 Args,
1522 OldMsg->getRightLoc(),
1523 OldMsg->isImplicit());
1524 break;
1525
1526 case ObjCMessageExpr::Instance:
1527 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1528 OldMsg->getValueKind(),
1529 OldMsg->getLeftLoc(),
1530 Base,
1531 OldMsg->getSelector(),
1532 SelLocs,
1533 OldMsg->getMethodDecl(),
1534 Args,
1535 OldMsg->getRightLoc(),
1536 OldMsg->isImplicit());
1537 break;
1538
1539 case ObjCMessageExpr::SuperClass:
1540 case ObjCMessageExpr::SuperInstance:
1541 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1542 OldMsg->getValueKind(),
1543 OldMsg->getLeftLoc(),
1544 OldMsg->getSuperLoc(),
1545 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1546 OldMsg->getSuperType(),
1547 OldMsg->getSelector(),
1548 SelLocs,
1549 OldMsg->getMethodDecl(),
1550 Args,
1551 OldMsg->getRightLoc(),
1552 OldMsg->isImplicit());
1553 break;
1554 }
1555
1556 Stmt *Replacement = SynthMessageExpr(NewMsg);
1557 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1558 return Replacement;
1559}
1560
1561/// SynthCountByEnumWithState - To print:
1562/// ((unsigned int (*)
1563/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1564/// (void *)objc_msgSend)((id)l_collection,
1565/// sel_registerName(
1566/// "countByEnumeratingWithState:objects:count:"),
1567/// &enumState,
1568/// (id *)__rw_items, (unsigned int)16)
1569///
1570void RewriteModernObjC::SynthCountByEnumWithState(std::string &buf) {
1571 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1572 "id *, unsigned int))(void *)objc_msgSend)";
1573 buf += "\n\t\t";
1574 buf += "((id)l_collection,\n\t\t";
1575 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1576 buf += "\n\t\t";
1577 buf += "&enumState, "
1578 "(id *)__rw_items, (unsigned int)16)";
1579}
1580
1581/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1582/// statement to exit to its outer synthesized loop.
1583///
1584Stmt *RewriteModernObjC::RewriteBreakStmt(BreakStmt *S) {
1585 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1586 return S;
1587 // replace break with goto __break_label
1588 std::string buf;
1589
1590 SourceLocation startLoc = S->getLocStart();
1591 buf = "goto __break_label_";
1592 buf += utostr(ObjCBcLabelNo.back());
1593 ReplaceText(startLoc, strlen("break"), buf);
1594
1595 return 0;
1596}
1597
1598/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1599/// statement to continue with its inner synthesized loop.
1600///
1601Stmt *RewriteModernObjC::RewriteContinueStmt(ContinueStmt *S) {
1602 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1603 return S;
1604 // replace continue with goto __continue_label
1605 std::string buf;
1606
1607 SourceLocation startLoc = S->getLocStart();
1608 buf = "goto __continue_label_";
1609 buf += utostr(ObjCBcLabelNo.back());
1610 ReplaceText(startLoc, strlen("continue"), buf);
1611
1612 return 0;
1613}
1614
1615/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
1616/// It rewrites:
1617/// for ( type elem in collection) { stmts; }
1618
1619/// Into:
1620/// {
1621/// type elem;
1622/// struct __objcFastEnumerationState enumState = { 0 };
1623/// id __rw_items[16];
1624/// id l_collection = (id)collection;
1625/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1626/// objects:__rw_items count:16];
1627/// if (limit) {
1628/// unsigned long startMutations = *enumState.mutationsPtr;
1629/// do {
1630/// unsigned long counter = 0;
1631/// do {
1632/// if (startMutations != *enumState.mutationsPtr)
1633/// objc_enumerationMutation(l_collection);
1634/// elem = (type)enumState.itemsPtr[counter++];
1635/// stmts;
1636/// __continue_label: ;
1637/// } while (counter < limit);
1638/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1639/// objects:__rw_items count:16]);
1640/// elem = nil;
1641/// __break_label: ;
1642/// }
1643/// else
1644/// elem = nil;
1645/// }
1646///
1647Stmt *RewriteModernObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
1648 SourceLocation OrigEnd) {
1649 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
1650 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
1651 "ObjCForCollectionStmt Statement stack mismatch");
1652 assert(!ObjCBcLabelNo.empty() &&
1653 "ObjCForCollectionStmt - Label No stack empty");
1654
1655 SourceLocation startLoc = S->getLocStart();
1656 const char *startBuf = SM->getCharacterData(startLoc);
1657 StringRef elementName;
1658 std::string elementTypeAsString;
1659 std::string buf;
1660 buf = "\n{\n\t";
1661 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1662 // type elem;
1663 NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
1664 QualType ElementType = cast<ValueDecl>(D)->getType();
1665 if (ElementType->isObjCQualifiedIdType() ||
1666 ElementType->isObjCQualifiedInterfaceType())
1667 // Simply use 'id' for all qualified types.
1668 elementTypeAsString = "id";
1669 else
1670 elementTypeAsString = ElementType.getAsString(Context->getPrintingPolicy());
1671 buf += elementTypeAsString;
1672 buf += " ";
1673 elementName = D->getName();
1674 buf += elementName;
1675 buf += ";\n\t";
1676 }
1677 else {
1678 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
1679 elementName = DR->getDecl()->getName();
1680 ValueDecl *VD = cast<ValueDecl>(DR->getDecl());
1681 if (VD->getType()->isObjCQualifiedIdType() ||
1682 VD->getType()->isObjCQualifiedInterfaceType())
1683 // Simply use 'id' for all qualified types.
1684 elementTypeAsString = "id";
1685 else
1686 elementTypeAsString = VD->getType().getAsString(Context->getPrintingPolicy());
1687 }
1688
1689 // struct __objcFastEnumerationState enumState = { 0 };
1690 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1691 // id __rw_items[16];
1692 buf += "id __rw_items[16];\n\t";
1693 // id l_collection = (id)
1694 buf += "id l_collection = (id)";
1695 // Find start location of 'collection' the hard way!
1696 const char *startCollectionBuf = startBuf;
1697 startCollectionBuf += 3; // skip 'for'
1698 startCollectionBuf = strchr(startCollectionBuf, '(');
1699 startCollectionBuf++; // skip '('
1700 // find 'in' and skip it.
1701 while (*startCollectionBuf != ' ' ||
1702 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1703 (*(startCollectionBuf+3) != ' ' &&
1704 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1705 startCollectionBuf++;
1706 startCollectionBuf += 3;
1707
1708 // Replace: "for (type element in" with string constructed thus far.
1709 ReplaceText(startLoc, startCollectionBuf - startBuf, buf);
1710 // Replace ')' in for '(' type elem in collection ')' with ';'
1711 SourceLocation rightParenLoc = S->getRParenLoc();
1712 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1713 SourceLocation lparenLoc = startLoc.getLocWithOffset(rparenBuf-startBuf);
1714 buf = ";\n\t";
1715
1716 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1717 // objects:__rw_items count:16];
1718 // which is synthesized into:
1719 // unsigned int limit =
1720 // ((unsigned int (*)
1721 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1722 // (void *)objc_msgSend)((id)l_collection,
1723 // sel_registerName(
1724 // "countByEnumeratingWithState:objects:count:"),
1725 // (struct __objcFastEnumerationState *)&state,
1726 // (id *)__rw_items, (unsigned int)16);
1727 buf += "unsigned long limit =\n\t\t";
1728 SynthCountByEnumWithState(buf);
1729 buf += ";\n\t";
1730 /// if (limit) {
1731 /// unsigned long startMutations = *enumState.mutationsPtr;
1732 /// do {
1733 /// unsigned long counter = 0;
1734 /// do {
1735 /// if (startMutations != *enumState.mutationsPtr)
1736 /// objc_enumerationMutation(l_collection);
1737 /// elem = (type)enumState.itemsPtr[counter++];
1738 buf += "if (limit) {\n\t";
1739 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1740 buf += "do {\n\t\t";
1741 buf += "unsigned long counter = 0;\n\t\t";
1742 buf += "do {\n\t\t\t";
1743 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1744 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1745 buf += elementName;
1746 buf += " = (";
1747 buf += elementTypeAsString;
1748 buf += ")enumState.itemsPtr[counter++];";
1749 // Replace ')' in for '(' type elem in collection ')' with all of these.
1750 ReplaceText(lparenLoc, 1, buf);
1751
1752 /// __continue_label: ;
1753 /// } while (counter < limit);
1754 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1755 /// objects:__rw_items count:16]);
1756 /// elem = nil;
1757 /// __break_label: ;
1758 /// }
1759 /// else
1760 /// elem = nil;
1761 /// }
1762 ///
1763 buf = ";\n\t";
1764 buf += "__continue_label_";
1765 buf += utostr(ObjCBcLabelNo.back());
1766 buf += ": ;";
1767 buf += "\n\t\t";
1768 buf += "} while (counter < limit);\n\t";
1769 buf += "} while (limit = ";
1770 SynthCountByEnumWithState(buf);
1771 buf += ");\n\t";
1772 buf += elementName;
1773 buf += " = ((";
1774 buf += elementTypeAsString;
1775 buf += ")0);\n\t";
1776 buf += "__break_label_";
1777 buf += utostr(ObjCBcLabelNo.back());
1778 buf += ": ;\n\t";
1779 buf += "}\n\t";
1780 buf += "else\n\t\t";
1781 buf += elementName;
1782 buf += " = ((";
1783 buf += elementTypeAsString;
1784 buf += ")0);\n\t";
1785 buf += "}\n";
1786
1787 // Insert all these *after* the statement body.
1788 // FIXME: If this should support Obj-C++, support CXXTryStmt
1789 if (isa<CompoundStmt>(S->getBody())) {
1790 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(1);
1791 InsertText(endBodyLoc, buf);
1792 } else {
1793 /* Need to treat single statements specially. For example:
1794 *
1795 * for (A *a in b) if (stuff()) break;
1796 * for (A *a in b) xxxyy;
1797 *
1798 * The following code simply scans ahead to the semi to find the actual end.
1799 */
1800 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1801 const char *semiBuf = strchr(stmtBuf, ';');
1802 assert(semiBuf && "Can't find ';'");
1803 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(semiBuf-stmtBuf+1);
1804 InsertText(endBodyLoc, buf);
1805 }
1806 Stmts.pop_back();
1807 ObjCBcLabelNo.pop_back();
1808 return 0;
1809}
1810
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001811static void Write_RethrowObject(std::string &buf) {
1812 buf += "{ struct _FIN { _FIN(id reth) : rethrow(reth) {}\n";
1813 buf += "\t~_FIN() { if (rethrow) objc_exception_throw(rethrow); }\n";
1814 buf += "\tid rethrow;\n";
1815 buf += "\t} _fin_force_rethow(_rethrow);";
1816}
1817
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001818/// RewriteObjCSynchronizedStmt -
1819/// This routine rewrites @synchronized(expr) stmt;
1820/// into:
1821/// objc_sync_enter(expr);
1822/// @try stmt @finally { objc_sync_exit(expr); }
1823///
1824Stmt *RewriteModernObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
1825 // Get the start location and compute the semi location.
1826 SourceLocation startLoc = S->getLocStart();
1827 const char *startBuf = SM->getCharacterData(startLoc);
1828
1829 assert((*startBuf == '@') && "bogus @synchronized location");
1830
1831 std::string buf;
Fariborz Jahanian22e2f852012-03-17 17:46:02 +00001832 buf = "{ id _rethrow = 0; id _sync_obj = ";
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001833
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001834 const char *lparenBuf = startBuf;
1835 while (*lparenBuf != '(') lparenBuf++;
1836 ReplaceText(startLoc, lparenBuf-startBuf+1, buf);
Fariborz Jahanian22e2f852012-03-17 17:46:02 +00001837
1838 buf = "; objc_sync_enter(_sync_obj);\n";
1839 buf += "try {\n\tstruct _SYNC_EXIT { _SYNC_EXIT(id arg) : sync_exit(arg) {}";
1840 buf += "\n\t~_SYNC_EXIT() {objc_sync_exit(sync_exit);}";
1841 buf += "\n\tid sync_exit;";
1842 buf += "\n\t} _sync_exit(_sync_obj);\n";
1843
1844 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1845 // the sync expression is typically a message expression that's already
1846 // been rewritten! (which implies the SourceLocation's are invalid).
1847 SourceLocation RParenExprLoc = S->getSynchBody()->getLocStart();
1848 const char *RParenExprLocBuf = SM->getCharacterData(RParenExprLoc);
1849 while (*RParenExprLocBuf != ')') RParenExprLocBuf--;
1850 RParenExprLoc = startLoc.getLocWithOffset(RParenExprLocBuf-startBuf);
1851
1852 SourceLocation LBranceLoc = S->getSynchBody()->getLocStart();
1853 const char *LBraceLocBuf = SM->getCharacterData(LBranceLoc);
1854 assert (*LBraceLocBuf == '{');
1855 ReplaceText(RParenExprLoc, (LBraceLocBuf - SM->getCharacterData(RParenExprLoc) + 1), buf);
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001856
Fariborz Jahanianb655bf02012-03-16 21:43:45 +00001857 SourceLocation startRBraceLoc = S->getSynchBody()->getLocEnd();
Matt Beaumont-Gay9ab511c2012-03-16 22:20:39 +00001858 assert((*SM->getCharacterData(startRBraceLoc) == '}') &&
1859 "bogus @synchronized block");
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001860
1861 buf = "} catch (id e) {_rethrow = e;}\n";
1862 Write_RethrowObject(buf);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001863 buf += "}\n";
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001864 buf += "}\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001865
Fariborz Jahanianb655bf02012-03-16 21:43:45 +00001866 ReplaceText(startRBraceLoc, 1, buf);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001867
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001868 return 0;
1869}
1870
1871void RewriteModernObjC::WarnAboutReturnGotoStmts(Stmt *S)
1872{
1873 // Perform a bottom up traversal of all children.
1874 for (Stmt::child_range CI = S->children(); CI; ++CI)
1875 if (*CI)
1876 WarnAboutReturnGotoStmts(*CI);
1877
1878 if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
1879 Diags.Report(Context->getFullLoc(S->getLocStart()),
1880 TryFinallyContainsReturnDiag);
1881 }
1882 return;
1883}
1884
Fariborz Jahanian042b91d2012-05-23 23:47:20 +00001885Stmt *RewriteModernObjC::RewriteObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S) {
1886 SourceLocation startLoc = S->getAtLoc();
1887 ReplaceText(startLoc, strlen("@autoreleasepool"), "/* @autoreleasepool */");
1888 std::string buf;
1889 buf = "{ __AtAutoreleasePool __autoreleasepool; ";
1890 ReplaceText(S->getSubStmt()->getLocStart(), 1, buf);
1891
1892 return 0;
1893}
1894
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001895Stmt *RewriteModernObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Fariborz Jahanianb1228182012-03-15 22:42:15 +00001896 ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt();
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001897 bool noCatch = S->getNumCatchStmts() == 0;
Fariborz Jahanianb1228182012-03-15 22:42:15 +00001898 std::string buf;
1899
1900 if (finalStmt) {
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001901 if (noCatch)
1902 buf = "{ id volatile _rethrow = 0;\n";
1903 else {
1904 buf = "{ id volatile _rethrow = 0;\ntry {\n";
1905 }
Fariborz Jahanianb1228182012-03-15 22:42:15 +00001906 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001907 // Get the start location and compute the semi location.
1908 SourceLocation startLoc = S->getLocStart();
1909 const char *startBuf = SM->getCharacterData(startLoc);
1910
1911 assert((*startBuf == '@') && "bogus @try location");
Fariborz Jahanianb1228182012-03-15 22:42:15 +00001912 if (finalStmt)
1913 ReplaceText(startLoc, 1, buf);
1914 else
1915 // @try -> try
1916 ReplaceText(startLoc, 1, "");
1917
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001918 for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I) {
1919 ObjCAtCatchStmt *Catch = S->getCatchStmt(I);
Fariborz Jahanian4c148812012-03-15 20:11:10 +00001920 VarDecl *catchDecl = Catch->getCatchParamDecl();
Fariborz Jahanianc38503b2012-03-12 23:58:28 +00001921
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001922 startLoc = Catch->getLocStart();
Fariborz Jahanian4c148812012-03-15 20:11:10 +00001923 bool AtRemoved = false;
1924 if (catchDecl) {
1925 QualType t = catchDecl->getType();
1926 if (const ObjCObjectPointerType *Ptr = t->getAs<ObjCObjectPointerType>()) {
1927 // Should be a pointer to a class.
1928 ObjCInterfaceDecl *IDecl = Ptr->getObjectType()->getInterface();
1929 if (IDecl) {
1930 std::string Result;
1931 startBuf = SM->getCharacterData(startLoc);
1932 assert((*startBuf == '@') && "bogus @catch location");
1933 SourceLocation rParenLoc = Catch->getRParenLoc();
1934 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1935
1936 // _objc_exc_Foo *_e as argument to catch.
1937 Result = "catch (_objc_exc_"; Result += IDecl->getNameAsString();
1938 Result += " *_"; Result += catchDecl->getNameAsString();
1939 Result += ")";
1940 ReplaceText(startLoc, rParenBuf-startBuf+1, Result);
1941 // Foo *e = (Foo *)_e;
1942 Result.clear();
1943 Result = "{ ";
1944 Result += IDecl->getNameAsString();
1945 Result += " *"; Result += catchDecl->getNameAsString();
1946 Result += " = ("; Result += IDecl->getNameAsString(); Result += "*)";
1947 Result += "_"; Result += catchDecl->getNameAsString();
1948
1949 Result += "; ";
1950 SourceLocation lBraceLoc = Catch->getCatchBody()->getLocStart();
1951 ReplaceText(lBraceLoc, 1, Result);
1952 AtRemoved = true;
1953 }
1954 }
1955 }
1956 if (!AtRemoved)
1957 // @catch -> catch
1958 ReplaceText(startLoc, 1, "");
Fariborz Jahanianc38503b2012-03-12 23:58:28 +00001959
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001960 }
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001961 if (finalStmt) {
1962 buf.clear();
1963 if (noCatch)
1964 buf = "catch (id e) {_rethrow = e;}\n";
1965 else
1966 buf = "}\ncatch (id e) {_rethrow = e;}\n";
1967
1968 SourceLocation startFinalLoc = finalStmt->getLocStart();
1969 ReplaceText(startFinalLoc, 8, buf);
1970 Stmt *body = finalStmt->getFinallyBody();
1971 SourceLocation startFinalBodyLoc = body->getLocStart();
1972 buf.clear();
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001973 Write_RethrowObject(buf);
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001974 ReplaceText(startFinalBodyLoc, 1, buf);
1975
1976 SourceLocation endFinalBodyLoc = body->getLocEnd();
1977 ReplaceText(endFinalBodyLoc, 1, "}\n}");
Fariborz Jahanian22e2f852012-03-17 17:46:02 +00001978 // Now check for any return/continue/go statements within the @try.
1979 WarnAboutReturnGotoStmts(S->getTryBody());
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001980 }
1981
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001982 return 0;
1983}
1984
1985// This can't be done with ReplaceStmt(S, ThrowExpr), since
1986// the throw expression is typically a message expression that's already
1987// been rewritten! (which implies the SourceLocation's are invalid).
1988Stmt *RewriteModernObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
1989 // Get the start location and compute the semi location.
1990 SourceLocation startLoc = S->getLocStart();
1991 const char *startBuf = SM->getCharacterData(startLoc);
1992
1993 assert((*startBuf == '@') && "bogus @throw location");
1994
1995 std::string buf;
1996 /* void objc_exception_throw(id) __attribute__((noreturn)); */
1997 if (S->getThrowExpr())
1998 buf = "objc_exception_throw(";
Fariborz Jahanian40539462012-03-16 16:52:06 +00001999 else
2000 buf = "throw";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002001
2002 // handle "@ throw" correctly.
2003 const char *wBuf = strchr(startBuf, 'w');
2004 assert((*wBuf == 'w') && "@throw: can't find 'w'");
2005 ReplaceText(startLoc, wBuf-startBuf+1, buf);
2006
2007 const char *semiBuf = strchr(startBuf, ';');
2008 assert((*semiBuf == ';') && "@throw: can't find ';'");
2009 SourceLocation semiLoc = startLoc.getLocWithOffset(semiBuf-startBuf);
Fariborz Jahanian40539462012-03-16 16:52:06 +00002010 if (S->getThrowExpr())
2011 ReplaceText(semiLoc, 1, ");");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002012 return 0;
2013}
2014
2015Stmt *RewriteModernObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
2016 // Create a new string expression.
2017 QualType StrType = Context->getPointerType(Context->CharTy);
2018 std::string StrEncoding;
2019 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
2020 Expr *Replacement = StringLiteral::Create(*Context, StrEncoding,
2021 StringLiteral::Ascii, false,
2022 StrType, SourceLocation());
2023 ReplaceStmt(Exp, Replacement);
2024
2025 // Replace this subexpr in the parent.
2026 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2027 return Replacement;
2028}
2029
2030Stmt *RewriteModernObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
2031 if (!SelGetUidFunctionDecl)
2032 SynthSelGetUidFunctionDecl();
2033 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
2034 // Create a call to sel_registerName("selName").
2035 SmallVector<Expr*, 8> SelExprs;
2036 QualType argType = Context->getPointerType(Context->CharTy);
2037 SelExprs.push_back(StringLiteral::Create(*Context,
2038 Exp->getSelector().getAsString(),
2039 StringLiteral::Ascii, false,
2040 argType, SourceLocation()));
2041 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2042 &SelExprs[0], SelExprs.size());
2043 ReplaceStmt(Exp, SelExp);
2044 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2045 return SelExp;
2046}
2047
2048CallExpr *RewriteModernObjC::SynthesizeCallToFunctionDecl(
2049 FunctionDecl *FD, Expr **args, unsigned nargs, SourceLocation StartLoc,
2050 SourceLocation EndLoc) {
2051 // Get the type, we will need to reference it in a couple spots.
2052 QualType msgSendType = FD->getType();
2053
2054 // Create a reference to the objc_msgSend() declaration.
2055 DeclRefExpr *DRE =
John McCallf4b88a42012-03-10 09:33:50 +00002056 new (Context) DeclRefExpr(FD, false, msgSendType, VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002057
2058 // Now, we cast the reference to a pointer to the objc_msgSend type.
2059 QualType pToFunc = Context->getPointerType(msgSendType);
2060 ImplicitCastExpr *ICE =
2061 ImplicitCastExpr::Create(*Context, pToFunc, CK_FunctionToPointerDecay,
2062 DRE, 0, VK_RValue);
2063
2064 const FunctionType *FT = msgSendType->getAs<FunctionType>();
2065
2066 CallExpr *Exp =
2067 new (Context) CallExpr(*Context, ICE, args, nargs,
2068 FT->getCallResultType(*Context),
2069 VK_RValue, EndLoc);
2070 return Exp;
2071}
2072
2073static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
2074 const char *&startRef, const char *&endRef) {
2075 while (startBuf < endBuf) {
2076 if (*startBuf == '<')
2077 startRef = startBuf; // mark the start.
2078 if (*startBuf == '>') {
2079 if (startRef && *startRef == '<') {
2080 endRef = startBuf; // mark the end.
2081 return true;
2082 }
2083 return false;
2084 }
2085 startBuf++;
2086 }
2087 return false;
2088}
2089
2090static void scanToNextArgument(const char *&argRef) {
2091 int angle = 0;
2092 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
2093 if (*argRef == '<')
2094 angle++;
2095 else if (*argRef == '>')
2096 angle--;
2097 argRef++;
2098 }
2099 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
2100}
2101
2102bool RewriteModernObjC::needToScanForQualifiers(QualType T) {
2103 if (T->isObjCQualifiedIdType())
2104 return true;
2105 if (const PointerType *PT = T->getAs<PointerType>()) {
2106 if (PT->getPointeeType()->isObjCQualifiedIdType())
2107 return true;
2108 }
2109 if (T->isObjCObjectPointerType()) {
2110 T = T->getPointeeType();
2111 return T->isObjCQualifiedInterfaceType();
2112 }
2113 if (T->isArrayType()) {
2114 QualType ElemTy = Context->getBaseElementType(T);
2115 return needToScanForQualifiers(ElemTy);
2116 }
2117 return false;
2118}
2119
2120void RewriteModernObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
2121 QualType Type = E->getType();
2122 if (needToScanForQualifiers(Type)) {
2123 SourceLocation Loc, EndLoc;
2124
2125 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
2126 Loc = ECE->getLParenLoc();
2127 EndLoc = ECE->getRParenLoc();
2128 } else {
2129 Loc = E->getLocStart();
2130 EndLoc = E->getLocEnd();
2131 }
2132 // This will defend against trying to rewrite synthesized expressions.
2133 if (Loc.isInvalid() || EndLoc.isInvalid())
2134 return;
2135
2136 const char *startBuf = SM->getCharacterData(Loc);
2137 const char *endBuf = SM->getCharacterData(EndLoc);
2138 const char *startRef = 0, *endRef = 0;
2139 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2140 // Get the locations of the startRef, endRef.
2141 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-startBuf);
2142 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-startBuf+1);
2143 // Comment out the protocol references.
2144 InsertText(LessLoc, "/*");
2145 InsertText(GreaterLoc, "*/");
2146 }
2147 }
2148}
2149
2150void RewriteModernObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
2151 SourceLocation Loc;
2152 QualType Type;
2153 const FunctionProtoType *proto = 0;
2154 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
2155 Loc = VD->getLocation();
2156 Type = VD->getType();
2157 }
2158 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
2159 Loc = FD->getLocation();
2160 // Check for ObjC 'id' and class types that have been adorned with protocol
2161 // information (id<p>, C<p>*). The protocol references need to be rewritten!
2162 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2163 assert(funcType && "missing function type");
2164 proto = dyn_cast<FunctionProtoType>(funcType);
2165 if (!proto)
2166 return;
2167 Type = proto->getResultType();
2168 }
2169 else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
2170 Loc = FD->getLocation();
2171 Type = FD->getType();
2172 }
2173 else
2174 return;
2175
2176 if (needToScanForQualifiers(Type)) {
2177 // Since types are unique, we need to scan the buffer.
2178
2179 const char *endBuf = SM->getCharacterData(Loc);
2180 const char *startBuf = endBuf;
2181 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
2182 startBuf--; // scan backward (from the decl location) for return type.
2183 const char *startRef = 0, *endRef = 0;
2184 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2185 // Get the locations of the startRef, endRef.
2186 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-endBuf);
2187 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-endBuf+1);
2188 // Comment out the protocol references.
2189 InsertText(LessLoc, "/*");
2190 InsertText(GreaterLoc, "*/");
2191 }
2192 }
2193 if (!proto)
2194 return; // most likely, was a variable
2195 // Now check arguments.
2196 const char *startBuf = SM->getCharacterData(Loc);
2197 const char *startFuncBuf = startBuf;
2198 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
2199 if (needToScanForQualifiers(proto->getArgType(i))) {
2200 // Since types are unique, we need to scan the buffer.
2201
2202 const char *endBuf = startBuf;
2203 // scan forward (from the decl location) for argument types.
2204 scanToNextArgument(endBuf);
2205 const char *startRef = 0, *endRef = 0;
2206 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2207 // Get the locations of the startRef, endRef.
2208 SourceLocation LessLoc =
2209 Loc.getLocWithOffset(startRef-startFuncBuf);
2210 SourceLocation GreaterLoc =
2211 Loc.getLocWithOffset(endRef-startFuncBuf+1);
2212 // Comment out the protocol references.
2213 InsertText(LessLoc, "/*");
2214 InsertText(GreaterLoc, "*/");
2215 }
2216 startBuf = ++endBuf;
2217 }
2218 else {
2219 // If the function name is derived from a macro expansion, then the
2220 // argument buffer will not follow the name. Need to speak with Chris.
2221 while (*startBuf && *startBuf != ')' && *startBuf != ',')
2222 startBuf++; // scan forward (from the decl location) for argument types.
2223 startBuf++;
2224 }
2225 }
2226}
2227
2228void RewriteModernObjC::RewriteTypeOfDecl(VarDecl *ND) {
2229 QualType QT = ND->getType();
2230 const Type* TypePtr = QT->getAs<Type>();
2231 if (!isa<TypeOfExprType>(TypePtr))
2232 return;
2233 while (isa<TypeOfExprType>(TypePtr)) {
2234 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
2235 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
2236 TypePtr = QT->getAs<Type>();
2237 }
2238 // FIXME. This will not work for multiple declarators; as in:
2239 // __typeof__(a) b,c,d;
2240 std::string TypeAsString(QT.getAsString(Context->getPrintingPolicy()));
2241 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
2242 const char *startBuf = SM->getCharacterData(DeclLoc);
2243 if (ND->getInit()) {
2244 std::string Name(ND->getNameAsString());
2245 TypeAsString += " " + Name + " = ";
2246 Expr *E = ND->getInit();
2247 SourceLocation startLoc;
2248 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
2249 startLoc = ECE->getLParenLoc();
2250 else
2251 startLoc = E->getLocStart();
2252 startLoc = SM->getExpansionLoc(startLoc);
2253 const char *endBuf = SM->getCharacterData(startLoc);
2254 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
2255 }
2256 else {
2257 SourceLocation X = ND->getLocEnd();
2258 X = SM->getExpansionLoc(X);
2259 const char *endBuf = SM->getCharacterData(X);
2260 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
2261 }
2262}
2263
2264// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
2265void RewriteModernObjC::SynthSelGetUidFunctionDecl() {
2266 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
2267 SmallVector<QualType, 16> ArgTys;
2268 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2269 QualType getFuncType =
2270 getSimpleFunctionType(Context->getObjCSelType(), &ArgTys[0], ArgTys.size());
2271 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2272 SourceLocation(),
2273 SourceLocation(),
2274 SelGetUidIdent, getFuncType, 0,
2275 SC_Extern,
2276 SC_None, false);
2277}
2278
2279void RewriteModernObjC::RewriteFunctionDecl(FunctionDecl *FD) {
2280 // declared in <objc/objc.h>
2281 if (FD->getIdentifier() &&
2282 FD->getName() == "sel_registerName") {
2283 SelGetUidFunctionDecl = FD;
2284 return;
2285 }
2286 RewriteObjCQualifiedInterfaceTypes(FD);
2287}
2288
2289void RewriteModernObjC::RewriteBlockPointerType(std::string& Str, QualType Type) {
2290 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
2291 const char *argPtr = TypeString.c_str();
2292 if (!strchr(argPtr, '^')) {
2293 Str += TypeString;
2294 return;
2295 }
2296 while (*argPtr) {
2297 Str += (*argPtr == '^' ? '*' : *argPtr);
2298 argPtr++;
2299 }
2300}
2301
2302// FIXME. Consolidate this routine with RewriteBlockPointerType.
2303void RewriteModernObjC::RewriteBlockPointerTypeVariable(std::string& Str,
2304 ValueDecl *VD) {
2305 QualType Type = VD->getType();
2306 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
2307 const char *argPtr = TypeString.c_str();
2308 int paren = 0;
2309 while (*argPtr) {
2310 switch (*argPtr) {
2311 case '(':
2312 Str += *argPtr;
2313 paren++;
2314 break;
2315 case ')':
2316 Str += *argPtr;
2317 paren--;
2318 break;
2319 case '^':
2320 Str += '*';
2321 if (paren == 1)
2322 Str += VD->getNameAsString();
2323 break;
2324 default:
2325 Str += *argPtr;
2326 break;
2327 }
2328 argPtr++;
2329 }
2330}
2331
Fariborz Jahanianb75f8de2012-04-19 00:50:01 +00002332void RewriteModernObjC::RewriteBlockLiteralFunctionDecl(FunctionDecl *FD) {
2333 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
2334 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2335 const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(funcType);
2336 if (!proto)
2337 return;
2338 QualType Type = proto->getResultType();
2339 std::string FdStr = Type.getAsString(Context->getPrintingPolicy());
2340 FdStr += " ";
2341 FdStr += FD->getName();
2342 FdStr += "(";
2343 unsigned numArgs = proto->getNumArgs();
2344 for (unsigned i = 0; i < numArgs; i++) {
2345 QualType ArgType = proto->getArgType(i);
2346 RewriteBlockPointerType(FdStr, ArgType);
2347 if (i+1 < numArgs)
2348 FdStr += ", ";
2349 }
Fariborz Jahanianb5863da2012-04-19 16:30:28 +00002350 if (FD->isVariadic()) {
2351 FdStr += (numArgs > 0) ? ", ...);\n" : "...);\n";
2352 }
2353 else
2354 FdStr += ");\n";
Fariborz Jahanianb75f8de2012-04-19 00:50:01 +00002355 InsertText(FunLocStart, FdStr);
2356}
2357
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002358// SynthSuperContructorFunctionDecl - id __rw_objc_super(id obj, id super);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002359void RewriteModernObjC::SynthSuperContructorFunctionDecl() {
2360 if (SuperContructorFunctionDecl)
2361 return;
2362 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
2363 SmallVector<QualType, 16> ArgTys;
2364 QualType argT = Context->getObjCIdType();
2365 assert(!argT.isNull() && "Can't find 'id' type");
2366 ArgTys.push_back(argT);
2367 ArgTys.push_back(argT);
2368 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2369 &ArgTys[0], ArgTys.size());
2370 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2371 SourceLocation(),
2372 SourceLocation(),
2373 msgSendIdent, msgSendType, 0,
2374 SC_Extern,
2375 SC_None, false);
2376}
2377
2378// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
2379void RewriteModernObjC::SynthMsgSendFunctionDecl() {
2380 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
2381 SmallVector<QualType, 16> ArgTys;
2382 QualType argT = Context->getObjCIdType();
2383 assert(!argT.isNull() && "Can't find 'id' type");
2384 ArgTys.push_back(argT);
2385 argT = Context->getObjCSelType();
2386 assert(!argT.isNull() && "Can't find 'SEL' type");
2387 ArgTys.push_back(argT);
2388 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2389 &ArgTys[0], ArgTys.size(),
2390 true /*isVariadic*/);
2391 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2392 SourceLocation(),
2393 SourceLocation(),
2394 msgSendIdent, msgSendType, 0,
2395 SC_Extern,
2396 SC_None, false);
2397}
2398
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002399// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(void);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002400void RewriteModernObjC::SynthMsgSendSuperFunctionDecl() {
2401 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002402 SmallVector<QualType, 2> ArgTys;
2403 ArgTys.push_back(Context->VoidTy);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002404 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002405 &ArgTys[0], 1,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002406 true /*isVariadic*/);
2407 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2408 SourceLocation(),
2409 SourceLocation(),
2410 msgSendIdent, msgSendType, 0,
2411 SC_Extern,
2412 SC_None, false);
2413}
2414
2415// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
2416void RewriteModernObjC::SynthMsgSendStretFunctionDecl() {
2417 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
2418 SmallVector<QualType, 16> ArgTys;
2419 QualType argT = Context->getObjCIdType();
2420 assert(!argT.isNull() && "Can't find 'id' type");
2421 ArgTys.push_back(argT);
2422 argT = Context->getObjCSelType();
2423 assert(!argT.isNull() && "Can't find 'SEL' type");
2424 ArgTys.push_back(argT);
2425 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2426 &ArgTys[0], ArgTys.size(),
2427 true /*isVariadic*/);
2428 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2429 SourceLocation(),
2430 SourceLocation(),
2431 msgSendIdent, msgSendType, 0,
2432 SC_Extern,
2433 SC_None, false);
2434}
2435
2436// SynthMsgSendSuperStretFunctionDecl -
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002437// id objc_msgSendSuper_stret(void);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002438void RewriteModernObjC::SynthMsgSendSuperStretFunctionDecl() {
2439 IdentifierInfo *msgSendIdent =
2440 &Context->Idents.get("objc_msgSendSuper_stret");
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002441 SmallVector<QualType, 2> ArgTys;
2442 ArgTys.push_back(Context->VoidTy);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002443 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002444 &ArgTys[0], 1,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002445 true /*isVariadic*/);
2446 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2447 SourceLocation(),
2448 SourceLocation(),
2449 msgSendIdent, msgSendType, 0,
2450 SC_Extern,
2451 SC_None, false);
2452}
2453
2454// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
2455void RewriteModernObjC::SynthMsgSendFpretFunctionDecl() {
2456 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
2457 SmallVector<QualType, 16> ArgTys;
2458 QualType argT = Context->getObjCIdType();
2459 assert(!argT.isNull() && "Can't find 'id' type");
2460 ArgTys.push_back(argT);
2461 argT = Context->getObjCSelType();
2462 assert(!argT.isNull() && "Can't find 'SEL' type");
2463 ArgTys.push_back(argT);
2464 QualType msgSendType = getSimpleFunctionType(Context->DoubleTy,
2465 &ArgTys[0], ArgTys.size(),
2466 true /*isVariadic*/);
2467 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2468 SourceLocation(),
2469 SourceLocation(),
2470 msgSendIdent, msgSendType, 0,
2471 SC_Extern,
2472 SC_None, false);
2473}
2474
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00002475// SynthGetClassFunctionDecl - Class objc_getClass(const char *name);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002476void RewriteModernObjC::SynthGetClassFunctionDecl() {
2477 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
2478 SmallVector<QualType, 16> ArgTys;
2479 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00002480 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002481 &ArgTys[0], ArgTys.size());
2482 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2483 SourceLocation(),
2484 SourceLocation(),
2485 getClassIdent, getClassType, 0,
2486 SC_Extern,
2487 SC_None, false);
2488}
2489
2490// SynthGetSuperClassFunctionDecl - Class class_getSuperclass(Class cls);
2491void RewriteModernObjC::SynthGetSuperClassFunctionDecl() {
2492 IdentifierInfo *getSuperClassIdent =
2493 &Context->Idents.get("class_getSuperclass");
2494 SmallVector<QualType, 16> ArgTys;
2495 ArgTys.push_back(Context->getObjCClassType());
2496 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
2497 &ArgTys[0], ArgTys.size());
2498 GetSuperClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2499 SourceLocation(),
2500 SourceLocation(),
2501 getSuperClassIdent,
2502 getClassType, 0,
2503 SC_Extern,
2504 SC_None,
2505 false);
2506}
2507
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00002508// SynthGetMetaClassFunctionDecl - Class objc_getMetaClass(const char *name);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002509void RewriteModernObjC::SynthGetMetaClassFunctionDecl() {
2510 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
2511 SmallVector<QualType, 16> ArgTys;
2512 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00002513 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002514 &ArgTys[0], ArgTys.size());
2515 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2516 SourceLocation(),
2517 SourceLocation(),
2518 getClassIdent, getClassType, 0,
2519 SC_Extern,
2520 SC_None, false);
2521}
2522
2523Stmt *RewriteModernObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
2524 QualType strType = getConstantStringStructType();
2525
2526 std::string S = "__NSConstantStringImpl_";
2527
2528 std::string tmpName = InFileName;
2529 unsigned i;
2530 for (i=0; i < tmpName.length(); i++) {
2531 char c = tmpName.at(i);
2532 // replace any non alphanumeric characters with '_'.
2533 if (!isalpha(c) && (c < '0' || c > '9'))
2534 tmpName[i] = '_';
2535 }
2536 S += tmpName;
2537 S += "_";
2538 S += utostr(NumObjCStringLiterals++);
2539
2540 Preamble += "static __NSConstantStringImpl " + S;
2541 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2542 Preamble += "0x000007c8,"; // utf8_str
2543 // The pretty printer for StringLiteral handles escape characters properly.
2544 std::string prettyBufS;
2545 llvm::raw_string_ostream prettyBuf(prettyBufS);
2546 Exp->getString()->printPretty(prettyBuf, *Context, 0,
2547 PrintingPolicy(LangOpts));
2548 Preamble += prettyBuf.str();
2549 Preamble += ",";
2550 Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
2551
2552 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
2553 SourceLocation(), &Context->Idents.get(S),
2554 strType, 0, SC_Static, SC_None);
John McCallf4b88a42012-03-10 09:33:50 +00002555 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, false, strType, VK_LValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002556 SourceLocation());
2557 Expr *Unop = new (Context) UnaryOperator(DRE, UO_AddrOf,
2558 Context->getPointerType(DRE->getType()),
2559 VK_RValue, OK_Ordinary,
2560 SourceLocation());
2561 // cast to NSConstantString *
2562 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Exp->getType(),
2563 CK_CPointerToObjCPointerCast, Unop);
2564 ReplaceStmt(Exp, cast);
2565 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2566 return cast;
2567}
2568
Fariborz Jahanian55947042012-03-27 20:17:30 +00002569Stmt *RewriteModernObjC::RewriteObjCBoolLiteralExpr(ObjCBoolLiteralExpr *Exp) {
2570 unsigned IntSize =
2571 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
2572
2573 Expr *FlagExp = IntegerLiteral::Create(*Context,
2574 llvm::APInt(IntSize, Exp->getValue()),
2575 Context->IntTy, Exp->getLocation());
2576 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Context->ObjCBuiltinBoolTy,
2577 CK_BitCast, FlagExp);
2578 ParenExpr *PE = new (Context) ParenExpr(Exp->getLocation(), Exp->getExprLoc(),
2579 cast);
2580 ReplaceStmt(Exp, PE);
2581 return PE;
2582}
2583
Patrick Beardeb382ec2012-04-19 00:25:12 +00002584Stmt *RewriteModernObjC::RewriteObjCBoxedExpr(ObjCBoxedExpr *Exp) {
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002585 // synthesize declaration of helper functions needed in this routine.
2586 if (!SelGetUidFunctionDecl)
2587 SynthSelGetUidFunctionDecl();
2588 // use objc_msgSend() for all.
2589 if (!MsgSendFunctionDecl)
2590 SynthMsgSendFunctionDecl();
2591 if (!GetClassFunctionDecl)
2592 SynthGetClassFunctionDecl();
2593
2594 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2595 SourceLocation StartLoc = Exp->getLocStart();
2596 SourceLocation EndLoc = Exp->getLocEnd();
2597
2598 // Synthesize a call to objc_msgSend().
2599 SmallVector<Expr*, 4> MsgExprs;
2600 SmallVector<Expr*, 4> ClsExprs;
2601 QualType argType = Context->getPointerType(Context->CharTy);
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002602
Patrick Beardeb382ec2012-04-19 00:25:12 +00002603 // Create a call to objc_getClass("<BoxingClass>"). It will be the 1st argument.
2604 ObjCMethodDecl *BoxingMethod = Exp->getBoxingMethod();
2605 ObjCInterfaceDecl *BoxingClass = BoxingMethod->getClassInterface();
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002606
Patrick Beardeb382ec2012-04-19 00:25:12 +00002607 IdentifierInfo *clsName = BoxingClass->getIdentifier();
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002608 ClsExprs.push_back(StringLiteral::Create(*Context,
2609 clsName->getName(),
2610 StringLiteral::Ascii, false,
2611 argType, SourceLocation()));
2612 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2613 &ClsExprs[0],
2614 ClsExprs.size(),
2615 StartLoc, EndLoc);
2616 MsgExprs.push_back(Cls);
2617
Patrick Beardeb382ec2012-04-19 00:25:12 +00002618 // Create a call to sel_registerName("<BoxingMethod>:"), etc.
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002619 // it will be the 2nd argument.
2620 SmallVector<Expr*, 4> SelExprs;
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002621 SelExprs.push_back(StringLiteral::Create(*Context,
Patrick Beardeb382ec2012-04-19 00:25:12 +00002622 BoxingMethod->getSelector().getAsString(),
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002623 StringLiteral::Ascii, false,
2624 argType, SourceLocation()));
2625 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2626 &SelExprs[0], SelExprs.size(),
2627 StartLoc, EndLoc);
2628 MsgExprs.push_back(SelExp);
2629
Patrick Beardeb382ec2012-04-19 00:25:12 +00002630 // User provided sub-expression is the 3rd, and last, argument.
2631 Expr *subExpr = Exp->getSubExpr();
2632 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(subExpr)) {
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002633 QualType type = ICE->getType();
2634 const Expr *SubExpr = ICE->IgnoreParenImpCasts();
2635 CastKind CK = CK_BitCast;
2636 if (SubExpr->getType()->isIntegralType(*Context) && type->isBooleanType())
2637 CK = CK_IntegralToBoolean;
Patrick Beardeb382ec2012-04-19 00:25:12 +00002638 subExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, subExpr);
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002639 }
Patrick Beardeb382ec2012-04-19 00:25:12 +00002640 MsgExprs.push_back(subExpr);
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002641
2642 SmallVector<QualType, 4> ArgTypes;
2643 ArgTypes.push_back(Context->getObjCIdType());
2644 ArgTypes.push_back(Context->getObjCSelType());
Patrick Beardeb382ec2012-04-19 00:25:12 +00002645 for (ObjCMethodDecl::param_iterator PI = BoxingMethod->param_begin(),
2646 E = BoxingMethod->param_end(); PI != E; ++PI)
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002647 ArgTypes.push_back((*PI)->getType());
Patrick Beardeb382ec2012-04-19 00:25:12 +00002648
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002649 QualType returnType = Exp->getType();
2650 // Get the type, we will need to reference it in a couple spots.
2651 QualType msgSendType = MsgSendFlavor->getType();
2652
2653 // Create a reference to the objc_msgSend() declaration.
2654 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
2655 VK_LValue, SourceLocation());
2656
2657 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
Patrick Beardeb382ec2012-04-19 00:25:12 +00002658 Context->getPointerType(Context->VoidTy),
2659 CK_BitCast, DRE);
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002660
2661 // Now do the "normal" pointer to function cast.
2662 QualType castType =
Patrick Beardeb382ec2012-04-19 00:25:12 +00002663 getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
2664 BoxingMethod->isVariadic());
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002665 castType = Context->getPointerType(castType);
2666 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2667 cast);
2668
2669 // Don't forget the parens to enforce the proper binding.
2670 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
2671
2672 const FunctionType *FT = msgSendType->getAs<FunctionType>();
2673 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
2674 MsgExprs.size(),
2675 FT->getResultType(), VK_RValue,
2676 EndLoc);
2677 ReplaceStmt(Exp, CE);
2678 return CE;
2679}
2680
Fariborz Jahanian86cff602012-03-30 23:35:47 +00002681Stmt *RewriteModernObjC::RewriteObjCArrayLiteralExpr(ObjCArrayLiteral *Exp) {
2682 // synthesize declaration of helper functions needed in this routine.
2683 if (!SelGetUidFunctionDecl)
2684 SynthSelGetUidFunctionDecl();
2685 // use objc_msgSend() for all.
2686 if (!MsgSendFunctionDecl)
2687 SynthMsgSendFunctionDecl();
2688 if (!GetClassFunctionDecl)
2689 SynthGetClassFunctionDecl();
2690
2691 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2692 SourceLocation StartLoc = Exp->getLocStart();
2693 SourceLocation EndLoc = Exp->getLocEnd();
2694
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00002695 // Build the expression: __NSContainer_literal(int, ...).arr
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00002696 QualType IntQT = Context->IntTy;
2697 QualType NSArrayFType =
2698 getSimpleFunctionType(Context->VoidTy, &IntQT, 1, true);
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00002699 std::string NSArrayFName("__NSContainer_literal");
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00002700 FunctionDecl *NSArrayFD = SynthBlockInitFunctionDecl(NSArrayFName);
2701 DeclRefExpr *NSArrayDRE =
2702 new (Context) DeclRefExpr(NSArrayFD, false, NSArrayFType, VK_RValue,
2703 SourceLocation());
2704
2705 SmallVector<Expr*, 16> InitExprs;
2706 unsigned NumElements = Exp->getNumElements();
2707 unsigned UnsignedIntSize =
2708 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
2709 Expr *count = IntegerLiteral::Create(*Context,
2710 llvm::APInt(UnsignedIntSize, NumElements),
2711 Context->UnsignedIntTy, SourceLocation());
2712 InitExprs.push_back(count);
2713 for (unsigned i = 0; i < NumElements; i++)
2714 InitExprs.push_back(Exp->getElement(i));
2715 Expr *NSArrayCallExpr =
2716 new (Context) CallExpr(*Context, NSArrayDRE, &InitExprs[0], InitExprs.size(),
2717 NSArrayFType, VK_LValue, SourceLocation());
2718
2719 FieldDecl *ARRFD = FieldDecl::Create(*Context, 0, SourceLocation(),
2720 SourceLocation(),
2721 &Context->Idents.get("arr"),
2722 Context->getPointerType(Context->VoidPtrTy), 0,
2723 /*BitWidth=*/0, /*Mutable=*/true,
2724 /*HasInit=*/false);
2725 MemberExpr *ArrayLiteralME =
2726 new (Context) MemberExpr(NSArrayCallExpr, false, ARRFD,
2727 SourceLocation(),
2728 ARRFD->getType(), VK_LValue,
2729 OK_Ordinary);
2730 QualType ConstIdT = Context->getObjCIdType().withConst();
2731 CStyleCastExpr * ArrayLiteralObjects =
2732 NoTypeInfoCStyleCastExpr(Context,
2733 Context->getPointerType(ConstIdT),
2734 CK_BitCast,
2735 ArrayLiteralME);
2736
Fariborz Jahanian86cff602012-03-30 23:35:47 +00002737 // Synthesize a call to objc_msgSend().
2738 SmallVector<Expr*, 32> MsgExprs;
2739 SmallVector<Expr*, 4> ClsExprs;
2740 QualType argType = Context->getPointerType(Context->CharTy);
2741 QualType expType = Exp->getType();
2742
2743 // Create a call to objc_getClass("NSArray"). It will be th 1st argument.
2744 ObjCInterfaceDecl *Class =
2745 expType->getPointeeType()->getAs<ObjCObjectType>()->getInterface();
2746
2747 IdentifierInfo *clsName = Class->getIdentifier();
2748 ClsExprs.push_back(StringLiteral::Create(*Context,
2749 clsName->getName(),
2750 StringLiteral::Ascii, false,
2751 argType, SourceLocation()));
2752 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2753 &ClsExprs[0],
2754 ClsExprs.size(),
2755 StartLoc, EndLoc);
2756 MsgExprs.push_back(Cls);
2757
2758 // Create a call to sel_registerName("arrayWithObjects:count:").
2759 // it will be the 2nd argument.
2760 SmallVector<Expr*, 4> SelExprs;
2761 ObjCMethodDecl *ArrayMethod = Exp->getArrayWithObjectsMethod();
2762 SelExprs.push_back(StringLiteral::Create(*Context,
2763 ArrayMethod->getSelector().getAsString(),
2764 StringLiteral::Ascii, false,
2765 argType, SourceLocation()));
2766 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2767 &SelExprs[0], SelExprs.size(),
2768 StartLoc, EndLoc);
2769 MsgExprs.push_back(SelExp);
2770
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00002771 // (const id [])objects
2772 MsgExprs.push_back(ArrayLiteralObjects);
Fariborz Jahanian86cff602012-03-30 23:35:47 +00002773
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00002774 // (NSUInteger)cnt
2775 Expr *cnt = IntegerLiteral::Create(*Context,
2776 llvm::APInt(UnsignedIntSize, NumElements),
2777 Context->UnsignedIntTy, SourceLocation());
2778 MsgExprs.push_back(cnt);
Fariborz Jahanian86cff602012-03-30 23:35:47 +00002779
2780
2781 SmallVector<QualType, 4> ArgTypes;
2782 ArgTypes.push_back(Context->getObjCIdType());
2783 ArgTypes.push_back(Context->getObjCSelType());
2784 for (ObjCMethodDecl::param_iterator PI = ArrayMethod->param_begin(),
2785 E = ArrayMethod->param_end(); PI != E; ++PI)
2786 ArgTypes.push_back((*PI)->getType());
2787
2788 QualType returnType = Exp->getType();
2789 // Get the type, we will need to reference it in a couple spots.
2790 QualType msgSendType = MsgSendFlavor->getType();
2791
2792 // Create a reference to the objc_msgSend() declaration.
2793 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
2794 VK_LValue, SourceLocation());
2795
2796 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
2797 Context->getPointerType(Context->VoidTy),
2798 CK_BitCast, DRE);
2799
2800 // Now do the "normal" pointer to function cast.
2801 QualType castType =
2802 getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
2803 ArrayMethod->isVariadic());
2804 castType = Context->getPointerType(castType);
2805 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2806 cast);
2807
2808 // Don't forget the parens to enforce the proper binding.
2809 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
2810
2811 const FunctionType *FT = msgSendType->getAs<FunctionType>();
2812 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
2813 MsgExprs.size(),
2814 FT->getResultType(), VK_RValue,
2815 EndLoc);
2816 ReplaceStmt(Exp, CE);
2817 return CE;
2818}
2819
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00002820Stmt *RewriteModernObjC::RewriteObjCDictionaryLiteralExpr(ObjCDictionaryLiteral *Exp) {
2821 // synthesize declaration of helper functions needed in this routine.
2822 if (!SelGetUidFunctionDecl)
2823 SynthSelGetUidFunctionDecl();
2824 // use objc_msgSend() for all.
2825 if (!MsgSendFunctionDecl)
2826 SynthMsgSendFunctionDecl();
2827 if (!GetClassFunctionDecl)
2828 SynthGetClassFunctionDecl();
2829
2830 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2831 SourceLocation StartLoc = Exp->getLocStart();
2832 SourceLocation EndLoc = Exp->getLocEnd();
2833
2834 // Build the expression: __NSContainer_literal(int, ...).arr
2835 QualType IntQT = Context->IntTy;
2836 QualType NSDictFType =
2837 getSimpleFunctionType(Context->VoidTy, &IntQT, 1, true);
2838 std::string NSDictFName("__NSContainer_literal");
2839 FunctionDecl *NSDictFD = SynthBlockInitFunctionDecl(NSDictFName);
2840 DeclRefExpr *NSDictDRE =
2841 new (Context) DeclRefExpr(NSDictFD, false, NSDictFType, VK_RValue,
2842 SourceLocation());
2843
2844 SmallVector<Expr*, 16> KeyExprs;
2845 SmallVector<Expr*, 16> ValueExprs;
2846
2847 unsigned NumElements = Exp->getNumElements();
2848 unsigned UnsignedIntSize =
2849 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
2850 Expr *count = IntegerLiteral::Create(*Context,
2851 llvm::APInt(UnsignedIntSize, NumElements),
2852 Context->UnsignedIntTy, SourceLocation());
2853 KeyExprs.push_back(count);
2854 ValueExprs.push_back(count);
2855 for (unsigned i = 0; i < NumElements; i++) {
2856 ObjCDictionaryElement Element = Exp->getKeyValueElement(i);
2857 KeyExprs.push_back(Element.Key);
2858 ValueExprs.push_back(Element.Value);
2859 }
2860
2861 // (const id [])objects
2862 Expr *NSValueCallExpr =
2863 new (Context) CallExpr(*Context, NSDictDRE, &ValueExprs[0], ValueExprs.size(),
2864 NSDictFType, VK_LValue, SourceLocation());
2865
2866 FieldDecl *ARRFD = FieldDecl::Create(*Context, 0, SourceLocation(),
2867 SourceLocation(),
2868 &Context->Idents.get("arr"),
2869 Context->getPointerType(Context->VoidPtrTy), 0,
2870 /*BitWidth=*/0, /*Mutable=*/true,
2871 /*HasInit=*/false);
2872 MemberExpr *DictLiteralValueME =
2873 new (Context) MemberExpr(NSValueCallExpr, false, ARRFD,
2874 SourceLocation(),
2875 ARRFD->getType(), VK_LValue,
2876 OK_Ordinary);
2877 QualType ConstIdT = Context->getObjCIdType().withConst();
2878 CStyleCastExpr * DictValueObjects =
2879 NoTypeInfoCStyleCastExpr(Context,
2880 Context->getPointerType(ConstIdT),
2881 CK_BitCast,
2882 DictLiteralValueME);
2883 // (const id <NSCopying> [])keys
2884 Expr *NSKeyCallExpr =
2885 new (Context) CallExpr(*Context, NSDictDRE, &KeyExprs[0], KeyExprs.size(),
2886 NSDictFType, VK_LValue, SourceLocation());
2887
2888 MemberExpr *DictLiteralKeyME =
2889 new (Context) MemberExpr(NSKeyCallExpr, false, ARRFD,
2890 SourceLocation(),
2891 ARRFD->getType(), VK_LValue,
2892 OK_Ordinary);
2893
2894 CStyleCastExpr * DictKeyObjects =
2895 NoTypeInfoCStyleCastExpr(Context,
2896 Context->getPointerType(ConstIdT),
2897 CK_BitCast,
2898 DictLiteralKeyME);
2899
2900
2901
2902 // Synthesize a call to objc_msgSend().
2903 SmallVector<Expr*, 32> MsgExprs;
2904 SmallVector<Expr*, 4> ClsExprs;
2905 QualType argType = Context->getPointerType(Context->CharTy);
2906 QualType expType = Exp->getType();
2907
2908 // Create a call to objc_getClass("NSArray"). It will be th 1st argument.
2909 ObjCInterfaceDecl *Class =
2910 expType->getPointeeType()->getAs<ObjCObjectType>()->getInterface();
2911
2912 IdentifierInfo *clsName = Class->getIdentifier();
2913 ClsExprs.push_back(StringLiteral::Create(*Context,
2914 clsName->getName(),
2915 StringLiteral::Ascii, false,
2916 argType, SourceLocation()));
2917 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2918 &ClsExprs[0],
2919 ClsExprs.size(),
2920 StartLoc, EndLoc);
2921 MsgExprs.push_back(Cls);
2922
2923 // Create a call to sel_registerName("arrayWithObjects:count:").
2924 // it will be the 2nd argument.
2925 SmallVector<Expr*, 4> SelExprs;
2926 ObjCMethodDecl *DictMethod = Exp->getDictWithObjectsMethod();
2927 SelExprs.push_back(StringLiteral::Create(*Context,
2928 DictMethod->getSelector().getAsString(),
2929 StringLiteral::Ascii, false,
2930 argType, SourceLocation()));
2931 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2932 &SelExprs[0], SelExprs.size(),
2933 StartLoc, EndLoc);
2934 MsgExprs.push_back(SelExp);
2935
2936 // (const id [])objects
2937 MsgExprs.push_back(DictValueObjects);
2938
2939 // (const id <NSCopying> [])keys
2940 MsgExprs.push_back(DictKeyObjects);
2941
2942 // (NSUInteger)cnt
2943 Expr *cnt = IntegerLiteral::Create(*Context,
2944 llvm::APInt(UnsignedIntSize, NumElements),
2945 Context->UnsignedIntTy, SourceLocation());
2946 MsgExprs.push_back(cnt);
2947
2948
2949 SmallVector<QualType, 8> ArgTypes;
2950 ArgTypes.push_back(Context->getObjCIdType());
2951 ArgTypes.push_back(Context->getObjCSelType());
2952 for (ObjCMethodDecl::param_iterator PI = DictMethod->param_begin(),
2953 E = DictMethod->param_end(); PI != E; ++PI) {
2954 QualType T = (*PI)->getType();
2955 if (const PointerType* PT = T->getAs<PointerType>()) {
2956 QualType PointeeTy = PT->getPointeeType();
2957 convertToUnqualifiedObjCType(PointeeTy);
2958 T = Context->getPointerType(PointeeTy);
2959 }
2960 ArgTypes.push_back(T);
2961 }
2962
2963 QualType returnType = Exp->getType();
2964 // Get the type, we will need to reference it in a couple spots.
2965 QualType msgSendType = MsgSendFlavor->getType();
2966
2967 // Create a reference to the objc_msgSend() declaration.
2968 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
2969 VK_LValue, SourceLocation());
2970
2971 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
2972 Context->getPointerType(Context->VoidTy),
2973 CK_BitCast, DRE);
2974
2975 // Now do the "normal" pointer to function cast.
2976 QualType castType =
2977 getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
2978 DictMethod->isVariadic());
2979 castType = Context->getPointerType(castType);
2980 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2981 cast);
2982
2983 // Don't forget the parens to enforce the proper binding.
2984 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
2985
2986 const FunctionType *FT = msgSendType->getAs<FunctionType>();
2987 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
2988 MsgExprs.size(),
2989 FT->getResultType(), VK_RValue,
2990 EndLoc);
2991 ReplaceStmt(Exp, CE);
2992 return CE;
2993}
2994
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002995// struct __rw_objc_super {
2996// struct objc_object *object; struct objc_object *superClass;
2997// };
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002998QualType RewriteModernObjC::getSuperStructType() {
2999 if (!SuperStructDecl) {
3000 SuperStructDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
3001 SourceLocation(), SourceLocation(),
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003002 &Context->Idents.get("__rw_objc_super"));
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003003 QualType FieldTypes[2];
3004
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003005 // struct objc_object *object;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003006 FieldTypes[0] = Context->getObjCIdType();
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003007 // struct objc_object *superClass;
3008 FieldTypes[1] = Context->getObjCIdType();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003009
3010 // Create fields
3011 for (unsigned i = 0; i < 2; ++i) {
3012 SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
3013 SourceLocation(),
3014 SourceLocation(), 0,
3015 FieldTypes[i], 0,
3016 /*BitWidth=*/0,
3017 /*Mutable=*/false,
3018 /*HasInit=*/false));
3019 }
3020
3021 SuperStructDecl->completeDefinition();
3022 }
3023 return Context->getTagDeclType(SuperStructDecl);
3024}
3025
3026QualType RewriteModernObjC::getConstantStringStructType() {
3027 if (!ConstantStringDecl) {
3028 ConstantStringDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
3029 SourceLocation(), SourceLocation(),
3030 &Context->Idents.get("__NSConstantStringImpl"));
3031 QualType FieldTypes[4];
3032
3033 // struct objc_object *receiver;
3034 FieldTypes[0] = Context->getObjCIdType();
3035 // int flags;
3036 FieldTypes[1] = Context->IntTy;
3037 // char *str;
3038 FieldTypes[2] = Context->getPointerType(Context->CharTy);
3039 // long length;
3040 FieldTypes[3] = Context->LongTy;
3041
3042 // Create fields
3043 for (unsigned i = 0; i < 4; ++i) {
3044 ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
3045 ConstantStringDecl,
3046 SourceLocation(),
3047 SourceLocation(), 0,
3048 FieldTypes[i], 0,
3049 /*BitWidth=*/0,
3050 /*Mutable=*/true,
3051 /*HasInit=*/false));
3052 }
3053
3054 ConstantStringDecl->completeDefinition();
3055 }
3056 return Context->getTagDeclType(ConstantStringDecl);
3057}
3058
3059Stmt *RewriteModernObjC::SynthMessageExpr(ObjCMessageExpr *Exp,
3060 SourceLocation StartLoc,
3061 SourceLocation EndLoc) {
3062 if (!SelGetUidFunctionDecl)
3063 SynthSelGetUidFunctionDecl();
3064 if (!MsgSendFunctionDecl)
3065 SynthMsgSendFunctionDecl();
3066 if (!MsgSendSuperFunctionDecl)
3067 SynthMsgSendSuperFunctionDecl();
3068 if (!MsgSendStretFunctionDecl)
3069 SynthMsgSendStretFunctionDecl();
3070 if (!MsgSendSuperStretFunctionDecl)
3071 SynthMsgSendSuperStretFunctionDecl();
3072 if (!MsgSendFpretFunctionDecl)
3073 SynthMsgSendFpretFunctionDecl();
3074 if (!GetClassFunctionDecl)
3075 SynthGetClassFunctionDecl();
3076 if (!GetSuperClassFunctionDecl)
3077 SynthGetSuperClassFunctionDecl();
3078 if (!GetMetaClassFunctionDecl)
3079 SynthGetMetaClassFunctionDecl();
3080
3081 // default to objc_msgSend().
3082 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
3083 // May need to use objc_msgSend_stret() as well.
3084 FunctionDecl *MsgSendStretFlavor = 0;
3085 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
3086 QualType resultType = mDecl->getResultType();
3087 if (resultType->isRecordType())
3088 MsgSendStretFlavor = MsgSendStretFunctionDecl;
3089 else if (resultType->isRealFloatingType())
3090 MsgSendFlavor = MsgSendFpretFunctionDecl;
3091 }
3092
3093 // Synthesize a call to objc_msgSend().
3094 SmallVector<Expr*, 8> MsgExprs;
3095 switch (Exp->getReceiverKind()) {
3096 case ObjCMessageExpr::SuperClass: {
3097 MsgSendFlavor = MsgSendSuperFunctionDecl;
3098 if (MsgSendStretFlavor)
3099 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
3100 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
3101
3102 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
3103
3104 SmallVector<Expr*, 4> InitExprs;
3105
3106 // set the receiver to self, the first argument to all methods.
3107 InitExprs.push_back(
3108 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3109 CK_BitCast,
3110 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCallf4b88a42012-03-10 09:33:50 +00003111 false,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003112 Context->getObjCIdType(),
3113 VK_RValue,
3114 SourceLocation()))
3115 ); // set the 'receiver'.
3116
3117 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3118 SmallVector<Expr*, 8> ClsExprs;
3119 QualType argType = Context->getPointerType(Context->CharTy);
3120 ClsExprs.push_back(StringLiteral::Create(*Context,
3121 ClassDecl->getIdentifier()->getName(),
3122 StringLiteral::Ascii, false,
3123 argType, SourceLocation()));
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00003124 // (Class)objc_getClass("CurrentClass")
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003125 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
3126 &ClsExprs[0],
3127 ClsExprs.size(),
3128 StartLoc,
3129 EndLoc);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003130 ClsExprs.clear();
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00003131 ClsExprs.push_back(Cls);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003132 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
3133 &ClsExprs[0], ClsExprs.size(),
3134 StartLoc, EndLoc);
3135
3136 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3137 // To turn off a warning, type-cast to 'id'
3138 InitExprs.push_back( // set 'super class', using class_getSuperclass().
3139 NoTypeInfoCStyleCastExpr(Context,
3140 Context->getObjCIdType(),
3141 CK_BitCast, Cls));
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003142 // struct __rw_objc_super
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003143 QualType superType = getSuperStructType();
3144 Expr *SuperRep;
3145
3146 if (LangOpts.MicrosoftExt) {
3147 SynthSuperContructorFunctionDecl();
3148 // Simulate a contructor call...
3149 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
John McCallf4b88a42012-03-10 09:33:50 +00003150 false, superType, VK_LValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003151 SourceLocation());
3152 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
3153 InitExprs.size(),
3154 superType, VK_LValue,
3155 SourceLocation());
3156 // The code for super is a little tricky to prevent collision with
3157 // the structure definition in the header. The rewriter has it's own
3158 // internal definition (__rw_objc_super) that is uses. This is why
3159 // we need the cast below. For example:
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003160 // (struct __rw_objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003161 //
3162 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
3163 Context->getPointerType(SuperRep->getType()),
3164 VK_RValue, OK_Ordinary,
3165 SourceLocation());
3166 SuperRep = NoTypeInfoCStyleCastExpr(Context,
3167 Context->getPointerType(superType),
3168 CK_BitCast, SuperRep);
3169 } else {
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003170 // (struct __rw_objc_super) { <exprs from above> }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003171 InitListExpr *ILE =
3172 new (Context) InitListExpr(*Context, SourceLocation(),
3173 &InitExprs[0], InitExprs.size(),
3174 SourceLocation());
3175 TypeSourceInfo *superTInfo
3176 = Context->getTrivialTypeSourceInfo(superType);
3177 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
3178 superType, VK_LValue,
3179 ILE, false);
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003180 // struct __rw_objc_super *
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003181 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
3182 Context->getPointerType(SuperRep->getType()),
3183 VK_RValue, OK_Ordinary,
3184 SourceLocation());
3185 }
3186 MsgExprs.push_back(SuperRep);
3187 break;
3188 }
3189
3190 case ObjCMessageExpr::Class: {
3191 SmallVector<Expr*, 8> ClsExprs;
3192 QualType argType = Context->getPointerType(Context->CharTy);
3193 ObjCInterfaceDecl *Class
3194 = Exp->getClassReceiver()->getAs<ObjCObjectType>()->getInterface();
3195 IdentifierInfo *clsName = Class->getIdentifier();
3196 ClsExprs.push_back(StringLiteral::Create(*Context,
3197 clsName->getName(),
3198 StringLiteral::Ascii, false,
3199 argType, SourceLocation()));
3200 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
3201 &ClsExprs[0],
3202 ClsExprs.size(),
3203 StartLoc, EndLoc);
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00003204 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
3205 Context->getObjCIdType(),
3206 CK_BitCast, Cls);
3207 MsgExprs.push_back(ArgExpr);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003208 break;
3209 }
3210
3211 case ObjCMessageExpr::SuperInstance:{
3212 MsgSendFlavor = MsgSendSuperFunctionDecl;
3213 if (MsgSendStretFlavor)
3214 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
3215 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
3216 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
3217 SmallVector<Expr*, 4> InitExprs;
3218
3219 InitExprs.push_back(
3220 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3221 CK_BitCast,
3222 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCallf4b88a42012-03-10 09:33:50 +00003223 false,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003224 Context->getObjCIdType(),
3225 VK_RValue, SourceLocation()))
3226 ); // set the 'receiver'.
3227
3228 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3229 SmallVector<Expr*, 8> ClsExprs;
3230 QualType argType = Context->getPointerType(Context->CharTy);
3231 ClsExprs.push_back(StringLiteral::Create(*Context,
3232 ClassDecl->getIdentifier()->getName(),
3233 StringLiteral::Ascii, false, argType,
3234 SourceLocation()));
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00003235 // (Class)objc_getClass("CurrentClass")
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003236 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
3237 &ClsExprs[0],
3238 ClsExprs.size(),
3239 StartLoc, EndLoc);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003240 ClsExprs.clear();
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00003241 ClsExprs.push_back(Cls);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003242 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
3243 &ClsExprs[0], ClsExprs.size(),
3244 StartLoc, EndLoc);
3245
3246 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3247 // To turn off a warning, type-cast to 'id'
3248 InitExprs.push_back(
3249 // set 'super class', using class_getSuperclass().
3250 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3251 CK_BitCast, Cls));
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003252 // struct __rw_objc_super
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003253 QualType superType = getSuperStructType();
3254 Expr *SuperRep;
3255
3256 if (LangOpts.MicrosoftExt) {
3257 SynthSuperContructorFunctionDecl();
3258 // Simulate a contructor call...
3259 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
John McCallf4b88a42012-03-10 09:33:50 +00003260 false, superType, VK_LValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003261 SourceLocation());
3262 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
3263 InitExprs.size(),
3264 superType, VK_LValue, SourceLocation());
3265 // The code for super is a little tricky to prevent collision with
3266 // the structure definition in the header. The rewriter has it's own
3267 // internal definition (__rw_objc_super) that is uses. This is why
3268 // we need the cast below. For example:
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003269 // (struct __rw_objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003270 //
3271 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
3272 Context->getPointerType(SuperRep->getType()),
3273 VK_RValue, OK_Ordinary,
3274 SourceLocation());
3275 SuperRep = NoTypeInfoCStyleCastExpr(Context,
3276 Context->getPointerType(superType),
3277 CK_BitCast, SuperRep);
3278 } else {
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003279 // (struct __rw_objc_super) { <exprs from above> }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003280 InitListExpr *ILE =
3281 new (Context) InitListExpr(*Context, SourceLocation(),
3282 &InitExprs[0], InitExprs.size(),
3283 SourceLocation());
3284 TypeSourceInfo *superTInfo
3285 = Context->getTrivialTypeSourceInfo(superType);
3286 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
3287 superType, VK_RValue, ILE,
3288 false);
3289 }
3290 MsgExprs.push_back(SuperRep);
3291 break;
3292 }
3293
3294 case ObjCMessageExpr::Instance: {
3295 // Remove all type-casts because it may contain objc-style types; e.g.
3296 // Foo<Proto> *.
3297 Expr *recExpr = Exp->getInstanceReceiver();
3298 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
3299 recExpr = CE->getSubExpr();
3300 CastKind CK = recExpr->getType()->isObjCObjectPointerType()
3301 ? CK_BitCast : recExpr->getType()->isBlockPointerType()
3302 ? CK_BlockPointerToObjCPointerCast
3303 : CK_CPointerToObjCPointerCast;
3304
3305 recExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3306 CK, recExpr);
3307 MsgExprs.push_back(recExpr);
3308 break;
3309 }
3310 }
3311
3312 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
3313 SmallVector<Expr*, 8> SelExprs;
3314 QualType argType = Context->getPointerType(Context->CharTy);
3315 SelExprs.push_back(StringLiteral::Create(*Context,
3316 Exp->getSelector().getAsString(),
3317 StringLiteral::Ascii, false,
3318 argType, SourceLocation()));
3319 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
3320 &SelExprs[0], SelExprs.size(),
3321 StartLoc,
3322 EndLoc);
3323 MsgExprs.push_back(SelExp);
3324
3325 // Now push any user supplied arguments.
3326 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
3327 Expr *userExpr = Exp->getArg(i);
3328 // Make all implicit casts explicit...ICE comes in handy:-)
3329 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
3330 // Reuse the ICE type, it is exactly what the doctor ordered.
3331 QualType type = ICE->getType();
3332 if (needToScanForQualifiers(type))
3333 type = Context->getObjCIdType();
3334 // Make sure we convert "type (^)(...)" to "type (*)(...)".
3335 (void)convertBlockPointerToFunctionPointer(type);
3336 const Expr *SubExpr = ICE->IgnoreParenImpCasts();
3337 CastKind CK;
3338 if (SubExpr->getType()->isIntegralType(*Context) &&
3339 type->isBooleanType()) {
3340 CK = CK_IntegralToBoolean;
3341 } else if (type->isObjCObjectPointerType()) {
3342 if (SubExpr->getType()->isBlockPointerType()) {
3343 CK = CK_BlockPointerToObjCPointerCast;
3344 } else if (SubExpr->getType()->isPointerType()) {
3345 CK = CK_CPointerToObjCPointerCast;
3346 } else {
3347 CK = CK_BitCast;
3348 }
3349 } else {
3350 CK = CK_BitCast;
3351 }
3352
3353 userExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, userExpr);
3354 }
3355 // Make id<P...> cast into an 'id' cast.
3356 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
3357 if (CE->getType()->isObjCQualifiedIdType()) {
3358 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
3359 userExpr = CE->getSubExpr();
3360 CastKind CK;
3361 if (userExpr->getType()->isIntegralType(*Context)) {
3362 CK = CK_IntegralToPointer;
3363 } else if (userExpr->getType()->isBlockPointerType()) {
3364 CK = CK_BlockPointerToObjCPointerCast;
3365 } else if (userExpr->getType()->isPointerType()) {
3366 CK = CK_CPointerToObjCPointerCast;
3367 } else {
3368 CK = CK_BitCast;
3369 }
3370 userExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3371 CK, userExpr);
3372 }
3373 }
3374 MsgExprs.push_back(userExpr);
3375 // We've transferred the ownership to MsgExprs. For now, we *don't* null
3376 // out the argument in the original expression (since we aren't deleting
3377 // the ObjCMessageExpr). See RewritePropertyOrImplicitSetter() usage for more info.
3378 //Exp->setArg(i, 0);
3379 }
3380 // Generate the funky cast.
3381 CastExpr *cast;
3382 SmallVector<QualType, 8> ArgTypes;
3383 QualType returnType;
3384
3385 // Push 'id' and 'SEL', the 2 implicit arguments.
3386 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
3387 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
3388 else
3389 ArgTypes.push_back(Context->getObjCIdType());
3390 ArgTypes.push_back(Context->getObjCSelType());
3391 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
3392 // Push any user argument types.
3393 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
3394 E = OMD->param_end(); PI != E; ++PI) {
3395 QualType t = (*PI)->getType()->isObjCQualifiedIdType()
3396 ? Context->getObjCIdType()
3397 : (*PI)->getType();
3398 // Make sure we convert "t (^)(...)" to "t (*)(...)".
3399 (void)convertBlockPointerToFunctionPointer(t);
3400 ArgTypes.push_back(t);
3401 }
3402 returnType = Exp->getType();
3403 convertToUnqualifiedObjCType(returnType);
3404 (void)convertBlockPointerToFunctionPointer(returnType);
3405 } else {
3406 returnType = Context->getObjCIdType();
3407 }
3408 // Get the type, we will need to reference it in a couple spots.
3409 QualType msgSendType = MsgSendFlavor->getType();
3410
3411 // Create a reference to the objc_msgSend() declaration.
John McCallf4b88a42012-03-10 09:33:50 +00003412 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003413 VK_LValue, SourceLocation());
3414
3415 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
3416 // If we don't do this cast, we get the following bizarre warning/note:
3417 // xx.m:13: warning: function called through a non-compatible type
3418 // xx.m:13: note: if this code is reached, the program will abort
3419 cast = NoTypeInfoCStyleCastExpr(Context,
3420 Context->getPointerType(Context->VoidTy),
3421 CK_BitCast, DRE);
3422
3423 // Now do the "normal" pointer to function cast.
3424 QualType castType =
3425 getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
3426 // If we don't have a method decl, force a variadic cast.
3427 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true);
3428 castType = Context->getPointerType(castType);
3429 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
3430 cast);
3431
3432 // Don't forget the parens to enforce the proper binding.
3433 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
3434
3435 const FunctionType *FT = msgSendType->getAs<FunctionType>();
3436 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
3437 MsgExprs.size(),
3438 FT->getResultType(), VK_RValue,
3439 EndLoc);
3440 Stmt *ReplacingStmt = CE;
3441 if (MsgSendStretFlavor) {
3442 // We have the method which returns a struct/union. Must also generate
3443 // call to objc_msgSend_stret and hang both varieties on a conditional
3444 // expression which dictate which one to envoke depending on size of
3445 // method's return type.
3446
3447 // Create a reference to the objc_msgSend_stret() declaration.
John McCallf4b88a42012-03-10 09:33:50 +00003448 DeclRefExpr *STDRE = new (Context) DeclRefExpr(MsgSendStretFlavor,
3449 false, msgSendType,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003450 VK_LValue, SourceLocation());
3451 // Need to cast objc_msgSend_stret to "void *" (see above comment).
3452 cast = NoTypeInfoCStyleCastExpr(Context,
3453 Context->getPointerType(Context->VoidTy),
3454 CK_BitCast, STDRE);
3455 // Now do the "normal" pointer to function cast.
3456 castType = getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
3457 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false);
3458 castType = Context->getPointerType(castType);
3459 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
3460 cast);
3461
3462 // Don't forget the parens to enforce the proper binding.
3463 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
3464
3465 FT = msgSendType->getAs<FunctionType>();
3466 CallExpr *STCE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
3467 MsgExprs.size(),
3468 FT->getResultType(), VK_RValue,
3469 SourceLocation());
3470
3471 // Build sizeof(returnType)
3472 UnaryExprOrTypeTraitExpr *sizeofExpr =
3473 new (Context) UnaryExprOrTypeTraitExpr(UETT_SizeOf,
3474 Context->getTrivialTypeSourceInfo(returnType),
3475 Context->getSizeType(), SourceLocation(),
3476 SourceLocation());
3477 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
3478 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
3479 // For X86 it is more complicated and some kind of target specific routine
3480 // is needed to decide what to do.
3481 unsigned IntSize =
3482 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
3483 IntegerLiteral *limit = IntegerLiteral::Create(*Context,
3484 llvm::APInt(IntSize, 8),
3485 Context->IntTy,
3486 SourceLocation());
3487 BinaryOperator *lessThanExpr =
3488 new (Context) BinaryOperator(sizeofExpr, limit, BO_LE, Context->IntTy,
3489 VK_RValue, OK_Ordinary, SourceLocation());
3490 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
3491 ConditionalOperator *CondExpr =
3492 new (Context) ConditionalOperator(lessThanExpr,
3493 SourceLocation(), CE,
3494 SourceLocation(), STCE,
3495 returnType, VK_RValue, OK_Ordinary);
3496 ReplacingStmt = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3497 CondExpr);
3498 }
3499 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3500 return ReplacingStmt;
3501}
3502
3503Stmt *RewriteModernObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
3504 Stmt *ReplacingStmt = SynthMessageExpr(Exp, Exp->getLocStart(),
3505 Exp->getLocEnd());
3506
3507 // Now do the actual rewrite.
3508 ReplaceStmt(Exp, ReplacingStmt);
3509
3510 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3511 return ReplacingStmt;
3512}
3513
3514// typedef struct objc_object Protocol;
3515QualType RewriteModernObjC::getProtocolType() {
3516 if (!ProtocolTypeDecl) {
3517 TypeSourceInfo *TInfo
3518 = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
3519 ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
3520 SourceLocation(), SourceLocation(),
3521 &Context->Idents.get("Protocol"),
3522 TInfo);
3523 }
3524 return Context->getTypeDeclType(ProtocolTypeDecl);
3525}
3526
3527/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
3528/// a synthesized/forward data reference (to the protocol's metadata).
3529/// The forward references (and metadata) are generated in
3530/// RewriteModernObjC::HandleTranslationUnit().
3531Stmt *RewriteModernObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00003532 std::string Name = "_OBJC_PROTOCOL_REFERENCE_$_" +
3533 Exp->getProtocol()->getNameAsString();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003534 IdentifierInfo *ID = &Context->Idents.get(Name);
3535 VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
3536 SourceLocation(), ID, getProtocolType(), 0,
3537 SC_Extern, SC_None);
John McCallf4b88a42012-03-10 09:33:50 +00003538 DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, false, getProtocolType(),
3539 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003540 Expr *DerefExpr = new (Context) UnaryOperator(DRE, UO_AddrOf,
3541 Context->getPointerType(DRE->getType()),
3542 VK_RValue, OK_Ordinary, SourceLocation());
3543 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, DerefExpr->getType(),
3544 CK_BitCast,
3545 DerefExpr);
3546 ReplaceStmt(Exp, castExpr);
3547 ProtocolExprDecls.insert(Exp->getProtocol()->getCanonicalDecl());
3548 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3549 return castExpr;
3550
3551}
3552
3553bool RewriteModernObjC::BufferContainsPPDirectives(const char *startBuf,
3554 const char *endBuf) {
3555 while (startBuf < endBuf) {
3556 if (*startBuf == '#') {
3557 // Skip whitespace.
3558 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
3559 ;
3560 if (!strncmp(startBuf, "if", strlen("if")) ||
3561 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
3562 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
3563 !strncmp(startBuf, "define", strlen("define")) ||
3564 !strncmp(startBuf, "undef", strlen("undef")) ||
3565 !strncmp(startBuf, "else", strlen("else")) ||
3566 !strncmp(startBuf, "elif", strlen("elif")) ||
3567 !strncmp(startBuf, "endif", strlen("endif")) ||
3568 !strncmp(startBuf, "pragma", strlen("pragma")) ||
3569 !strncmp(startBuf, "include", strlen("include")) ||
3570 !strncmp(startBuf, "import", strlen("import")) ||
3571 !strncmp(startBuf, "include_next", strlen("include_next")))
3572 return true;
3573 }
3574 startBuf++;
3575 }
3576 return false;
3577}
3578
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003579/// IsTagDefinedInsideClass - This routine checks that a named tagged type
3580/// is defined inside an objective-c class. If so, it returns true.
Fariborz Jahanianb68258f2012-05-01 17:46:45 +00003581bool RewriteModernObjC::IsTagDefinedInsideClass(ObjCContainerDecl *IDecl,
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003582 TagDecl *Tag,
3583 bool &IsNamedDefinition) {
Fariborz Jahanian89585e802012-04-30 19:46:53 +00003584 if (!IDecl)
3585 return false;
3586 SourceLocation TagLocation;
3587 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) {
3588 RD = RD->getDefinition();
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003589 if (!RD || !RD->getDeclName().getAsIdentifierInfo())
Fariborz Jahanian89585e802012-04-30 19:46:53 +00003590 return false;
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003591 IsNamedDefinition = true;
Fariborz Jahanian89585e802012-04-30 19:46:53 +00003592 TagLocation = RD->getLocation();
3593 return Context->getSourceManager().isBeforeInTranslationUnit(
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003594 IDecl->getLocation(), TagLocation);
3595 }
3596 if (EnumDecl *ED = dyn_cast<EnumDecl>(Tag)) {
3597 if (!ED || !ED->getDeclName().getAsIdentifierInfo())
3598 return false;
3599 IsNamedDefinition = true;
3600 TagLocation = ED->getLocation();
3601 return Context->getSourceManager().isBeforeInTranslationUnit(
3602 IDecl->getLocation(), TagLocation);
3603
Fariborz Jahanian89585e802012-04-30 19:46:53 +00003604 }
3605 return false;
3606}
3607
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003608/// RewriteObjCFieldDeclType - This routine rewrites a type into the buffer.
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003609/// It handles elaborated types, as well as enum types in the process.
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003610bool RewriteModernObjC::RewriteObjCFieldDeclType(QualType &Type,
3611 std::string &Result) {
Fariborz Jahanianf5eac482012-05-02 17:34:59 +00003612 if (isa<TypedefType>(Type)) {
3613 Result += "\t";
3614 return false;
3615 }
3616
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003617 if (Type->isArrayType()) {
3618 QualType ElemTy = Context->getBaseElementType(Type);
3619 return RewriteObjCFieldDeclType(ElemTy, Result);
3620 }
3621 else if (Type->isRecordType()) {
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003622 RecordDecl *RD = Type->getAs<RecordType>()->getDecl();
3623 if (RD->isCompleteDefinition()) {
3624 if (RD->isStruct())
3625 Result += "\n\tstruct ";
3626 else if (RD->isUnion())
3627 Result += "\n\tunion ";
3628 else
3629 assert(false && "class not allowed as an ivar type");
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003630
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003631 Result += RD->getName();
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003632 if (GlobalDefinedTags.count(RD)) {
3633 // struct/union is defined globally, use it.
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003634 Result += " ";
3635 return true;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003636 }
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003637 Result += " {\n";
3638 for (RecordDecl::field_iterator i = RD->field_begin(),
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003639 e = RD->field_end(); i != e; ++i) {
David Blaikie262bc182012-04-30 02:36:29 +00003640 FieldDecl *FD = &*i;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003641 RewriteObjCFieldDecl(FD, Result);
3642 }
3643 Result += "\t} ";
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003644 return true;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003645 }
3646 }
3647 else if (Type->isEnumeralType()) {
3648 EnumDecl *ED = Type->getAs<EnumType>()->getDecl();
3649 if (ED->isCompleteDefinition()) {
3650 Result += "\n\tenum ";
3651 Result += ED->getName();
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003652 if (GlobalDefinedTags.count(ED)) {
3653 // Enum is globall defined, use it.
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003654 Result += " ";
3655 return true;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003656 }
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003657
3658 Result += " {\n";
3659 for (EnumDecl::enumerator_iterator EC = ED->enumerator_begin(),
3660 ECEnd = ED->enumerator_end(); EC != ECEnd; ++EC) {
3661 Result += "\t"; Result += EC->getName(); Result += " = ";
3662 llvm::APSInt Val = EC->getInitVal();
3663 Result += Val.toString(10);
3664 Result += ",\n";
3665 }
3666 Result += "\t} ";
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003667 return true;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003668 }
3669 }
3670
3671 Result += "\t";
3672 convertObjCTypeToCStyleType(Type);
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003673 return false;
3674}
3675
3676
3677/// RewriteObjCFieldDecl - This routine rewrites a field into the buffer.
3678/// It handles elaborated types, as well as enum types in the process.
3679void RewriteModernObjC::RewriteObjCFieldDecl(FieldDecl *fieldDecl,
3680 std::string &Result) {
3681 QualType Type = fieldDecl->getType();
3682 std::string Name = fieldDecl->getNameAsString();
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003683
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003684 bool EleboratedType = RewriteObjCFieldDeclType(Type, Result);
3685 if (!EleboratedType)
3686 Type.getAsStringInternal(Name, Context->getPrintingPolicy());
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003687 Result += Name;
3688 if (fieldDecl->isBitField()) {
3689 Result += " : "; Result += utostr(fieldDecl->getBitWidthValue(*Context));
3690 }
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003691 else if (EleboratedType && Type->isArrayType()) {
3692 CanQualType CType = Context->getCanonicalType(Type);
3693 while (isa<ArrayType>(CType)) {
3694 if (const ConstantArrayType *CAT = Context->getAsConstantArrayType(CType)) {
3695 Result += "[";
3696 llvm::APInt Dim = CAT->getSize();
3697 Result += utostr(Dim.getZExtValue());
3698 Result += "]";
3699 }
3700 CType = CType->getAs<ArrayType>()->getElementType();
3701 }
3702 }
3703
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003704 Result += ";\n";
3705}
3706
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003707/// RewriteLocallyDefinedNamedAggregates - This routine rewrites locally defined
3708/// named aggregate types into the input buffer.
3709void RewriteModernObjC::RewriteLocallyDefinedNamedAggregates(FieldDecl *fieldDecl,
3710 std::string &Result) {
3711 QualType Type = fieldDecl->getType();
Fariborz Jahanianf5eac482012-05-02 17:34:59 +00003712 if (isa<TypedefType>(Type))
3713 return;
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003714 if (Type->isArrayType())
3715 Type = Context->getBaseElementType(Type);
Fariborz Jahanianb68258f2012-05-01 17:46:45 +00003716 ObjCContainerDecl *IDecl =
3717 dyn_cast<ObjCContainerDecl>(fieldDecl->getDeclContext());
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003718
3719 TagDecl *TD = 0;
3720 if (Type->isRecordType()) {
3721 TD = Type->getAs<RecordType>()->getDecl();
3722 }
3723 else if (Type->isEnumeralType()) {
3724 TD = Type->getAs<EnumType>()->getDecl();
3725 }
3726
3727 if (TD) {
3728 if (GlobalDefinedTags.count(TD))
3729 return;
3730
3731 bool IsNamedDefinition = false;
3732 if (IsTagDefinedInsideClass(IDecl, TD, IsNamedDefinition)) {
3733 RewriteObjCFieldDeclType(Type, Result);
3734 Result += ";";
3735 }
3736 if (IsNamedDefinition)
3737 GlobalDefinedTags.insert(TD);
3738 }
3739
3740}
3741
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003742/// RewriteObjCInternalStruct - Rewrite one internal struct corresponding to
3743/// an objective-c class with ivars.
3744void RewriteModernObjC::RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
3745 std::string &Result) {
3746 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
3747 assert(CDecl->getName() != "" &&
3748 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003749 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003750 SmallVector<ObjCIvarDecl *, 8> IVars;
3751 for (ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
Fariborz Jahanian9a2105b2012-03-06 17:16:27 +00003752 IVD; IVD = IVD->getNextIvar())
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003753 IVars.push_back(IVD);
Fariborz Jahanian9a2105b2012-03-06 17:16:27 +00003754
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003755 SourceLocation LocStart = CDecl->getLocStart();
3756 SourceLocation LocEnd = CDecl->getEndOfDefinitionLoc();
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003757
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003758 const char *startBuf = SM->getCharacterData(LocStart);
3759 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003760
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003761 // If no ivars and no root or if its root, directly or indirectly,
3762 // have no ivars (thus not synthesized) then no need to synthesize this class.
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003763 if ((!CDecl->isThisDeclarationADefinition() || IVars.size() == 0) &&
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003764 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
3765 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
3766 ReplaceText(LocStart, endBuf-startBuf, Result);
3767 return;
3768 }
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003769
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003770 // Insert named struct/union definitions inside class to
3771 // outer scope. This follows semantics of locally defined
3772 // struct/unions in objective-c classes.
3773 for (unsigned i = 0, e = IVars.size(); i < e; i++)
3774 RewriteLocallyDefinedNamedAggregates(IVars[i], Result);
3775
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003776 Result += "\nstruct ";
3777 Result += CDecl->getNameAsString();
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003778 Result += "_IMPL {\n";
3779
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00003780 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003781 Result += "\tstruct "; Result += RCDecl->getNameAsString();
3782 Result += "_IMPL "; Result += RCDecl->getNameAsString();
3783 Result += "_IVARS;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003784 }
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003785
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003786 for (unsigned i = 0, e = IVars.size(); i < e; i++)
3787 RewriteObjCFieldDecl(IVars[i], Result);
Fariborz Jahanian0b17b9a2012-02-12 21:36:23 +00003788
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003789 Result += "};\n";
3790 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
3791 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00003792 // Mark this struct as having been generated.
3793 if (!ObjCSynthesizedStructs.insert(CDecl))
3794 llvm_unreachable("struct already synthesize- RewriteObjCInternalStruct");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003795}
3796
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00003797/// RewriteIvarOffsetSymbols - Rewrite ivar offset symbols of those ivars which
3798/// have been referenced in an ivar access expression.
3799void RewriteModernObjC::RewriteIvarOffsetSymbols(ObjCInterfaceDecl *CDecl,
3800 std::string &Result) {
3801 // write out ivar offset symbols which have been referenced in an ivar
3802 // access expression.
3803 llvm::SmallPtrSet<ObjCIvarDecl *, 8> Ivars = ReferencedIvars[CDecl];
3804 if (Ivars.empty())
3805 return;
3806 for (llvm::SmallPtrSet<ObjCIvarDecl *, 8>::iterator i = Ivars.begin(),
3807 e = Ivars.end(); i != e; i++) {
3808 ObjCIvarDecl *IvarDecl = (*i);
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00003809 Result += "\n";
3810 if (LangOpts.MicrosoftExt)
3811 Result += "__declspec(allocate(\".objc_ivar$B\")) ";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00003812 Result += "extern \"C\" ";
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00003813 if (LangOpts.MicrosoftExt &&
3814 IvarDecl->getAccessControl() != ObjCIvarDecl::Private &&
Fariborz Jahanian297976d2012-03-29 17:51:09 +00003815 IvarDecl->getAccessControl() != ObjCIvarDecl::Package)
3816 Result += "__declspec(dllimport) ";
3817
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00003818 Result += "unsigned long ";
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00003819 WriteInternalIvarName(CDecl, IvarDecl, Result);
3820 Result += ";";
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00003821 }
3822}
3823
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003824//===----------------------------------------------------------------------===//
3825// Meta Data Emission
3826//===----------------------------------------------------------------------===//
3827
3828
3829/// RewriteImplementations - This routine rewrites all method implementations
3830/// and emits meta-data.
3831
3832void RewriteModernObjC::RewriteImplementations() {
3833 int ClsDefCount = ClassImplementation.size();
3834 int CatDefCount = CategoryImplementation.size();
3835
3836 // Rewrite implemented methods
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00003837 for (int i = 0; i < ClsDefCount; i++) {
3838 ObjCImplementationDecl *OIMP = ClassImplementation[i];
3839 ObjCInterfaceDecl *CDecl = OIMP->getClassInterface();
3840 if (CDecl->isImplicitInterfaceDecl())
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +00003841 assert(false &&
3842 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00003843 RewriteImplementationDecl(OIMP);
3844 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003845
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00003846 for (int i = 0; i < CatDefCount; i++) {
3847 ObjCCategoryImplDecl *CIMP = CategoryImplementation[i];
3848 ObjCInterfaceDecl *CDecl = CIMP->getClassInterface();
3849 if (CDecl->isImplicitInterfaceDecl())
3850 assert(false &&
3851 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00003852 RewriteImplementationDecl(CIMP);
3853 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003854}
3855
3856void RewriteModernObjC::RewriteByRefString(std::string &ResultStr,
3857 const std::string &Name,
3858 ValueDecl *VD, bool def) {
3859 assert(BlockByRefDeclNo.count(VD) &&
3860 "RewriteByRefString: ByRef decl missing");
3861 if (def)
3862 ResultStr += "struct ";
3863 ResultStr += "__Block_byref_" + Name +
3864 "_" + utostr(BlockByRefDeclNo[VD]) ;
3865}
3866
3867static bool HasLocalVariableExternalStorage(ValueDecl *VD) {
3868 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
3869 return (Var->isFunctionOrMethodVarDecl() && !Var->hasLocalStorage());
3870 return false;
3871}
3872
3873std::string RewriteModernObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
3874 StringRef funcName,
3875 std::string Tag) {
3876 const FunctionType *AFT = CE->getFunctionType();
3877 QualType RT = AFT->getResultType();
3878 std::string StructRef = "struct " + Tag;
3879 std::string S = "static " + RT.getAsString(Context->getPrintingPolicy()) + " __" +
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00003880 funcName.str() + "_block_func_" + utostr(i);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003881
3882 BlockDecl *BD = CE->getBlockDecl();
3883
3884 if (isa<FunctionNoProtoType>(AFT)) {
3885 // No user-supplied arguments. Still need to pass in a pointer to the
3886 // block (to reference imported block decl refs).
3887 S += "(" + StructRef + " *__cself)";
3888 } else if (BD->param_empty()) {
3889 S += "(" + StructRef + " *__cself)";
3890 } else {
3891 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
3892 assert(FT && "SynthesizeBlockFunc: No function proto");
3893 S += '(';
3894 // first add the implicit argument.
3895 S += StructRef + " *__cself, ";
3896 std::string ParamStr;
3897 for (BlockDecl::param_iterator AI = BD->param_begin(),
3898 E = BD->param_end(); AI != E; ++AI) {
3899 if (AI != BD->param_begin()) S += ", ";
3900 ParamStr = (*AI)->getNameAsString();
3901 QualType QT = (*AI)->getType();
Fariborz Jahanian2610f902012-03-27 16:42:20 +00003902 (void)convertBlockPointerToFunctionPointer(QT);
3903 QT.getAsStringInternal(ParamStr, Context->getPrintingPolicy());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003904 S += ParamStr;
3905 }
3906 if (FT->isVariadic()) {
3907 if (!BD->param_empty()) S += ", ";
3908 S += "...";
3909 }
3910 S += ')';
3911 }
3912 S += " {\n";
3913
3914 // Create local declarations to avoid rewriting all closure decl ref exprs.
3915 // First, emit a declaration for all "by ref" decls.
3916 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3917 E = BlockByRefDecls.end(); I != E; ++I) {
3918 S += " ";
3919 std::string Name = (*I)->getNameAsString();
3920 std::string TypeString;
3921 RewriteByRefString(TypeString, Name, (*I));
3922 TypeString += " *";
3923 Name = TypeString + Name;
3924 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
3925 }
3926 // Next, emit a declaration for all "by copy" declarations.
3927 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3928 E = BlockByCopyDecls.end(); I != E; ++I) {
3929 S += " ";
3930 // Handle nested closure invocation. For example:
3931 //
3932 // void (^myImportedClosure)(void);
3933 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
3934 //
3935 // void (^anotherClosure)(void);
3936 // anotherClosure = ^(void) {
3937 // myImportedClosure(); // import and invoke the closure
3938 // };
3939 //
3940 if (isTopLevelBlockPointerType((*I)->getType())) {
3941 RewriteBlockPointerTypeVariable(S, (*I));
3942 S += " = (";
3943 RewriteBlockPointerType(S, (*I)->getType());
3944 S += ")";
3945 S += "__cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
3946 }
3947 else {
3948 std::string Name = (*I)->getNameAsString();
3949 QualType QT = (*I)->getType();
3950 if (HasLocalVariableExternalStorage(*I))
3951 QT = Context->getPointerType(QT);
3952 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
3953 S += Name + " = __cself->" +
3954 (*I)->getNameAsString() + "; // bound by copy\n";
3955 }
3956 }
3957 std::string RewrittenStr = RewrittenBlockExprs[CE];
3958 const char *cstr = RewrittenStr.c_str();
3959 while (*cstr++ != '{') ;
3960 S += cstr;
3961 S += "\n";
3962 return S;
3963}
3964
3965std::string RewriteModernObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
3966 StringRef funcName,
3967 std::string Tag) {
3968 std::string StructRef = "struct " + Tag;
3969 std::string S = "static void __";
3970
3971 S += funcName;
3972 S += "_block_copy_" + utostr(i);
3973 S += "(" + StructRef;
3974 S += "*dst, " + StructRef;
3975 S += "*src) {";
3976 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
3977 E = ImportedBlockDecls.end(); I != E; ++I) {
3978 ValueDecl *VD = (*I);
3979 S += "_Block_object_assign((void*)&dst->";
3980 S += (*I)->getNameAsString();
3981 S += ", (void*)src->";
3982 S += (*I)->getNameAsString();
3983 if (BlockByRefDeclsPtrSet.count((*I)))
3984 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
3985 else if (VD->getType()->isBlockPointerType())
3986 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
3987 else
3988 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
3989 }
3990 S += "}\n";
3991
3992 S += "\nstatic void __";
3993 S += funcName;
3994 S += "_block_dispose_" + utostr(i);
3995 S += "(" + StructRef;
3996 S += "*src) {";
3997 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
3998 E = ImportedBlockDecls.end(); I != E; ++I) {
3999 ValueDecl *VD = (*I);
4000 S += "_Block_object_dispose((void*)src->";
4001 S += (*I)->getNameAsString();
4002 if (BlockByRefDeclsPtrSet.count((*I)))
4003 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
4004 else if (VD->getType()->isBlockPointerType())
4005 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
4006 else
4007 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
4008 }
4009 S += "}\n";
4010 return S;
4011}
4012
4013std::string RewriteModernObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
4014 std::string Desc) {
4015 std::string S = "\nstruct " + Tag;
4016 std::string Constructor = " " + Tag;
4017
4018 S += " {\n struct __block_impl impl;\n";
4019 S += " struct " + Desc;
4020 S += "* Desc;\n";
4021
4022 Constructor += "(void *fp, "; // Invoke function pointer.
4023 Constructor += "struct " + Desc; // Descriptor pointer.
4024 Constructor += " *desc";
4025
4026 if (BlockDeclRefs.size()) {
4027 // Output all "by copy" declarations.
4028 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
4029 E = BlockByCopyDecls.end(); I != E; ++I) {
4030 S += " ";
4031 std::string FieldName = (*I)->getNameAsString();
4032 std::string ArgName = "_" + FieldName;
4033 // Handle nested closure invocation. For example:
4034 //
4035 // void (^myImportedBlock)(void);
4036 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
4037 //
4038 // void (^anotherBlock)(void);
4039 // anotherBlock = ^(void) {
4040 // myImportedBlock(); // import and invoke the closure
4041 // };
4042 //
4043 if (isTopLevelBlockPointerType((*I)->getType())) {
4044 S += "struct __block_impl *";
4045 Constructor += ", void *" + ArgName;
4046 } else {
4047 QualType QT = (*I)->getType();
4048 if (HasLocalVariableExternalStorage(*I))
4049 QT = Context->getPointerType(QT);
4050 QT.getAsStringInternal(FieldName, Context->getPrintingPolicy());
4051 QT.getAsStringInternal(ArgName, Context->getPrintingPolicy());
4052 Constructor += ", " + ArgName;
4053 }
4054 S += FieldName + ";\n";
4055 }
4056 // Output all "by ref" declarations.
4057 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
4058 E = BlockByRefDecls.end(); I != E; ++I) {
4059 S += " ";
4060 std::string FieldName = (*I)->getNameAsString();
4061 std::string ArgName = "_" + FieldName;
4062 {
4063 std::string TypeString;
4064 RewriteByRefString(TypeString, FieldName, (*I));
4065 TypeString += " *";
4066 FieldName = TypeString + FieldName;
4067 ArgName = TypeString + ArgName;
4068 Constructor += ", " + ArgName;
4069 }
4070 S += FieldName + "; // by ref\n";
4071 }
4072 // Finish writing the constructor.
4073 Constructor += ", int flags=0)";
4074 // Initialize all "by copy" arguments.
4075 bool firsTime = true;
4076 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
4077 E = BlockByCopyDecls.end(); I != E; ++I) {
4078 std::string Name = (*I)->getNameAsString();
4079 if (firsTime) {
4080 Constructor += " : ";
4081 firsTime = false;
4082 }
4083 else
4084 Constructor += ", ";
4085 if (isTopLevelBlockPointerType((*I)->getType()))
4086 Constructor += Name + "((struct __block_impl *)_" + Name + ")";
4087 else
4088 Constructor += Name + "(_" + Name + ")";
4089 }
4090 // Initialize all "by ref" arguments.
4091 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
4092 E = BlockByRefDecls.end(); I != E; ++I) {
4093 std::string Name = (*I)->getNameAsString();
4094 if (firsTime) {
4095 Constructor += " : ";
4096 firsTime = false;
4097 }
4098 else
4099 Constructor += ", ";
4100 Constructor += Name + "(_" + Name + "->__forwarding)";
4101 }
4102
4103 Constructor += " {\n";
4104 if (GlobalVarDecl)
4105 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4106 else
4107 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
4108 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
4109
4110 Constructor += " Desc = desc;\n";
4111 } else {
4112 // Finish writing the constructor.
4113 Constructor += ", int flags=0) {\n";
4114 if (GlobalVarDecl)
4115 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4116 else
4117 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
4118 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
4119 Constructor += " Desc = desc;\n";
4120 }
4121 Constructor += " ";
4122 Constructor += "}\n";
4123 S += Constructor;
4124 S += "};\n";
4125 return S;
4126}
4127
4128std::string RewriteModernObjC::SynthesizeBlockDescriptor(std::string DescTag,
4129 std::string ImplTag, int i,
4130 StringRef FunName,
4131 unsigned hasCopy) {
4132 std::string S = "\nstatic struct " + DescTag;
4133
Fariborz Jahanian8b08adb2012-05-03 21:44:12 +00004134 S += " {\n size_t reserved;\n";
4135 S += " size_t Block_size;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004136 if (hasCopy) {
4137 S += " void (*copy)(struct ";
4138 S += ImplTag; S += "*, struct ";
4139 S += ImplTag; S += "*);\n";
4140
4141 S += " void (*dispose)(struct ";
4142 S += ImplTag; S += "*);\n";
4143 }
4144 S += "} ";
4145
4146 S += DescTag + "_DATA = { 0, sizeof(struct ";
4147 S += ImplTag + ")";
4148 if (hasCopy) {
4149 S += ", __" + FunName.str() + "_block_copy_" + utostr(i);
4150 S += ", __" + FunName.str() + "_block_dispose_" + utostr(i);
4151 }
4152 S += "};\n";
4153 return S;
4154}
4155
Fariborz Jahanian76a98be2012-04-17 18:40:53 +00004156/// getFunctionSourceLocation - returns start location of a function
4157/// definition. Complication arises when function has declared as
4158/// extern "C" or extern "C" {...}
Fariborz Jahanianb75f8de2012-04-19 00:50:01 +00004159static SourceLocation getFunctionSourceLocation (RewriteModernObjC &R,
4160 FunctionDecl *FD) {
Fariborz Jahanianb5863da2012-04-19 16:30:28 +00004161 if (FD->isExternC() && !FD->isMain()) {
4162 const DeclContext *DC = FD->getDeclContext();
4163 if (const LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(DC))
4164 // if it is extern "C" {...}, return function decl's own location.
4165 if (!LSD->getRBraceLoc().isValid())
4166 return LSD->getExternLoc();
Fariborz Jahanianb75f8de2012-04-19 00:50:01 +00004167 }
Fariborz Jahanianb5863da2012-04-19 16:30:28 +00004168 if (FD->getStorageClassAsWritten() != SC_None)
4169 R.RewriteBlockLiteralFunctionDecl(FD);
Fariborz Jahanian76a98be2012-04-17 18:40:53 +00004170 return FD->getTypeSpecStartLoc();
4171}
4172
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004173void RewriteModernObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
4174 StringRef FunName) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004175 bool RewriteSC = (GlobalVarDecl &&
4176 !Blocks.empty() &&
4177 GlobalVarDecl->getStorageClass() == SC_Static &&
4178 GlobalVarDecl->getType().getCVRQualifiers());
4179 if (RewriteSC) {
4180 std::string SC(" void __");
4181 SC += GlobalVarDecl->getNameAsString();
4182 SC += "() {}";
4183 InsertText(FunLocStart, SC);
4184 }
4185
4186 // Insert closures that were part of the function.
4187 for (unsigned i = 0, count=0; i < Blocks.size(); i++) {
4188 CollectBlockDeclRefInfo(Blocks[i]);
4189 // Need to copy-in the inner copied-in variables not actually used in this
4190 // block.
4191 for (int j = 0; j < InnerDeclRefsCount[i]; j++) {
John McCallf4b88a42012-03-10 09:33:50 +00004192 DeclRefExpr *Exp = InnerDeclRefs[count++];
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004193 ValueDecl *VD = Exp->getDecl();
4194 BlockDeclRefs.push_back(Exp);
John McCallf4b88a42012-03-10 09:33:50 +00004195 if (!VD->hasAttr<BlocksAttr>()) {
4196 if (!BlockByCopyDeclsPtrSet.count(VD)) {
4197 BlockByCopyDeclsPtrSet.insert(VD);
4198 BlockByCopyDecls.push_back(VD);
4199 }
4200 continue;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004201 }
John McCallf4b88a42012-03-10 09:33:50 +00004202
4203 if (!BlockByRefDeclsPtrSet.count(VD)) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004204 BlockByRefDeclsPtrSet.insert(VD);
4205 BlockByRefDecls.push_back(VD);
4206 }
John McCallf4b88a42012-03-10 09:33:50 +00004207
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004208 // imported objects in the inner blocks not used in the outer
4209 // blocks must be copied/disposed in the outer block as well.
John McCallf4b88a42012-03-10 09:33:50 +00004210 if (VD->getType()->isObjCObjectPointerType() ||
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004211 VD->getType()->isBlockPointerType())
4212 ImportedBlockDecls.insert(VD);
4213 }
4214
4215 std::string ImplTag = "__" + FunName.str() + "_block_impl_" + utostr(i);
4216 std::string DescTag = "__" + FunName.str() + "_block_desc_" + utostr(i);
4217
4218 std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
4219
4220 InsertText(FunLocStart, CI);
4221
4222 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
4223
4224 InsertText(FunLocStart, CF);
4225
4226 if (ImportedBlockDecls.size()) {
4227 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
4228 InsertText(FunLocStart, HF);
4229 }
4230 std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
4231 ImportedBlockDecls.size() > 0);
4232 InsertText(FunLocStart, BD);
4233
4234 BlockDeclRefs.clear();
4235 BlockByRefDecls.clear();
4236 BlockByRefDeclsPtrSet.clear();
4237 BlockByCopyDecls.clear();
4238 BlockByCopyDeclsPtrSet.clear();
4239 ImportedBlockDecls.clear();
4240 }
4241 if (RewriteSC) {
4242 // Must insert any 'const/volatile/static here. Since it has been
4243 // removed as result of rewriting of block literals.
4244 std::string SC;
4245 if (GlobalVarDecl->getStorageClass() == SC_Static)
4246 SC = "static ";
4247 if (GlobalVarDecl->getType().isConstQualified())
4248 SC += "const ";
4249 if (GlobalVarDecl->getType().isVolatileQualified())
4250 SC += "volatile ";
4251 if (GlobalVarDecl->getType().isRestrictQualified())
4252 SC += "restrict ";
4253 InsertText(FunLocStart, SC);
4254 }
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00004255 if (GlobalConstructionExp) {
4256 // extra fancy dance for global literal expression.
4257
4258 // Always the latest block expression on the block stack.
4259 std::string Tag = "__";
4260 Tag += FunName;
4261 Tag += "_block_impl_";
4262 Tag += utostr(Blocks.size()-1);
4263 std::string globalBuf = "static ";
4264 globalBuf += Tag; globalBuf += " ";
4265 std::string SStr;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004266
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00004267 llvm::raw_string_ostream constructorExprBuf(SStr);
4268 GlobalConstructionExp->printPretty(constructorExprBuf, *Context, 0,
4269 PrintingPolicy(LangOpts));
4270 globalBuf += constructorExprBuf.str();
4271 globalBuf += ";\n";
4272 InsertText(FunLocStart, globalBuf);
4273 GlobalConstructionExp = 0;
4274 }
4275
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004276 Blocks.clear();
4277 InnerDeclRefsCount.clear();
4278 InnerDeclRefs.clear();
4279 RewrittenBlockExprs.clear();
4280}
4281
4282void RewriteModernObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
Fariborz Jahanian04189532012-04-25 17:56:48 +00004283 SourceLocation FunLocStart =
4284 (!Blocks.empty()) ? getFunctionSourceLocation(*this, FD)
4285 : FD->getTypeSpecStartLoc();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004286 StringRef FuncName = FD->getName();
4287
4288 SynthesizeBlockLiterals(FunLocStart, FuncName);
4289}
4290
4291static void BuildUniqueMethodName(std::string &Name,
4292 ObjCMethodDecl *MD) {
4293 ObjCInterfaceDecl *IFace = MD->getClassInterface();
4294 Name = IFace->getName();
4295 Name += "__" + MD->getSelector().getAsString();
4296 // Convert colons to underscores.
4297 std::string::size_type loc = 0;
4298 while ((loc = Name.find(":", loc)) != std::string::npos)
4299 Name.replace(loc, 1, "_");
4300}
4301
4302void RewriteModernObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
4303 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
4304 //SourceLocation FunLocStart = MD->getLocStart();
4305 SourceLocation FunLocStart = MD->getLocStart();
4306 std::string FuncName;
4307 BuildUniqueMethodName(FuncName, MD);
4308 SynthesizeBlockLiterals(FunLocStart, FuncName);
4309}
4310
4311void RewriteModernObjC::GetBlockDeclRefExprs(Stmt *S) {
4312 for (Stmt::child_range CI = S->children(); CI; ++CI)
4313 if (*CI) {
4314 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
4315 GetBlockDeclRefExprs(CBE->getBody());
4316 else
4317 GetBlockDeclRefExprs(*CI);
4318 }
4319 // Handle specific things.
Fariborz Jahanian0e976812012-04-16 23:00:57 +00004320 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4321 if (DRE->refersToEnclosingLocal()) {
4322 // FIXME: Handle enums.
4323 if (!isa<FunctionDecl>(DRE->getDecl()))
4324 BlockDeclRefs.push_back(DRE);
4325 if (HasLocalVariableExternalStorage(DRE->getDecl()))
4326 BlockDeclRefs.push_back(DRE);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004327 }
Fariborz Jahanian0e976812012-04-16 23:00:57 +00004328 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004329
4330 return;
4331}
4332
4333void RewriteModernObjC::GetInnerBlockDeclRefExprs(Stmt *S,
John McCallf4b88a42012-03-10 09:33:50 +00004334 SmallVector<DeclRefExpr *, 8> &InnerBlockDeclRefs,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004335 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts) {
4336 for (Stmt::child_range CI = S->children(); CI; ++CI)
4337 if (*CI) {
4338 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI)) {
4339 InnerContexts.insert(cast<DeclContext>(CBE->getBlockDecl()));
4340 GetInnerBlockDeclRefExprs(CBE->getBody(),
4341 InnerBlockDeclRefs,
4342 InnerContexts);
4343 }
4344 else
4345 GetInnerBlockDeclRefExprs(*CI,
4346 InnerBlockDeclRefs,
4347 InnerContexts);
4348
4349 }
4350 // Handle specific things.
John McCallf4b88a42012-03-10 09:33:50 +00004351 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4352 if (DRE->refersToEnclosingLocal()) {
4353 if (!isa<FunctionDecl>(DRE->getDecl()) &&
4354 !InnerContexts.count(DRE->getDecl()->getDeclContext()))
4355 InnerBlockDeclRefs.push_back(DRE);
4356 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl()))
4357 if (Var->isFunctionOrMethodVarDecl())
4358 ImportedLocalExternalDecls.insert(Var);
4359 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004360 }
4361
4362 return;
4363}
4364
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00004365/// convertObjCTypeToCStyleType - This routine converts such objc types
4366/// as qualified objects, and blocks to their closest c/c++ types that
4367/// it can. It returns true if input type was modified.
4368bool RewriteModernObjC::convertObjCTypeToCStyleType(QualType &T) {
4369 QualType oldT = T;
4370 convertBlockPointerToFunctionPointer(T);
4371 if (T->isFunctionPointerType()) {
4372 QualType PointeeTy;
4373 if (const PointerType* PT = T->getAs<PointerType>()) {
4374 PointeeTy = PT->getPointeeType();
4375 if (const FunctionType *FT = PointeeTy->getAs<FunctionType>()) {
4376 T = convertFunctionTypeOfBlocks(FT);
4377 T = Context->getPointerType(T);
4378 }
4379 }
4380 }
4381
4382 convertToUnqualifiedObjCType(T);
4383 return T != oldT;
4384}
4385
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004386/// convertFunctionTypeOfBlocks - This routine converts a function type
4387/// whose result type may be a block pointer or whose argument type(s)
4388/// might be block pointers to an equivalent function type replacing
4389/// all block pointers to function pointers.
4390QualType RewriteModernObjC::convertFunctionTypeOfBlocks(const FunctionType *FT) {
4391 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
4392 // FTP will be null for closures that don't take arguments.
4393 // Generate a funky cast.
4394 SmallVector<QualType, 8> ArgTypes;
4395 QualType Res = FT->getResultType();
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00004396 bool modified = convertObjCTypeToCStyleType(Res);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004397
4398 if (FTP) {
4399 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4400 E = FTP->arg_type_end(); I && (I != E); ++I) {
4401 QualType t = *I;
4402 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00004403 if (convertObjCTypeToCStyleType(t))
4404 modified = true;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004405 ArgTypes.push_back(t);
4406 }
4407 }
4408 QualType FuncType;
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00004409 if (modified)
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004410 FuncType = getSimpleFunctionType(Res, &ArgTypes[0], ArgTypes.size());
4411 else FuncType = QualType(FT, 0);
4412 return FuncType;
4413}
4414
4415Stmt *RewriteModernObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
4416 // Navigate to relevant type information.
4417 const BlockPointerType *CPT = 0;
4418
4419 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
4420 CPT = DRE->getType()->getAs<BlockPointerType>();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004421 } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
4422 CPT = MExpr->getType()->getAs<BlockPointerType>();
4423 }
4424 else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
4425 return SynthesizeBlockCall(Exp, PRE->getSubExpr());
4426 }
4427 else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
4428 CPT = IEXPR->getType()->getAs<BlockPointerType>();
4429 else if (const ConditionalOperator *CEXPR =
4430 dyn_cast<ConditionalOperator>(BlockExp)) {
4431 Expr *LHSExp = CEXPR->getLHS();
4432 Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
4433 Expr *RHSExp = CEXPR->getRHS();
4434 Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
4435 Expr *CONDExp = CEXPR->getCond();
4436 ConditionalOperator *CondExpr =
4437 new (Context) ConditionalOperator(CONDExp,
4438 SourceLocation(), cast<Expr>(LHSStmt),
4439 SourceLocation(), cast<Expr>(RHSStmt),
4440 Exp->getType(), VK_RValue, OK_Ordinary);
4441 return CondExpr;
4442 } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
4443 CPT = IRE->getType()->getAs<BlockPointerType>();
4444 } else if (const PseudoObjectExpr *POE
4445 = dyn_cast<PseudoObjectExpr>(BlockExp)) {
4446 CPT = POE->getType()->castAs<BlockPointerType>();
4447 } else {
4448 assert(1 && "RewriteBlockClass: Bad type");
4449 }
4450 assert(CPT && "RewriteBlockClass: Bad type");
4451 const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
4452 assert(FT && "RewriteBlockClass: Bad type");
4453 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
4454 // FTP will be null for closures that don't take arguments.
4455
4456 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
4457 SourceLocation(), SourceLocation(),
4458 &Context->Idents.get("__block_impl"));
4459 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
4460
4461 // Generate a funky cast.
4462 SmallVector<QualType, 8> ArgTypes;
4463
4464 // Push the block argument type.
4465 ArgTypes.push_back(PtrBlock);
4466 if (FTP) {
4467 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4468 E = FTP->arg_type_end(); I && (I != E); ++I) {
4469 QualType t = *I;
4470 // Make sure we convert "t (^)(...)" to "t (*)(...)".
4471 if (!convertBlockPointerToFunctionPointer(t))
4472 convertToUnqualifiedObjCType(t);
4473 ArgTypes.push_back(t);
4474 }
4475 }
4476 // Now do the pointer to function cast.
4477 QualType PtrToFuncCastType
4478 = getSimpleFunctionType(Exp->getType(), &ArgTypes[0], ArgTypes.size());
4479
4480 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
4481
4482 CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock,
4483 CK_BitCast,
4484 const_cast<Expr*>(BlockExp));
4485 // Don't forget the parens to enforce the proper binding.
4486 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4487 BlkCast);
4488 //PE->dump();
4489
4490 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4491 SourceLocation(),
4492 &Context->Idents.get("FuncPtr"),
4493 Context->VoidPtrTy, 0,
4494 /*BitWidth=*/0, /*Mutable=*/true,
4495 /*HasInit=*/false);
4496 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
4497 FD->getType(), VK_LValue,
4498 OK_Ordinary);
4499
4500
4501 CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType,
4502 CK_BitCast, ME);
4503 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
4504
4505 SmallVector<Expr*, 8> BlkExprs;
4506 // Add the implicit argument.
4507 BlkExprs.push_back(BlkCast);
4508 // Add the user arguments.
4509 for (CallExpr::arg_iterator I = Exp->arg_begin(),
4510 E = Exp->arg_end(); I != E; ++I) {
4511 BlkExprs.push_back(*I);
4512 }
4513 CallExpr *CE = new (Context) CallExpr(*Context, PE, &BlkExprs[0],
4514 BlkExprs.size(),
4515 Exp->getType(), VK_RValue,
4516 SourceLocation());
4517 return CE;
4518}
4519
4520// We need to return the rewritten expression to handle cases where the
John McCallf4b88a42012-03-10 09:33:50 +00004521// DeclRefExpr is embedded in another expression being rewritten.
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004522// For example:
4523//
4524// int main() {
4525// __block Foo *f;
4526// __block int i;
4527//
4528// void (^myblock)() = ^() {
John McCallf4b88a42012-03-10 09:33:50 +00004529// [f test]; // f is a DeclRefExpr embedded in a message (which is being rewritten).
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004530// i = 77;
4531// };
4532//}
John McCallf4b88a42012-03-10 09:33:50 +00004533Stmt *RewriteModernObjC::RewriteBlockDeclRefExpr(DeclRefExpr *DeclRefExp) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004534 // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
4535 // for each DeclRefExp where BYREFVAR is name of the variable.
John McCallf4b88a42012-03-10 09:33:50 +00004536 ValueDecl *VD = DeclRefExp->getDecl();
4537 bool isArrow = DeclRefExp->refersToEnclosingLocal();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004538
4539 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4540 SourceLocation(),
4541 &Context->Idents.get("__forwarding"),
4542 Context->VoidPtrTy, 0,
4543 /*BitWidth=*/0, /*Mutable=*/true,
4544 /*HasInit=*/false);
4545 MemberExpr *ME = new (Context) MemberExpr(DeclRefExp, isArrow,
4546 FD, SourceLocation(),
4547 FD->getType(), VK_LValue,
4548 OK_Ordinary);
4549
4550 StringRef Name = VD->getName();
4551 FD = FieldDecl::Create(*Context, 0, SourceLocation(), SourceLocation(),
4552 &Context->Idents.get(Name),
4553 Context->VoidPtrTy, 0,
4554 /*BitWidth=*/0, /*Mutable=*/true,
4555 /*HasInit=*/false);
4556 ME = new (Context) MemberExpr(ME, true, FD, SourceLocation(),
4557 DeclRefExp->getType(), VK_LValue, OK_Ordinary);
4558
4559
4560
4561 // Need parens to enforce precedence.
4562 ParenExpr *PE = new (Context) ParenExpr(DeclRefExp->getExprLoc(),
4563 DeclRefExp->getExprLoc(),
4564 ME);
4565 ReplaceStmt(DeclRefExp, PE);
4566 return PE;
4567}
4568
4569// Rewrites the imported local variable V with external storage
4570// (static, extern, etc.) as *V
4571//
4572Stmt *RewriteModernObjC::RewriteLocalVariableExternalStorage(DeclRefExpr *DRE) {
4573 ValueDecl *VD = DRE->getDecl();
4574 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4575 if (!ImportedLocalExternalDecls.count(Var))
4576 return DRE;
4577 Expr *Exp = new (Context) UnaryOperator(DRE, UO_Deref, DRE->getType(),
4578 VK_LValue, OK_Ordinary,
4579 DRE->getLocation());
4580 // Need parens to enforce precedence.
4581 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4582 Exp);
4583 ReplaceStmt(DRE, PE);
4584 return PE;
4585}
4586
4587void RewriteModernObjC::RewriteCastExpr(CStyleCastExpr *CE) {
4588 SourceLocation LocStart = CE->getLParenLoc();
4589 SourceLocation LocEnd = CE->getRParenLoc();
4590
4591 // Need to avoid trying to rewrite synthesized casts.
4592 if (LocStart.isInvalid())
4593 return;
4594 // Need to avoid trying to rewrite casts contained in macros.
4595 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
4596 return;
4597
4598 const char *startBuf = SM->getCharacterData(LocStart);
4599 const char *endBuf = SM->getCharacterData(LocEnd);
4600 QualType QT = CE->getType();
4601 const Type* TypePtr = QT->getAs<Type>();
4602 if (isa<TypeOfExprType>(TypePtr)) {
4603 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
4604 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
4605 std::string TypeAsString = "(";
4606 RewriteBlockPointerType(TypeAsString, QT);
4607 TypeAsString += ")";
4608 ReplaceText(LocStart, endBuf-startBuf+1, TypeAsString);
4609 return;
4610 }
4611 // advance the location to startArgList.
4612 const char *argPtr = startBuf;
4613
4614 while (*argPtr++ && (argPtr < endBuf)) {
4615 switch (*argPtr) {
4616 case '^':
4617 // Replace the '^' with '*'.
4618 LocStart = LocStart.getLocWithOffset(argPtr-startBuf);
4619 ReplaceText(LocStart, 1, "*");
4620 break;
4621 }
4622 }
4623 return;
4624}
4625
Fariborz Jahanianf1ee6872012-04-10 00:08:18 +00004626void RewriteModernObjC::RewriteImplicitCastObjCExpr(CastExpr *IC) {
4627 CastKind CastKind = IC->getCastKind();
Fariborz Jahanian43aa1c32012-04-16 22:14:01 +00004628 if (CastKind != CK_BlockPointerToObjCPointerCast &&
4629 CastKind != CK_AnyPointerToBlockPointerCast)
4630 return;
Fariborz Jahanianf1ee6872012-04-10 00:08:18 +00004631
Fariborz Jahanian43aa1c32012-04-16 22:14:01 +00004632 QualType QT = IC->getType();
4633 (void)convertBlockPointerToFunctionPointer(QT);
4634 std::string TypeString(QT.getAsString(Context->getPrintingPolicy()));
4635 std::string Str = "(";
4636 Str += TypeString;
4637 Str += ")";
4638 InsertText(IC->getSubExpr()->getLocStart(), &Str[0], Str.size());
4639
Fariborz Jahanianf1ee6872012-04-10 00:08:18 +00004640 return;
4641}
4642
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004643void RewriteModernObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
4644 SourceLocation DeclLoc = FD->getLocation();
4645 unsigned parenCount = 0;
4646
4647 // We have 1 or more arguments that have closure pointers.
4648 const char *startBuf = SM->getCharacterData(DeclLoc);
4649 const char *startArgList = strchr(startBuf, '(');
4650
4651 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
4652
4653 parenCount++;
4654 // advance the location to startArgList.
4655 DeclLoc = DeclLoc.getLocWithOffset(startArgList-startBuf);
4656 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
4657
4658 const char *argPtr = startArgList;
4659
4660 while (*argPtr++ && parenCount) {
4661 switch (*argPtr) {
4662 case '^':
4663 // Replace the '^' with '*'.
4664 DeclLoc = DeclLoc.getLocWithOffset(argPtr-startArgList);
4665 ReplaceText(DeclLoc, 1, "*");
4666 break;
4667 case '(':
4668 parenCount++;
4669 break;
4670 case ')':
4671 parenCount--;
4672 break;
4673 }
4674 }
4675 return;
4676}
4677
4678bool RewriteModernObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
4679 const FunctionProtoType *FTP;
4680 const PointerType *PT = QT->getAs<PointerType>();
4681 if (PT) {
4682 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4683 } else {
4684 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4685 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4686 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4687 }
4688 if (FTP) {
4689 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4690 E = FTP->arg_type_end(); I != E; ++I)
4691 if (isTopLevelBlockPointerType(*I))
4692 return true;
4693 }
4694 return false;
4695}
4696
4697bool RewriteModernObjC::PointerTypeTakesAnyObjCQualifiedType(QualType QT) {
4698 const FunctionProtoType *FTP;
4699 const PointerType *PT = QT->getAs<PointerType>();
4700 if (PT) {
4701 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4702 } else {
4703 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4704 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4705 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4706 }
4707 if (FTP) {
4708 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4709 E = FTP->arg_type_end(); I != E; ++I) {
4710 if ((*I)->isObjCQualifiedIdType())
4711 return true;
4712 if ((*I)->isObjCObjectPointerType() &&
4713 (*I)->getPointeeType()->isObjCQualifiedInterfaceType())
4714 return true;
4715 }
4716
4717 }
4718 return false;
4719}
4720
4721void RewriteModernObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
4722 const char *&RParen) {
4723 const char *argPtr = strchr(Name, '(');
4724 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
4725
4726 LParen = argPtr; // output the start.
4727 argPtr++; // skip past the left paren.
4728 unsigned parenCount = 1;
4729
4730 while (*argPtr && parenCount) {
4731 switch (*argPtr) {
4732 case '(': parenCount++; break;
4733 case ')': parenCount--; break;
4734 default: break;
4735 }
4736 if (parenCount) argPtr++;
4737 }
4738 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
4739 RParen = argPtr; // output the end
4740}
4741
4742void RewriteModernObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
4743 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4744 RewriteBlockPointerFunctionArgs(FD);
4745 return;
4746 }
4747 // Handle Variables and Typedefs.
4748 SourceLocation DeclLoc = ND->getLocation();
4749 QualType DeclT;
4750 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
4751 DeclT = VD->getType();
4752 else if (TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(ND))
4753 DeclT = TDD->getUnderlyingType();
4754 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
4755 DeclT = FD->getType();
4756 else
4757 llvm_unreachable("RewriteBlockPointerDecl(): Decl type not yet handled");
4758
4759 const char *startBuf = SM->getCharacterData(DeclLoc);
4760 const char *endBuf = startBuf;
4761 // scan backward (from the decl location) for the end of the previous decl.
4762 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
4763 startBuf--;
4764 SourceLocation Start = DeclLoc.getLocWithOffset(startBuf-endBuf);
4765 std::string buf;
4766 unsigned OrigLength=0;
4767 // *startBuf != '^' if we are dealing with a pointer to function that
4768 // may take block argument types (which will be handled below).
4769 if (*startBuf == '^') {
4770 // Replace the '^' with '*', computing a negative offset.
4771 buf = '*';
4772 startBuf++;
4773 OrigLength++;
4774 }
4775 while (*startBuf != ')') {
4776 buf += *startBuf;
4777 startBuf++;
4778 OrigLength++;
4779 }
4780 buf += ')';
4781 OrigLength++;
4782
4783 if (PointerTypeTakesAnyBlockArguments(DeclT) ||
4784 PointerTypeTakesAnyObjCQualifiedType(DeclT)) {
4785 // Replace the '^' with '*' for arguments.
4786 // Replace id<P> with id/*<>*/
4787 DeclLoc = ND->getLocation();
4788 startBuf = SM->getCharacterData(DeclLoc);
4789 const char *argListBegin, *argListEnd;
4790 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
4791 while (argListBegin < argListEnd) {
4792 if (*argListBegin == '^')
4793 buf += '*';
4794 else if (*argListBegin == '<') {
4795 buf += "/*";
4796 buf += *argListBegin++;
4797 OrigLength++;;
4798 while (*argListBegin != '>') {
4799 buf += *argListBegin++;
4800 OrigLength++;
4801 }
4802 buf += *argListBegin;
4803 buf += "*/";
4804 }
4805 else
4806 buf += *argListBegin;
4807 argListBegin++;
4808 OrigLength++;
4809 }
4810 buf += ')';
4811 OrigLength++;
4812 }
4813 ReplaceText(Start, OrigLength, buf);
4814
4815 return;
4816}
4817
4818
4819/// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
4820/// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
4821/// struct Block_byref_id_object *src) {
4822/// _Block_object_assign (&_dest->object, _src->object,
4823/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4824/// [|BLOCK_FIELD_IS_WEAK]) // object
4825/// _Block_object_assign(&_dest->object, _src->object,
4826/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4827/// [|BLOCK_FIELD_IS_WEAK]) // block
4828/// }
4829/// And:
4830/// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
4831/// _Block_object_dispose(_src->object,
4832/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4833/// [|BLOCK_FIELD_IS_WEAK]) // object
4834/// _Block_object_dispose(_src->object,
4835/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4836/// [|BLOCK_FIELD_IS_WEAK]) // block
4837/// }
4838
4839std::string RewriteModernObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
4840 int flag) {
4841 std::string S;
4842 if (CopyDestroyCache.count(flag))
4843 return S;
4844 CopyDestroyCache.insert(flag);
4845 S = "static void __Block_byref_id_object_copy_";
4846 S += utostr(flag);
4847 S += "(void *dst, void *src) {\n";
4848
4849 // offset into the object pointer is computed as:
4850 // void * + void* + int + int + void* + void *
4851 unsigned IntSize =
4852 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
4853 unsigned VoidPtrSize =
4854 static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
4855
4856 unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/Context->getCharWidth();
4857 S += " _Block_object_assign((char*)dst + ";
4858 S += utostr(offset);
4859 S += ", *(void * *) ((char*)src + ";
4860 S += utostr(offset);
4861 S += "), ";
4862 S += utostr(flag);
4863 S += ");\n}\n";
4864
4865 S += "static void __Block_byref_id_object_dispose_";
4866 S += utostr(flag);
4867 S += "(void *src) {\n";
4868 S += " _Block_object_dispose(*(void * *) ((char*)src + ";
4869 S += utostr(offset);
4870 S += "), ";
4871 S += utostr(flag);
4872 S += ");\n}\n";
4873 return S;
4874}
4875
4876/// RewriteByRefVar - For each __block typex ND variable this routine transforms
4877/// the declaration into:
4878/// struct __Block_byref_ND {
4879/// void *__isa; // NULL for everything except __weak pointers
4880/// struct __Block_byref_ND *__forwarding;
4881/// int32_t __flags;
4882/// int32_t __size;
4883/// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
4884/// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
4885/// typex ND;
4886/// };
4887///
4888/// It then replaces declaration of ND variable with:
4889/// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
4890/// __size=sizeof(struct __Block_byref_ND),
4891/// ND=initializer-if-any};
4892///
4893///
Fariborz Jahanian4fe261c2012-04-24 19:38:45 +00004894void RewriteModernObjC::RewriteByRefVar(VarDecl *ND, bool firstDecl,
4895 bool lastDecl) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004896 int flag = 0;
4897 int isa = 0;
4898 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
4899 if (DeclLoc.isInvalid())
4900 // If type location is missing, it is because of missing type (a warning).
4901 // Use variable's location which is good for this case.
4902 DeclLoc = ND->getLocation();
4903 const char *startBuf = SM->getCharacterData(DeclLoc);
4904 SourceLocation X = ND->getLocEnd();
4905 X = SM->getExpansionLoc(X);
4906 const char *endBuf = SM->getCharacterData(X);
4907 std::string Name(ND->getNameAsString());
4908 std::string ByrefType;
4909 RewriteByRefString(ByrefType, Name, ND, true);
4910 ByrefType += " {\n";
4911 ByrefType += " void *__isa;\n";
4912 RewriteByRefString(ByrefType, Name, ND);
4913 ByrefType += " *__forwarding;\n";
4914 ByrefType += " int __flags;\n";
4915 ByrefType += " int __size;\n";
4916 // Add void *__Block_byref_id_object_copy;
4917 // void *__Block_byref_id_object_dispose; if needed.
4918 QualType Ty = ND->getType();
4919 bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty);
4920 if (HasCopyAndDispose) {
4921 ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
4922 ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
4923 }
4924
4925 QualType T = Ty;
4926 (void)convertBlockPointerToFunctionPointer(T);
4927 T.getAsStringInternal(Name, Context->getPrintingPolicy());
4928
4929 ByrefType += " " + Name + ";\n";
4930 ByrefType += "};\n";
4931 // Insert this type in global scope. It is needed by helper function.
4932 SourceLocation FunLocStart;
4933 if (CurFunctionDef)
Fariborz Jahanianb75f8de2012-04-19 00:50:01 +00004934 FunLocStart = getFunctionSourceLocation(*this, CurFunctionDef);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004935 else {
4936 assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null");
4937 FunLocStart = CurMethodDef->getLocStart();
4938 }
4939 InsertText(FunLocStart, ByrefType);
Fariborz Jahanian8247c4e2012-04-24 16:45:27 +00004940
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004941 if (Ty.isObjCGCWeak()) {
4942 flag |= BLOCK_FIELD_IS_WEAK;
4943 isa = 1;
4944 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004945 if (HasCopyAndDispose) {
4946 flag = BLOCK_BYREF_CALLER;
4947 QualType Ty = ND->getType();
4948 // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
4949 if (Ty->isBlockPointerType())
4950 flag |= BLOCK_FIELD_IS_BLOCK;
4951 else
4952 flag |= BLOCK_FIELD_IS_OBJECT;
4953 std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
4954 if (!HF.empty())
4955 InsertText(FunLocStart, HF);
4956 }
4957
4958 // struct __Block_byref_ND ND =
4959 // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
4960 // initializer-if-any};
4961 bool hasInit = (ND->getInit() != 0);
Fariborz Jahanian104dbf92012-04-11 23:57:12 +00004962 // FIXME. rewriter does not support __block c++ objects which
4963 // require construction.
Fariborz Jahanian65a7c682012-04-26 23:20:25 +00004964 if (hasInit)
4965 if (CXXConstructExpr *CExp = dyn_cast<CXXConstructExpr>(ND->getInit())) {
4966 CXXConstructorDecl *CXXDecl = CExp->getConstructor();
4967 if (CXXDecl && CXXDecl->isDefaultConstructor())
4968 hasInit = false;
4969 }
4970
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004971 unsigned flags = 0;
4972 if (HasCopyAndDispose)
4973 flags |= BLOCK_HAS_COPY_DISPOSE;
4974 Name = ND->getNameAsString();
4975 ByrefType.clear();
4976 RewriteByRefString(ByrefType, Name, ND);
4977 std::string ForwardingCastType("(");
4978 ForwardingCastType += ByrefType + " *)";
Fariborz Jahanian8247c4e2012-04-24 16:45:27 +00004979 ByrefType += " " + Name + " = {(void*)";
4980 ByrefType += utostr(isa);
4981 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
4982 ByrefType += utostr(flags);
4983 ByrefType += ", ";
4984 ByrefType += "sizeof(";
4985 RewriteByRefString(ByrefType, Name, ND);
4986 ByrefType += ")";
4987 if (HasCopyAndDispose) {
4988 ByrefType += ", __Block_byref_id_object_copy_";
4989 ByrefType += utostr(flag);
4990 ByrefType += ", __Block_byref_id_object_dispose_";
4991 ByrefType += utostr(flag);
4992 }
4993
Fariborz Jahanian4fe261c2012-04-24 19:38:45 +00004994 if (!firstDecl) {
4995 // In multiple __block declarations, and for all but 1st declaration,
4996 // find location of the separating comma. This would be start location
4997 // where new text is to be inserted.
4998 DeclLoc = ND->getLocation();
4999 const char *startDeclBuf = SM->getCharacterData(DeclLoc);
5000 const char *commaBuf = startDeclBuf;
5001 while (*commaBuf != ',')
5002 commaBuf--;
5003 assert((*commaBuf == ',') && "RewriteByRefVar: can't find ','");
5004 DeclLoc = DeclLoc.getLocWithOffset(commaBuf - startDeclBuf);
5005 startBuf = commaBuf;
5006 }
5007
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005008 if (!hasInit) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005009 ByrefType += "};\n";
5010 unsigned nameSize = Name.size();
5011 // for block or function pointer declaration. Name is aleady
5012 // part of the declaration.
5013 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType())
5014 nameSize = 1;
5015 ReplaceText(DeclLoc, endBuf-startBuf+nameSize, ByrefType);
5016 }
5017 else {
Fariborz Jahanian8247c4e2012-04-24 16:45:27 +00005018 ByrefType += ", ";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005019 SourceLocation startLoc;
5020 Expr *E = ND->getInit();
5021 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
5022 startLoc = ECE->getLParenLoc();
5023 else
5024 startLoc = E->getLocStart();
5025 startLoc = SM->getExpansionLoc(startLoc);
5026 endBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005027 ReplaceText(DeclLoc, endBuf-startBuf, ByrefType);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005028
Fariborz Jahanian4fe261c2012-04-24 19:38:45 +00005029 const char separator = lastDecl ? ';' : ',';
5030 const char *startInitializerBuf = SM->getCharacterData(startLoc);
5031 const char *separatorBuf = strchr(startInitializerBuf, separator);
5032 assert((*separatorBuf == separator) &&
5033 "RewriteByRefVar: can't find ';' or ','");
5034 SourceLocation separatorLoc =
5035 startLoc.getLocWithOffset(separatorBuf-startInitializerBuf);
5036
5037 InsertText(separatorLoc, lastDecl ? "}" : "};\n");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005038 }
5039 return;
5040}
5041
5042void RewriteModernObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
5043 // Add initializers for any closure decl refs.
5044 GetBlockDeclRefExprs(Exp->getBody());
5045 if (BlockDeclRefs.size()) {
5046 // Unique all "by copy" declarations.
5047 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00005048 if (!BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005049 if (!BlockByCopyDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
5050 BlockByCopyDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
5051 BlockByCopyDecls.push_back(BlockDeclRefs[i]->getDecl());
5052 }
5053 }
5054 // Unique all "by ref" declarations.
5055 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00005056 if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005057 if (!BlockByRefDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
5058 BlockByRefDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
5059 BlockByRefDecls.push_back(BlockDeclRefs[i]->getDecl());
5060 }
5061 }
5062 // Find any imported blocks...they will need special attention.
5063 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00005064 if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005065 BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
5066 BlockDeclRefs[i]->getType()->isBlockPointerType())
5067 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
5068 }
5069}
5070
5071FunctionDecl *RewriteModernObjC::SynthBlockInitFunctionDecl(StringRef name) {
5072 IdentifierInfo *ID = &Context->Idents.get(name);
5073 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
5074 return FunctionDecl::Create(*Context, TUDecl, SourceLocation(),
5075 SourceLocation(), ID, FType, 0, SC_Extern,
5076 SC_None, false, false);
5077}
5078
5079Stmt *RewriteModernObjC::SynthBlockInitExpr(BlockExpr *Exp,
John McCallf4b88a42012-03-10 09:33:50 +00005080 const SmallVector<DeclRefExpr *, 8> &InnerBlockDeclRefs) {
Fariborz Jahaniand13c2c22012-03-22 19:54:39 +00005081
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005082 const BlockDecl *block = Exp->getBlockDecl();
Fariborz Jahaniand13c2c22012-03-22 19:54:39 +00005083
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005084 Blocks.push_back(Exp);
5085
5086 CollectBlockDeclRefInfo(Exp);
5087
5088 // Add inner imported variables now used in current block.
5089 int countOfInnerDecls = 0;
5090 if (!InnerBlockDeclRefs.empty()) {
5091 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++) {
John McCallf4b88a42012-03-10 09:33:50 +00005092 DeclRefExpr *Exp = InnerBlockDeclRefs[i];
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005093 ValueDecl *VD = Exp->getDecl();
John McCallf4b88a42012-03-10 09:33:50 +00005094 if (!VD->hasAttr<BlocksAttr>() && !BlockByCopyDeclsPtrSet.count(VD)) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005095 // We need to save the copied-in variables in nested
5096 // blocks because it is needed at the end for some of the API generations.
5097 // See SynthesizeBlockLiterals routine.
5098 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5099 BlockDeclRefs.push_back(Exp);
5100 BlockByCopyDeclsPtrSet.insert(VD);
5101 BlockByCopyDecls.push_back(VD);
5102 }
John McCallf4b88a42012-03-10 09:33:50 +00005103 if (VD->hasAttr<BlocksAttr>() && !BlockByRefDeclsPtrSet.count(VD)) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005104 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5105 BlockDeclRefs.push_back(Exp);
5106 BlockByRefDeclsPtrSet.insert(VD);
5107 BlockByRefDecls.push_back(VD);
5108 }
5109 }
5110 // Find any imported blocks...they will need special attention.
5111 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00005112 if (InnerBlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005113 InnerBlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
5114 InnerBlockDeclRefs[i]->getType()->isBlockPointerType())
5115 ImportedBlockDecls.insert(InnerBlockDeclRefs[i]->getDecl());
5116 }
5117 InnerDeclRefsCount.push_back(countOfInnerDecls);
5118
5119 std::string FuncName;
5120
5121 if (CurFunctionDef)
5122 FuncName = CurFunctionDef->getNameAsString();
5123 else if (CurMethodDef)
5124 BuildUniqueMethodName(FuncName, CurMethodDef);
5125 else if (GlobalVarDecl)
5126 FuncName = std::string(GlobalVarDecl->getNameAsString());
5127
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00005128 bool GlobalBlockExpr =
5129 block->getDeclContext()->getRedeclContext()->isFileContext();
5130
5131 if (GlobalBlockExpr && !GlobalVarDecl) {
5132 Diags.Report(block->getLocation(), GlobalBlockRewriteFailedDiag);
5133 GlobalBlockExpr = false;
5134 }
5135
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005136 std::string BlockNumber = utostr(Blocks.size()-1);
5137
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005138 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
5139
5140 // Get a pointer to the function type so we can cast appropriately.
5141 QualType BFT = convertFunctionTypeOfBlocks(Exp->getFunctionType());
5142 QualType FType = Context->getPointerType(BFT);
5143
5144 FunctionDecl *FD;
5145 Expr *NewRep;
5146
5147 // Simulate a contructor call...
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00005148 std::string Tag;
5149
5150 if (GlobalBlockExpr)
5151 Tag = "__global_";
5152 else
5153 Tag = "__";
5154 Tag += FuncName + "_block_impl_" + BlockNumber;
5155
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005156 FD = SynthBlockInitFunctionDecl(Tag);
John McCallf4b88a42012-03-10 09:33:50 +00005157 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, false, FType, VK_RValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005158 SourceLocation());
5159
5160 SmallVector<Expr*, 4> InitExprs;
5161
5162 // Initialize the block function.
5163 FD = SynthBlockInitFunctionDecl(Func);
John McCallf4b88a42012-03-10 09:33:50 +00005164 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, false, FD->getType(),
5165 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005166 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
5167 CK_BitCast, Arg);
5168 InitExprs.push_back(castExpr);
5169
5170 // Initialize the block descriptor.
5171 std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
5172
5173 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl,
5174 SourceLocation(), SourceLocation(),
5175 &Context->Idents.get(DescData.c_str()),
5176 Context->VoidPtrTy, 0,
5177 SC_Static, SC_None);
5178 UnaryOperator *DescRefExpr =
John McCallf4b88a42012-03-10 09:33:50 +00005179 new (Context) UnaryOperator(new (Context) DeclRefExpr(NewVD, false,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005180 Context->VoidPtrTy,
5181 VK_LValue,
5182 SourceLocation()),
5183 UO_AddrOf,
5184 Context->getPointerType(Context->VoidPtrTy),
5185 VK_RValue, OK_Ordinary,
5186 SourceLocation());
5187 InitExprs.push_back(DescRefExpr);
5188
5189 // Add initializers for any closure decl refs.
5190 if (BlockDeclRefs.size()) {
5191 Expr *Exp;
5192 // Output all "by copy" declarations.
5193 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
5194 E = BlockByCopyDecls.end(); I != E; ++I) {
5195 if (isObjCType((*I)->getType())) {
5196 // FIXME: Conform to ABI ([[obj retain] autorelease]).
5197 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00005198 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(),
5199 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005200 if (HasLocalVariableExternalStorage(*I)) {
5201 QualType QT = (*I)->getType();
5202 QT = Context->getPointerType(QT);
5203 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
5204 OK_Ordinary, SourceLocation());
5205 }
5206 } else if (isTopLevelBlockPointerType((*I)->getType())) {
5207 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00005208 Arg = new (Context) DeclRefExpr(FD, false, FD->getType(),
5209 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005210 Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
5211 CK_BitCast, Arg);
5212 } else {
5213 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00005214 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(),
5215 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005216 if (HasLocalVariableExternalStorage(*I)) {
5217 QualType QT = (*I)->getType();
5218 QT = Context->getPointerType(QT);
5219 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
5220 OK_Ordinary, SourceLocation());
5221 }
5222
5223 }
5224 InitExprs.push_back(Exp);
5225 }
5226 // Output all "by ref" declarations.
5227 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
5228 E = BlockByRefDecls.end(); I != E; ++I) {
5229 ValueDecl *ND = (*I);
5230 std::string Name(ND->getNameAsString());
5231 std::string RecName;
5232 RewriteByRefString(RecName, Name, ND, true);
5233 IdentifierInfo *II = &Context->Idents.get(RecName.c_str()
5234 + sizeof("struct"));
5235 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
5236 SourceLocation(), SourceLocation(),
5237 II);
5238 assert(RD && "SynthBlockInitExpr(): Can't find RecordDecl");
5239 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
5240
5241 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00005242 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(), VK_LValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005243 SourceLocation());
5244 bool isNestedCapturedVar = false;
5245 if (block)
5246 for (BlockDecl::capture_const_iterator ci = block->capture_begin(),
5247 ce = block->capture_end(); ci != ce; ++ci) {
5248 const VarDecl *variable = ci->getVariable();
5249 if (variable == ND && ci->isNested()) {
5250 assert (ci->isByRef() &&
5251 "SynthBlockInitExpr - captured block variable is not byref");
5252 isNestedCapturedVar = true;
5253 break;
5254 }
5255 }
5256 // captured nested byref variable has its address passed. Do not take
5257 // its address again.
5258 if (!isNestedCapturedVar)
5259 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf,
5260 Context->getPointerType(Exp->getType()),
5261 VK_RValue, OK_Ordinary, SourceLocation());
5262 Exp = NoTypeInfoCStyleCastExpr(Context, castT, CK_BitCast, Exp);
5263 InitExprs.push_back(Exp);
5264 }
5265 }
5266 if (ImportedBlockDecls.size()) {
5267 // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
5268 int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
5269 unsigned IntSize =
5270 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
5271 Expr *FlagExp = IntegerLiteral::Create(*Context, llvm::APInt(IntSize, flag),
5272 Context->IntTy, SourceLocation());
5273 InitExprs.push_back(FlagExp);
5274 }
5275 NewRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0], InitExprs.size(),
5276 FType, VK_LValue, SourceLocation());
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00005277
5278 if (GlobalBlockExpr) {
5279 assert (GlobalConstructionExp == 0 &&
5280 "SynthBlockInitExpr - GlobalConstructionExp must be null");
5281 GlobalConstructionExp = NewRep;
5282 NewRep = DRE;
5283 }
5284
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005285 NewRep = new (Context) UnaryOperator(NewRep, UO_AddrOf,
5286 Context->getPointerType(NewRep->getType()),
5287 VK_RValue, OK_Ordinary, SourceLocation());
5288 NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CK_BitCast,
5289 NewRep);
5290 BlockDeclRefs.clear();
5291 BlockByRefDecls.clear();
5292 BlockByRefDeclsPtrSet.clear();
5293 BlockByCopyDecls.clear();
5294 BlockByCopyDeclsPtrSet.clear();
5295 ImportedBlockDecls.clear();
5296 return NewRep;
5297}
5298
5299bool RewriteModernObjC::IsDeclStmtInForeachHeader(DeclStmt *DS) {
5300 if (const ObjCForCollectionStmt * CS =
5301 dyn_cast<ObjCForCollectionStmt>(Stmts.back()))
5302 return CS->getElement() == DS;
5303 return false;
5304}
5305
5306//===----------------------------------------------------------------------===//
5307// Function Body / Expression rewriting
5308//===----------------------------------------------------------------------===//
5309
5310Stmt *RewriteModernObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
5311 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
5312 isa<DoStmt>(S) || isa<ForStmt>(S))
5313 Stmts.push_back(S);
5314 else if (isa<ObjCForCollectionStmt>(S)) {
5315 Stmts.push_back(S);
5316 ObjCBcLabelNo.push_back(++BcLabelCount);
5317 }
5318
5319 // Pseudo-object operations and ivar references need special
5320 // treatment because we're going to recursively rewrite them.
5321 if (PseudoObjectExpr *PseudoOp = dyn_cast<PseudoObjectExpr>(S)) {
5322 if (isa<BinaryOperator>(PseudoOp->getSyntacticForm())) {
5323 return RewritePropertyOrImplicitSetter(PseudoOp);
5324 } else {
5325 return RewritePropertyOrImplicitGetter(PseudoOp);
5326 }
5327 } else if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
5328 return RewriteObjCIvarRefExpr(IvarRefExpr);
5329 }
5330
5331 SourceRange OrigStmtRange = S->getSourceRange();
5332
5333 // Perform a bottom up rewrite of all children.
5334 for (Stmt::child_range CI = S->children(); CI; ++CI)
5335 if (*CI) {
5336 Stmt *childStmt = (*CI);
5337 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(childStmt);
5338 if (newStmt) {
5339 *CI = newStmt;
5340 }
5341 }
5342
5343 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
John McCallf4b88a42012-03-10 09:33:50 +00005344 SmallVector<DeclRefExpr *, 8> InnerBlockDeclRefs;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005345 llvm::SmallPtrSet<const DeclContext *, 8> InnerContexts;
5346 InnerContexts.insert(BE->getBlockDecl());
5347 ImportedLocalExternalDecls.clear();
5348 GetInnerBlockDeclRefExprs(BE->getBody(),
5349 InnerBlockDeclRefs, InnerContexts);
5350 // Rewrite the block body in place.
5351 Stmt *SaveCurrentBody = CurrentBody;
5352 CurrentBody = BE->getBody();
5353 PropParentMap = 0;
5354 // block literal on rhs of a property-dot-sytax assignment
5355 // must be replaced by its synthesize ast so getRewrittenText
5356 // works as expected. In this case, what actually ends up on RHS
5357 // is the blockTranscribed which is the helper function for the
5358 // block literal; as in: self.c = ^() {[ace ARR];};
5359 bool saveDisableReplaceStmt = DisableReplaceStmt;
5360 DisableReplaceStmt = false;
5361 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
5362 DisableReplaceStmt = saveDisableReplaceStmt;
5363 CurrentBody = SaveCurrentBody;
5364 PropParentMap = 0;
5365 ImportedLocalExternalDecls.clear();
5366 // Now we snarf the rewritten text and stash it away for later use.
5367 std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
5368 RewrittenBlockExprs[BE] = Str;
5369
5370 Stmt *blockTranscribed = SynthBlockInitExpr(BE, InnerBlockDeclRefs);
5371
5372 //blockTranscribed->dump();
5373 ReplaceStmt(S, blockTranscribed);
5374 return blockTranscribed;
5375 }
5376 // Handle specific things.
5377 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
5378 return RewriteAtEncode(AtEncode);
5379
5380 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
5381 return RewriteAtSelector(AtSelector);
5382
5383 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
5384 return RewriteObjCStringLiteral(AtString);
Fariborz Jahanian55947042012-03-27 20:17:30 +00005385
5386 if (ObjCBoolLiteralExpr *BoolLitExpr = dyn_cast<ObjCBoolLiteralExpr>(S))
5387 return RewriteObjCBoolLiteralExpr(BoolLitExpr);
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00005388
Patrick Beardeb382ec2012-04-19 00:25:12 +00005389 if (ObjCBoxedExpr *BoxedExpr = dyn_cast<ObjCBoxedExpr>(S))
5390 return RewriteObjCBoxedExpr(BoxedExpr);
Fariborz Jahanian86cff602012-03-30 23:35:47 +00005391
5392 if (ObjCArrayLiteral *ArrayLitExpr = dyn_cast<ObjCArrayLiteral>(S))
5393 return RewriteObjCArrayLiteralExpr(ArrayLitExpr);
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00005394
5395 if (ObjCDictionaryLiteral *DictionaryLitExpr =
5396 dyn_cast<ObjCDictionaryLiteral>(S))
5397 return RewriteObjCDictionaryLiteralExpr(DictionaryLitExpr);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005398
5399 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
5400#if 0
5401 // Before we rewrite it, put the original message expression in a comment.
5402 SourceLocation startLoc = MessExpr->getLocStart();
5403 SourceLocation endLoc = MessExpr->getLocEnd();
5404
5405 const char *startBuf = SM->getCharacterData(startLoc);
5406 const char *endBuf = SM->getCharacterData(endLoc);
5407
5408 std::string messString;
5409 messString += "// ";
5410 messString.append(startBuf, endBuf-startBuf+1);
5411 messString += "\n";
5412
5413 // FIXME: Missing definition of
5414 // InsertText(clang::SourceLocation, char const*, unsigned int).
5415 // InsertText(startLoc, messString.c_str(), messString.size());
5416 // Tried this, but it didn't work either...
5417 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
5418#endif
5419 return RewriteMessageExpr(MessExpr);
5420 }
5421
Fariborz Jahanian042b91d2012-05-23 23:47:20 +00005422 if (ObjCAutoreleasePoolStmt *StmtAutoRelease =
5423 dyn_cast<ObjCAutoreleasePoolStmt>(S)) {
5424 return RewriteObjCAutoreleasePoolStmt(StmtAutoRelease);
5425 }
5426
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005427 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
5428 return RewriteObjCTryStmt(StmtTry);
5429
5430 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
5431 return RewriteObjCSynchronizedStmt(StmtTry);
5432
5433 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
5434 return RewriteObjCThrowStmt(StmtThrow);
5435
5436 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
5437 return RewriteObjCProtocolExpr(ProtocolExp);
5438
5439 if (ObjCForCollectionStmt *StmtForCollection =
5440 dyn_cast<ObjCForCollectionStmt>(S))
5441 return RewriteObjCForCollectionStmt(StmtForCollection,
5442 OrigStmtRange.getEnd());
5443 if (BreakStmt *StmtBreakStmt =
5444 dyn_cast<BreakStmt>(S))
5445 return RewriteBreakStmt(StmtBreakStmt);
5446 if (ContinueStmt *StmtContinueStmt =
5447 dyn_cast<ContinueStmt>(S))
5448 return RewriteContinueStmt(StmtContinueStmt);
5449
5450 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
5451 // and cast exprs.
5452 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
5453 // FIXME: What we're doing here is modifying the type-specifier that
5454 // precedes the first Decl. In the future the DeclGroup should have
5455 // a separate type-specifier that we can rewrite.
5456 // NOTE: We need to avoid rewriting the DeclStmt if it is within
5457 // the context of an ObjCForCollectionStmt. For example:
5458 // NSArray *someArray;
5459 // for (id <FooProtocol> index in someArray) ;
5460 // This is because RewriteObjCForCollectionStmt() does textual rewriting
5461 // and it depends on the original text locations/positions.
5462 if (Stmts.empty() || !IsDeclStmtInForeachHeader(DS))
5463 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
5464
5465 // Blocks rewrite rules.
5466 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
5467 DI != DE; ++DI) {
5468 Decl *SD = *DI;
5469 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
5470 if (isTopLevelBlockPointerType(ND->getType()))
5471 RewriteBlockPointerDecl(ND);
5472 else if (ND->getType()->isFunctionPointerType())
5473 CheckFunctionPointerDecl(ND->getType(), ND);
5474 if (VarDecl *VD = dyn_cast<VarDecl>(SD)) {
5475 if (VD->hasAttr<BlocksAttr>()) {
5476 static unsigned uniqueByrefDeclCount = 0;
5477 assert(!BlockByRefDeclNo.count(ND) &&
5478 "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl");
5479 BlockByRefDeclNo[ND] = uniqueByrefDeclCount++;
Fariborz Jahanian4fe261c2012-04-24 19:38:45 +00005480 RewriteByRefVar(VD, (DI == DS->decl_begin()), ((DI+1) == DE));
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005481 }
5482 else
5483 RewriteTypeOfDecl(VD);
5484 }
5485 }
5486 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(SD)) {
5487 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
5488 RewriteBlockPointerDecl(TD);
5489 else if (TD->getUnderlyingType()->isFunctionPointerType())
5490 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5491 }
5492 }
5493 }
5494
5495 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
5496 RewriteObjCQualifiedInterfaceTypes(CE);
5497
5498 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
5499 isa<DoStmt>(S) || isa<ForStmt>(S)) {
5500 assert(!Stmts.empty() && "Statement stack is empty");
5501 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
5502 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
5503 && "Statement stack mismatch");
5504 Stmts.pop_back();
5505 }
5506 // Handle blocks rewriting.
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005507 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
5508 ValueDecl *VD = DRE->getDecl();
5509 if (VD->hasAttr<BlocksAttr>())
5510 return RewriteBlockDeclRefExpr(DRE);
5511 if (HasLocalVariableExternalStorage(VD))
5512 return RewriteLocalVariableExternalStorage(DRE);
5513 }
5514
5515 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
5516 if (CE->getCallee()->getType()->isBlockPointerType()) {
5517 Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
5518 ReplaceStmt(S, BlockCall);
5519 return BlockCall;
5520 }
5521 }
5522 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
5523 RewriteCastExpr(CE);
5524 }
Fariborz Jahanianf1ee6872012-04-10 00:08:18 +00005525 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
5526 RewriteImplicitCastObjCExpr(ICE);
5527 }
Fariborz Jahanian43aa1c32012-04-16 22:14:01 +00005528#if 0
Fariborz Jahanian653b7cf2012-04-13 18:00:54 +00005529
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005530 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
5531 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(),
5532 ICE->getSubExpr(),
5533 SourceLocation());
5534 // Get the new text.
5535 std::string SStr;
5536 llvm::raw_string_ostream Buf(SStr);
5537 Replacement->printPretty(Buf, *Context);
5538 const std::string &Str = Buf.str();
5539
5540 printf("CAST = %s\n", &Str[0]);
5541 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
5542 delete S;
5543 return Replacement;
5544 }
5545#endif
5546 // Return this stmt unmodified.
5547 return S;
5548}
5549
5550void RewriteModernObjC::RewriteRecordBody(RecordDecl *RD) {
5551 for (RecordDecl::field_iterator i = RD->field_begin(),
5552 e = RD->field_end(); i != e; ++i) {
David Blaikie262bc182012-04-30 02:36:29 +00005553 FieldDecl *FD = &*i;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005554 if (isTopLevelBlockPointerType(FD->getType()))
5555 RewriteBlockPointerDecl(FD);
5556 if (FD->getType()->isObjCQualifiedIdType() ||
5557 FD->getType()->isObjCQualifiedInterfaceType())
5558 RewriteObjCQualifiedInterfaceTypes(FD);
5559 }
5560}
5561
5562/// HandleDeclInMainFile - This is called for each top-level decl defined in the
5563/// main file of the input.
5564void RewriteModernObjC::HandleDeclInMainFile(Decl *D) {
5565 switch (D->getKind()) {
5566 case Decl::Function: {
5567 FunctionDecl *FD = cast<FunctionDecl>(D);
5568 if (FD->isOverloadedOperator())
5569 return;
5570
5571 // Since function prototypes don't have ParmDecl's, we check the function
5572 // prototype. This enables us to rewrite function declarations and
5573 // definitions using the same code.
5574 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
5575
Argyrios Kyrtzidis9335df32012-02-12 04:48:45 +00005576 if (!FD->isThisDeclarationADefinition())
5577 break;
5578
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005579 // FIXME: If this should support Obj-C++, support CXXTryStmt
5580 if (CompoundStmt *Body = dyn_cast_or_null<CompoundStmt>(FD->getBody())) {
5581 CurFunctionDef = FD;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005582 CurrentBody = Body;
5583 Body =
5584 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5585 FD->setBody(Body);
5586 CurrentBody = 0;
5587 if (PropParentMap) {
5588 delete PropParentMap;
5589 PropParentMap = 0;
5590 }
5591 // This synthesizes and inserts the block "impl" struct, invoke function,
5592 // and any copy/dispose helper functions.
5593 InsertBlockLiteralsWithinFunction(FD);
5594 CurFunctionDef = 0;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005595 }
5596 break;
5597 }
5598 case Decl::ObjCMethod: {
5599 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(D);
5600 if (CompoundStmt *Body = MD->getCompoundBody()) {
5601 CurMethodDef = MD;
5602 CurrentBody = Body;
5603 Body =
5604 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5605 MD->setBody(Body);
5606 CurrentBody = 0;
5607 if (PropParentMap) {
5608 delete PropParentMap;
5609 PropParentMap = 0;
5610 }
5611 InsertBlockLiteralsWithinMethod(MD);
5612 CurMethodDef = 0;
5613 }
5614 break;
5615 }
5616 case Decl::ObjCImplementation: {
5617 ObjCImplementationDecl *CI = cast<ObjCImplementationDecl>(D);
5618 ClassImplementation.push_back(CI);
5619 break;
5620 }
5621 case Decl::ObjCCategoryImpl: {
5622 ObjCCategoryImplDecl *CI = cast<ObjCCategoryImplDecl>(D);
5623 CategoryImplementation.push_back(CI);
5624 break;
5625 }
5626 case Decl::Var: {
5627 VarDecl *VD = cast<VarDecl>(D);
5628 RewriteObjCQualifiedInterfaceTypes(VD);
5629 if (isTopLevelBlockPointerType(VD->getType()))
5630 RewriteBlockPointerDecl(VD);
5631 else if (VD->getType()->isFunctionPointerType()) {
5632 CheckFunctionPointerDecl(VD->getType(), VD);
5633 if (VD->getInit()) {
5634 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
5635 RewriteCastExpr(CE);
5636 }
5637 }
5638 } else if (VD->getType()->isRecordType()) {
5639 RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
5640 if (RD->isCompleteDefinition())
5641 RewriteRecordBody(RD);
5642 }
5643 if (VD->getInit()) {
5644 GlobalVarDecl = VD;
5645 CurrentBody = VD->getInit();
5646 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
5647 CurrentBody = 0;
5648 if (PropParentMap) {
5649 delete PropParentMap;
5650 PropParentMap = 0;
5651 }
5652 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(), VD->getName());
5653 GlobalVarDecl = 0;
5654
5655 // This is needed for blocks.
5656 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
5657 RewriteCastExpr(CE);
5658 }
5659 }
5660 break;
5661 }
5662 case Decl::TypeAlias:
5663 case Decl::Typedef: {
5664 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
5665 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
5666 RewriteBlockPointerDecl(TD);
5667 else if (TD->getUnderlyingType()->isFunctionPointerType())
5668 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5669 }
5670 break;
5671 }
5672 case Decl::CXXRecord:
5673 case Decl::Record: {
5674 RecordDecl *RD = cast<RecordDecl>(D);
5675 if (RD->isCompleteDefinition())
5676 RewriteRecordBody(RD);
5677 break;
5678 }
5679 default:
5680 break;
5681 }
5682 // Nothing yet.
5683}
5684
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00005685/// Write_ProtocolExprReferencedMetadata - This routine writer out the
5686/// protocol reference symbols in the for of:
5687/// struct _protocol_t *PROTOCOL_REF = &PROTOCOL_METADATA.
5688static void Write_ProtocolExprReferencedMetadata(ASTContext *Context,
5689 ObjCProtocolDecl *PDecl,
5690 std::string &Result) {
5691 // Also output .objc_protorefs$B section and its meta-data.
5692 if (Context->getLangOpts().MicrosoftExt)
Fariborz Jahanianbd78cfa2012-04-27 21:39:49 +00005693 Result += "static ";
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00005694 Result += "struct _protocol_t *";
5695 Result += "_OBJC_PROTOCOL_REFERENCE_$_";
5696 Result += PDecl->getNameAsString();
5697 Result += " = &";
5698 Result += "_OBJC_PROTOCOL_"; Result += PDecl->getNameAsString();
5699 Result += ";\n";
5700}
5701
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005702void RewriteModernObjC::HandleTranslationUnit(ASTContext &C) {
5703 if (Diags.hasErrorOccurred())
5704 return;
5705
5706 RewriteInclude();
5707
5708 // Here's a great place to add any extra declarations that may be needed.
5709 // Write out meta data for each @protocol(<expr>).
5710 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00005711 E = ProtocolExprDecls.end(); I != E; ++I) {
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00005712 RewriteObjCProtocolMetaData(*I, Preamble);
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00005713 Write_ProtocolExprReferencedMetadata(Context, (*I), Preamble);
5714 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005715
5716 InsertText(SM->getLocForStartOfFile(MainFileID), Preamble, false);
Fariborz Jahanian163d3ce2012-05-08 23:54:35 +00005717
5718 if (ClassImplementation.size() || CategoryImplementation.size())
5719 RewriteImplementations();
5720
Fariborz Jahanian57317782012-02-21 23:58:41 +00005721 for (unsigned i = 0, e = ObjCInterfacesSeen.size(); i < e; i++) {
5722 ObjCInterfaceDecl *CDecl = ObjCInterfacesSeen[i];
5723 // Write struct declaration for the class matching its ivar declarations.
5724 // Note that for modern abi, this is postponed until the end of TU
5725 // because class extensions and the implementation might declare their own
5726 // private ivars.
5727 RewriteInterfaceDecl(CDecl);
5728 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005729
5730 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
5731 // we are done.
5732 if (const RewriteBuffer *RewriteBuf =
5733 Rewrite.getRewriteBufferFor(MainFileID)) {
5734 //printf("Changed:\n");
5735 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
5736 } else {
5737 llvm::errs() << "No changes\n";
5738 }
5739
5740 if (ClassImplementation.size() || CategoryImplementation.size() ||
5741 ProtocolExprDecls.size()) {
5742 // Rewrite Objective-c meta data*
5743 std::string ResultStr;
5744 RewriteMetaDataIntoBuffer(ResultStr);
5745 // Emit metadata.
5746 *OutFile << ResultStr;
5747 }
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005748 // Emit ImageInfo;
5749 {
5750 std::string ResultStr;
5751 WriteImageInfo(ResultStr);
5752 *OutFile << ResultStr;
5753 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005754 OutFile->flush();
5755}
5756
5757void RewriteModernObjC::Initialize(ASTContext &context) {
5758 InitializeCommon(context);
5759
Fariborz Jahanian6991bc52012-03-10 17:45:38 +00005760 Preamble += "#ifndef __OBJC2__\n";
5761 Preamble += "#define __OBJC2__\n";
5762 Preamble += "#endif\n";
5763
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005764 // declaring objc_selector outside the parameter list removes a silly
5765 // scope related warning...
5766 if (IsHeader)
5767 Preamble = "#pragma once\n";
5768 Preamble += "struct objc_selector; struct objc_class;\n";
Fariborz Jahaniane2d87bc2012-04-12 23:52:52 +00005769 Preamble += "struct __rw_objc_super { \n\tstruct objc_object *object; ";
5770 Preamble += "\n\tstruct objc_object *superClass; ";
5771 // Add a constructor for creating temporary objects.
5772 Preamble += "\n\t__rw_objc_super(struct objc_object *o, struct objc_object *s) ";
5773 Preamble += ": object(o), superClass(s) {} ";
5774 Preamble += "\n};\n";
5775
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005776 if (LangOpts.MicrosoftExt) {
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00005777 // Define all sections using syntax that makes sense.
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005778 // These are currently generated.
5779 Preamble += "\n#pragma section(\".objc_classlist$B\", long, read, write)\n";
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00005780 Preamble += "#pragma section(\".objc_catlist$B\", long, read, write)\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005781 Preamble += "#pragma section(\".objc_imageinfo$B\", long, read, write)\n";
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00005782 Preamble += "#pragma section(\".objc_nlclslist$B\", long, read, write)\n";
5783 Preamble += "#pragma section(\".objc_nlcatlist$B\", long, read, write)\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005784 // These are generated but not necessary for functionality.
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005785 Preamble += "#pragma section(\".cat_cls_meth$B\", long, read, write)\n";
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00005786 Preamble += "#pragma section(\".inst_meth$B\", long, read, write)\n";
5787 Preamble += "#pragma section(\".cls_meth$B\", long, read, write)\n";
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00005788 Preamble += "#pragma section(\".objc_ivar$B\", long, read, write)\n";
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00005789
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00005790 // These need be generated for performance. Currently they are not,
5791 // using API calls instead.
5792 Preamble += "#pragma section(\".objc_selrefs$B\", long, read, write)\n";
5793 Preamble += "#pragma section(\".objc_classrefs$B\", long, read, write)\n";
5794 Preamble += "#pragma section(\".objc_superrefs$B\", long, read, write)\n";
5795
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005796 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005797 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
5798 Preamble += "typedef struct objc_object Protocol;\n";
5799 Preamble += "#define _REWRITER_typedef_Protocol\n";
5800 Preamble += "#endif\n";
5801 if (LangOpts.MicrosoftExt) {
5802 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
5803 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
Fariborz Jahanian5cf6b6c2012-03-21 23:41:04 +00005804 }
5805 else
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005806 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
Fariborz Jahanian5cf6b6c2012-03-21 23:41:04 +00005807
5808 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend(void);\n";
5809 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSendSuper(void);\n";
5810 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend_stret(void);\n";
5811 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSendSuper_stret(void);\n";
5812 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend_fpret(void);\n";
5813
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00005814 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *objc_getClass";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005815 Preamble += "(const char *);\n";
5816 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *class_getSuperclass";
5817 Preamble += "(struct objc_class *);\n";
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00005818 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *objc_getMetaClass";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005819 Preamble += "(const char *);\n";
Fariborz Jahanian55261af2012-03-19 18:11:32 +00005820 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw( struct objc_object *);\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005821 // @synchronized hooks.
Fariborz Jahanian55261af2012-03-19 18:11:32 +00005822 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_enter( struct objc_object *);\n";
5823 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_exit( struct objc_object *);\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005824 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
5825 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
5826 Preamble += "struct __objcFastEnumerationState {\n\t";
5827 Preamble += "unsigned long state;\n\t";
5828 Preamble += "void **itemsPtr;\n\t";
5829 Preamble += "unsigned long *mutationsPtr;\n\t";
5830 Preamble += "unsigned long extra[5];\n};\n";
5831 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
5832 Preamble += "#define __FASTENUMERATIONSTATE\n";
5833 Preamble += "#endif\n";
5834 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
5835 Preamble += "struct __NSConstantStringImpl {\n";
5836 Preamble += " int *isa;\n";
5837 Preamble += " int flags;\n";
5838 Preamble += " char *str;\n";
5839 Preamble += " long length;\n";
5840 Preamble += "};\n";
5841 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
5842 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
5843 Preamble += "#else\n";
5844 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
5845 Preamble += "#endif\n";
5846 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
5847 Preamble += "#endif\n";
5848 // Blocks preamble.
5849 Preamble += "#ifndef BLOCK_IMPL\n";
5850 Preamble += "#define BLOCK_IMPL\n";
5851 Preamble += "struct __block_impl {\n";
5852 Preamble += " void *isa;\n";
5853 Preamble += " int Flags;\n";
5854 Preamble += " int Reserved;\n";
5855 Preamble += " void *FuncPtr;\n";
5856 Preamble += "};\n";
5857 Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
5858 Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n";
5859 Preamble += "extern \"C\" __declspec(dllexport) "
5860 "void _Block_object_assign(void *, const void *, const int);\n";
5861 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
5862 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
5863 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
5864 Preamble += "#else\n";
5865 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n";
5866 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n";
5867 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
5868 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
5869 Preamble += "#endif\n";
5870 Preamble += "#endif\n";
5871 if (LangOpts.MicrosoftExt) {
5872 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
5873 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
5874 Preamble += "#ifndef KEEP_ATTRIBUTES\n"; // We use this for clang tests.
5875 Preamble += "#define __attribute__(X)\n";
5876 Preamble += "#endif\n";
Fariborz Jahanian5ce28272012-04-12 16:33:31 +00005877 Preamble += "#ifndef __weak\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005878 Preamble += "#define __weak\n";
Fariborz Jahanian5ce28272012-04-12 16:33:31 +00005879 Preamble += "#endif\n";
5880 Preamble += "#ifndef __block\n";
5881 Preamble += "#define __block\n";
5882 Preamble += "#endif\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005883 }
5884 else {
5885 Preamble += "#define __block\n";
5886 Preamble += "#define __weak\n";
5887 }
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00005888
5889 // Declarations required for modern objective-c array and dictionary literals.
5890 Preamble += "\n#include <stdarg.h>\n";
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00005891 Preamble += "struct __NSContainer_literal {\n";
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00005892 Preamble += " void * *arr;\n";
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00005893 Preamble += " __NSContainer_literal (unsigned int count, ...) {\n";
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00005894 Preamble += "\tva_list marker;\n";
5895 Preamble += "\tva_start(marker, count);\n";
5896 Preamble += "\tarr = new void *[count];\n";
5897 Preamble += "\tfor (unsigned i = 0; i < count; i++)\n";
5898 Preamble += "\t arr[i] = va_arg(marker, void *);\n";
5899 Preamble += "\tva_end( marker );\n";
5900 Preamble += " };\n";
Fariborz Jahanian13a9c022012-05-02 23:53:46 +00005901 Preamble += " ~__NSContainer_literal() {\n";
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00005902 Preamble += "\tdelete[] arr;\n";
5903 Preamble += " }\n";
5904 Preamble += "};\n";
5905
Fariborz Jahanian042b91d2012-05-23 23:47:20 +00005906 // Declaration required for implementation of @autoreleasepool statement.
5907 Preamble += "extern \"C\" __declspec(dllimport) void * objc_autoreleasePoolPush(void);\n";
5908 Preamble += "extern \"C\" __declspec(dllimport) void objc_autoreleasePoolPop(void *);\n\n";
5909 Preamble += "struct __AtAutoreleasePool {\n";
5910 Preamble += " __AtAutoreleasePool() {atautoreleasepoolobj = objc_autoreleasePoolPush();}\n";
5911 Preamble += " ~__AtAutoreleasePool() {objc_autoreleasePoolPop(atautoreleasepoolobj);}\n";
5912 Preamble += " void * atautoreleasepoolobj;\n";
5913 Preamble += "};\n";
5914
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005915 // NOTE! Windows uses LLP64 for 64bit mode. So, cast pointer to long long
5916 // as this avoids warning in any 64bit/32bit compilation model.
5917 Preamble += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long long) &((TYPE *)0)->MEMBER)\n";
5918}
5919
5920/// RewriteIvarOffsetComputation - This rutine synthesizes computation of
5921/// ivar offset.
5922void RewriteModernObjC::RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
5923 std::string &Result) {
5924 if (ivar->isBitField()) {
5925 // FIXME: The hack below doesn't work for bitfields. For now, we simply
5926 // place all bitfields at offset 0.
5927 Result += "0";
5928 } else {
5929 Result += "__OFFSETOFIVAR__(struct ";
5930 Result += ivar->getContainingInterface()->getNameAsString();
5931 if (LangOpts.MicrosoftExt)
5932 Result += "_IMPL";
5933 Result += ", ";
5934 Result += ivar->getNameAsString();
5935 Result += ")";
5936 }
5937}
5938
5939/// WriteModernMetadataDeclarations - Writes out metadata declarations for modern ABI.
5940/// struct _prop_t {
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00005941/// const char *name;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005942/// char *attributes;
5943/// }
5944
5945/// struct _prop_list_t {
5946/// uint32_t entsize; // sizeof(struct _prop_t)
5947/// uint32_t count_of_properties;
5948/// struct _prop_t prop_list[count_of_properties];
5949/// }
5950
5951/// struct _protocol_t;
5952
5953/// struct _protocol_list_t {
5954/// long protocol_count; // Note, this is 32/64 bit
5955/// struct _protocol_t * protocol_list[protocol_count];
5956/// }
5957
5958/// struct _objc_method {
5959/// SEL _cmd;
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005960/// const char *method_type;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005961/// char *_imp;
5962/// }
5963
5964/// struct _method_list_t {
5965/// uint32_t entsize; // sizeof(struct _objc_method)
5966/// uint32_t method_count;
5967/// struct _objc_method method_list[method_count];
5968/// }
5969
5970/// struct _protocol_t {
5971/// id isa; // NULL
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005972/// const char *protocol_name;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005973/// const struct _protocol_list_t * protocol_list; // super protocols
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005974/// const struct method_list_t *instance_methods;
5975/// const struct method_list_t *class_methods;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005976/// const struct method_list_t *optionalInstanceMethods;
5977/// const struct method_list_t *optionalClassMethods;
5978/// const struct _prop_list_t * properties;
5979/// const uint32_t size; // sizeof(struct _protocol_t)
5980/// const uint32_t flags; // = 0
5981/// const char ** extendedMethodTypes;
5982/// }
5983
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005984/// struct _ivar_t {
5985/// unsigned long int *offset; // pointer to ivar offset location
Fariborz Jahanianae932952012-02-10 20:47:10 +00005986/// const char *name;
5987/// const char *type;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005988/// uint32_t alignment;
5989/// uint32_t size;
5990/// }
5991
5992/// struct _ivar_list_t {
5993/// uint32 entsize; // sizeof(struct _ivar_t)
5994/// uint32 count;
Fariborz Jahanianae932952012-02-10 20:47:10 +00005995/// struct _ivar_t list[count];
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005996/// }
5997
5998/// struct _class_ro_t {
Fariborz Jahanian249cd102012-03-24 16:53:16 +00005999/// uint32_t flags;
6000/// uint32_t instanceStart;
6001/// uint32_t instanceSize;
6002/// uint32_t reserved; // only when building for 64bit targets
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006003/// const uint8_t *ivarLayout;
6004/// const char *name;
6005/// const struct _method_list_t *baseMethods;
6006/// const struct _protocol_list_t *baseProtocols;
6007/// const struct _ivar_list_t *ivars;
6008/// const uint8_t *weakIvarLayout;
6009/// const struct _prop_list_t *properties;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006010/// }
6011
6012/// struct _class_t {
6013/// struct _class_t *isa;
Fariborz Jahanianfd4ce2c2012-03-20 17:34:50 +00006014/// struct _class_t *superclass;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006015/// void *cache;
6016/// IMP *vtable;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006017/// struct _class_ro_t *ro;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006018/// }
6019
6020/// struct _category_t {
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006021/// const char *name;
Fariborz Jahanian4b2fe6e2012-03-20 21:41:28 +00006022/// struct _class_t *cls;
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006023/// const struct _method_list_t *instance_methods;
6024/// const struct _method_list_t *class_methods;
6025/// const struct _protocol_list_t *protocols;
6026/// const struct _prop_list_t *properties;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006027/// }
6028
6029/// MessageRefTy - LLVM for:
6030/// struct _message_ref_t {
6031/// IMP messenger;
6032/// SEL name;
6033/// };
6034
6035/// SuperMessageRefTy - LLVM for:
6036/// struct _super_message_ref_t {
6037/// SUPER_IMP messenger;
6038/// SEL name;
6039/// };
6040
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00006041static void WriteModernMetadataDeclarations(ASTContext *Context, std::string &Result) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006042 static bool meta_data_declared = false;
6043 if (meta_data_declared)
6044 return;
6045
6046 Result += "\nstruct _prop_t {\n";
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006047 Result += "\tconst char *name;\n";
6048 Result += "\tconst char *attributes;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006049 Result += "};\n";
6050
6051 Result += "\nstruct _protocol_t;\n";
6052
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006053 Result += "\nstruct _objc_method {\n";
6054 Result += "\tstruct objc_selector * _cmd;\n";
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006055 Result += "\tconst char *method_type;\n";
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006056 Result += "\tvoid *_imp;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006057 Result += "};\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006058
6059 Result += "\nstruct _protocol_t {\n";
6060 Result += "\tvoid * isa; // NULL\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006061 Result += "\tconst char *protocol_name;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006062 Result += "\tconst struct _protocol_list_t * protocol_list; // super protocols\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006063 Result += "\tconst struct method_list_t *instance_methods;\n";
6064 Result += "\tconst struct method_list_t *class_methods;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006065 Result += "\tconst struct method_list_t *optionalInstanceMethods;\n";
6066 Result += "\tconst struct method_list_t *optionalClassMethods;\n";
6067 Result += "\tconst struct _prop_list_t * properties;\n";
6068 Result += "\tconst unsigned int size; // sizeof(struct _protocol_t)\n";
6069 Result += "\tconst unsigned int flags; // = 0\n";
6070 Result += "\tconst char ** extendedMethodTypes;\n";
6071 Result += "};\n";
6072
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006073 Result += "\nstruct _ivar_t {\n";
6074 Result += "\tunsigned long int *offset; // pointer to ivar offset location\n";
Fariborz Jahanianae932952012-02-10 20:47:10 +00006075 Result += "\tconst char *name;\n";
6076 Result += "\tconst char *type;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006077 Result += "\tunsigned int alignment;\n";
6078 Result += "\tunsigned int size;\n";
6079 Result += "};\n";
6080
6081 Result += "\nstruct _class_ro_t {\n";
Fariborz Jahanian249cd102012-03-24 16:53:16 +00006082 Result += "\tunsigned int flags;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006083 Result += "\tunsigned int instanceStart;\n";
Fariborz Jahanian249cd102012-03-24 16:53:16 +00006084 Result += "\tunsigned int instanceSize;\n";
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00006085 const llvm::Triple &Triple(Context->getTargetInfo().getTriple());
6086 if (Triple.getArch() == llvm::Triple::x86_64)
Fariborz Jahanian249cd102012-03-24 16:53:16 +00006087 Result += "\tunsigned int reserved;\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006088 Result += "\tconst unsigned char *ivarLayout;\n";
6089 Result += "\tconst char *name;\n";
6090 Result += "\tconst struct _method_list_t *baseMethods;\n";
6091 Result += "\tconst struct _objc_protocol_list *baseProtocols;\n";
6092 Result += "\tconst struct _ivar_list_t *ivars;\n";
6093 Result += "\tconst unsigned char *weakIvarLayout;\n";
6094 Result += "\tconst struct _prop_list_t *properties;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006095 Result += "};\n";
6096
6097 Result += "\nstruct _class_t {\n";
6098 Result += "\tstruct _class_t *isa;\n";
Fariborz Jahanianfd4ce2c2012-03-20 17:34:50 +00006099 Result += "\tstruct _class_t *superclass;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006100 Result += "\tvoid *cache;\n";
6101 Result += "\tvoid *vtable;\n";
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006102 Result += "\tstruct _class_ro_t *ro;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006103 Result += "};\n";
6104
6105 Result += "\nstruct _category_t {\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006106 Result += "\tconst char *name;\n";
Fariborz Jahanian4b2fe6e2012-03-20 21:41:28 +00006107 Result += "\tstruct _class_t *cls;\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006108 Result += "\tconst struct _method_list_t *instance_methods;\n";
6109 Result += "\tconst struct _method_list_t *class_methods;\n";
6110 Result += "\tconst struct _protocol_list_t *protocols;\n";
6111 Result += "\tconst struct _prop_list_t *properties;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006112 Result += "};\n";
6113
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006114 Result += "extern \"C\" __declspec(dllimport) struct objc_cache _objc_empty_cache;\n";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006115 Result += "#pragma warning(disable:4273)\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006116 meta_data_declared = true;
6117}
6118
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006119static void Write_protocol_list_t_TypeDecl(std::string &Result,
6120 long super_protocol_count) {
6121 Result += "struct /*_protocol_list_t*/"; Result += " {\n";
6122 Result += "\tlong protocol_count; // Note, this is 32/64 bit\n";
6123 Result += "\tstruct _protocol_t *super_protocols[";
6124 Result += utostr(super_protocol_count); Result += "];\n";
6125 Result += "}";
6126}
6127
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006128static void Write_method_list_t_TypeDecl(std::string &Result,
6129 unsigned int method_count) {
6130 Result += "struct /*_method_list_t*/"; Result += " {\n";
6131 Result += "\tunsigned int entsize; // sizeof(struct _objc_method)\n";
6132 Result += "\tunsigned int method_count;\n";
6133 Result += "\tstruct _objc_method method_list[";
6134 Result += utostr(method_count); Result += "];\n";
6135 Result += "}";
6136}
6137
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006138static void Write__prop_list_t_TypeDecl(std::string &Result,
6139 unsigned int property_count) {
6140 Result += "struct /*_prop_list_t*/"; Result += " {\n";
6141 Result += "\tunsigned int entsize; // sizeof(struct _prop_t)\n";
6142 Result += "\tunsigned int count_of_properties;\n";
6143 Result += "\tstruct _prop_t prop_list[";
6144 Result += utostr(property_count); Result += "];\n";
6145 Result += "}";
6146}
6147
Fariborz Jahanianae932952012-02-10 20:47:10 +00006148static void Write__ivar_list_t_TypeDecl(std::string &Result,
6149 unsigned int ivar_count) {
6150 Result += "struct /*_ivar_list_t*/"; Result += " {\n";
6151 Result += "\tunsigned int entsize; // sizeof(struct _prop_t)\n";
6152 Result += "\tunsigned int count;\n";
6153 Result += "\tstruct _ivar_t ivar_list[";
6154 Result += utostr(ivar_count); Result += "];\n";
6155 Result += "}";
6156}
6157
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006158static void Write_protocol_list_initializer(ASTContext *Context, std::string &Result,
6159 ArrayRef<ObjCProtocolDecl *> SuperProtocols,
6160 StringRef VarName,
6161 StringRef ProtocolName) {
6162 if (SuperProtocols.size() > 0) {
6163 Result += "\nstatic ";
6164 Write_protocol_list_t_TypeDecl(Result, SuperProtocols.size());
6165 Result += " "; Result += VarName;
6166 Result += ProtocolName;
6167 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6168 Result += "\t"; Result += utostr(SuperProtocols.size()); Result += ",\n";
6169 for (unsigned i = 0, e = SuperProtocols.size(); i < e; i++) {
6170 ObjCProtocolDecl *SuperPD = SuperProtocols[i];
6171 Result += "\t&"; Result += "_OBJC_PROTOCOL_";
6172 Result += SuperPD->getNameAsString();
6173 if (i == e-1)
6174 Result += "\n};\n";
6175 else
6176 Result += ",\n";
6177 }
6178 }
6179}
6180
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006181static void Write_method_list_t_initializer(RewriteModernObjC &RewriteObj,
6182 ASTContext *Context, std::string &Result,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006183 ArrayRef<ObjCMethodDecl *> Methods,
6184 StringRef VarName,
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006185 StringRef TopLevelDeclName,
6186 bool MethodImpl) {
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006187 if (Methods.size() > 0) {
6188 Result += "\nstatic ";
6189 Write_method_list_t_TypeDecl(Result, Methods.size());
6190 Result += " "; Result += VarName;
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006191 Result += TopLevelDeclName;
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006192 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6193 Result += "\t"; Result += "sizeof(_objc_method)"; Result += ",\n";
6194 Result += "\t"; Result += utostr(Methods.size()); Result += ",\n";
6195 for (unsigned i = 0, e = Methods.size(); i < e; i++) {
6196 ObjCMethodDecl *MD = Methods[i];
6197 if (i == 0)
6198 Result += "\t{{(struct objc_selector *)\"";
6199 else
6200 Result += "\t{(struct objc_selector *)\"";
6201 Result += (MD)->getSelector().getAsString(); Result += "\"";
6202 Result += ", ";
6203 std::string MethodTypeString;
6204 Context->getObjCEncodingForMethodDecl(MD, MethodTypeString);
6205 Result += "\""; Result += MethodTypeString; Result += "\"";
6206 Result += ", ";
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006207 if (!MethodImpl)
6208 Result += "0";
6209 else {
6210 Result += "(void *)";
6211 Result += RewriteObj.MethodInternalNames[MD];
6212 }
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006213 if (i == e-1)
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006214 Result += "}}\n";
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006215 else
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006216 Result += "},\n";
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006217 }
6218 Result += "};\n";
6219 }
6220}
6221
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006222static void Write_prop_list_t_initializer(RewriteModernObjC &RewriteObj,
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006223 ASTContext *Context, std::string &Result,
6224 ArrayRef<ObjCPropertyDecl *> Properties,
6225 const Decl *Container,
6226 StringRef VarName,
6227 StringRef ProtocolName) {
6228 if (Properties.size() > 0) {
6229 Result += "\nstatic ";
6230 Write__prop_list_t_TypeDecl(Result, Properties.size());
6231 Result += " "; Result += VarName;
6232 Result += ProtocolName;
6233 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6234 Result += "\t"; Result += "sizeof(_prop_t)"; Result += ",\n";
6235 Result += "\t"; Result += utostr(Properties.size()); Result += ",\n";
6236 for (unsigned i = 0, e = Properties.size(); i < e; i++) {
6237 ObjCPropertyDecl *PropDecl = Properties[i];
6238 if (i == 0)
6239 Result += "\t{{\"";
6240 else
6241 Result += "\t{\"";
6242 Result += PropDecl->getName(); Result += "\",";
6243 std::string PropertyTypeString, QuotePropertyTypeString;
6244 Context->getObjCEncodingForPropertyDecl(PropDecl, Container, PropertyTypeString);
6245 RewriteObj.QuoteDoublequotes(PropertyTypeString, QuotePropertyTypeString);
6246 Result += "\""; Result += QuotePropertyTypeString; Result += "\"";
6247 if (i == e-1)
6248 Result += "}}\n";
6249 else
6250 Result += "},\n";
6251 }
6252 Result += "};\n";
6253 }
6254}
6255
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006256// Metadata flags
6257enum MetaDataDlags {
6258 CLS = 0x0,
6259 CLS_META = 0x1,
6260 CLS_ROOT = 0x2,
6261 OBJC2_CLS_HIDDEN = 0x10,
6262 CLS_EXCEPTION = 0x20,
6263
6264 /// (Obsolete) ARC-specific: this class has a .release_ivars method
6265 CLS_HAS_IVAR_RELEASER = 0x40,
6266 /// class was compiled with -fobjc-arr
6267 CLS_COMPILED_BY_ARC = 0x80 // (1<<7)
6268};
6269
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006270static void Write__class_ro_t_initializer(ASTContext *Context, std::string &Result,
6271 unsigned int flags,
6272 const std::string &InstanceStart,
6273 const std::string &InstanceSize,
6274 ArrayRef<ObjCMethodDecl *>baseMethods,
6275 ArrayRef<ObjCProtocolDecl *>baseProtocols,
6276 ArrayRef<ObjCIvarDecl *>ivars,
6277 ArrayRef<ObjCPropertyDecl *>Properties,
6278 StringRef VarName,
6279 StringRef ClassName) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006280 Result += "\nstatic struct _class_ro_t ";
6281 Result += VarName; Result += ClassName;
6282 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6283 Result += "\t";
6284 Result += llvm::utostr(flags); Result += ", ";
6285 Result += InstanceStart; Result += ", ";
6286 Result += InstanceSize; Result += ", \n";
6287 Result += "\t";
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00006288 const llvm::Triple &Triple(Context->getTargetInfo().getTriple());
6289 if (Triple.getArch() == llvm::Triple::x86_64)
6290 // uint32_t const reserved; // only when building for 64bit targets
6291 Result += "(unsigned int)0, \n\t";
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006292 // const uint8_t * const ivarLayout;
6293 Result += "0, \n\t";
6294 Result += "\""; Result += ClassName; Result += "\",\n\t";
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006295 bool metaclass = ((flags & CLS_META) != 0);
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006296 if (baseMethods.size() > 0) {
6297 Result += "(const struct _method_list_t *)&";
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006298 if (metaclass)
6299 Result += "_OBJC_$_CLASS_METHODS_";
6300 else
6301 Result += "_OBJC_$_INSTANCE_METHODS_";
6302 Result += ClassName;
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006303 Result += ",\n\t";
6304 }
6305 else
6306 Result += "0, \n\t";
6307
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006308 if (!metaclass && baseProtocols.size() > 0) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006309 Result += "(const struct _objc_protocol_list *)&";
6310 Result += "_OBJC_CLASS_PROTOCOLS_$_"; Result += ClassName;
6311 Result += ",\n\t";
6312 }
6313 else
6314 Result += "0, \n\t";
6315
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006316 if (!metaclass && ivars.size() > 0) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006317 Result += "(const struct _ivar_list_t *)&";
6318 Result += "_OBJC_$_INSTANCE_VARIABLES_"; Result += ClassName;
6319 Result += ",\n\t";
6320 }
6321 else
6322 Result += "0, \n\t";
6323
6324 // weakIvarLayout
6325 Result += "0, \n\t";
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006326 if (!metaclass && Properties.size() > 0) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006327 Result += "(const struct _prop_list_t *)&";
Fariborz Jahanianeeabf382012-02-16 21:57:59 +00006328 Result += "_OBJC_$_PROP_LIST_"; Result += ClassName;
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006329 Result += ",\n";
6330 }
6331 else
6332 Result += "0, \n";
6333
6334 Result += "};\n";
6335}
6336
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006337static void Write_class_t(ASTContext *Context, std::string &Result,
6338 StringRef VarName,
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006339 const ObjCInterfaceDecl *CDecl, bool metaclass) {
6340 bool rootClass = (!CDecl->getSuperClass());
6341 const ObjCInterfaceDecl *RootClass = CDecl;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006342
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006343 if (!rootClass) {
6344 // Find the Root class
6345 RootClass = CDecl->getSuperClass();
6346 while (RootClass->getSuperClass()) {
6347 RootClass = RootClass->getSuperClass();
6348 }
6349 }
6350
6351 if (metaclass && rootClass) {
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006352 // Need to handle a case of use of forward declaration.
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00006353 Result += "\n";
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006354 Result += "extern \"C\" ";
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00006355 if (CDecl->getImplementation())
6356 Result += "__declspec(dllexport) ";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006357 else
6358 Result += "__declspec(dllimport) ";
6359
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006360 Result += "struct _class_t OBJC_CLASS_$_";
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006361 Result += CDecl->getNameAsString();
6362 Result += ";\n";
6363 }
6364 // Also, for possibility of 'super' metadata class not having been defined yet.
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006365 if (!rootClass) {
Fariborz Jahanian868e9852012-03-29 19:04:10 +00006366 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00006367 Result += "\n";
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006368 Result += "extern \"C\" ";
Fariborz Jahanian868e9852012-03-29 19:04:10 +00006369 if (SuperClass->getImplementation())
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00006370 Result += "__declspec(dllexport) ";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006371 else
6372 Result += "__declspec(dllimport) ";
6373
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006374 Result += "struct _class_t ";
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00006375 Result += VarName;
Fariborz Jahanian868e9852012-03-29 19:04:10 +00006376 Result += SuperClass->getNameAsString();
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006377 Result += ";\n";
Fariborz Jahanian452eac12012-03-20 21:09:58 +00006378
Fariborz Jahanian868e9852012-03-29 19:04:10 +00006379 if (metaclass && RootClass != SuperClass) {
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006380 Result += "extern \"C\" ";
Fariborz Jahanian452eac12012-03-20 21:09:58 +00006381 if (RootClass->getImplementation())
6382 Result += "__declspec(dllexport) ";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006383 else
6384 Result += "__declspec(dllimport) ";
6385
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006386 Result += "struct _class_t ";
Fariborz Jahanian452eac12012-03-20 21:09:58 +00006387 Result += VarName;
6388 Result += RootClass->getNameAsString();
6389 Result += ";\n";
6390 }
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006391 }
6392
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006393 Result += "\nextern \"C\" __declspec(dllexport) struct _class_t ";
6394 Result += VarName; Result += CDecl->getNameAsString();
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006395 Result += " __attribute__ ((used, section (\"__DATA,__objc_data\"))) = {\n";
6396 Result += "\t";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006397 if (metaclass) {
6398 if (!rootClass) {
6399 Result += "0, // &"; Result += VarName;
6400 Result += RootClass->getNameAsString();
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006401 Result += ",\n\t";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006402 Result += "0, // &"; Result += VarName;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006403 Result += CDecl->getSuperClass()->getNameAsString();
6404 Result += ",\n\t";
6405 }
6406 else {
Fariborz Jahanian452eac12012-03-20 21:09:58 +00006407 Result += "0, // &"; Result += VarName;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006408 Result += CDecl->getNameAsString();
6409 Result += ",\n\t";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006410 Result += "0, // &OBJC_CLASS_$_"; Result += CDecl->getNameAsString();
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006411 Result += ",\n\t";
6412 }
6413 }
6414 else {
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006415 Result += "0, // &OBJC_METACLASS_$_";
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006416 Result += CDecl->getNameAsString();
6417 Result += ",\n\t";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006418 if (!rootClass) {
6419 Result += "0, // &"; Result += VarName;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006420 Result += CDecl->getSuperClass()->getNameAsString();
6421 Result += ",\n\t";
6422 }
6423 else
6424 Result += "0,\n\t";
6425 }
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006426 Result += "0, // (void *)&_objc_empty_cache,\n\t";
6427 Result += "0, // unused, was (void *)&_objc_empty_vtable,\n\t";
6428 if (metaclass)
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006429 Result += "&_OBJC_METACLASS_RO_$_";
6430 else
6431 Result += "&_OBJC_CLASS_RO_$_";
6432 Result += CDecl->getNameAsString();
6433 Result += ",\n};\n";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006434
6435 // Add static function to initialize some of the meta-data fields.
6436 // avoid doing it twice.
6437 if (metaclass)
6438 return;
6439
6440 const ObjCInterfaceDecl *SuperClass =
6441 rootClass ? CDecl : CDecl->getSuperClass();
6442
6443 Result += "static void OBJC_CLASS_SETUP_$_";
6444 Result += CDecl->getNameAsString();
6445 Result += "(void ) {\n";
6446 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
6447 Result += ".isa = "; Result += "&OBJC_METACLASS_$_";
Fariborz Jahanian452eac12012-03-20 21:09:58 +00006448 Result += RootClass->getNameAsString(); Result += ";\n";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006449
6450 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
Fariborz Jahanian452eac12012-03-20 21:09:58 +00006451 Result += ".superclass = ";
6452 if (rootClass)
6453 Result += "&OBJC_CLASS_$_";
6454 else
6455 Result += "&OBJC_METACLASS_$_";
6456
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006457 Result += SuperClass->getNameAsString(); Result += ";\n";
6458
6459 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
6460 Result += ".cache = "; Result += "&_objc_empty_cache"; Result += ";\n";
6461
6462 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6463 Result += ".isa = "; Result += "&OBJC_METACLASS_$_";
6464 Result += CDecl->getNameAsString(); Result += ";\n";
6465
6466 if (!rootClass) {
6467 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6468 Result += ".superclass = "; Result += "&OBJC_CLASS_$_";
6469 Result += SuperClass->getNameAsString(); Result += ";\n";
6470 }
6471
6472 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6473 Result += ".cache = "; Result += "&_objc_empty_cache"; Result += ";\n";
6474 Result += "}\n";
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006475}
6476
Fariborz Jahanian61186122012-02-17 18:40:41 +00006477static void Write_category_t(RewriteModernObjC &RewriteObj, ASTContext *Context,
6478 std::string &Result,
Fariborz Jahaniane0335782012-03-27 18:41:05 +00006479 ObjCCategoryDecl *CatDecl,
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006480 ObjCInterfaceDecl *ClassDecl,
Fariborz Jahanian61186122012-02-17 18:40:41 +00006481 ArrayRef<ObjCMethodDecl *> InstanceMethods,
6482 ArrayRef<ObjCMethodDecl *> ClassMethods,
6483 ArrayRef<ObjCProtocolDecl *> RefedProtocols,
6484 ArrayRef<ObjCPropertyDecl *> ClassProperties) {
Fariborz Jahaniane0335782012-03-27 18:41:05 +00006485 StringRef CatName = CatDecl->getName();
NAKAMURA Takumi20f89392012-03-21 03:21:46 +00006486 StringRef ClassName = ClassDecl->getName();
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00006487 // must declare an extern class object in case this class is not implemented
6488 // in this TU.
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006489 Result += "\n";
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006490 Result += "extern \"C\" ";
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006491 if (ClassDecl->getImplementation())
6492 Result += "__declspec(dllexport) ";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006493 else
6494 Result += "__declspec(dllimport) ";
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006495
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006496 Result += "struct _class_t ";
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00006497 Result += "OBJC_CLASS_$_"; Result += ClassName;
6498 Result += ";\n";
6499
Fariborz Jahanian61186122012-02-17 18:40:41 +00006500 Result += "\nstatic struct _category_t ";
6501 Result += "_OBJC_$_CATEGORY_";
6502 Result += ClassName; Result += "_$_"; Result += CatName;
6503 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = \n";
6504 Result += "{\n";
6505 Result += "\t\""; Result += ClassName; Result += "\",\n";
Fariborz Jahanian4b2fe6e2012-03-20 21:41:28 +00006506 Result += "\t0, // &"; Result += "OBJC_CLASS_$_"; Result += ClassName;
Fariborz Jahanian61186122012-02-17 18:40:41 +00006507 Result += ",\n";
6508 if (InstanceMethods.size() > 0) {
6509 Result += "\t(const struct _method_list_t *)&";
6510 Result += "_OBJC_$_CATEGORY_INSTANCE_METHODS_";
6511 Result += ClassName; Result += "_$_"; Result += CatName;
6512 Result += ",\n";
6513 }
6514 else
6515 Result += "\t0,\n";
6516
6517 if (ClassMethods.size() > 0) {
6518 Result += "\t(const struct _method_list_t *)&";
6519 Result += "_OBJC_$_CATEGORY_CLASS_METHODS_";
6520 Result += ClassName; Result += "_$_"; Result += CatName;
6521 Result += ",\n";
6522 }
6523 else
6524 Result += "\t0,\n";
6525
6526 if (RefedProtocols.size() > 0) {
6527 Result += "\t(const struct _protocol_list_t *)&";
6528 Result += "_OBJC_CATEGORY_PROTOCOLS_$_";
6529 Result += ClassName; Result += "_$_"; Result += CatName;
6530 Result += ",\n";
6531 }
6532 else
6533 Result += "\t0,\n";
6534
6535 if (ClassProperties.size() > 0) {
6536 Result += "\t(const struct _prop_list_t *)&"; Result += "_OBJC_$_PROP_LIST_";
6537 Result += ClassName; Result += "_$_"; Result += CatName;
6538 Result += ",\n";
6539 }
6540 else
6541 Result += "\t0,\n";
6542
6543 Result += "};\n";
Fariborz Jahanian4b2fe6e2012-03-20 21:41:28 +00006544
6545 // Add static function to initialize the class pointer in the category structure.
6546 Result += "static void OBJC_CATEGORY_SETUP_$_";
6547 Result += ClassDecl->getNameAsString();
6548 Result += "_$_";
6549 Result += CatName;
6550 Result += "(void ) {\n";
6551 Result += "\t_OBJC_$_CATEGORY_";
6552 Result += ClassDecl->getNameAsString();
6553 Result += "_$_";
6554 Result += CatName;
6555 Result += ".cls = "; Result += "&OBJC_CLASS_$_"; Result += ClassName;
6556 Result += ";\n}\n";
Fariborz Jahanian61186122012-02-17 18:40:41 +00006557}
6558
Fariborz Jahaniane0adbd82012-02-08 22:23:26 +00006559static void Write__extendedMethodTypes_initializer(RewriteModernObjC &RewriteObj,
6560 ASTContext *Context, std::string &Result,
6561 ArrayRef<ObjCMethodDecl *> Methods,
6562 StringRef VarName,
6563 StringRef ProtocolName) {
6564 if (Methods.size() == 0)
6565 return;
6566
6567 Result += "\nstatic const char *";
6568 Result += VarName; Result += ProtocolName;
6569 Result += " [] __attribute__ ((used, section (\"__DATA,__objc_const\"))) = \n";
6570 Result += "{\n";
6571 for (unsigned i = 0, e = Methods.size(); i < e; i++) {
6572 ObjCMethodDecl *MD = Methods[i];
6573 std::string MethodTypeString, QuoteMethodTypeString;
6574 Context->getObjCEncodingForMethodDecl(MD, MethodTypeString, true);
6575 RewriteObj.QuoteDoublequotes(MethodTypeString, QuoteMethodTypeString);
6576 Result += "\t\""; Result += QuoteMethodTypeString; Result += "\"";
6577 if (i == e-1)
6578 Result += "\n};\n";
6579 else {
6580 Result += ",\n";
6581 }
6582 }
6583}
6584
Fariborz Jahanianacee1c92012-04-11 21:12:36 +00006585static void Write_IvarOffsetVar(RewriteModernObjC &RewriteObj,
6586 ASTContext *Context,
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00006587 std::string &Result,
Fariborz Jahaniandb649232012-02-13 20:59:02 +00006588 ArrayRef<ObjCIvarDecl *> Ivars,
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006589 ObjCInterfaceDecl *CDecl) {
Fariborz Jahaniandb649232012-02-13 20:59:02 +00006590 // FIXME. visibilty of offset symbols may have to be set; for Darwin
6591 // this is what happens:
6592 /**
6593 if (Ivar->getAccessControl() == ObjCIvarDecl::Private ||
6594 Ivar->getAccessControl() == ObjCIvarDecl::Package ||
6595 Class->getVisibility() == HiddenVisibility)
6596 Visibility shoud be: HiddenVisibility;
6597 else
6598 Visibility shoud be: DefaultVisibility;
6599 */
6600
Fariborz Jahanian07e52882012-02-13 21:34:45 +00006601 Result += "\n";
6602 for (unsigned i =0, e = Ivars.size(); i < e; i++) {
6603 ObjCIvarDecl *IvarDecl = Ivars[i];
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00006604 if (Context->getLangOpts().MicrosoftExt)
6605 Result += "__declspec(allocate(\".objc_ivar$B\")) ";
6606
6607 if (!Context->getLangOpts().MicrosoftExt ||
6608 IvarDecl->getAccessControl() == ObjCIvarDecl::Private ||
Fariborz Jahanian117591f2012-03-10 01:34:42 +00006609 IvarDecl->getAccessControl() == ObjCIvarDecl::Package)
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006610 Result += "extern \"C\" unsigned long int ";
Fariborz Jahaniand1c84d32012-03-10 00:53:02 +00006611 else
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006612 Result += "extern \"C\" __declspec(dllexport) unsigned long int ";
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006613 WriteInternalIvarName(CDecl, IvarDecl, Result);
Fariborz Jahanian07e52882012-02-13 21:34:45 +00006614 Result += " __attribute__ ((used, section (\"__DATA,__objc_ivar\")))";
6615 Result += " = ";
Fariborz Jahanianacee1c92012-04-11 21:12:36 +00006616 RewriteObj.RewriteIvarOffsetComputation(IvarDecl, Result);
6617 Result += ";\n";
Fariborz Jahaniandb649232012-02-13 20:59:02 +00006618 }
6619}
6620
Fariborz Jahanianae932952012-02-10 20:47:10 +00006621static void Write__ivar_list_t_initializer(RewriteModernObjC &RewriteObj,
6622 ASTContext *Context, std::string &Result,
6623 ArrayRef<ObjCIvarDecl *> Ivars,
6624 StringRef VarName,
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006625 ObjCInterfaceDecl *CDecl) {
Fariborz Jahanianae932952012-02-10 20:47:10 +00006626 if (Ivars.size() > 0) {
Fariborz Jahanianacee1c92012-04-11 21:12:36 +00006627 Write_IvarOffsetVar(RewriteObj, Context, Result, Ivars, CDecl);
Fariborz Jahanian07e52882012-02-13 21:34:45 +00006628
Fariborz Jahanianae932952012-02-10 20:47:10 +00006629 Result += "\nstatic ";
6630 Write__ivar_list_t_TypeDecl(Result, Ivars.size());
6631 Result += " "; Result += VarName;
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006632 Result += CDecl->getNameAsString();
Fariborz Jahanianae932952012-02-10 20:47:10 +00006633 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6634 Result += "\t"; Result += "sizeof(_ivar_t)"; Result += ",\n";
6635 Result += "\t"; Result += utostr(Ivars.size()); Result += ",\n";
6636 for (unsigned i =0, e = Ivars.size(); i < e; i++) {
6637 ObjCIvarDecl *IvarDecl = Ivars[i];
6638 if (i == 0)
6639 Result += "\t{{";
6640 else
6641 Result += "\t {";
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006642 Result += "(unsigned long int *)&";
6643 WriteInternalIvarName(CDecl, IvarDecl, Result);
Fariborz Jahaniandb649232012-02-13 20:59:02 +00006644 Result += ", ";
Fariborz Jahanianae932952012-02-10 20:47:10 +00006645
6646 Result += "\""; Result += IvarDecl->getName(); Result += "\", ";
6647 std::string IvarTypeString, QuoteIvarTypeString;
6648 Context->getObjCEncodingForType(IvarDecl->getType(), IvarTypeString,
6649 IvarDecl);
6650 RewriteObj.QuoteDoublequotes(IvarTypeString, QuoteIvarTypeString);
6651 Result += "\""; Result += QuoteIvarTypeString; Result += "\", ";
6652
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00006653 // FIXME. this alignment represents the host alignment and need be changed to
6654 // represent the target alignment.
6655 unsigned Align = Context->getTypeAlign(IvarDecl->getType())/8;
6656 Align = llvm::Log2_32(Align);
Fariborz Jahanianae932952012-02-10 20:47:10 +00006657 Result += llvm::utostr(Align); Result += ", ";
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00006658 CharUnits Size = Context->getTypeSizeInChars(IvarDecl->getType());
6659 Result += llvm::utostr(Size.getQuantity());
Fariborz Jahanianae932952012-02-10 20:47:10 +00006660 if (i == e-1)
6661 Result += "}}\n";
6662 else
6663 Result += "},\n";
6664 }
6665 Result += "};\n";
6666 }
6667}
6668
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006669/// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006670void RewriteModernObjC::RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl,
6671 std::string &Result) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006672
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006673 // Do not synthesize the protocol more than once.
6674 if (ObjCSynthesizedProtocols.count(PDecl->getCanonicalDecl()))
6675 return;
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00006676 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006677
6678 if (ObjCProtocolDecl *Def = PDecl->getDefinition())
6679 PDecl = Def;
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006680 // Must write out all protocol definitions in current qualifier list,
6681 // and in their nested qualifiers before writing out current definition.
6682 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
6683 E = PDecl->protocol_end(); I != E; ++I)
6684 RewriteObjCProtocolMetaData(*I, Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006685
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006686 // Construct method lists.
6687 std::vector<ObjCMethodDecl *> InstanceMethods, ClassMethods;
6688 std::vector<ObjCMethodDecl *> OptInstanceMethods, OptClassMethods;
6689 for (ObjCProtocolDecl::instmeth_iterator
6690 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
6691 I != E; ++I) {
6692 ObjCMethodDecl *MD = *I;
6693 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
6694 OptInstanceMethods.push_back(MD);
6695 } else {
6696 InstanceMethods.push_back(MD);
6697 }
6698 }
6699
6700 for (ObjCProtocolDecl::classmeth_iterator
6701 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
6702 I != E; ++I) {
6703 ObjCMethodDecl *MD = *I;
6704 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
6705 OptClassMethods.push_back(MD);
6706 } else {
6707 ClassMethods.push_back(MD);
6708 }
6709 }
Fariborz Jahaniane0adbd82012-02-08 22:23:26 +00006710 std::vector<ObjCMethodDecl *> AllMethods;
6711 for (unsigned i = 0, e = InstanceMethods.size(); i < e; i++)
6712 AllMethods.push_back(InstanceMethods[i]);
6713 for (unsigned i = 0, e = ClassMethods.size(); i < e; i++)
6714 AllMethods.push_back(ClassMethods[i]);
6715 for (unsigned i = 0, e = OptInstanceMethods.size(); i < e; i++)
6716 AllMethods.push_back(OptInstanceMethods[i]);
6717 for (unsigned i = 0, e = OptClassMethods.size(); i < e; i++)
6718 AllMethods.push_back(OptClassMethods[i]);
6719
6720 Write__extendedMethodTypes_initializer(*this, Context, Result,
6721 AllMethods,
6722 "_OBJC_PROTOCOL_METHOD_TYPES_",
6723 PDecl->getNameAsString());
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006724 // Protocol's super protocol list
6725 std::vector<ObjCProtocolDecl *> SuperProtocols;
6726 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
6727 E = PDecl->protocol_end(); I != E; ++I)
6728 SuperProtocols.push_back(*I);
6729
6730 Write_protocol_list_initializer(Context, Result, SuperProtocols,
6731 "_OBJC_PROTOCOL_REFS_",
6732 PDecl->getNameAsString());
6733
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006734 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006735 "_OBJC_PROTOCOL_INSTANCE_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006736 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006737
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006738 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006739 "_OBJC_PROTOCOL_CLASS_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006740 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006741
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006742 Write_method_list_t_initializer(*this, Context, Result, OptInstanceMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006743 "_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006744 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006745
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006746 Write_method_list_t_initializer(*this, Context, Result, OptClassMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006747 "_OBJC_PROTOCOL_OPT_CLASS_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006748 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006749
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006750 // Protocol's property metadata.
6751 std::vector<ObjCPropertyDecl *> ProtocolProperties;
6752 for (ObjCContainerDecl::prop_iterator I = PDecl->prop_begin(),
6753 E = PDecl->prop_end(); I != E; ++I)
David Blaikie262bc182012-04-30 02:36:29 +00006754 ProtocolProperties.push_back(&*I);
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006755
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006756 Write_prop_list_t_initializer(*this, Context, Result, ProtocolProperties,
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006757 /* Container */0,
6758 "_OBJC_PROTOCOL_PROPERTIES_",
6759 PDecl->getNameAsString());
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006760
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006761 // Writer out root metadata for current protocol: struct _protocol_t
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00006762 Result += "\n";
6763 if (LangOpts.MicrosoftExt)
Fariborz Jahanian8590d862012-04-14 17:13:08 +00006764 Result += "static ";
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00006765 Result += "struct _protocol_t _OBJC_PROTOCOL_";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006766 Result += PDecl->getNameAsString();
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006767 Result += " __attribute__ ((used, section (\"__DATA,__datacoal_nt,coalesced\"))) = {\n";
6768 Result += "\t0,\n"; // id is; is null
6769 Result += "\t\""; Result += PDecl->getNameAsString(); Result += "\",\n";
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006770 if (SuperProtocols.size() > 0) {
6771 Result += "\t(const struct _protocol_list_t *)&"; Result += "_OBJC_PROTOCOL_REFS_";
6772 Result += PDecl->getNameAsString(); Result += ",\n";
6773 }
6774 else
6775 Result += "\t0,\n";
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006776 if (InstanceMethods.size() > 0) {
6777 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
6778 Result += PDecl->getNameAsString(); Result += ",\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006779 }
6780 else
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006781 Result += "\t0,\n";
6782
6783 if (ClassMethods.size() > 0) {
6784 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_CLASS_METHODS_";
6785 Result += PDecl->getNameAsString(); Result += ",\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006786 }
6787 else
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006788 Result += "\t0,\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006789
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006790 if (OptInstanceMethods.size() > 0) {
6791 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_";
6792 Result += PDecl->getNameAsString(); Result += ",\n";
6793 }
6794 else
6795 Result += "\t0,\n";
6796
6797 if (OptClassMethods.size() > 0) {
6798 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_CLASS_METHODS_";
6799 Result += PDecl->getNameAsString(); Result += ",\n";
6800 }
6801 else
6802 Result += "\t0,\n";
6803
6804 if (ProtocolProperties.size() > 0) {
6805 Result += "\t(const struct _prop_list_t *)&_OBJC_PROTOCOL_PROPERTIES_";
6806 Result += PDecl->getNameAsString(); Result += ",\n";
6807 }
6808 else
6809 Result += "\t0,\n";
6810
6811 Result += "\t"; Result += "sizeof(_protocol_t)"; Result += ",\n";
6812 Result += "\t0,\n";
6813
Fariborz Jahaniane0adbd82012-02-08 22:23:26 +00006814 if (AllMethods.size() > 0) {
6815 Result += "\t(const char **)&"; Result += "_OBJC_PROTOCOL_METHOD_TYPES_";
6816 Result += PDecl->getNameAsString();
6817 Result += "\n};\n";
6818 }
6819 else
6820 Result += "\t0\n};\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00006821
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00006822 if (LangOpts.MicrosoftExt)
Fariborz Jahanian8590d862012-04-14 17:13:08 +00006823 Result += "static ";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00006824 Result += "struct _protocol_t *";
6825 Result += "_OBJC_LABEL_PROTOCOL_$_"; Result += PDecl->getNameAsString();
6826 Result += " = &_OBJC_PROTOCOL_"; Result += PDecl->getNameAsString();
6827 Result += ";\n";
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006828
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006829 // Mark this protocol as having been generated.
6830 if (!ObjCSynthesizedProtocols.insert(PDecl->getCanonicalDecl()))
6831 llvm_unreachable("protocol already synthesized");
6832
6833}
6834
6835void RewriteModernObjC::RewriteObjCProtocolListMetaData(
6836 const ObjCList<ObjCProtocolDecl> &Protocols,
6837 StringRef prefix, StringRef ClassName,
6838 std::string &Result) {
6839 if (Protocols.empty()) return;
6840
6841 for (unsigned i = 0; i != Protocols.size(); i++)
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006842 RewriteObjCProtocolMetaData(Protocols[i], Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006843
6844 // Output the top lovel protocol meta-data for the class.
6845 /* struct _objc_protocol_list {
6846 struct _objc_protocol_list *next;
6847 int protocol_count;
6848 struct _objc_protocol *class_protocols[];
6849 }
6850 */
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00006851 Result += "\n";
6852 if (LangOpts.MicrosoftExt)
6853 Result += "__declspec(allocate(\".cat_cls_meth$B\")) ";
6854 Result += "static struct {\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006855 Result += "\tstruct _objc_protocol_list *next;\n";
6856 Result += "\tint protocol_count;\n";
6857 Result += "\tstruct _objc_protocol *class_protocols[";
6858 Result += utostr(Protocols.size());
6859 Result += "];\n} _OBJC_";
6860 Result += prefix;
6861 Result += "_PROTOCOLS_";
6862 Result += ClassName;
6863 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
6864 "{\n\t0, ";
6865 Result += utostr(Protocols.size());
6866 Result += "\n";
6867
6868 Result += "\t,{&_OBJC_PROTOCOL_";
6869 Result += Protocols[0]->getNameAsString();
6870 Result += " \n";
6871
6872 for (unsigned i = 1; i != Protocols.size(); i++) {
6873 Result += "\t ,&_OBJC_PROTOCOL_";
6874 Result += Protocols[i]->getNameAsString();
6875 Result += "\n";
6876 }
6877 Result += "\t }\n};\n";
6878}
6879
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006880/// hasObjCExceptionAttribute - Return true if this class or any super
6881/// class has the __objc_exception__ attribute.
6882/// FIXME. Move this to ASTContext.cpp as it is also used for IRGen.
6883static bool hasObjCExceptionAttribute(ASTContext &Context,
6884 const ObjCInterfaceDecl *OID) {
6885 if (OID->hasAttr<ObjCExceptionAttr>())
6886 return true;
6887 if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
6888 return hasObjCExceptionAttribute(Context, Super);
6889 return false;
6890}
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006891
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006892void RewriteModernObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
6893 std::string &Result) {
6894 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
6895
6896 // Explicitly declared @interface's are already synthesized.
Fariborz Jahanianae932952012-02-10 20:47:10 +00006897 if (CDecl->isImplicitInterfaceDecl())
6898 assert(false &&
6899 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00006900
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00006901 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanianae932952012-02-10 20:47:10 +00006902 SmallVector<ObjCIvarDecl *, 8> IVars;
6903
6904 for (ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
6905 IVD; IVD = IVD->getNextIvar()) {
6906 // Ignore unnamed bit-fields.
6907 if (!IVD->getDeclName())
6908 continue;
6909 IVars.push_back(IVD);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006910 }
6911
Fariborz Jahanianae932952012-02-10 20:47:10 +00006912 Write__ivar_list_t_initializer(*this, Context, Result, IVars,
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006913 "_OBJC_$_INSTANCE_VARIABLES_",
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006914 CDecl);
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006915
6916 // Build _objc_method_list for class's instance methods if needed
6917 SmallVector<ObjCMethodDecl *, 32>
6918 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
6919
6920 // If any of our property implementations have associated getters or
6921 // setters, produce metadata for them as well.
6922 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
6923 PropEnd = IDecl->propimpl_end();
6924 Prop != PropEnd; ++Prop) {
David Blaikie262bc182012-04-30 02:36:29 +00006925 if (Prop->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006926 continue;
David Blaikie262bc182012-04-30 02:36:29 +00006927 if (!Prop->getPropertyIvarDecl())
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006928 continue;
David Blaikie262bc182012-04-30 02:36:29 +00006929 ObjCPropertyDecl *PD = Prop->getPropertyDecl();
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006930 if (!PD)
6931 continue;
6932 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
Fariborz Jahanian301e2e42012-05-03 22:52:13 +00006933 if (mustSynthesizeSetterGetterMethod(IDecl, PD, true /*getter*/))
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006934 InstanceMethods.push_back(Getter);
6935 if (PD->isReadOnly())
6936 continue;
6937 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
Fariborz Jahanian301e2e42012-05-03 22:52:13 +00006938 if (mustSynthesizeSetterGetterMethod(IDecl, PD, false /*setter*/))
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006939 InstanceMethods.push_back(Setter);
6940 }
6941
6942 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
6943 "_OBJC_$_INSTANCE_METHODS_",
6944 IDecl->getNameAsString(), true);
6945
6946 SmallVector<ObjCMethodDecl *, 32>
6947 ClassMethods(IDecl->classmeth_begin(), IDecl->classmeth_end());
6948
6949 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
6950 "_OBJC_$_CLASS_METHODS_",
6951 IDecl->getNameAsString(), true);
Fariborz Jahanian0a525342012-02-14 19:31:35 +00006952
6953 // Protocols referenced in class declaration?
6954 // Protocol's super protocol list
6955 std::vector<ObjCProtocolDecl *> RefedProtocols;
6956 const ObjCList<ObjCProtocolDecl> &Protocols = CDecl->getReferencedProtocols();
6957 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
6958 E = Protocols.end();
6959 I != E; ++I) {
6960 RefedProtocols.push_back(*I);
6961 // Must write out all protocol definitions in current qualifier list,
6962 // and in their nested qualifiers before writing out current definition.
6963 RewriteObjCProtocolMetaData(*I, Result);
6964 }
6965
6966 Write_protocol_list_initializer(Context, Result,
6967 RefedProtocols,
6968 "_OBJC_CLASS_PROTOCOLS_$_",
6969 IDecl->getNameAsString());
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006970
6971 // Protocol's property metadata.
6972 std::vector<ObjCPropertyDecl *> ClassProperties;
6973 for (ObjCContainerDecl::prop_iterator I = CDecl->prop_begin(),
6974 E = CDecl->prop_end(); I != E; ++I)
David Blaikie262bc182012-04-30 02:36:29 +00006975 ClassProperties.push_back(&*I);
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006976
6977 Write_prop_list_t_initializer(*this, Context, Result, ClassProperties,
Fariborz Jahanian2df089d2012-03-22 17:39:35 +00006978 /* Container */IDecl,
Fariborz Jahanianeeabf382012-02-16 21:57:59 +00006979 "_OBJC_$_PROP_LIST_",
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006980 CDecl->getNameAsString());
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006981
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006982
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006983 // Data for initializing _class_ro_t metaclass meta-data
6984 uint32_t flags = CLS_META;
6985 std::string InstanceSize;
6986 std::string InstanceStart;
6987
6988
6989 bool classIsHidden = CDecl->getVisibility() == HiddenVisibility;
6990 if (classIsHidden)
6991 flags |= OBJC2_CLS_HIDDEN;
6992
6993 if (!CDecl->getSuperClass())
6994 // class is root
6995 flags |= CLS_ROOT;
6996 InstanceSize = "sizeof(struct _class_t)";
6997 InstanceStart = InstanceSize;
6998 Write__class_ro_t_initializer(Context, Result, flags,
6999 InstanceStart, InstanceSize,
7000 ClassMethods,
7001 0,
7002 0,
7003 0,
7004 "_OBJC_METACLASS_RO_$_",
7005 CDecl->getNameAsString());
7006
7007
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00007008 // Data for initializing _class_ro_t meta-data
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00007009 flags = CLS;
7010 if (classIsHidden)
7011 flags |= OBJC2_CLS_HIDDEN;
7012
7013 if (hasObjCExceptionAttribute(*Context, CDecl))
7014 flags |= CLS_EXCEPTION;
7015
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00007016 if (!CDecl->getSuperClass())
7017 // class is root
7018 flags |= CLS_ROOT;
7019
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00007020 InstanceSize.clear();
7021 InstanceStart.clear();
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00007022 if (!ObjCSynthesizedStructs.count(CDecl)) {
7023 InstanceSize = "0";
7024 InstanceStart = "0";
7025 }
7026 else {
7027 InstanceSize = "sizeof(struct ";
7028 InstanceSize += CDecl->getNameAsString();
7029 InstanceSize += "_IMPL)";
7030
7031 ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
7032 if (IVD) {
Fariborz Jahanianacee1c92012-04-11 21:12:36 +00007033 RewriteIvarOffsetComputation(IVD, InstanceStart);
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00007034 }
7035 else
7036 InstanceStart = InstanceSize;
7037 }
7038 Write__class_ro_t_initializer(Context, Result, flags,
7039 InstanceStart, InstanceSize,
7040 InstanceMethods,
7041 RefedProtocols,
7042 IVars,
7043 ClassProperties,
7044 "_OBJC_CLASS_RO_$_",
7045 CDecl->getNameAsString());
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00007046
7047 Write_class_t(Context, Result,
7048 "OBJC_METACLASS_$_",
7049 CDecl, /*metaclass*/true);
7050
7051 Write_class_t(Context, Result,
7052 "OBJC_CLASS_$_",
7053 CDecl, /*metaclass*/false);
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00007054
7055 if (ImplementationIsNonLazy(IDecl))
7056 DefinedNonLazyClasses.push_back(CDecl);
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00007057
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007058}
7059
Fariborz Jahaniane0335782012-03-27 18:41:05 +00007060void RewriteModernObjC::RewriteClassSetupInitHook(std::string &Result) {
7061 int ClsDefCount = ClassImplementation.size();
7062 if (!ClsDefCount)
7063 return;
7064 Result += "#pragma section(\".objc_inithooks$B\", long, read, write)\n";
7065 Result += "__declspec(allocate(\".objc_inithooks$B\")) ";
7066 Result += "static void *OBJC_CLASS_SETUP[] = {\n";
7067 for (int i = 0; i < ClsDefCount; i++) {
7068 ObjCImplementationDecl *IDecl = ClassImplementation[i];
7069 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
7070 Result += "\t(void *)&OBJC_CLASS_SETUP_$_";
7071 Result += CDecl->getName(); Result += ",\n";
7072 }
7073 Result += "};\n";
7074}
7075
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007076void RewriteModernObjC::RewriteMetaDataIntoBuffer(std::string &Result) {
7077 int ClsDefCount = ClassImplementation.size();
7078 int CatDefCount = CategoryImplementation.size();
7079
7080 // For each implemented class, write out all its meta data.
7081 for (int i = 0; i < ClsDefCount; i++)
7082 RewriteObjCClassMetaData(ClassImplementation[i], Result);
7083
Fariborz Jahaniane0335782012-03-27 18:41:05 +00007084 RewriteClassSetupInitHook(Result);
7085
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007086 // For each implemented category, write out all its meta data.
7087 for (int i = 0; i < CatDefCount; i++)
7088 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
7089
Fariborz Jahaniane0335782012-03-27 18:41:05 +00007090 RewriteCategorySetupInitHook(Result);
7091
Fariborz Jahaniandf795672012-02-17 00:06:14 +00007092 if (ClsDefCount > 0) {
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00007093 if (LangOpts.MicrosoftExt)
7094 Result += "__declspec(allocate(\".objc_classlist$B\")) ";
Fariborz Jahaniandf795672012-02-17 00:06:14 +00007095 Result += "static struct _class_t *L_OBJC_LABEL_CLASS_$ [";
7096 Result += llvm::utostr(ClsDefCount); Result += "]";
7097 Result +=
7098 " __attribute__((used, section (\"__DATA, __objc_classlist,"
7099 "regular,no_dead_strip\")))= {\n";
7100 for (int i = 0; i < ClsDefCount; i++) {
7101 Result += "\t&OBJC_CLASS_$_";
7102 Result += ClassImplementation[i]->getNameAsString();
7103 Result += ",\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007104 }
Fariborz Jahaniandf795672012-02-17 00:06:14 +00007105 Result += "};\n";
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00007106
7107 if (!DefinedNonLazyClasses.empty()) {
7108 if (LangOpts.MicrosoftExt)
7109 Result += "__declspec(allocate(\".objc_nlclslist$B\")) \n";
7110 Result += "static struct _class_t *_OBJC_LABEL_NONLAZY_CLASS_$[] = {\n\t";
7111 for (unsigned i = 0, e = DefinedNonLazyClasses.size(); i < e; i++) {
7112 Result += "\t&OBJC_CLASS_$_"; Result += DefinedNonLazyClasses[i]->getNameAsString();
7113 Result += ",\n";
7114 }
7115 Result += "};\n";
7116 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007117 }
Fariborz Jahanian61186122012-02-17 18:40:41 +00007118
7119 if (CatDefCount > 0) {
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00007120 if (LangOpts.MicrosoftExt)
7121 Result += "__declspec(allocate(\".objc_catlist$B\")) ";
Fariborz Jahanian61186122012-02-17 18:40:41 +00007122 Result += "static struct _category_t *L_OBJC_LABEL_CATEGORY_$ [";
7123 Result += llvm::utostr(CatDefCount); Result += "]";
7124 Result +=
7125 " __attribute__((used, section (\"__DATA, __objc_catlist,"
7126 "regular,no_dead_strip\")))= {\n";
7127 for (int i = 0; i < CatDefCount; i++) {
7128 Result += "\t&_OBJC_$_CATEGORY_";
7129 Result +=
7130 CategoryImplementation[i]->getClassInterface()->getNameAsString();
7131 Result += "_$_";
7132 Result += CategoryImplementation[i]->getNameAsString();
7133 Result += ",\n";
7134 }
7135 Result += "};\n";
7136 }
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00007137
7138 if (!DefinedNonLazyCategories.empty()) {
7139 if (LangOpts.MicrosoftExt)
7140 Result += "__declspec(allocate(\".objc_nlcatlist$B\")) \n";
7141 Result += "static struct _category_t *_OBJC_LABEL_NONLAZY_CATEGORY_$[] = {\n\t";
7142 for (unsigned i = 0, e = DefinedNonLazyCategories.size(); i < e; i++) {
7143 Result += "\t&_OBJC_$_CATEGORY_";
7144 Result +=
7145 DefinedNonLazyCategories[i]->getClassInterface()->getNameAsString();
7146 Result += "_$_";
7147 Result += DefinedNonLazyCategories[i]->getNameAsString();
7148 Result += ",\n";
7149 }
7150 Result += "};\n";
7151 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007152}
7153
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00007154void RewriteModernObjC::WriteImageInfo(std::string &Result) {
7155 if (LangOpts.MicrosoftExt)
7156 Result += "__declspec(allocate(\".objc_imageinfo$B\")) \n";
7157
7158 Result += "static struct IMAGE_INFO { unsigned version; unsigned flag; } ";
7159 // version 0, ObjCABI is 2
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00007160 Result += "_OBJC_IMAGE_INFO = { 0, 2 };\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00007161}
7162
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007163/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
7164/// implementation.
7165void RewriteModernObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
7166 std::string &Result) {
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00007167 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007168 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
7169 // Find category declaration for this implementation.
Fariborz Jahanian61186122012-02-17 18:40:41 +00007170 ObjCCategoryDecl *CDecl=0;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007171 for (CDecl = ClassDecl->getCategoryList(); CDecl;
7172 CDecl = CDecl->getNextClassCategory())
7173 if (CDecl->getIdentifier() == IDecl->getIdentifier())
7174 break;
7175
7176 std::string FullCategoryName = ClassDecl->getNameAsString();
Fariborz Jahanian61186122012-02-17 18:40:41 +00007177 FullCategoryName += "_$_";
7178 FullCategoryName += CDecl->getNameAsString();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007179
7180 // Build _objc_method_list for class's instance methods if needed
7181 SmallVector<ObjCMethodDecl *, 32>
7182 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
7183
7184 // If any of our property implementations have associated getters or
7185 // setters, produce metadata for them as well.
7186 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
7187 PropEnd = IDecl->propimpl_end();
7188 Prop != PropEnd; ++Prop) {
David Blaikie262bc182012-04-30 02:36:29 +00007189 if (Prop->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007190 continue;
David Blaikie262bc182012-04-30 02:36:29 +00007191 if (!Prop->getPropertyIvarDecl())
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007192 continue;
David Blaikie262bc182012-04-30 02:36:29 +00007193 ObjCPropertyDecl *PD = Prop->getPropertyDecl();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007194 if (!PD)
7195 continue;
7196 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
7197 InstanceMethods.push_back(Getter);
7198 if (PD->isReadOnly())
7199 continue;
7200 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
7201 InstanceMethods.push_back(Setter);
7202 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007203
Fariborz Jahanian61186122012-02-17 18:40:41 +00007204 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
7205 "_OBJC_$_CATEGORY_INSTANCE_METHODS_",
7206 FullCategoryName, true);
7207
7208 SmallVector<ObjCMethodDecl *, 32>
7209 ClassMethods(IDecl->classmeth_begin(), IDecl->classmeth_end());
7210
7211 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
7212 "_OBJC_$_CATEGORY_CLASS_METHODS_",
7213 FullCategoryName, true);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007214
7215 // Protocols referenced in class declaration?
Fariborz Jahanian61186122012-02-17 18:40:41 +00007216 // Protocol's super protocol list
7217 std::vector<ObjCProtocolDecl *> RefedProtocols;
Argyrios Kyrtzidisa5f44412012-03-13 01:09:41 +00007218 for (ObjCInterfaceDecl::protocol_iterator I = CDecl->protocol_begin(),
7219 E = CDecl->protocol_end();
7220
7221 I != E; ++I) {
Fariborz Jahanian61186122012-02-17 18:40:41 +00007222 RefedProtocols.push_back(*I);
7223 // Must write out all protocol definitions in current qualifier list,
7224 // and in their nested qualifiers before writing out current definition.
7225 RewriteObjCProtocolMetaData(*I, Result);
7226 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007227
Fariborz Jahanian61186122012-02-17 18:40:41 +00007228 Write_protocol_list_initializer(Context, Result,
7229 RefedProtocols,
7230 "_OBJC_CATEGORY_PROTOCOLS_$_",
7231 FullCategoryName);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007232
Fariborz Jahanian61186122012-02-17 18:40:41 +00007233 // Protocol's property metadata.
7234 std::vector<ObjCPropertyDecl *> ClassProperties;
7235 for (ObjCContainerDecl::prop_iterator I = CDecl->prop_begin(),
7236 E = CDecl->prop_end(); I != E; ++I)
David Blaikie262bc182012-04-30 02:36:29 +00007237 ClassProperties.push_back(&*I);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007238
Fariborz Jahanian61186122012-02-17 18:40:41 +00007239 Write_prop_list_t_initializer(*this, Context, Result, ClassProperties,
Fariborz Jahanianebfa2722012-05-03 23:19:33 +00007240 /* Container */IDecl,
Fariborz Jahanian61186122012-02-17 18:40:41 +00007241 "_OBJC_$_PROP_LIST_",
7242 FullCategoryName);
7243
7244 Write_category_t(*this, Context, Result,
Fariborz Jahaniane0335782012-03-27 18:41:05 +00007245 CDecl,
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00007246 ClassDecl,
Fariborz Jahanian61186122012-02-17 18:40:41 +00007247 InstanceMethods,
7248 ClassMethods,
7249 RefedProtocols,
7250 ClassProperties);
7251
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00007252 // Determine if this category is also "non-lazy".
7253 if (ImplementationIsNonLazy(IDecl))
7254 DefinedNonLazyCategories.push_back(CDecl);
Fariborz Jahaniane0335782012-03-27 18:41:05 +00007255
7256}
7257
7258void RewriteModernObjC::RewriteCategorySetupInitHook(std::string &Result) {
7259 int CatDefCount = CategoryImplementation.size();
7260 if (!CatDefCount)
7261 return;
7262 Result += "#pragma section(\".objc_inithooks$B\", long, read, write)\n";
7263 Result += "__declspec(allocate(\".objc_inithooks$B\")) ";
7264 Result += "static void *OBJC_CATEGORY_SETUP[] = {\n";
7265 for (int i = 0; i < CatDefCount; i++) {
7266 ObjCCategoryImplDecl *IDecl = CategoryImplementation[i];
7267 ObjCCategoryDecl *CatDecl= IDecl->getCategoryDecl();
7268 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
7269 Result += "\t(void *)&OBJC_CATEGORY_SETUP_$_";
7270 Result += ClassDecl->getName();
7271 Result += "_$_";
7272 Result += CatDecl->getName();
7273 Result += ",\n";
7274 }
7275 Result += "};\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007276}
7277
7278// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
7279/// class methods.
7280template<typename MethodIterator>
7281void RewriteModernObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
7282 MethodIterator MethodEnd,
7283 bool IsInstanceMethod,
7284 StringRef prefix,
7285 StringRef ClassName,
7286 std::string &Result) {
7287 if (MethodBegin == MethodEnd) return;
7288
7289 if (!objc_impl_method) {
7290 /* struct _objc_method {
7291 SEL _cmd;
7292 char *method_types;
7293 void *_imp;
7294 }
7295 */
7296 Result += "\nstruct _objc_method {\n";
7297 Result += "\tSEL _cmd;\n";
7298 Result += "\tchar *method_types;\n";
7299 Result += "\tvoid *_imp;\n";
7300 Result += "};\n";
7301
7302 objc_impl_method = true;
7303 }
7304
7305 // Build _objc_method_list for class's methods if needed
7306
7307 /* struct {
7308 struct _objc_method_list *next_method;
7309 int method_count;
7310 struct _objc_method method_list[];
7311 }
7312 */
7313 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00007314 Result += "\n";
7315 if (LangOpts.MicrosoftExt) {
7316 if (IsInstanceMethod)
7317 Result += "__declspec(allocate(\".inst_meth$B\")) ";
7318 else
7319 Result += "__declspec(allocate(\".cls_meth$B\")) ";
7320 }
7321 Result += "static struct {\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007322 Result += "\tstruct _objc_method_list *next_method;\n";
7323 Result += "\tint method_count;\n";
7324 Result += "\tstruct _objc_method method_list[";
7325 Result += utostr(NumMethods);
7326 Result += "];\n} _OBJC_";
7327 Result += prefix;
7328 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
7329 Result += "_METHODS_";
7330 Result += ClassName;
7331 Result += " __attribute__ ((used, section (\"__OBJC, __";
7332 Result += IsInstanceMethod ? "inst" : "cls";
7333 Result += "_meth\")))= ";
7334 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
7335
7336 Result += "\t,{{(SEL)\"";
7337 Result += (*MethodBegin)->getSelector().getAsString().c_str();
7338 std::string MethodTypeString;
7339 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
7340 Result += "\", \"";
7341 Result += MethodTypeString;
7342 Result += "\", (void *)";
7343 Result += MethodInternalNames[*MethodBegin];
7344 Result += "}\n";
7345 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
7346 Result += "\t ,{(SEL)\"";
7347 Result += (*MethodBegin)->getSelector().getAsString().c_str();
7348 std::string MethodTypeString;
7349 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
7350 Result += "\", \"";
7351 Result += MethodTypeString;
7352 Result += "\", (void *)";
7353 Result += MethodInternalNames[*MethodBegin];
7354 Result += "}\n";
7355 }
7356 Result += "\t }\n};\n";
7357}
7358
7359Stmt *RewriteModernObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) {
7360 SourceRange OldRange = IV->getSourceRange();
7361 Expr *BaseExpr = IV->getBase();
7362
7363 // Rewrite the base, but without actually doing replaces.
7364 {
7365 DisableReplaceStmtScope S(*this);
7366 BaseExpr = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(BaseExpr));
7367 IV->setBase(BaseExpr);
7368 }
7369
7370 ObjCIvarDecl *D = IV->getDecl();
7371
7372 Expr *Replacement = IV;
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007373
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007374 if (BaseExpr->getType()->isObjCObjectPointerType()) {
7375 const ObjCInterfaceType *iFaceDecl =
Fariborz Jahanian163d3ce2012-05-08 23:54:35 +00007376 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007377 assert(iFaceDecl && "RewriteObjCIvarRefExpr - iFaceDecl is null");
7378 // lookup which class implements the instance variable.
7379 ObjCInterfaceDecl *clsDeclared = 0;
7380 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
7381 clsDeclared);
7382 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
7383
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007384 // Build name of symbol holding ivar offset.
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00007385 std::string IvarOffsetName;
7386 WriteInternalIvarName(clsDeclared, D, IvarOffsetName);
7387
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00007388 ReferencedIvars[clsDeclared].insert(D);
7389
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007390 // cast offset to "char *".
7391 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context,
7392 Context->getPointerType(Context->CharTy),
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007393 CK_BitCast,
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007394 BaseExpr);
7395 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
7396 SourceLocation(), &Context->Idents.get(IvarOffsetName),
7397 Context->UnsignedLongTy, 0, SC_Extern, SC_None);
John McCallf4b88a42012-03-10 09:33:50 +00007398 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, false,
7399 Context->UnsignedLongTy, VK_LValue,
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007400 SourceLocation());
7401 BinaryOperator *addExpr =
7402 new (Context) BinaryOperator(castExpr, DRE, BO_Add,
7403 Context->getPointerType(Context->CharTy),
7404 VK_RValue, OK_Ordinary, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007405 // Don't forget the parens to enforce the proper binding.
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007406 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(),
7407 SourceLocation(),
7408 addExpr);
Fariborz Jahanian0d6e22a2012-02-24 17:35:35 +00007409 QualType IvarT = D->getType();
Fariborz Jahanian27fc81b2012-04-27 22:48:54 +00007410
Fariborz Jahanianf5eac482012-05-02 17:34:59 +00007411 if (!isa<TypedefType>(IvarT) && IvarT->isRecordType()) {
Fariborz Jahanian27fc81b2012-04-27 22:48:54 +00007412 RecordDecl *RD = IvarT->getAs<RecordType>()->getDecl();
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00007413 RD = RD->getDefinition();
7414 if (RD && !RD->getDeclName().getAsIdentifierInfo()) {
Fariborz Jahanian27fc81b2012-04-27 22:48:54 +00007415 // decltype(((Foo_IMPL*)0)->bar) *
Fariborz Jahanianf5eac482012-05-02 17:34:59 +00007416 ObjCContainerDecl *CDecl =
7417 dyn_cast<ObjCContainerDecl>(D->getDeclContext());
7418 // ivar in class extensions requires special treatment.
7419 if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(CDecl))
7420 CDecl = CatDecl->getClassInterface();
7421 std::string RecName = CDecl->getName();
Fariborz Jahanian27fc81b2012-04-27 22:48:54 +00007422 RecName += "_IMPL";
7423 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
7424 SourceLocation(), SourceLocation(),
7425 &Context->Idents.get(RecName.c_str()));
7426 QualType PtrStructIMPL = Context->getPointerType(Context->getTagDeclType(RD));
7427 unsigned UnsignedIntSize =
7428 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
7429 Expr *Zero = IntegerLiteral::Create(*Context,
7430 llvm::APInt(UnsignedIntSize, 0),
7431 Context->UnsignedIntTy, SourceLocation());
7432 Zero = NoTypeInfoCStyleCastExpr(Context, PtrStructIMPL, CK_BitCast, Zero);
7433 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
7434 Zero);
7435 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
7436 SourceLocation(),
7437 &Context->Idents.get(D->getNameAsString()),
7438 IvarT, 0,
7439 /*BitWidth=*/0, /*Mutable=*/true,
7440 /*HasInit=*/false);
7441 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
7442 FD->getType(), VK_LValue,
7443 OK_Ordinary);
7444 IvarT = Context->getDecltypeType(ME, ME->getType());
7445 }
7446 }
Fariborz Jahanian8e0913d2012-02-29 00:26:20 +00007447 convertObjCTypeToCStyleType(IvarT);
Fariborz Jahanian0d6e22a2012-02-24 17:35:35 +00007448 QualType castT = Context->getPointerType(IvarT);
Fariborz Jahanian27fc81b2012-04-27 22:48:54 +00007449
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007450 castExpr = NoTypeInfoCStyleCastExpr(Context,
7451 castT,
7452 CK_BitCast,
7453 PE);
Fariborz Jahanian27fc81b2012-04-27 22:48:54 +00007454
7455
Fariborz Jahanian8e0913d2012-02-29 00:26:20 +00007456 Expr *Exp = new (Context) UnaryOperator(castExpr, UO_Deref, IvarT,
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007457 VK_LValue, OK_Ordinary,
7458 SourceLocation());
7459 PE = new (Context) ParenExpr(OldRange.getBegin(),
7460 OldRange.getEnd(),
7461 Exp);
7462
7463 Replacement = PE;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007464 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007465
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007466 ReplaceStmtWithRange(IV, Replacement, OldRange);
7467 return Replacement;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007468}