blob: 245e809c90d98d7359507aff5ca13cc2a585ed68 [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
Ted Kremenek305c6132012-09-01 05:09:24 +000014#include "clang/Rewrite/Frontend/ASTConsumers.h"
15#include "clang/Rewrite/Core/Rewriter.h"
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +000016#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);
Richard Smithd1420c62012-08-16 03:56:14 +0000244 New->printPretty(S, 0, PrintingPolicy(LangOpts));
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000245 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
Benjamin Kramer48d798c2012-06-02 10:20:41 +0000364 // Misc. AST transformation routines. Sometimes they end up calling
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000365 // rewriting routines on the new ASTs.
366 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
367 Expr **args, unsigned nargs,
368 SourceLocation StartLoc=SourceLocation(),
369 SourceLocation EndLoc=SourceLocation());
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +0000370
371 Expr *SynthMsgSendStretCallExpr(FunctionDecl *MsgSendStretFlavor,
372 QualType msgSendType,
373 QualType returnType,
374 SmallVectorImpl<QualType> &ArgTypes,
375 SmallVectorImpl<Expr*> &MsgExprs,
376 ObjCMethodDecl *Method);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000377
378 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp,
379 SourceLocation StartLoc=SourceLocation(),
380 SourceLocation EndLoc=SourceLocation());
381
382 void SynthCountByEnumWithState(std::string &buf);
383 void SynthMsgSendFunctionDecl();
384 void SynthMsgSendSuperFunctionDecl();
385 void SynthMsgSendStretFunctionDecl();
386 void SynthMsgSendFpretFunctionDecl();
387 void SynthMsgSendSuperStretFunctionDecl();
388 void SynthGetClassFunctionDecl();
389 void SynthGetMetaClassFunctionDecl();
390 void SynthGetSuperClassFunctionDecl();
391 void SynthSelGetUidFunctionDecl();
392 void SynthSuperContructorFunctionDecl();
393
394 // Rewriting metadata
395 template<typename MethodIterator>
396 void RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
397 MethodIterator MethodEnd,
398 bool IsInstanceMethod,
399 StringRef prefix,
400 StringRef ClassName,
401 std::string &Result);
Fariborz Jahanianda9624a2012-02-08 19:53:58 +0000402 void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
403 std::string &Result);
Fariborz Jahanianb4ee8802012-04-30 16:57:52 +0000404 void RewriteObjCProtocolListMetaData(
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000405 const ObjCList<ObjCProtocolDecl> &Prots,
406 StringRef prefix, StringRef ClassName, std::string &Result);
Fariborz Jahanianb4ee8802012-04-30 16:57:52 +0000407 void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000408 std::string &Result);
Fariborz Jahanianb4ee8802012-04-30 16:57:52 +0000409 void RewriteClassSetupInitHook(std::string &Result);
Fariborz Jahaniane0335782012-03-27 18:41:05 +0000410
Fariborz Jahanianb4ee8802012-04-30 16:57:52 +0000411 void RewriteMetaDataIntoBuffer(std::string &Result);
412 void WriteImageInfo(std::string &Result);
413 void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000414 std::string &Result);
Fariborz Jahanianb4ee8802012-04-30 16:57:52 +0000415 void RewriteCategorySetupInitHook(std::string &Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000416
417 // Rewriting ivar
Fariborz Jahanianb4ee8802012-04-30 16:57:52 +0000418 void RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000419 std::string &Result);
Fariborz Jahanianb4ee8802012-04-30 16:57:52 +0000420 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000421
422
423 std::string SynthesizeByrefCopyDestroyHelper(VarDecl *VD, int flag);
424 std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
425 StringRef funcName, std::string Tag);
426 std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
427 StringRef funcName, std::string Tag);
428 std::string SynthesizeBlockImpl(BlockExpr *CE,
429 std::string Tag, std::string Desc);
430 std::string SynthesizeBlockDescriptor(std::string DescTag,
431 std::string ImplTag,
432 int i, StringRef funcName,
433 unsigned hasCopy);
434 Stmt *SynthesizeBlockCall(CallExpr *Exp, const Expr* BlockExp);
435 void SynthesizeBlockLiterals(SourceLocation FunLocStart,
436 StringRef FunName);
437 FunctionDecl *SynthBlockInitFunctionDecl(StringRef name);
438 Stmt *SynthBlockInitExpr(BlockExpr *Exp,
John McCallf4b88a42012-03-10 09:33:50 +0000439 const SmallVector<DeclRefExpr *, 8> &InnerBlockDeclRefs);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000440
441 // Misc. helper routines.
442 QualType getProtocolType();
443 void WarnAboutReturnGotoStmts(Stmt *S);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000444 void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
445 void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
446 void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
447
448 bool IsDeclStmtInForeachHeader(DeclStmt *DS);
449 void CollectBlockDeclRefInfo(BlockExpr *Exp);
450 void GetBlockDeclRefExprs(Stmt *S);
451 void GetInnerBlockDeclRefExprs(Stmt *S,
John McCallf4b88a42012-03-10 09:33:50 +0000452 SmallVector<DeclRefExpr *, 8> &InnerBlockDeclRefs,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000453 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts);
454
455 // We avoid calling Type::isBlockPointerType(), since it operates on the
456 // canonical type. We only care if the top-level type is a closure pointer.
457 bool isTopLevelBlockPointerType(QualType T) {
458 return isa<BlockPointerType>(T);
459 }
460
461 /// convertBlockPointerToFunctionPointer - Converts a block-pointer type
462 /// to a function pointer type and upon success, returns true; false
463 /// otherwise.
464 bool convertBlockPointerToFunctionPointer(QualType &T) {
465 if (isTopLevelBlockPointerType(T)) {
466 const BlockPointerType *BPT = T->getAs<BlockPointerType>();
467 T = Context->getPointerType(BPT->getPointeeType());
468 return true;
469 }
470 return false;
471 }
472
Fariborz Jahanian164d6f82012-02-13 18:57:49 +0000473 bool convertObjCTypeToCStyleType(QualType &T);
474
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000475 bool needToScanForQualifiers(QualType T);
476 QualType getSuperStructType();
477 QualType getConstantStringStructType();
478 QualType convertFunctionTypeOfBlocks(const FunctionType *FT);
479 bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf);
480
481 void convertToUnqualifiedObjCType(QualType &T) {
Fariborz Jahaniane35abe12012-04-06 22:29:36 +0000482 if (T->isObjCQualifiedIdType()) {
483 bool isConst = T.isConstQualified();
484 T = isConst ? Context->getObjCIdType().withConst()
485 : Context->getObjCIdType();
486 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000487 else if (T->isObjCQualifiedClassType())
488 T = Context->getObjCClassType();
489 else if (T->isObjCObjectPointerType() &&
490 T->getPointeeType()->isObjCQualifiedInterfaceType()) {
491 if (const ObjCObjectPointerType * OBJPT =
492 T->getAsObjCInterfacePointerType()) {
493 const ObjCInterfaceType *IFaceT = OBJPT->getInterfaceType();
494 T = QualType(IFaceT, 0);
495 T = Context->getPointerType(T);
496 }
497 }
498 }
499
500 // FIXME: This predicate seems like it would be useful to add to ASTContext.
501 bool isObjCType(QualType T) {
502 if (!LangOpts.ObjC1 && !LangOpts.ObjC2)
503 return false;
504
505 QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
506
507 if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
508 OCT == Context->getCanonicalType(Context->getObjCClassType()))
509 return true;
510
511 if (const PointerType *PT = OCT->getAs<PointerType>()) {
512 if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
513 PT->getPointeeType()->isObjCQualifiedIdType())
514 return true;
515 }
516 return false;
517 }
518 bool PointerTypeTakesAnyBlockArguments(QualType QT);
519 bool PointerTypeTakesAnyObjCQualifiedType(QualType QT);
520 void GetExtentOfArgList(const char *Name, const char *&LParen,
521 const char *&RParen);
522
523 void QuoteDoublequotes(std::string &From, std::string &To) {
524 for (unsigned i = 0; i < From.length(); i++) {
525 if (From[i] == '"')
526 To += "\\\"";
527 else
528 To += From[i];
529 }
530 }
531
532 QualType getSimpleFunctionType(QualType result,
533 const QualType *args,
534 unsigned numArgs,
535 bool variadic = false) {
536 if (result == Context->getObjCInstanceType())
537 result = Context->getObjCIdType();
538 FunctionProtoType::ExtProtoInfo fpi;
539 fpi.Variadic = variadic;
540 return Context->getFunctionType(result, args, numArgs, fpi);
541 }
542
543 // Helper function: create a CStyleCastExpr with trivial type source info.
544 CStyleCastExpr* NoTypeInfoCStyleCastExpr(ASTContext *Ctx, QualType Ty,
545 CastKind Kind, Expr *E) {
546 TypeSourceInfo *TInfo = Ctx->getTrivialTypeSourceInfo(Ty, SourceLocation());
547 return CStyleCastExpr::Create(*Ctx, Ty, VK_RValue, Kind, E, 0, TInfo,
548 SourceLocation(), SourceLocation());
549 }
Fariborz Jahanian88f7f752012-03-14 23:18:19 +0000550
551 bool ImplementationIsNonLazy(const ObjCImplDecl *OD) const {
552 IdentifierInfo* II = &Context->Idents.get("load");
553 Selector LoadSel = Context->Selectors.getSelector(0, &II);
554 return OD->getClassMethod(LoadSel) != 0;
555 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000556 };
557
558}
559
560void RewriteModernObjC::RewriteBlocksInFunctionProtoType(QualType funcType,
561 NamedDecl *D) {
562 if (const FunctionProtoType *fproto
563 = dyn_cast<FunctionProtoType>(funcType.IgnoreParens())) {
564 for (FunctionProtoType::arg_type_iterator I = fproto->arg_type_begin(),
565 E = fproto->arg_type_end(); I && (I != E); ++I)
566 if (isTopLevelBlockPointerType(*I)) {
567 // All the args are checked/rewritten. Don't call twice!
568 RewriteBlockPointerDecl(D);
569 break;
570 }
571 }
572}
573
574void RewriteModernObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
575 const PointerType *PT = funcType->getAs<PointerType>();
576 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
577 RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND);
578}
579
580static bool IsHeaderFile(const std::string &Filename) {
581 std::string::size_type DotPos = Filename.rfind('.');
582
583 if (DotPos == std::string::npos) {
584 // no file extension
585 return false;
586 }
587
588 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
589 // C header: .h
590 // C++ header: .hh or .H;
591 return Ext == "h" || Ext == "hh" || Ext == "H";
592}
593
594RewriteModernObjC::RewriteModernObjC(std::string inFile, raw_ostream* OS,
595 DiagnosticsEngine &D, const LangOptions &LOpts,
596 bool silenceMacroWarn)
597 : Diags(D), LangOpts(LOpts), InFileName(inFile), OutFile(OS),
598 SilenceRewriteMacroWarning(silenceMacroWarn) {
599 IsHeader = IsHeaderFile(inFile);
600 RewriteFailedDiag = Diags.getCustomDiagID(DiagnosticsEngine::Warning,
601 "rewriting sub-expression within a macro (may not be correct)");
Fariborz Jahaniand13c2c22012-03-22 19:54:39 +0000602 // FIXME. This should be an error. But if block is not called, it is OK. And it
603 // may break including some headers.
604 GlobalBlockRewriteFailedDiag = Diags.getCustomDiagID(DiagnosticsEngine::Warning,
605 "rewriting block literal declared in global scope is not implemented");
606
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000607 TryFinallyContainsReturnDiag = Diags.getCustomDiagID(
608 DiagnosticsEngine::Warning,
609 "rewriter doesn't support user-specified control flow semantics "
610 "for @try/@finally (code may not execute properly)");
611}
612
613ASTConsumer *clang::CreateModernObjCRewriter(const std::string& InFile,
614 raw_ostream* OS,
615 DiagnosticsEngine &Diags,
616 const LangOptions &LOpts,
617 bool SilenceRewriteMacroWarning) {
618 return new RewriteModernObjC(InFile, OS, Diags, LOpts, SilenceRewriteMacroWarning);
619}
620
621void RewriteModernObjC::InitializeCommon(ASTContext &context) {
622 Context = &context;
623 SM = &Context->getSourceManager();
624 TUDecl = Context->getTranslationUnitDecl();
625 MsgSendFunctionDecl = 0;
626 MsgSendSuperFunctionDecl = 0;
627 MsgSendStretFunctionDecl = 0;
628 MsgSendSuperStretFunctionDecl = 0;
629 MsgSendFpretFunctionDecl = 0;
630 GetClassFunctionDecl = 0;
631 GetMetaClassFunctionDecl = 0;
632 GetSuperClassFunctionDecl = 0;
633 SelGetUidFunctionDecl = 0;
634 CFStringFunctionDecl = 0;
635 ConstantStringClassReference = 0;
636 NSStringRecord = 0;
637 CurMethodDef = 0;
638 CurFunctionDef = 0;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000639 GlobalVarDecl = 0;
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +0000640 GlobalConstructionExp = 0;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000641 SuperStructDecl = 0;
642 ProtocolTypeDecl = 0;
643 ConstantStringDecl = 0;
644 BcLabelCount = 0;
645 SuperContructorFunctionDecl = 0;
646 NumObjCStringLiterals = 0;
647 PropParentMap = 0;
648 CurrentBody = 0;
649 DisableReplaceStmt = false;
650 objc_impl_method = false;
651
652 // Get the ID and start/end of the main file.
653 MainFileID = SM->getMainFileID();
654 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
655 MainFileStart = MainBuf->getBufferStart();
656 MainFileEnd = MainBuf->getBufferEnd();
657
David Blaikie4e4d0842012-03-11 07:00:24 +0000658 Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOpts());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000659}
660
661//===----------------------------------------------------------------------===//
662// Top Level Driver Code
663//===----------------------------------------------------------------------===//
664
665void RewriteModernObjC::HandleTopLevelSingleDecl(Decl *D) {
666 if (Diags.hasErrorOccurred())
667 return;
668
669 // Two cases: either the decl could be in the main file, or it could be in a
670 // #included file. If the former, rewrite it now. If the later, check to see
671 // if we rewrote the #include/#import.
672 SourceLocation Loc = D->getLocation();
673 Loc = SM->getExpansionLoc(Loc);
674
675 // If this is for a builtin, ignore it.
676 if (Loc.isInvalid()) return;
677
678 // Look for built-in declarations that we need to refer during the rewrite.
679 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
680 RewriteFunctionDecl(FD);
681 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
682 // declared in <Foundation/NSString.h>
683 if (FVD->getName() == "_NSConstantStringClassReference") {
684 ConstantStringClassReference = FVD;
685 return;
686 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000687 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
688 RewriteCategoryDecl(CD);
689 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
690 if (PD->isThisDeclarationADefinition())
691 RewriteProtocolDecl(PD);
692 } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) {
Fariborz Jahanian8e86b2d2012-04-04 17:16:15 +0000693 // FIXME. This will not work in all situations and leaving it out
694 // is harmless.
695 // RewriteLinkageSpec(LSD);
696
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000697 // Recurse into linkage specifications
698 for (DeclContext::decl_iterator DI = LSD->decls_begin(),
699 DIEnd = LSD->decls_end();
700 DI != DIEnd; ) {
701 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>((*DI))) {
702 if (!IFace->isThisDeclarationADefinition()) {
703 SmallVector<Decl *, 8> DG;
704 SourceLocation StartLoc = IFace->getLocStart();
705 do {
706 if (isa<ObjCInterfaceDecl>(*DI) &&
707 !cast<ObjCInterfaceDecl>(*DI)->isThisDeclarationADefinition() &&
708 StartLoc == (*DI)->getLocStart())
709 DG.push_back(*DI);
710 else
711 break;
712
713 ++DI;
714 } while (DI != DIEnd);
715 RewriteForwardClassDecl(DG);
716 continue;
717 }
Fariborz Jahanianb3f904f2012-04-03 17:35:38 +0000718 else {
719 // Keep track of all interface declarations seen.
720 ObjCInterfacesSeen.push_back(IFace);
721 ++DI;
722 continue;
723 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000724 }
725
726 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>((*DI))) {
727 if (!Proto->isThisDeclarationADefinition()) {
728 SmallVector<Decl *, 8> DG;
729 SourceLocation StartLoc = Proto->getLocStart();
730 do {
731 if (isa<ObjCProtocolDecl>(*DI) &&
732 !cast<ObjCProtocolDecl>(*DI)->isThisDeclarationADefinition() &&
733 StartLoc == (*DI)->getLocStart())
734 DG.push_back(*DI);
735 else
736 break;
737
738 ++DI;
739 } while (DI != DIEnd);
740 RewriteForwardProtocolDecl(DG);
741 continue;
742 }
743 }
744
745 HandleTopLevelSingleDecl(*DI);
746 ++DI;
747 }
748 }
749 // If we have a decl in the main file, see if we should rewrite it.
750 if (SM->isFromMainFile(Loc))
751 return HandleDeclInMainFile(D);
752}
753
754//===----------------------------------------------------------------------===//
755// Syntactic (non-AST) Rewriting Code
756//===----------------------------------------------------------------------===//
757
758void RewriteModernObjC::RewriteInclude() {
759 SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID);
760 StringRef MainBuf = SM->getBufferData(MainFileID);
761 const char *MainBufStart = MainBuf.begin();
762 const char *MainBufEnd = MainBuf.end();
763 size_t ImportLen = strlen("import");
764
765 // Loop over the whole file, looking for includes.
766 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
767 if (*BufPtr == '#') {
768 if (++BufPtr == MainBufEnd)
769 return;
770 while (*BufPtr == ' ' || *BufPtr == '\t')
771 if (++BufPtr == MainBufEnd)
772 return;
773 if (!strncmp(BufPtr, "import", ImportLen)) {
774 // replace import with include
775 SourceLocation ImportLoc =
776 LocStart.getLocWithOffset(BufPtr-MainBufStart);
777 ReplaceText(ImportLoc, ImportLen, "include");
778 BufPtr += ImportLen;
779 }
780 }
781 }
782}
783
Fariborz Jahanian163d3ce2012-05-08 23:54:35 +0000784static void WriteInternalIvarName(const ObjCInterfaceDecl *IDecl,
785 ObjCIvarDecl *IvarDecl, std::string &Result) {
786 Result += "OBJC_IVAR_$_";
787 Result += IDecl->getName();
788 Result += "$";
789 Result += IvarDecl->getName();
790}
791
792std::string
793RewriteModernObjC::getIvarAccessString(ObjCIvarDecl *D) {
794 const ObjCInterfaceDecl *ClassDecl = D->getContainingInterface();
795
796 // Build name of symbol holding ivar offset.
797 std::string IvarOffsetName;
798 WriteInternalIvarName(ClassDecl, D, IvarOffsetName);
799
800
801 std::string S = "(*(";
802 QualType IvarT = D->getType();
803
804 if (!isa<TypedefType>(IvarT) && IvarT->isRecordType()) {
805 RecordDecl *RD = IvarT->getAs<RecordType>()->getDecl();
806 RD = RD->getDefinition();
807 if (RD && !RD->getDeclName().getAsIdentifierInfo()) {
808 // decltype(((Foo_IMPL*)0)->bar) *
809 ObjCContainerDecl *CDecl =
810 dyn_cast<ObjCContainerDecl>(D->getDeclContext());
811 // ivar in class extensions requires special treatment.
812 if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(CDecl))
813 CDecl = CatDecl->getClassInterface();
814 std::string RecName = CDecl->getName();
815 RecName += "_IMPL";
816 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
817 SourceLocation(), SourceLocation(),
818 &Context->Idents.get(RecName.c_str()));
819 QualType PtrStructIMPL = Context->getPointerType(Context->getTagDeclType(RD));
820 unsigned UnsignedIntSize =
821 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
822 Expr *Zero = IntegerLiteral::Create(*Context,
823 llvm::APInt(UnsignedIntSize, 0),
824 Context->UnsignedIntTy, SourceLocation());
825 Zero = NoTypeInfoCStyleCastExpr(Context, PtrStructIMPL, CK_BitCast, Zero);
826 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
827 Zero);
828 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
829 SourceLocation(),
830 &Context->Idents.get(D->getNameAsString()),
831 IvarT, 0,
832 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smithca523302012-06-10 03:12:00 +0000833 ICIS_NoInit);
Fariborz Jahanian163d3ce2012-05-08 23:54:35 +0000834 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
835 FD->getType(), VK_LValue,
836 OK_Ordinary);
837 IvarT = Context->getDecltypeType(ME, ME->getType());
838 }
839 }
840 convertObjCTypeToCStyleType(IvarT);
841 QualType castT = Context->getPointerType(IvarT);
842 std::string TypeString(castT.getAsString(Context->getPrintingPolicy()));
843 S += TypeString;
844 S += ")";
845
846 // ((char *)self + IVAR_OFFSET_SYMBOL_NAME)
847 S += "((char *)self + ";
848 S += IvarOffsetName;
849 S += "))";
850 ReferencedIvars[const_cast<ObjCInterfaceDecl *>(ClassDecl)].insert(D);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000851 return S;
852}
853
Fariborz Jahanian301e2e42012-05-03 22:52:13 +0000854/// mustSynthesizeSetterGetterMethod - returns true if setter or getter has not
855/// been found in the class implementation. In this case, it must be synthesized.
856static bool mustSynthesizeSetterGetterMethod(ObjCImplementationDecl *IMP,
857 ObjCPropertyDecl *PD,
858 bool getter) {
859 return getter ? !IMP->getInstanceMethod(PD->getGetterName())
860 : !IMP->getInstanceMethod(PD->getSetterName());
861
862}
863
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000864void RewriteModernObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
865 ObjCImplementationDecl *IMD,
866 ObjCCategoryImplDecl *CID) {
867 static bool objcGetPropertyDefined = false;
868 static bool objcSetPropertyDefined = false;
Fariborz Jahanian301e2e42012-05-03 22:52:13 +0000869 SourceLocation startGetterSetterLoc;
870
871 if (PID->getLocStart().isValid()) {
872 SourceLocation startLoc = PID->getLocStart();
873 InsertText(startLoc, "// ");
874 const char *startBuf = SM->getCharacterData(startLoc);
875 assert((*startBuf == '@') && "bogus @synthesize location");
876 const char *semiBuf = strchr(startBuf, ';');
877 assert((*semiBuf == ';') && "@synthesize: can't find ';'");
878 startGetterSetterLoc = startLoc.getLocWithOffset(semiBuf-startBuf+1);
879 }
880 else
881 startGetterSetterLoc = IMD ? IMD->getLocEnd() : CID->getLocEnd();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000882
883 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
884 return; // FIXME: is this correct?
885
886 // Generate the 'getter' function.
887 ObjCPropertyDecl *PD = PID->getPropertyDecl();
888 ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
889
890 if (!OID)
891 return;
892 unsigned Attributes = PD->getPropertyAttributes();
Fariborz Jahanian301e2e42012-05-03 22:52:13 +0000893 if (mustSynthesizeSetterGetterMethod(IMD, PD, true /*getter*/)) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000894 bool GenGetProperty = !(Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic) &&
895 (Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
896 ObjCPropertyDecl::OBJC_PR_copy));
897 std::string Getr;
898 if (GenGetProperty && !objcGetPropertyDefined) {
899 objcGetPropertyDefined = true;
900 // FIXME. Is this attribute correct in all cases?
901 Getr = "\nextern \"C\" __declspec(dllimport) "
902 "id objc_getProperty(id, SEL, long, bool);\n";
903 }
904 RewriteObjCMethodDecl(OID->getContainingInterface(),
905 PD->getGetterMethodDecl(), Getr);
906 Getr += "{ ";
907 // Synthesize an explicit cast to gain access to the ivar.
908 // See objc-act.c:objc_synthesize_new_getter() for details.
909 if (GenGetProperty) {
910 // return objc_getProperty(self, _cmd, offsetof(ClassDecl, OID), 1)
911 Getr += "typedef ";
912 const FunctionType *FPRetType = 0;
913 RewriteTypeIntoString(PD->getGetterMethodDecl()->getResultType(), Getr,
914 FPRetType);
915 Getr += " _TYPE";
916 if (FPRetType) {
917 Getr += ")"; // close the precedence "scope" for "*".
918
919 // Now, emit the argument types (if any).
920 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)){
921 Getr += "(";
922 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
923 if (i) Getr += ", ";
924 std::string ParamStr = FT->getArgType(i).getAsString(
925 Context->getPrintingPolicy());
926 Getr += ParamStr;
927 }
928 if (FT->isVariadic()) {
929 if (FT->getNumArgs()) Getr += ", ";
930 Getr += "...";
931 }
932 Getr += ")";
933 } else
934 Getr += "()";
935 }
936 Getr += ";\n";
937 Getr += "return (_TYPE)";
938 Getr += "objc_getProperty(self, _cmd, ";
939 RewriteIvarOffsetComputation(OID, Getr);
940 Getr += ", 1)";
941 }
942 else
943 Getr += "return " + getIvarAccessString(OID);
944 Getr += "; }";
Fariborz Jahanian301e2e42012-05-03 22:52:13 +0000945 InsertText(startGetterSetterLoc, Getr);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000946 }
947
Fariborz Jahanian301e2e42012-05-03 22:52:13 +0000948 if (PD->isReadOnly() ||
949 !mustSynthesizeSetterGetterMethod(IMD, PD, false /*setter*/))
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000950 return;
951
952 // Generate the 'setter' function.
953 std::string Setr;
954 bool GenSetProperty = Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
955 ObjCPropertyDecl::OBJC_PR_copy);
956 if (GenSetProperty && !objcSetPropertyDefined) {
957 objcSetPropertyDefined = true;
958 // FIXME. Is this attribute correct in all cases?
959 Setr = "\nextern \"C\" __declspec(dllimport) "
960 "void objc_setProperty (id, SEL, long, id, bool, bool);\n";
961 }
962
963 RewriteObjCMethodDecl(OID->getContainingInterface(),
964 PD->getSetterMethodDecl(), Setr);
965 Setr += "{ ";
966 // Synthesize an explicit cast to initialize the ivar.
967 // See objc-act.c:objc_synthesize_new_setter() for details.
968 if (GenSetProperty) {
969 Setr += "objc_setProperty (self, _cmd, ";
970 RewriteIvarOffsetComputation(OID, Setr);
971 Setr += ", (id)";
972 Setr += PD->getName();
973 Setr += ", ";
974 if (Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic)
975 Setr += "0, ";
976 else
977 Setr += "1, ";
978 if (Attributes & ObjCPropertyDecl::OBJC_PR_copy)
979 Setr += "1)";
980 else
981 Setr += "0)";
982 }
983 else {
984 Setr += getIvarAccessString(OID) + " = ";
985 Setr += PD->getName();
986 }
Fariborz Jahanian301e2e42012-05-03 22:52:13 +0000987 Setr += "; }\n";
988 InsertText(startGetterSetterLoc, Setr);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000989}
990
991static void RewriteOneForwardClassDecl(ObjCInterfaceDecl *ForwardDecl,
992 std::string &typedefString) {
993 typedefString += "#ifndef _REWRITER_typedef_";
994 typedefString += ForwardDecl->getNameAsString();
995 typedefString += "\n";
996 typedefString += "#define _REWRITER_typedef_";
997 typedefString += ForwardDecl->getNameAsString();
998 typedefString += "\n";
999 typedefString += "typedef struct objc_object ";
1000 typedefString += ForwardDecl->getNameAsString();
Fariborz Jahanianc38503b2012-03-12 23:58:28 +00001001 // typedef struct { } _objc_exc_Classname;
1002 typedefString += ";\ntypedef struct {} _objc_exc_";
1003 typedefString += ForwardDecl->getNameAsString();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001004 typedefString += ";\n#endif\n";
1005}
1006
1007void RewriteModernObjC::RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
1008 const std::string &typedefString) {
1009 SourceLocation startLoc = ClassDecl->getLocStart();
1010 const char *startBuf = SM->getCharacterData(startLoc);
1011 const char *semiPtr = strchr(startBuf, ';');
1012 // Replace the @class with typedefs corresponding to the classes.
1013 ReplaceText(startLoc, semiPtr-startBuf+1, typedefString);
1014}
1015
1016void RewriteModernObjC::RewriteForwardClassDecl(DeclGroupRef D) {
1017 std::string typedefString;
1018 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
1019 ObjCInterfaceDecl *ForwardDecl = cast<ObjCInterfaceDecl>(*I);
1020 if (I == D.begin()) {
1021 // Translate to typedef's that forward reference structs with the same name
1022 // as the class. As a convenience, we include the original declaration
1023 // as a comment.
1024 typedefString += "// @class ";
1025 typedefString += ForwardDecl->getNameAsString();
1026 typedefString += ";\n";
1027 }
1028 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
1029 }
1030 DeclGroupRef::iterator I = D.begin();
1031 RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(*I), typedefString);
1032}
1033
1034void RewriteModernObjC::RewriteForwardClassDecl(
1035 const llvm::SmallVector<Decl*, 8> &D) {
1036 std::string typedefString;
1037 for (unsigned i = 0; i < D.size(); i++) {
1038 ObjCInterfaceDecl *ForwardDecl = cast<ObjCInterfaceDecl>(D[i]);
1039 if (i == 0) {
1040 typedefString += "// @class ";
1041 typedefString += ForwardDecl->getNameAsString();
1042 typedefString += ";\n";
1043 }
1044 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
1045 }
1046 RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(D[0]), typedefString);
1047}
1048
1049void RewriteModernObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
1050 // When method is a synthesized one, such as a getter/setter there is
1051 // nothing to rewrite.
1052 if (Method->isImplicit())
1053 return;
1054 SourceLocation LocStart = Method->getLocStart();
1055 SourceLocation LocEnd = Method->getLocEnd();
1056
1057 if (SM->getExpansionLineNumber(LocEnd) >
1058 SM->getExpansionLineNumber(LocStart)) {
1059 InsertText(LocStart, "#if 0\n");
1060 ReplaceText(LocEnd, 1, ";\n#endif\n");
1061 } else {
1062 InsertText(LocStart, "// ");
1063 }
1064}
1065
1066void RewriteModernObjC::RewriteProperty(ObjCPropertyDecl *prop) {
1067 SourceLocation Loc = prop->getAtLoc();
1068
1069 ReplaceText(Loc, 0, "// ");
1070 // FIXME: handle properties that are declared across multiple lines.
1071}
1072
1073void RewriteModernObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
1074 SourceLocation LocStart = CatDecl->getLocStart();
1075
1076 // FIXME: handle category headers that are declared across multiple lines.
Fariborz Jahanianb68258f2012-05-01 17:46:45 +00001077 if (CatDecl->getIvarRBraceLoc().isValid()) {
1078 ReplaceText(LocStart, 1, "/** ");
1079 ReplaceText(CatDecl->getIvarRBraceLoc(), 1, "**/ ");
1080 }
1081 else {
Fariborz Jahaniand2aea122012-02-19 19:00:05 +00001082 ReplaceText(LocStart, 0, "// ");
Fariborz Jahanianb68258f2012-05-01 17:46:45 +00001083 }
Fariborz Jahanianaf300292012-02-20 20:09:20 +00001084
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001085 for (ObjCCategoryDecl::prop_iterator I = CatDecl->prop_begin(),
1086 E = CatDecl->prop_end(); I != E; ++I)
David Blaikie581deb32012-06-06 20:45:41 +00001087 RewriteProperty(*I);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001088
1089 for (ObjCCategoryDecl::instmeth_iterator
1090 I = CatDecl->instmeth_begin(), E = CatDecl->instmeth_end();
1091 I != E; ++I)
1092 RewriteMethodDeclaration(*I);
1093 for (ObjCCategoryDecl::classmeth_iterator
1094 I = CatDecl->classmeth_begin(), E = CatDecl->classmeth_end();
1095 I != E; ++I)
1096 RewriteMethodDeclaration(*I);
1097
1098 // Lastly, comment out the @end.
1099 ReplaceText(CatDecl->getAtEndRange().getBegin(),
1100 strlen("@end"), "/* @end */");
1101}
1102
1103void RewriteModernObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
1104 SourceLocation LocStart = PDecl->getLocStart();
1105 assert(PDecl->isThisDeclarationADefinition());
1106
1107 // FIXME: handle protocol headers that are declared across multiple lines.
1108 ReplaceText(LocStart, 0, "// ");
1109
1110 for (ObjCProtocolDecl::instmeth_iterator
1111 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
1112 I != E; ++I)
1113 RewriteMethodDeclaration(*I);
1114 for (ObjCProtocolDecl::classmeth_iterator
1115 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
1116 I != E; ++I)
1117 RewriteMethodDeclaration(*I);
1118
1119 for (ObjCInterfaceDecl::prop_iterator I = PDecl->prop_begin(),
1120 E = PDecl->prop_end(); I != E; ++I)
David Blaikie581deb32012-06-06 20:45:41 +00001121 RewriteProperty(*I);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001122
1123 // Lastly, comment out the @end.
1124 SourceLocation LocEnd = PDecl->getAtEndRange().getBegin();
1125 ReplaceText(LocEnd, strlen("@end"), "/* @end */");
1126
1127 // Must comment out @optional/@required
1128 const char *startBuf = SM->getCharacterData(LocStart);
1129 const char *endBuf = SM->getCharacterData(LocEnd);
1130 for (const char *p = startBuf; p < endBuf; p++) {
1131 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
1132 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
1133 ReplaceText(OptionalLoc, strlen("@optional"), "/* @optional */");
1134
1135 }
1136 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
1137 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
1138 ReplaceText(OptionalLoc, strlen("@required"), "/* @required */");
1139
1140 }
1141 }
1142}
1143
1144void RewriteModernObjC::RewriteForwardProtocolDecl(DeclGroupRef D) {
1145 SourceLocation LocStart = (*D.begin())->getLocStart();
1146 if (LocStart.isInvalid())
1147 llvm_unreachable("Invalid SourceLocation");
1148 // FIXME: handle forward protocol that are declared across multiple lines.
1149 ReplaceText(LocStart, 0, "// ");
1150}
1151
1152void
1153RewriteModernObjC::RewriteForwardProtocolDecl(const llvm::SmallVector<Decl*, 8> &DG) {
1154 SourceLocation LocStart = DG[0]->getLocStart();
1155 if (LocStart.isInvalid())
1156 llvm_unreachable("Invalid SourceLocation");
1157 // FIXME: handle forward protocol that are declared across multiple lines.
1158 ReplaceText(LocStart, 0, "// ");
1159}
1160
Fariborz Jahanianb3f904f2012-04-03 17:35:38 +00001161void
1162RewriteModernObjC::RewriteLinkageSpec(LinkageSpecDecl *LSD) {
1163 SourceLocation LocStart = LSD->getExternLoc();
1164 if (LocStart.isInvalid())
1165 llvm_unreachable("Invalid extern SourceLocation");
1166
1167 ReplaceText(LocStart, 0, "// ");
1168 if (!LSD->hasBraces())
1169 return;
1170 // FIXME. We don't rewrite well if '{' is not on same line as 'extern'.
1171 SourceLocation LocRBrace = LSD->getRBraceLoc();
1172 if (LocRBrace.isInvalid())
1173 llvm_unreachable("Invalid rbrace SourceLocation");
1174 ReplaceText(LocRBrace, 0, "// ");
1175}
1176
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001177void RewriteModernObjC::RewriteTypeIntoString(QualType T, std::string &ResultStr,
1178 const FunctionType *&FPRetType) {
1179 if (T->isObjCQualifiedIdType())
1180 ResultStr += "id";
1181 else if (T->isFunctionPointerType() ||
1182 T->isBlockPointerType()) {
1183 // needs special handling, since pointer-to-functions have special
1184 // syntax (where a decaration models use).
1185 QualType retType = T;
1186 QualType PointeeTy;
1187 if (const PointerType* PT = retType->getAs<PointerType>())
1188 PointeeTy = PT->getPointeeType();
1189 else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>())
1190 PointeeTy = BPT->getPointeeType();
1191 if ((FPRetType = PointeeTy->getAs<FunctionType>())) {
1192 ResultStr += FPRetType->getResultType().getAsString(
1193 Context->getPrintingPolicy());
1194 ResultStr += "(*";
1195 }
1196 } else
1197 ResultStr += T.getAsString(Context->getPrintingPolicy());
1198}
1199
1200void RewriteModernObjC::RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
1201 ObjCMethodDecl *OMD,
1202 std::string &ResultStr) {
1203 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
1204 const FunctionType *FPRetType = 0;
1205 ResultStr += "\nstatic ";
1206 RewriteTypeIntoString(OMD->getResultType(), ResultStr, FPRetType);
1207 ResultStr += " ";
1208
1209 // Unique method name
1210 std::string NameStr;
1211
1212 if (OMD->isInstanceMethod())
1213 NameStr += "_I_";
1214 else
1215 NameStr += "_C_";
1216
1217 NameStr += IDecl->getNameAsString();
1218 NameStr += "_";
1219
1220 if (ObjCCategoryImplDecl *CID =
1221 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
1222 NameStr += CID->getNameAsString();
1223 NameStr += "_";
1224 }
1225 // Append selector names, replacing ':' with '_'
1226 {
1227 std::string selString = OMD->getSelector().getAsString();
1228 int len = selString.size();
1229 for (int i = 0; i < len; i++)
1230 if (selString[i] == ':')
1231 selString[i] = '_';
1232 NameStr += selString;
1233 }
1234 // Remember this name for metadata emission
1235 MethodInternalNames[OMD] = NameStr;
1236 ResultStr += NameStr;
1237
1238 // Rewrite arguments
1239 ResultStr += "(";
1240
1241 // invisible arguments
1242 if (OMD->isInstanceMethod()) {
1243 QualType selfTy = Context->getObjCInterfaceType(IDecl);
1244 selfTy = Context->getPointerType(selfTy);
1245 if (!LangOpts.MicrosoftExt) {
1246 if (ObjCSynthesizedStructs.count(const_cast<ObjCInterfaceDecl*>(IDecl)))
1247 ResultStr += "struct ";
1248 }
1249 // When rewriting for Microsoft, explicitly omit the structure name.
1250 ResultStr += IDecl->getNameAsString();
1251 ResultStr += " *";
1252 }
1253 else
1254 ResultStr += Context->getObjCClassType().getAsString(
1255 Context->getPrintingPolicy());
1256
1257 ResultStr += " self, ";
1258 ResultStr += Context->getObjCSelType().getAsString(Context->getPrintingPolicy());
1259 ResultStr += " _cmd";
1260
1261 // Method arguments.
1262 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
1263 E = OMD->param_end(); PI != E; ++PI) {
1264 ParmVarDecl *PDecl = *PI;
1265 ResultStr += ", ";
1266 if (PDecl->getType()->isObjCQualifiedIdType()) {
1267 ResultStr += "id ";
1268 ResultStr += PDecl->getNameAsString();
1269 } else {
1270 std::string Name = PDecl->getNameAsString();
1271 QualType QT = PDecl->getType();
1272 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian2610f902012-03-27 16:42:20 +00001273 (void)convertBlockPointerToFunctionPointer(QT);
1274 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001275 ResultStr += Name;
1276 }
1277 }
1278 if (OMD->isVariadic())
1279 ResultStr += ", ...";
1280 ResultStr += ") ";
1281
1282 if (FPRetType) {
1283 ResultStr += ")"; // close the precedence "scope" for "*".
1284
1285 // Now, emit the argument types (if any).
1286 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
1287 ResultStr += "(";
1288 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
1289 if (i) ResultStr += ", ";
1290 std::string ParamStr = FT->getArgType(i).getAsString(
1291 Context->getPrintingPolicy());
1292 ResultStr += ParamStr;
1293 }
1294 if (FT->isVariadic()) {
1295 if (FT->getNumArgs()) ResultStr += ", ";
1296 ResultStr += "...";
1297 }
1298 ResultStr += ")";
1299 } else {
1300 ResultStr += "()";
1301 }
1302 }
1303}
1304void RewriteModernObjC::RewriteImplementationDecl(Decl *OID) {
1305 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
1306 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
1307
Fariborz Jahaniand2aea122012-02-19 19:00:05 +00001308 if (IMD) {
Fariborz Jahanianb68258f2012-05-01 17:46:45 +00001309 if (IMD->getIvarRBraceLoc().isValid()) {
1310 ReplaceText(IMD->getLocStart(), 1, "/** ");
1311 ReplaceText(IMD->getIvarRBraceLoc(), 1, "**/ ");
Fariborz Jahaniand2aea122012-02-19 19:00:05 +00001312 }
Fariborz Jahanianb68258f2012-05-01 17:46:45 +00001313 else {
1314 InsertText(IMD->getLocStart(), "// ");
1315 }
Fariborz Jahaniand2aea122012-02-19 19:00:05 +00001316 }
1317 else
1318 InsertText(CID->getLocStart(), "// ");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001319
1320 for (ObjCCategoryImplDecl::instmeth_iterator
1321 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
1322 E = IMD ? IMD->instmeth_end() : CID->instmeth_end();
1323 I != E; ++I) {
1324 std::string ResultStr;
1325 ObjCMethodDecl *OMD = *I;
1326 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
1327 SourceLocation LocStart = OMD->getLocStart();
1328 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
1329
1330 const char *startBuf = SM->getCharacterData(LocStart);
1331 const char *endBuf = SM->getCharacterData(LocEnd);
1332 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
1333 }
1334
1335 for (ObjCCategoryImplDecl::classmeth_iterator
1336 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
1337 E = IMD ? IMD->classmeth_end() : CID->classmeth_end();
1338 I != E; ++I) {
1339 std::string ResultStr;
1340 ObjCMethodDecl *OMD = *I;
1341 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
1342 SourceLocation LocStart = OMD->getLocStart();
1343 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
1344
1345 const char *startBuf = SM->getCharacterData(LocStart);
1346 const char *endBuf = SM->getCharacterData(LocEnd);
1347 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
1348 }
1349 for (ObjCCategoryImplDecl::propimpl_iterator
1350 I = IMD ? IMD->propimpl_begin() : CID->propimpl_begin(),
1351 E = IMD ? IMD->propimpl_end() : CID->propimpl_end();
1352 I != E; ++I) {
David Blaikie581deb32012-06-06 20:45:41 +00001353 RewritePropertyImplDecl(*I, IMD, CID);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001354 }
1355
1356 InsertText(IMD ? IMD->getLocEnd() : CID->getLocEnd(), "// ");
1357}
1358
1359void RewriteModernObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00001360 // Do not synthesize more than once.
1361 if (ObjCSynthesizedStructs.count(ClassDecl))
1362 return;
1363 // Make sure super class's are written before current class is written.
1364 ObjCInterfaceDecl *SuperClass = ClassDecl->getSuperClass();
1365 while (SuperClass) {
1366 RewriteInterfaceDecl(SuperClass);
1367 SuperClass = SuperClass->getSuperClass();
1368 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001369 std::string ResultStr;
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +00001370 if (!ObjCWrittenInterfaces.count(ClassDecl->getCanonicalDecl())) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001371 // we haven't seen a forward decl - generate a typedef.
Fariborz Jahanianc38503b2012-03-12 23:58:28 +00001372 RewriteOneForwardClassDecl(ClassDecl, ResultStr);
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00001373 RewriteIvarOffsetSymbols(ClassDecl, ResultStr);
1374
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001375 RewriteObjCInternalStruct(ClassDecl, ResultStr);
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +00001376 // Mark this typedef as having been written into its c++ equivalent.
1377 ObjCWrittenInterfaces.insert(ClassDecl->getCanonicalDecl());
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001378
1379 for (ObjCInterfaceDecl::prop_iterator I = ClassDecl->prop_begin(),
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001380 E = ClassDecl->prop_end(); I != E; ++I)
David Blaikie581deb32012-06-06 20:45:41 +00001381 RewriteProperty(*I);
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001382 for (ObjCInterfaceDecl::instmeth_iterator
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001383 I = ClassDecl->instmeth_begin(), E = ClassDecl->instmeth_end();
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001384 I != E; ++I)
1385 RewriteMethodDeclaration(*I);
1386 for (ObjCInterfaceDecl::classmeth_iterator
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001387 I = ClassDecl->classmeth_begin(), E = ClassDecl->classmeth_end();
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001388 I != E; ++I)
1389 RewriteMethodDeclaration(*I);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001390
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001391 // Lastly, comment out the @end.
1392 ReplaceText(ClassDecl->getAtEndRange().getBegin(), strlen("@end"),
1393 "/* @end */");
1394 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001395}
1396
1397Stmt *RewriteModernObjC::RewritePropertyOrImplicitSetter(PseudoObjectExpr *PseudoOp) {
1398 SourceRange OldRange = PseudoOp->getSourceRange();
1399
1400 // We just magically know some things about the structure of this
1401 // expression.
1402 ObjCMessageExpr *OldMsg =
1403 cast<ObjCMessageExpr>(PseudoOp->getSemanticExpr(
1404 PseudoOp->getNumSemanticExprs() - 1));
1405
1406 // Because the rewriter doesn't allow us to rewrite rewritten code,
1407 // we need to suppress rewriting the sub-statements.
Fariborz Jahanian88ec6102012-04-10 22:06:54 +00001408 Expr *Base;
1409 SmallVector<Expr*, 2> Args;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001410 {
1411 DisableReplaceStmtScope S(*this);
1412
1413 // Rebuild the base expression if we have one.
1414 Base = 0;
1415 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1416 Base = OldMsg->getInstanceReceiver();
1417 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1418 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1419 }
Fariborz Jahanian88ec6102012-04-10 22:06:54 +00001420
1421 unsigned numArgs = OldMsg->getNumArgs();
1422 for (unsigned i = 0; i < numArgs; i++) {
1423 Expr *Arg = OldMsg->getArg(i);
1424 if (isa<OpaqueValueExpr>(Arg))
1425 Arg = cast<OpaqueValueExpr>(Arg)->getSourceExpr();
1426 Arg = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Arg));
1427 Args.push_back(Arg);
1428 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001429 }
1430
1431 // TODO: avoid this copy.
1432 SmallVector<SourceLocation, 1> SelLocs;
1433 OldMsg->getSelectorLocs(SelLocs);
1434
1435 ObjCMessageExpr *NewMsg = 0;
1436 switch (OldMsg->getReceiverKind()) {
1437 case ObjCMessageExpr::Class:
1438 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1439 OldMsg->getValueKind(),
1440 OldMsg->getLeftLoc(),
1441 OldMsg->getClassReceiverTypeInfo(),
1442 OldMsg->getSelector(),
1443 SelLocs,
1444 OldMsg->getMethodDecl(),
Fariborz Jahanian88ec6102012-04-10 22:06:54 +00001445 Args,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001446 OldMsg->getRightLoc(),
1447 OldMsg->isImplicit());
1448 break;
1449
1450 case ObjCMessageExpr::Instance:
1451 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1452 OldMsg->getValueKind(),
1453 OldMsg->getLeftLoc(),
1454 Base,
1455 OldMsg->getSelector(),
1456 SelLocs,
1457 OldMsg->getMethodDecl(),
Fariborz Jahanian88ec6102012-04-10 22:06:54 +00001458 Args,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001459 OldMsg->getRightLoc(),
1460 OldMsg->isImplicit());
1461 break;
1462
1463 case ObjCMessageExpr::SuperClass:
1464 case ObjCMessageExpr::SuperInstance:
1465 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1466 OldMsg->getValueKind(),
1467 OldMsg->getLeftLoc(),
1468 OldMsg->getSuperLoc(),
1469 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1470 OldMsg->getSuperType(),
1471 OldMsg->getSelector(),
1472 SelLocs,
1473 OldMsg->getMethodDecl(),
Fariborz Jahanian88ec6102012-04-10 22:06:54 +00001474 Args,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001475 OldMsg->getRightLoc(),
1476 OldMsg->isImplicit());
1477 break;
1478 }
1479
1480 Stmt *Replacement = SynthMessageExpr(NewMsg);
1481 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1482 return Replacement;
1483}
1484
1485Stmt *RewriteModernObjC::RewritePropertyOrImplicitGetter(PseudoObjectExpr *PseudoOp) {
1486 SourceRange OldRange = PseudoOp->getSourceRange();
1487
1488 // We just magically know some things about the structure of this
1489 // expression.
1490 ObjCMessageExpr *OldMsg =
1491 cast<ObjCMessageExpr>(PseudoOp->getResultExpr()->IgnoreImplicit());
1492
1493 // Because the rewriter doesn't allow us to rewrite rewritten code,
1494 // we need to suppress rewriting the sub-statements.
1495 Expr *Base = 0;
Fariborz Jahanian88ec6102012-04-10 22:06:54 +00001496 SmallVector<Expr*, 1> Args;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001497 {
1498 DisableReplaceStmtScope S(*this);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001499 // Rebuild the base expression if we have one.
1500 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1501 Base = OldMsg->getInstanceReceiver();
1502 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1503 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1504 }
Fariborz Jahanian88ec6102012-04-10 22:06:54 +00001505 unsigned numArgs = OldMsg->getNumArgs();
1506 for (unsigned i = 0; i < numArgs; i++) {
1507 Expr *Arg = OldMsg->getArg(i);
1508 if (isa<OpaqueValueExpr>(Arg))
1509 Arg = cast<OpaqueValueExpr>(Arg)->getSourceExpr();
1510 Arg = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Arg));
1511 Args.push_back(Arg);
1512 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001513 }
1514
1515 // Intentionally empty.
1516 SmallVector<SourceLocation, 1> SelLocs;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001517
1518 ObjCMessageExpr *NewMsg = 0;
1519 switch (OldMsg->getReceiverKind()) {
1520 case ObjCMessageExpr::Class:
1521 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1522 OldMsg->getValueKind(),
1523 OldMsg->getLeftLoc(),
1524 OldMsg->getClassReceiverTypeInfo(),
1525 OldMsg->getSelector(),
1526 SelLocs,
1527 OldMsg->getMethodDecl(),
1528 Args,
1529 OldMsg->getRightLoc(),
1530 OldMsg->isImplicit());
1531 break;
1532
1533 case ObjCMessageExpr::Instance:
1534 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1535 OldMsg->getValueKind(),
1536 OldMsg->getLeftLoc(),
1537 Base,
1538 OldMsg->getSelector(),
1539 SelLocs,
1540 OldMsg->getMethodDecl(),
1541 Args,
1542 OldMsg->getRightLoc(),
1543 OldMsg->isImplicit());
1544 break;
1545
1546 case ObjCMessageExpr::SuperClass:
1547 case ObjCMessageExpr::SuperInstance:
1548 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1549 OldMsg->getValueKind(),
1550 OldMsg->getLeftLoc(),
1551 OldMsg->getSuperLoc(),
1552 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1553 OldMsg->getSuperType(),
1554 OldMsg->getSelector(),
1555 SelLocs,
1556 OldMsg->getMethodDecl(),
1557 Args,
1558 OldMsg->getRightLoc(),
1559 OldMsg->isImplicit());
1560 break;
1561 }
1562
1563 Stmt *Replacement = SynthMessageExpr(NewMsg);
1564 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1565 return Replacement;
1566}
1567
1568/// SynthCountByEnumWithState - To print:
1569/// ((unsigned int (*)
1570/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1571/// (void *)objc_msgSend)((id)l_collection,
1572/// sel_registerName(
1573/// "countByEnumeratingWithState:objects:count:"),
1574/// &enumState,
1575/// (id *)__rw_items, (unsigned int)16)
1576///
1577void RewriteModernObjC::SynthCountByEnumWithState(std::string &buf) {
1578 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1579 "id *, unsigned int))(void *)objc_msgSend)";
1580 buf += "\n\t\t";
1581 buf += "((id)l_collection,\n\t\t";
1582 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1583 buf += "\n\t\t";
1584 buf += "&enumState, "
1585 "(id *)__rw_items, (unsigned int)16)";
1586}
1587
1588/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1589/// statement to exit to its outer synthesized loop.
1590///
1591Stmt *RewriteModernObjC::RewriteBreakStmt(BreakStmt *S) {
1592 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1593 return S;
1594 // replace break with goto __break_label
1595 std::string buf;
1596
1597 SourceLocation startLoc = S->getLocStart();
1598 buf = "goto __break_label_";
1599 buf += utostr(ObjCBcLabelNo.back());
1600 ReplaceText(startLoc, strlen("break"), buf);
1601
1602 return 0;
1603}
1604
1605/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1606/// statement to continue with its inner synthesized loop.
1607///
1608Stmt *RewriteModernObjC::RewriteContinueStmt(ContinueStmt *S) {
1609 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1610 return S;
1611 // replace continue with goto __continue_label
1612 std::string buf;
1613
1614 SourceLocation startLoc = S->getLocStart();
1615 buf = "goto __continue_label_";
1616 buf += utostr(ObjCBcLabelNo.back());
1617 ReplaceText(startLoc, strlen("continue"), buf);
1618
1619 return 0;
1620}
1621
1622/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
1623/// It rewrites:
1624/// for ( type elem in collection) { stmts; }
1625
1626/// Into:
1627/// {
1628/// type elem;
1629/// struct __objcFastEnumerationState enumState = { 0 };
1630/// id __rw_items[16];
1631/// id l_collection = (id)collection;
1632/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1633/// objects:__rw_items count:16];
1634/// if (limit) {
1635/// unsigned long startMutations = *enumState.mutationsPtr;
1636/// do {
1637/// unsigned long counter = 0;
1638/// do {
1639/// if (startMutations != *enumState.mutationsPtr)
1640/// objc_enumerationMutation(l_collection);
1641/// elem = (type)enumState.itemsPtr[counter++];
1642/// stmts;
1643/// __continue_label: ;
1644/// } while (counter < limit);
1645/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1646/// objects:__rw_items count:16]);
1647/// elem = nil;
1648/// __break_label: ;
1649/// }
1650/// else
1651/// elem = nil;
1652/// }
1653///
1654Stmt *RewriteModernObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
1655 SourceLocation OrigEnd) {
1656 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
1657 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
1658 "ObjCForCollectionStmt Statement stack mismatch");
1659 assert(!ObjCBcLabelNo.empty() &&
1660 "ObjCForCollectionStmt - Label No stack empty");
1661
1662 SourceLocation startLoc = S->getLocStart();
1663 const char *startBuf = SM->getCharacterData(startLoc);
1664 StringRef elementName;
1665 std::string elementTypeAsString;
1666 std::string buf;
1667 buf = "\n{\n\t";
1668 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1669 // type elem;
1670 NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
1671 QualType ElementType = cast<ValueDecl>(D)->getType();
1672 if (ElementType->isObjCQualifiedIdType() ||
1673 ElementType->isObjCQualifiedInterfaceType())
1674 // Simply use 'id' for all qualified types.
1675 elementTypeAsString = "id";
1676 else
1677 elementTypeAsString = ElementType.getAsString(Context->getPrintingPolicy());
1678 buf += elementTypeAsString;
1679 buf += " ";
1680 elementName = D->getName();
1681 buf += elementName;
1682 buf += ";\n\t";
1683 }
1684 else {
1685 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
1686 elementName = DR->getDecl()->getName();
1687 ValueDecl *VD = cast<ValueDecl>(DR->getDecl());
1688 if (VD->getType()->isObjCQualifiedIdType() ||
1689 VD->getType()->isObjCQualifiedInterfaceType())
1690 // Simply use 'id' for all qualified types.
1691 elementTypeAsString = "id";
1692 else
1693 elementTypeAsString = VD->getType().getAsString(Context->getPrintingPolicy());
1694 }
1695
1696 // struct __objcFastEnumerationState enumState = { 0 };
1697 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1698 // id __rw_items[16];
1699 buf += "id __rw_items[16];\n\t";
1700 // id l_collection = (id)
1701 buf += "id l_collection = (id)";
1702 // Find start location of 'collection' the hard way!
1703 const char *startCollectionBuf = startBuf;
1704 startCollectionBuf += 3; // skip 'for'
1705 startCollectionBuf = strchr(startCollectionBuf, '(');
1706 startCollectionBuf++; // skip '('
1707 // find 'in' and skip it.
1708 while (*startCollectionBuf != ' ' ||
1709 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1710 (*(startCollectionBuf+3) != ' ' &&
1711 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1712 startCollectionBuf++;
1713 startCollectionBuf += 3;
1714
1715 // Replace: "for (type element in" with string constructed thus far.
1716 ReplaceText(startLoc, startCollectionBuf - startBuf, buf);
1717 // Replace ')' in for '(' type elem in collection ')' with ';'
1718 SourceLocation rightParenLoc = S->getRParenLoc();
1719 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1720 SourceLocation lparenLoc = startLoc.getLocWithOffset(rparenBuf-startBuf);
1721 buf = ";\n\t";
1722
1723 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1724 // objects:__rw_items count:16];
1725 // which is synthesized into:
1726 // unsigned int limit =
1727 // ((unsigned int (*)
1728 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1729 // (void *)objc_msgSend)((id)l_collection,
1730 // sel_registerName(
1731 // "countByEnumeratingWithState:objects:count:"),
1732 // (struct __objcFastEnumerationState *)&state,
1733 // (id *)__rw_items, (unsigned int)16);
1734 buf += "unsigned long limit =\n\t\t";
1735 SynthCountByEnumWithState(buf);
1736 buf += ";\n\t";
1737 /// if (limit) {
1738 /// unsigned long startMutations = *enumState.mutationsPtr;
1739 /// do {
1740 /// unsigned long counter = 0;
1741 /// do {
1742 /// if (startMutations != *enumState.mutationsPtr)
1743 /// objc_enumerationMutation(l_collection);
1744 /// elem = (type)enumState.itemsPtr[counter++];
1745 buf += "if (limit) {\n\t";
1746 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1747 buf += "do {\n\t\t";
1748 buf += "unsigned long counter = 0;\n\t\t";
1749 buf += "do {\n\t\t\t";
1750 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1751 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1752 buf += elementName;
1753 buf += " = (";
1754 buf += elementTypeAsString;
1755 buf += ")enumState.itemsPtr[counter++];";
1756 // Replace ')' in for '(' type elem in collection ')' with all of these.
1757 ReplaceText(lparenLoc, 1, buf);
1758
1759 /// __continue_label: ;
1760 /// } while (counter < limit);
1761 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1762 /// objects:__rw_items count:16]);
1763 /// elem = nil;
1764 /// __break_label: ;
1765 /// }
1766 /// else
1767 /// elem = nil;
1768 /// }
1769 ///
1770 buf = ";\n\t";
1771 buf += "__continue_label_";
1772 buf += utostr(ObjCBcLabelNo.back());
1773 buf += ": ;";
1774 buf += "\n\t\t";
1775 buf += "} while (counter < limit);\n\t";
1776 buf += "} while (limit = ";
1777 SynthCountByEnumWithState(buf);
1778 buf += ");\n\t";
1779 buf += elementName;
1780 buf += " = ((";
1781 buf += elementTypeAsString;
1782 buf += ")0);\n\t";
1783 buf += "__break_label_";
1784 buf += utostr(ObjCBcLabelNo.back());
1785 buf += ": ;\n\t";
1786 buf += "}\n\t";
1787 buf += "else\n\t\t";
1788 buf += elementName;
1789 buf += " = ((";
1790 buf += elementTypeAsString;
1791 buf += ")0);\n\t";
1792 buf += "}\n";
1793
1794 // Insert all these *after* the statement body.
1795 // FIXME: If this should support Obj-C++, support CXXTryStmt
1796 if (isa<CompoundStmt>(S->getBody())) {
1797 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(1);
1798 InsertText(endBodyLoc, buf);
1799 } else {
1800 /* Need to treat single statements specially. For example:
1801 *
1802 * for (A *a in b) if (stuff()) break;
1803 * for (A *a in b) xxxyy;
1804 *
1805 * The following code simply scans ahead to the semi to find the actual end.
1806 */
1807 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1808 const char *semiBuf = strchr(stmtBuf, ';');
1809 assert(semiBuf && "Can't find ';'");
1810 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(semiBuf-stmtBuf+1);
1811 InsertText(endBodyLoc, buf);
1812 }
1813 Stmts.pop_back();
1814 ObjCBcLabelNo.pop_back();
1815 return 0;
1816}
1817
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001818static void Write_RethrowObject(std::string &buf) {
1819 buf += "{ struct _FIN { _FIN(id reth) : rethrow(reth) {}\n";
1820 buf += "\t~_FIN() { if (rethrow) objc_exception_throw(rethrow); }\n";
1821 buf += "\tid rethrow;\n";
1822 buf += "\t} _fin_force_rethow(_rethrow);";
1823}
1824
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001825/// RewriteObjCSynchronizedStmt -
1826/// This routine rewrites @synchronized(expr) stmt;
1827/// into:
1828/// objc_sync_enter(expr);
1829/// @try stmt @finally { objc_sync_exit(expr); }
1830///
1831Stmt *RewriteModernObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
1832 // Get the start location and compute the semi location.
1833 SourceLocation startLoc = S->getLocStart();
1834 const char *startBuf = SM->getCharacterData(startLoc);
1835
1836 assert((*startBuf == '@') && "bogus @synchronized location");
1837
1838 std::string buf;
Fariborz Jahanian22e2f852012-03-17 17:46:02 +00001839 buf = "{ id _rethrow = 0; id _sync_obj = ";
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001840
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001841 const char *lparenBuf = startBuf;
1842 while (*lparenBuf != '(') lparenBuf++;
1843 ReplaceText(startLoc, lparenBuf-startBuf+1, buf);
Fariborz Jahanian22e2f852012-03-17 17:46:02 +00001844
1845 buf = "; objc_sync_enter(_sync_obj);\n";
1846 buf += "try {\n\tstruct _SYNC_EXIT { _SYNC_EXIT(id arg) : sync_exit(arg) {}";
1847 buf += "\n\t~_SYNC_EXIT() {objc_sync_exit(sync_exit);}";
1848 buf += "\n\tid sync_exit;";
1849 buf += "\n\t} _sync_exit(_sync_obj);\n";
1850
1851 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1852 // the sync expression is typically a message expression that's already
1853 // been rewritten! (which implies the SourceLocation's are invalid).
1854 SourceLocation RParenExprLoc = S->getSynchBody()->getLocStart();
1855 const char *RParenExprLocBuf = SM->getCharacterData(RParenExprLoc);
1856 while (*RParenExprLocBuf != ')') RParenExprLocBuf--;
1857 RParenExprLoc = startLoc.getLocWithOffset(RParenExprLocBuf-startBuf);
1858
1859 SourceLocation LBranceLoc = S->getSynchBody()->getLocStart();
1860 const char *LBraceLocBuf = SM->getCharacterData(LBranceLoc);
1861 assert (*LBraceLocBuf == '{');
1862 ReplaceText(RParenExprLoc, (LBraceLocBuf - SM->getCharacterData(RParenExprLoc) + 1), buf);
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001863
Fariborz Jahanianb655bf02012-03-16 21:43:45 +00001864 SourceLocation startRBraceLoc = S->getSynchBody()->getLocEnd();
Matt Beaumont-Gay9ab511c2012-03-16 22:20:39 +00001865 assert((*SM->getCharacterData(startRBraceLoc) == '}') &&
1866 "bogus @synchronized block");
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001867
1868 buf = "} catch (id e) {_rethrow = e;}\n";
1869 Write_RethrowObject(buf);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001870 buf += "}\n";
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001871 buf += "}\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001872
Fariborz Jahanianb655bf02012-03-16 21:43:45 +00001873 ReplaceText(startRBraceLoc, 1, buf);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001874
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001875 return 0;
1876}
1877
1878void RewriteModernObjC::WarnAboutReturnGotoStmts(Stmt *S)
1879{
1880 // Perform a bottom up traversal of all children.
1881 for (Stmt::child_range CI = S->children(); CI; ++CI)
1882 if (*CI)
1883 WarnAboutReturnGotoStmts(*CI);
1884
1885 if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
1886 Diags.Report(Context->getFullLoc(S->getLocStart()),
1887 TryFinallyContainsReturnDiag);
1888 }
1889 return;
1890}
1891
Fariborz Jahanian042b91d2012-05-23 23:47:20 +00001892Stmt *RewriteModernObjC::RewriteObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S) {
1893 SourceLocation startLoc = S->getAtLoc();
1894 ReplaceText(startLoc, strlen("@autoreleasepool"), "/* @autoreleasepool */");
Fariborz Jahanianc9b72b62012-05-24 22:59:56 +00001895 ReplaceText(S->getSubStmt()->getLocStart(), 1,
1896 "{ __AtAutoreleasePool __autoreleasepool; ");
Fariborz Jahanian042b91d2012-05-23 23:47:20 +00001897
1898 return 0;
1899}
1900
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001901Stmt *RewriteModernObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Fariborz Jahanianb1228182012-03-15 22:42:15 +00001902 ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt();
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001903 bool noCatch = S->getNumCatchStmts() == 0;
Fariborz Jahanianb1228182012-03-15 22:42:15 +00001904 std::string buf;
1905
1906 if (finalStmt) {
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001907 if (noCatch)
1908 buf = "{ id volatile _rethrow = 0;\n";
1909 else {
1910 buf = "{ id volatile _rethrow = 0;\ntry {\n";
1911 }
Fariborz Jahanianb1228182012-03-15 22:42:15 +00001912 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001913 // Get the start location and compute the semi location.
1914 SourceLocation startLoc = S->getLocStart();
1915 const char *startBuf = SM->getCharacterData(startLoc);
1916
1917 assert((*startBuf == '@') && "bogus @try location");
Fariborz Jahanianb1228182012-03-15 22:42:15 +00001918 if (finalStmt)
1919 ReplaceText(startLoc, 1, buf);
1920 else
1921 // @try -> try
1922 ReplaceText(startLoc, 1, "");
1923
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001924 for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I) {
1925 ObjCAtCatchStmt *Catch = S->getCatchStmt(I);
Fariborz Jahanian4c148812012-03-15 20:11:10 +00001926 VarDecl *catchDecl = Catch->getCatchParamDecl();
Fariborz Jahanianc38503b2012-03-12 23:58:28 +00001927
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001928 startLoc = Catch->getLocStart();
Fariborz Jahanian4c148812012-03-15 20:11:10 +00001929 bool AtRemoved = false;
1930 if (catchDecl) {
1931 QualType t = catchDecl->getType();
1932 if (const ObjCObjectPointerType *Ptr = t->getAs<ObjCObjectPointerType>()) {
1933 // Should be a pointer to a class.
1934 ObjCInterfaceDecl *IDecl = Ptr->getObjectType()->getInterface();
1935 if (IDecl) {
1936 std::string Result;
1937 startBuf = SM->getCharacterData(startLoc);
1938 assert((*startBuf == '@') && "bogus @catch location");
1939 SourceLocation rParenLoc = Catch->getRParenLoc();
1940 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1941
1942 // _objc_exc_Foo *_e as argument to catch.
1943 Result = "catch (_objc_exc_"; Result += IDecl->getNameAsString();
1944 Result += " *_"; Result += catchDecl->getNameAsString();
1945 Result += ")";
1946 ReplaceText(startLoc, rParenBuf-startBuf+1, Result);
1947 // Foo *e = (Foo *)_e;
1948 Result.clear();
1949 Result = "{ ";
1950 Result += IDecl->getNameAsString();
1951 Result += " *"; Result += catchDecl->getNameAsString();
1952 Result += " = ("; Result += IDecl->getNameAsString(); Result += "*)";
1953 Result += "_"; Result += catchDecl->getNameAsString();
1954
1955 Result += "; ";
1956 SourceLocation lBraceLoc = Catch->getCatchBody()->getLocStart();
1957 ReplaceText(lBraceLoc, 1, Result);
1958 AtRemoved = true;
1959 }
1960 }
1961 }
1962 if (!AtRemoved)
1963 // @catch -> catch
1964 ReplaceText(startLoc, 1, "");
Fariborz Jahanianc38503b2012-03-12 23:58:28 +00001965
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001966 }
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001967 if (finalStmt) {
1968 buf.clear();
1969 if (noCatch)
1970 buf = "catch (id e) {_rethrow = e;}\n";
1971 else
1972 buf = "}\ncatch (id e) {_rethrow = e;}\n";
1973
1974 SourceLocation startFinalLoc = finalStmt->getLocStart();
1975 ReplaceText(startFinalLoc, 8, buf);
1976 Stmt *body = finalStmt->getFinallyBody();
1977 SourceLocation startFinalBodyLoc = body->getLocStart();
1978 buf.clear();
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001979 Write_RethrowObject(buf);
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001980 ReplaceText(startFinalBodyLoc, 1, buf);
1981
1982 SourceLocation endFinalBodyLoc = body->getLocEnd();
1983 ReplaceText(endFinalBodyLoc, 1, "}\n}");
Fariborz Jahanian22e2f852012-03-17 17:46:02 +00001984 // Now check for any return/continue/go statements within the @try.
1985 WarnAboutReturnGotoStmts(S->getTryBody());
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001986 }
1987
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001988 return 0;
1989}
1990
1991// This can't be done with ReplaceStmt(S, ThrowExpr), since
1992// the throw expression is typically a message expression that's already
1993// been rewritten! (which implies the SourceLocation's are invalid).
1994Stmt *RewriteModernObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
1995 // Get the start location and compute the semi location.
1996 SourceLocation startLoc = S->getLocStart();
1997 const char *startBuf = SM->getCharacterData(startLoc);
1998
1999 assert((*startBuf == '@') && "bogus @throw location");
2000
2001 std::string buf;
2002 /* void objc_exception_throw(id) __attribute__((noreturn)); */
2003 if (S->getThrowExpr())
2004 buf = "objc_exception_throw(";
Fariborz Jahanian40539462012-03-16 16:52:06 +00002005 else
2006 buf = "throw";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002007
2008 // handle "@ throw" correctly.
2009 const char *wBuf = strchr(startBuf, 'w');
2010 assert((*wBuf == 'w') && "@throw: can't find 'w'");
2011 ReplaceText(startLoc, wBuf-startBuf+1, buf);
2012
2013 const char *semiBuf = strchr(startBuf, ';');
2014 assert((*semiBuf == ';') && "@throw: can't find ';'");
2015 SourceLocation semiLoc = startLoc.getLocWithOffset(semiBuf-startBuf);
Fariborz Jahanian40539462012-03-16 16:52:06 +00002016 if (S->getThrowExpr())
2017 ReplaceText(semiLoc, 1, ");");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002018 return 0;
2019}
2020
2021Stmt *RewriteModernObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
2022 // Create a new string expression.
2023 QualType StrType = Context->getPointerType(Context->CharTy);
2024 std::string StrEncoding;
2025 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
2026 Expr *Replacement = StringLiteral::Create(*Context, StrEncoding,
2027 StringLiteral::Ascii, false,
2028 StrType, SourceLocation());
2029 ReplaceStmt(Exp, Replacement);
2030
2031 // Replace this subexpr in the parent.
2032 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2033 return Replacement;
2034}
2035
2036Stmt *RewriteModernObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
2037 if (!SelGetUidFunctionDecl)
2038 SynthSelGetUidFunctionDecl();
2039 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
2040 // Create a call to sel_registerName("selName").
2041 SmallVector<Expr*, 8> SelExprs;
2042 QualType argType = Context->getPointerType(Context->CharTy);
2043 SelExprs.push_back(StringLiteral::Create(*Context,
2044 Exp->getSelector().getAsString(),
2045 StringLiteral::Ascii, false,
2046 argType, SourceLocation()));
2047 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2048 &SelExprs[0], SelExprs.size());
2049 ReplaceStmt(Exp, SelExp);
2050 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2051 return SelExp;
2052}
2053
2054CallExpr *RewriteModernObjC::SynthesizeCallToFunctionDecl(
2055 FunctionDecl *FD, Expr **args, unsigned nargs, SourceLocation StartLoc,
2056 SourceLocation EndLoc) {
2057 // Get the type, we will need to reference it in a couple spots.
2058 QualType msgSendType = FD->getType();
2059
2060 // Create a reference to the objc_msgSend() declaration.
2061 DeclRefExpr *DRE =
John McCallf4b88a42012-03-10 09:33:50 +00002062 new (Context) DeclRefExpr(FD, false, msgSendType, VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002063
2064 // Now, we cast the reference to a pointer to the objc_msgSend type.
2065 QualType pToFunc = Context->getPointerType(msgSendType);
2066 ImplicitCastExpr *ICE =
2067 ImplicitCastExpr::Create(*Context, pToFunc, CK_FunctionToPointerDecay,
2068 DRE, 0, VK_RValue);
2069
2070 const FunctionType *FT = msgSendType->getAs<FunctionType>();
2071
2072 CallExpr *Exp =
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002073 new (Context) CallExpr(*Context, ICE, llvm::makeArrayRef(args, nargs),
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002074 FT->getCallResultType(*Context),
2075 VK_RValue, EndLoc);
2076 return Exp;
2077}
2078
2079static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
2080 const char *&startRef, const char *&endRef) {
2081 while (startBuf < endBuf) {
2082 if (*startBuf == '<')
2083 startRef = startBuf; // mark the start.
2084 if (*startBuf == '>') {
2085 if (startRef && *startRef == '<') {
2086 endRef = startBuf; // mark the end.
2087 return true;
2088 }
2089 return false;
2090 }
2091 startBuf++;
2092 }
2093 return false;
2094}
2095
2096static void scanToNextArgument(const char *&argRef) {
2097 int angle = 0;
2098 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
2099 if (*argRef == '<')
2100 angle++;
2101 else if (*argRef == '>')
2102 angle--;
2103 argRef++;
2104 }
2105 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
2106}
2107
2108bool RewriteModernObjC::needToScanForQualifiers(QualType T) {
2109 if (T->isObjCQualifiedIdType())
2110 return true;
2111 if (const PointerType *PT = T->getAs<PointerType>()) {
2112 if (PT->getPointeeType()->isObjCQualifiedIdType())
2113 return true;
2114 }
2115 if (T->isObjCObjectPointerType()) {
2116 T = T->getPointeeType();
2117 return T->isObjCQualifiedInterfaceType();
2118 }
2119 if (T->isArrayType()) {
2120 QualType ElemTy = Context->getBaseElementType(T);
2121 return needToScanForQualifiers(ElemTy);
2122 }
2123 return false;
2124}
2125
2126void RewriteModernObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
2127 QualType Type = E->getType();
2128 if (needToScanForQualifiers(Type)) {
2129 SourceLocation Loc, EndLoc;
2130
2131 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
2132 Loc = ECE->getLParenLoc();
2133 EndLoc = ECE->getRParenLoc();
2134 } else {
2135 Loc = E->getLocStart();
2136 EndLoc = E->getLocEnd();
2137 }
2138 // This will defend against trying to rewrite synthesized expressions.
2139 if (Loc.isInvalid() || EndLoc.isInvalid())
2140 return;
2141
2142 const char *startBuf = SM->getCharacterData(Loc);
2143 const char *endBuf = SM->getCharacterData(EndLoc);
2144 const char *startRef = 0, *endRef = 0;
2145 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2146 // Get the locations of the startRef, endRef.
2147 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-startBuf);
2148 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-startBuf+1);
2149 // Comment out the protocol references.
2150 InsertText(LessLoc, "/*");
2151 InsertText(GreaterLoc, "*/");
2152 }
2153 }
2154}
2155
2156void RewriteModernObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
2157 SourceLocation Loc;
2158 QualType Type;
2159 const FunctionProtoType *proto = 0;
2160 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
2161 Loc = VD->getLocation();
2162 Type = VD->getType();
2163 }
2164 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
2165 Loc = FD->getLocation();
2166 // Check for ObjC 'id' and class types that have been adorned with protocol
2167 // information (id<p>, C<p>*). The protocol references need to be rewritten!
2168 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2169 assert(funcType && "missing function type");
2170 proto = dyn_cast<FunctionProtoType>(funcType);
2171 if (!proto)
2172 return;
2173 Type = proto->getResultType();
2174 }
2175 else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
2176 Loc = FD->getLocation();
2177 Type = FD->getType();
2178 }
2179 else
2180 return;
2181
2182 if (needToScanForQualifiers(Type)) {
2183 // Since types are unique, we need to scan the buffer.
2184
2185 const char *endBuf = SM->getCharacterData(Loc);
2186 const char *startBuf = endBuf;
2187 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
2188 startBuf--; // scan backward (from the decl location) for return type.
2189 const char *startRef = 0, *endRef = 0;
2190 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2191 // Get the locations of the startRef, endRef.
2192 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-endBuf);
2193 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-endBuf+1);
2194 // Comment out the protocol references.
2195 InsertText(LessLoc, "/*");
2196 InsertText(GreaterLoc, "*/");
2197 }
2198 }
2199 if (!proto)
2200 return; // most likely, was a variable
2201 // Now check arguments.
2202 const char *startBuf = SM->getCharacterData(Loc);
2203 const char *startFuncBuf = startBuf;
2204 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
2205 if (needToScanForQualifiers(proto->getArgType(i))) {
2206 // Since types are unique, we need to scan the buffer.
2207
2208 const char *endBuf = startBuf;
2209 // scan forward (from the decl location) for argument types.
2210 scanToNextArgument(endBuf);
2211 const char *startRef = 0, *endRef = 0;
2212 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2213 // Get the locations of the startRef, endRef.
2214 SourceLocation LessLoc =
2215 Loc.getLocWithOffset(startRef-startFuncBuf);
2216 SourceLocation GreaterLoc =
2217 Loc.getLocWithOffset(endRef-startFuncBuf+1);
2218 // Comment out the protocol references.
2219 InsertText(LessLoc, "/*");
2220 InsertText(GreaterLoc, "*/");
2221 }
2222 startBuf = ++endBuf;
2223 }
2224 else {
2225 // If the function name is derived from a macro expansion, then the
2226 // argument buffer will not follow the name. Need to speak with Chris.
2227 while (*startBuf && *startBuf != ')' && *startBuf != ',')
2228 startBuf++; // scan forward (from the decl location) for argument types.
2229 startBuf++;
2230 }
2231 }
2232}
2233
2234void RewriteModernObjC::RewriteTypeOfDecl(VarDecl *ND) {
2235 QualType QT = ND->getType();
2236 const Type* TypePtr = QT->getAs<Type>();
2237 if (!isa<TypeOfExprType>(TypePtr))
2238 return;
2239 while (isa<TypeOfExprType>(TypePtr)) {
2240 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
2241 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
2242 TypePtr = QT->getAs<Type>();
2243 }
2244 // FIXME. This will not work for multiple declarators; as in:
2245 // __typeof__(a) b,c,d;
2246 std::string TypeAsString(QT.getAsString(Context->getPrintingPolicy()));
2247 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
2248 const char *startBuf = SM->getCharacterData(DeclLoc);
2249 if (ND->getInit()) {
2250 std::string Name(ND->getNameAsString());
2251 TypeAsString += " " + Name + " = ";
2252 Expr *E = ND->getInit();
2253 SourceLocation startLoc;
2254 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
2255 startLoc = ECE->getLParenLoc();
2256 else
2257 startLoc = E->getLocStart();
2258 startLoc = SM->getExpansionLoc(startLoc);
2259 const char *endBuf = SM->getCharacterData(startLoc);
2260 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
2261 }
2262 else {
2263 SourceLocation X = ND->getLocEnd();
2264 X = SM->getExpansionLoc(X);
2265 const char *endBuf = SM->getCharacterData(X);
2266 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
2267 }
2268}
2269
2270// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
2271void RewriteModernObjC::SynthSelGetUidFunctionDecl() {
2272 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
2273 SmallVector<QualType, 16> ArgTys;
2274 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2275 QualType getFuncType =
2276 getSimpleFunctionType(Context->getObjCSelType(), &ArgTys[0], ArgTys.size());
2277 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2278 SourceLocation(),
2279 SourceLocation(),
2280 SelGetUidIdent, getFuncType, 0,
2281 SC_Extern,
2282 SC_None, false);
2283}
2284
2285void RewriteModernObjC::RewriteFunctionDecl(FunctionDecl *FD) {
2286 // declared in <objc/objc.h>
2287 if (FD->getIdentifier() &&
2288 FD->getName() == "sel_registerName") {
2289 SelGetUidFunctionDecl = FD;
2290 return;
2291 }
2292 RewriteObjCQualifiedInterfaceTypes(FD);
2293}
2294
2295void RewriteModernObjC::RewriteBlockPointerType(std::string& Str, QualType Type) {
2296 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
2297 const char *argPtr = TypeString.c_str();
2298 if (!strchr(argPtr, '^')) {
2299 Str += TypeString;
2300 return;
2301 }
2302 while (*argPtr) {
2303 Str += (*argPtr == '^' ? '*' : *argPtr);
2304 argPtr++;
2305 }
2306}
2307
2308// FIXME. Consolidate this routine with RewriteBlockPointerType.
2309void RewriteModernObjC::RewriteBlockPointerTypeVariable(std::string& Str,
2310 ValueDecl *VD) {
2311 QualType Type = VD->getType();
2312 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
2313 const char *argPtr = TypeString.c_str();
2314 int paren = 0;
2315 while (*argPtr) {
2316 switch (*argPtr) {
2317 case '(':
2318 Str += *argPtr;
2319 paren++;
2320 break;
2321 case ')':
2322 Str += *argPtr;
2323 paren--;
2324 break;
2325 case '^':
2326 Str += '*';
2327 if (paren == 1)
2328 Str += VD->getNameAsString();
2329 break;
2330 default:
2331 Str += *argPtr;
2332 break;
2333 }
2334 argPtr++;
2335 }
2336}
2337
Fariborz Jahanianb75f8de2012-04-19 00:50:01 +00002338void RewriteModernObjC::RewriteBlockLiteralFunctionDecl(FunctionDecl *FD) {
2339 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
2340 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2341 const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(funcType);
2342 if (!proto)
2343 return;
2344 QualType Type = proto->getResultType();
2345 std::string FdStr = Type.getAsString(Context->getPrintingPolicy());
2346 FdStr += " ";
2347 FdStr += FD->getName();
2348 FdStr += "(";
2349 unsigned numArgs = proto->getNumArgs();
2350 for (unsigned i = 0; i < numArgs; i++) {
2351 QualType ArgType = proto->getArgType(i);
2352 RewriteBlockPointerType(FdStr, ArgType);
2353 if (i+1 < numArgs)
2354 FdStr += ", ";
2355 }
Fariborz Jahanianb5863da2012-04-19 16:30:28 +00002356 if (FD->isVariadic()) {
2357 FdStr += (numArgs > 0) ? ", ...);\n" : "...);\n";
2358 }
2359 else
2360 FdStr += ");\n";
Fariborz Jahanianb75f8de2012-04-19 00:50:01 +00002361 InsertText(FunLocStart, FdStr);
2362}
2363
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002364// SynthSuperContructorFunctionDecl - id __rw_objc_super(id obj, id super);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002365void RewriteModernObjC::SynthSuperContructorFunctionDecl() {
2366 if (SuperContructorFunctionDecl)
2367 return;
2368 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
2369 SmallVector<QualType, 16> ArgTys;
2370 QualType argT = Context->getObjCIdType();
2371 assert(!argT.isNull() && "Can't find 'id' type");
2372 ArgTys.push_back(argT);
2373 ArgTys.push_back(argT);
2374 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2375 &ArgTys[0], ArgTys.size());
2376 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2377 SourceLocation(),
2378 SourceLocation(),
2379 msgSendIdent, msgSendType, 0,
2380 SC_Extern,
2381 SC_None, false);
2382}
2383
2384// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
2385void RewriteModernObjC::SynthMsgSendFunctionDecl() {
2386 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
2387 SmallVector<QualType, 16> ArgTys;
2388 QualType argT = Context->getObjCIdType();
2389 assert(!argT.isNull() && "Can't find 'id' type");
2390 ArgTys.push_back(argT);
2391 argT = Context->getObjCSelType();
2392 assert(!argT.isNull() && "Can't find 'SEL' type");
2393 ArgTys.push_back(argT);
2394 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2395 &ArgTys[0], ArgTys.size(),
2396 true /*isVariadic*/);
2397 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2398 SourceLocation(),
2399 SourceLocation(),
2400 msgSendIdent, msgSendType, 0,
2401 SC_Extern,
2402 SC_None, false);
2403}
2404
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002405// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(void);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002406void RewriteModernObjC::SynthMsgSendSuperFunctionDecl() {
2407 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002408 SmallVector<QualType, 2> ArgTys;
2409 ArgTys.push_back(Context->VoidTy);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002410 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002411 &ArgTys[0], 1,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002412 true /*isVariadic*/);
2413 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2414 SourceLocation(),
2415 SourceLocation(),
2416 msgSendIdent, msgSendType, 0,
2417 SC_Extern,
2418 SC_None, false);
2419}
2420
2421// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
2422void RewriteModernObjC::SynthMsgSendStretFunctionDecl() {
2423 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
2424 SmallVector<QualType, 16> ArgTys;
2425 QualType argT = Context->getObjCIdType();
2426 assert(!argT.isNull() && "Can't find 'id' type");
2427 ArgTys.push_back(argT);
2428 argT = Context->getObjCSelType();
2429 assert(!argT.isNull() && "Can't find 'SEL' type");
2430 ArgTys.push_back(argT);
2431 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2432 &ArgTys[0], ArgTys.size(),
2433 true /*isVariadic*/);
2434 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2435 SourceLocation(),
2436 SourceLocation(),
2437 msgSendIdent, msgSendType, 0,
2438 SC_Extern,
2439 SC_None, false);
2440}
2441
2442// SynthMsgSendSuperStretFunctionDecl -
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002443// id objc_msgSendSuper_stret(void);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002444void RewriteModernObjC::SynthMsgSendSuperStretFunctionDecl() {
2445 IdentifierInfo *msgSendIdent =
2446 &Context->Idents.get("objc_msgSendSuper_stret");
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002447 SmallVector<QualType, 2> ArgTys;
2448 ArgTys.push_back(Context->VoidTy);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002449 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002450 &ArgTys[0], 1,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002451 true /*isVariadic*/);
2452 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2453 SourceLocation(),
2454 SourceLocation(),
2455 msgSendIdent, msgSendType, 0,
2456 SC_Extern,
2457 SC_None, false);
2458}
2459
2460// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
2461void RewriteModernObjC::SynthMsgSendFpretFunctionDecl() {
2462 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
2463 SmallVector<QualType, 16> ArgTys;
2464 QualType argT = Context->getObjCIdType();
2465 assert(!argT.isNull() && "Can't find 'id' type");
2466 ArgTys.push_back(argT);
2467 argT = Context->getObjCSelType();
2468 assert(!argT.isNull() && "Can't find 'SEL' type");
2469 ArgTys.push_back(argT);
2470 QualType msgSendType = getSimpleFunctionType(Context->DoubleTy,
2471 &ArgTys[0], ArgTys.size(),
2472 true /*isVariadic*/);
2473 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2474 SourceLocation(),
2475 SourceLocation(),
2476 msgSendIdent, msgSendType, 0,
2477 SC_Extern,
2478 SC_None, false);
2479}
2480
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00002481// SynthGetClassFunctionDecl - Class objc_getClass(const char *name);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002482void RewriteModernObjC::SynthGetClassFunctionDecl() {
2483 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
2484 SmallVector<QualType, 16> ArgTys;
2485 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00002486 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002487 &ArgTys[0], ArgTys.size());
2488 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2489 SourceLocation(),
2490 SourceLocation(),
2491 getClassIdent, getClassType, 0,
2492 SC_Extern,
2493 SC_None, false);
2494}
2495
2496// SynthGetSuperClassFunctionDecl - Class class_getSuperclass(Class cls);
2497void RewriteModernObjC::SynthGetSuperClassFunctionDecl() {
2498 IdentifierInfo *getSuperClassIdent =
2499 &Context->Idents.get("class_getSuperclass");
2500 SmallVector<QualType, 16> ArgTys;
2501 ArgTys.push_back(Context->getObjCClassType());
2502 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
2503 &ArgTys[0], ArgTys.size());
2504 GetSuperClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2505 SourceLocation(),
2506 SourceLocation(),
2507 getSuperClassIdent,
2508 getClassType, 0,
2509 SC_Extern,
2510 SC_None,
2511 false);
2512}
2513
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00002514// SynthGetMetaClassFunctionDecl - Class objc_getMetaClass(const char *name);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002515void RewriteModernObjC::SynthGetMetaClassFunctionDecl() {
2516 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
2517 SmallVector<QualType, 16> ArgTys;
2518 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00002519 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002520 &ArgTys[0], ArgTys.size());
2521 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2522 SourceLocation(),
2523 SourceLocation(),
2524 getClassIdent, getClassType, 0,
2525 SC_Extern,
2526 SC_None, false);
2527}
2528
2529Stmt *RewriteModernObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
2530 QualType strType = getConstantStringStructType();
2531
2532 std::string S = "__NSConstantStringImpl_";
2533
2534 std::string tmpName = InFileName;
2535 unsigned i;
2536 for (i=0; i < tmpName.length(); i++) {
2537 char c = tmpName.at(i);
2538 // replace any non alphanumeric characters with '_'.
2539 if (!isalpha(c) && (c < '0' || c > '9'))
2540 tmpName[i] = '_';
2541 }
2542 S += tmpName;
2543 S += "_";
2544 S += utostr(NumObjCStringLiterals++);
2545
2546 Preamble += "static __NSConstantStringImpl " + S;
2547 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2548 Preamble += "0x000007c8,"; // utf8_str
2549 // The pretty printer for StringLiteral handles escape characters properly.
2550 std::string prettyBufS;
2551 llvm::raw_string_ostream prettyBuf(prettyBufS);
Richard Smithd1420c62012-08-16 03:56:14 +00002552 Exp->getString()->printPretty(prettyBuf, 0, PrintingPolicy(LangOpts));
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002553 Preamble += prettyBuf.str();
2554 Preamble += ",";
2555 Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
2556
2557 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
2558 SourceLocation(), &Context->Idents.get(S),
2559 strType, 0, SC_Static, SC_None);
John McCallf4b88a42012-03-10 09:33:50 +00002560 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, false, strType, VK_LValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002561 SourceLocation());
2562 Expr *Unop = new (Context) UnaryOperator(DRE, UO_AddrOf,
2563 Context->getPointerType(DRE->getType()),
2564 VK_RValue, OK_Ordinary,
2565 SourceLocation());
2566 // cast to NSConstantString *
2567 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Exp->getType(),
2568 CK_CPointerToObjCPointerCast, Unop);
2569 ReplaceStmt(Exp, cast);
2570 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2571 return cast;
2572}
2573
Fariborz Jahanian55947042012-03-27 20:17:30 +00002574Stmt *RewriteModernObjC::RewriteObjCBoolLiteralExpr(ObjCBoolLiteralExpr *Exp) {
2575 unsigned IntSize =
2576 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
2577
2578 Expr *FlagExp = IntegerLiteral::Create(*Context,
2579 llvm::APInt(IntSize, Exp->getValue()),
2580 Context->IntTy, Exp->getLocation());
2581 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Context->ObjCBuiltinBoolTy,
2582 CK_BitCast, FlagExp);
2583 ParenExpr *PE = new (Context) ParenExpr(Exp->getLocation(), Exp->getExprLoc(),
2584 cast);
2585 ReplaceStmt(Exp, PE);
2586 return PE;
2587}
2588
Patrick Beardeb382ec2012-04-19 00:25:12 +00002589Stmt *RewriteModernObjC::RewriteObjCBoxedExpr(ObjCBoxedExpr *Exp) {
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002590 // synthesize declaration of helper functions needed in this routine.
2591 if (!SelGetUidFunctionDecl)
2592 SynthSelGetUidFunctionDecl();
2593 // use objc_msgSend() for all.
2594 if (!MsgSendFunctionDecl)
2595 SynthMsgSendFunctionDecl();
2596 if (!GetClassFunctionDecl)
2597 SynthGetClassFunctionDecl();
2598
2599 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2600 SourceLocation StartLoc = Exp->getLocStart();
2601 SourceLocation EndLoc = Exp->getLocEnd();
2602
2603 // Synthesize a call to objc_msgSend().
2604 SmallVector<Expr*, 4> MsgExprs;
2605 SmallVector<Expr*, 4> ClsExprs;
2606 QualType argType = Context->getPointerType(Context->CharTy);
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002607
Patrick Beardeb382ec2012-04-19 00:25:12 +00002608 // Create a call to objc_getClass("<BoxingClass>"). It will be the 1st argument.
2609 ObjCMethodDecl *BoxingMethod = Exp->getBoxingMethod();
2610 ObjCInterfaceDecl *BoxingClass = BoxingMethod->getClassInterface();
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002611
Patrick Beardeb382ec2012-04-19 00:25:12 +00002612 IdentifierInfo *clsName = BoxingClass->getIdentifier();
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002613 ClsExprs.push_back(StringLiteral::Create(*Context,
2614 clsName->getName(),
2615 StringLiteral::Ascii, false,
2616 argType, SourceLocation()));
2617 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2618 &ClsExprs[0],
2619 ClsExprs.size(),
2620 StartLoc, EndLoc);
2621 MsgExprs.push_back(Cls);
2622
Patrick Beardeb382ec2012-04-19 00:25:12 +00002623 // Create a call to sel_registerName("<BoxingMethod>:"), etc.
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002624 // it will be the 2nd argument.
2625 SmallVector<Expr*, 4> SelExprs;
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002626 SelExprs.push_back(StringLiteral::Create(*Context,
Patrick Beardeb382ec2012-04-19 00:25:12 +00002627 BoxingMethod->getSelector().getAsString(),
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002628 StringLiteral::Ascii, false,
2629 argType, SourceLocation()));
2630 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2631 &SelExprs[0], SelExprs.size(),
2632 StartLoc, EndLoc);
2633 MsgExprs.push_back(SelExp);
2634
Patrick Beardeb382ec2012-04-19 00:25:12 +00002635 // User provided sub-expression is the 3rd, and last, argument.
2636 Expr *subExpr = Exp->getSubExpr();
2637 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(subExpr)) {
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002638 QualType type = ICE->getType();
2639 const Expr *SubExpr = ICE->IgnoreParenImpCasts();
2640 CastKind CK = CK_BitCast;
2641 if (SubExpr->getType()->isIntegralType(*Context) && type->isBooleanType())
2642 CK = CK_IntegralToBoolean;
Patrick Beardeb382ec2012-04-19 00:25:12 +00002643 subExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, subExpr);
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002644 }
Patrick Beardeb382ec2012-04-19 00:25:12 +00002645 MsgExprs.push_back(subExpr);
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002646
2647 SmallVector<QualType, 4> ArgTypes;
2648 ArgTypes.push_back(Context->getObjCIdType());
2649 ArgTypes.push_back(Context->getObjCSelType());
Patrick Beardeb382ec2012-04-19 00:25:12 +00002650 for (ObjCMethodDecl::param_iterator PI = BoxingMethod->param_begin(),
2651 E = BoxingMethod->param_end(); PI != E; ++PI)
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002652 ArgTypes.push_back((*PI)->getType());
Patrick Beardeb382ec2012-04-19 00:25:12 +00002653
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002654 QualType returnType = Exp->getType();
2655 // Get the type, we will need to reference it in a couple spots.
2656 QualType msgSendType = MsgSendFlavor->getType();
2657
2658 // Create a reference to the objc_msgSend() declaration.
2659 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
2660 VK_LValue, SourceLocation());
2661
2662 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
Patrick Beardeb382ec2012-04-19 00:25:12 +00002663 Context->getPointerType(Context->VoidTy),
2664 CK_BitCast, DRE);
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002665
2666 // Now do the "normal" pointer to function cast.
2667 QualType castType =
Patrick Beardeb382ec2012-04-19 00:25:12 +00002668 getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
2669 BoxingMethod->isVariadic());
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002670 castType = Context->getPointerType(castType);
2671 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2672 cast);
2673
2674 // Don't forget the parens to enforce the proper binding.
2675 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
2676
2677 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002678 CallExpr *CE = new (Context) CallExpr(*Context, PE, MsgExprs,
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002679 FT->getResultType(), VK_RValue,
2680 EndLoc);
2681 ReplaceStmt(Exp, CE);
2682 return CE;
2683}
2684
Fariborz Jahanian86cff602012-03-30 23:35:47 +00002685Stmt *RewriteModernObjC::RewriteObjCArrayLiteralExpr(ObjCArrayLiteral *Exp) {
2686 // synthesize declaration of helper functions needed in this routine.
2687 if (!SelGetUidFunctionDecl)
2688 SynthSelGetUidFunctionDecl();
2689 // use objc_msgSend() for all.
2690 if (!MsgSendFunctionDecl)
2691 SynthMsgSendFunctionDecl();
2692 if (!GetClassFunctionDecl)
2693 SynthGetClassFunctionDecl();
2694
2695 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2696 SourceLocation StartLoc = Exp->getLocStart();
2697 SourceLocation EndLoc = Exp->getLocEnd();
2698
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00002699 // Build the expression: __NSContainer_literal(int, ...).arr
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00002700 QualType IntQT = Context->IntTy;
2701 QualType NSArrayFType =
2702 getSimpleFunctionType(Context->VoidTy, &IntQT, 1, true);
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00002703 std::string NSArrayFName("__NSContainer_literal");
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00002704 FunctionDecl *NSArrayFD = SynthBlockInitFunctionDecl(NSArrayFName);
2705 DeclRefExpr *NSArrayDRE =
2706 new (Context) DeclRefExpr(NSArrayFD, false, NSArrayFType, VK_RValue,
2707 SourceLocation());
2708
2709 SmallVector<Expr*, 16> InitExprs;
2710 unsigned NumElements = Exp->getNumElements();
2711 unsigned UnsignedIntSize =
2712 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
2713 Expr *count = IntegerLiteral::Create(*Context,
2714 llvm::APInt(UnsignedIntSize, NumElements),
2715 Context->UnsignedIntTy, SourceLocation());
2716 InitExprs.push_back(count);
2717 for (unsigned i = 0; i < NumElements; i++)
2718 InitExprs.push_back(Exp->getElement(i));
2719 Expr *NSArrayCallExpr =
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002720 new (Context) CallExpr(*Context, NSArrayDRE, InitExprs,
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00002721 NSArrayFType, VK_LValue, SourceLocation());
2722
2723 FieldDecl *ARRFD = FieldDecl::Create(*Context, 0, SourceLocation(),
2724 SourceLocation(),
2725 &Context->Idents.get("arr"),
2726 Context->getPointerType(Context->VoidPtrTy), 0,
2727 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smithca523302012-06-10 03:12:00 +00002728 ICIS_NoInit);
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00002729 MemberExpr *ArrayLiteralME =
2730 new (Context) MemberExpr(NSArrayCallExpr, false, ARRFD,
2731 SourceLocation(),
2732 ARRFD->getType(), VK_LValue,
2733 OK_Ordinary);
2734 QualType ConstIdT = Context->getObjCIdType().withConst();
2735 CStyleCastExpr * ArrayLiteralObjects =
2736 NoTypeInfoCStyleCastExpr(Context,
2737 Context->getPointerType(ConstIdT),
2738 CK_BitCast,
2739 ArrayLiteralME);
2740
Fariborz Jahanian86cff602012-03-30 23:35:47 +00002741 // Synthesize a call to objc_msgSend().
2742 SmallVector<Expr*, 32> MsgExprs;
2743 SmallVector<Expr*, 4> ClsExprs;
2744 QualType argType = Context->getPointerType(Context->CharTy);
2745 QualType expType = Exp->getType();
2746
2747 // Create a call to objc_getClass("NSArray"). It will be th 1st argument.
2748 ObjCInterfaceDecl *Class =
2749 expType->getPointeeType()->getAs<ObjCObjectType>()->getInterface();
2750
2751 IdentifierInfo *clsName = Class->getIdentifier();
2752 ClsExprs.push_back(StringLiteral::Create(*Context,
2753 clsName->getName(),
2754 StringLiteral::Ascii, false,
2755 argType, SourceLocation()));
2756 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2757 &ClsExprs[0],
2758 ClsExprs.size(),
2759 StartLoc, EndLoc);
2760 MsgExprs.push_back(Cls);
2761
2762 // Create a call to sel_registerName("arrayWithObjects:count:").
2763 // it will be the 2nd argument.
2764 SmallVector<Expr*, 4> SelExprs;
2765 ObjCMethodDecl *ArrayMethod = Exp->getArrayWithObjectsMethod();
2766 SelExprs.push_back(StringLiteral::Create(*Context,
2767 ArrayMethod->getSelector().getAsString(),
2768 StringLiteral::Ascii, false,
2769 argType, SourceLocation()));
2770 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2771 &SelExprs[0], SelExprs.size(),
2772 StartLoc, EndLoc);
2773 MsgExprs.push_back(SelExp);
2774
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00002775 // (const id [])objects
2776 MsgExprs.push_back(ArrayLiteralObjects);
Fariborz Jahanian86cff602012-03-30 23:35:47 +00002777
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00002778 // (NSUInteger)cnt
2779 Expr *cnt = IntegerLiteral::Create(*Context,
2780 llvm::APInt(UnsignedIntSize, NumElements),
2781 Context->UnsignedIntTy, SourceLocation());
2782 MsgExprs.push_back(cnt);
Fariborz Jahanian86cff602012-03-30 23:35:47 +00002783
2784
2785 SmallVector<QualType, 4> ArgTypes;
2786 ArgTypes.push_back(Context->getObjCIdType());
2787 ArgTypes.push_back(Context->getObjCSelType());
2788 for (ObjCMethodDecl::param_iterator PI = ArrayMethod->param_begin(),
2789 E = ArrayMethod->param_end(); PI != E; ++PI)
2790 ArgTypes.push_back((*PI)->getType());
2791
2792 QualType returnType = Exp->getType();
2793 // Get the type, we will need to reference it in a couple spots.
2794 QualType msgSendType = MsgSendFlavor->getType();
2795
2796 // Create a reference to the objc_msgSend() declaration.
2797 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
2798 VK_LValue, SourceLocation());
2799
2800 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
2801 Context->getPointerType(Context->VoidTy),
2802 CK_BitCast, DRE);
2803
2804 // Now do the "normal" pointer to function cast.
2805 QualType castType =
2806 getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
2807 ArrayMethod->isVariadic());
2808 castType = Context->getPointerType(castType);
2809 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2810 cast);
2811
2812 // Don't forget the parens to enforce the proper binding.
2813 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
2814
2815 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002816 CallExpr *CE = new (Context) CallExpr(*Context, PE, MsgExprs,
Fariborz Jahanian86cff602012-03-30 23:35:47 +00002817 FT->getResultType(), VK_RValue,
2818 EndLoc);
2819 ReplaceStmt(Exp, CE);
2820 return CE;
2821}
2822
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00002823Stmt *RewriteModernObjC::RewriteObjCDictionaryLiteralExpr(ObjCDictionaryLiteral *Exp) {
2824 // synthesize declaration of helper functions needed in this routine.
2825 if (!SelGetUidFunctionDecl)
2826 SynthSelGetUidFunctionDecl();
2827 // use objc_msgSend() for all.
2828 if (!MsgSendFunctionDecl)
2829 SynthMsgSendFunctionDecl();
2830 if (!GetClassFunctionDecl)
2831 SynthGetClassFunctionDecl();
2832
2833 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2834 SourceLocation StartLoc = Exp->getLocStart();
2835 SourceLocation EndLoc = Exp->getLocEnd();
2836
2837 // Build the expression: __NSContainer_literal(int, ...).arr
2838 QualType IntQT = Context->IntTy;
2839 QualType NSDictFType =
2840 getSimpleFunctionType(Context->VoidTy, &IntQT, 1, true);
2841 std::string NSDictFName("__NSContainer_literal");
2842 FunctionDecl *NSDictFD = SynthBlockInitFunctionDecl(NSDictFName);
2843 DeclRefExpr *NSDictDRE =
2844 new (Context) DeclRefExpr(NSDictFD, false, NSDictFType, VK_RValue,
2845 SourceLocation());
2846
2847 SmallVector<Expr*, 16> KeyExprs;
2848 SmallVector<Expr*, 16> ValueExprs;
2849
2850 unsigned NumElements = Exp->getNumElements();
2851 unsigned UnsignedIntSize =
2852 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
2853 Expr *count = IntegerLiteral::Create(*Context,
2854 llvm::APInt(UnsignedIntSize, NumElements),
2855 Context->UnsignedIntTy, SourceLocation());
2856 KeyExprs.push_back(count);
2857 ValueExprs.push_back(count);
2858 for (unsigned i = 0; i < NumElements; i++) {
2859 ObjCDictionaryElement Element = Exp->getKeyValueElement(i);
2860 KeyExprs.push_back(Element.Key);
2861 ValueExprs.push_back(Element.Value);
2862 }
2863
2864 // (const id [])objects
2865 Expr *NSValueCallExpr =
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002866 new (Context) CallExpr(*Context, NSDictDRE, ValueExprs,
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00002867 NSDictFType, VK_LValue, SourceLocation());
2868
2869 FieldDecl *ARRFD = FieldDecl::Create(*Context, 0, SourceLocation(),
2870 SourceLocation(),
2871 &Context->Idents.get("arr"),
2872 Context->getPointerType(Context->VoidPtrTy), 0,
2873 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smithca523302012-06-10 03:12:00 +00002874 ICIS_NoInit);
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00002875 MemberExpr *DictLiteralValueME =
2876 new (Context) MemberExpr(NSValueCallExpr, false, ARRFD,
2877 SourceLocation(),
2878 ARRFD->getType(), VK_LValue,
2879 OK_Ordinary);
2880 QualType ConstIdT = Context->getObjCIdType().withConst();
2881 CStyleCastExpr * DictValueObjects =
2882 NoTypeInfoCStyleCastExpr(Context,
2883 Context->getPointerType(ConstIdT),
2884 CK_BitCast,
2885 DictLiteralValueME);
2886 // (const id <NSCopying> [])keys
2887 Expr *NSKeyCallExpr =
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002888 new (Context) CallExpr(*Context, NSDictDRE, KeyExprs,
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00002889 NSDictFType, VK_LValue, SourceLocation());
2890
2891 MemberExpr *DictLiteralKeyME =
2892 new (Context) MemberExpr(NSKeyCallExpr, false, ARRFD,
2893 SourceLocation(),
2894 ARRFD->getType(), VK_LValue,
2895 OK_Ordinary);
2896
2897 CStyleCastExpr * DictKeyObjects =
2898 NoTypeInfoCStyleCastExpr(Context,
2899 Context->getPointerType(ConstIdT),
2900 CK_BitCast,
2901 DictLiteralKeyME);
2902
2903
2904
2905 // Synthesize a call to objc_msgSend().
2906 SmallVector<Expr*, 32> MsgExprs;
2907 SmallVector<Expr*, 4> ClsExprs;
2908 QualType argType = Context->getPointerType(Context->CharTy);
2909 QualType expType = Exp->getType();
2910
2911 // Create a call to objc_getClass("NSArray"). It will be th 1st argument.
2912 ObjCInterfaceDecl *Class =
2913 expType->getPointeeType()->getAs<ObjCObjectType>()->getInterface();
2914
2915 IdentifierInfo *clsName = Class->getIdentifier();
2916 ClsExprs.push_back(StringLiteral::Create(*Context,
2917 clsName->getName(),
2918 StringLiteral::Ascii, false,
2919 argType, SourceLocation()));
2920 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2921 &ClsExprs[0],
2922 ClsExprs.size(),
2923 StartLoc, EndLoc);
2924 MsgExprs.push_back(Cls);
2925
2926 // Create a call to sel_registerName("arrayWithObjects:count:").
2927 // it will be the 2nd argument.
2928 SmallVector<Expr*, 4> SelExprs;
2929 ObjCMethodDecl *DictMethod = Exp->getDictWithObjectsMethod();
2930 SelExprs.push_back(StringLiteral::Create(*Context,
2931 DictMethod->getSelector().getAsString(),
2932 StringLiteral::Ascii, false,
2933 argType, SourceLocation()));
2934 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2935 &SelExprs[0], SelExprs.size(),
2936 StartLoc, EndLoc);
2937 MsgExprs.push_back(SelExp);
2938
2939 // (const id [])objects
2940 MsgExprs.push_back(DictValueObjects);
2941
2942 // (const id <NSCopying> [])keys
2943 MsgExprs.push_back(DictKeyObjects);
2944
2945 // (NSUInteger)cnt
2946 Expr *cnt = IntegerLiteral::Create(*Context,
2947 llvm::APInt(UnsignedIntSize, NumElements),
2948 Context->UnsignedIntTy, SourceLocation());
2949 MsgExprs.push_back(cnt);
2950
2951
2952 SmallVector<QualType, 8> ArgTypes;
2953 ArgTypes.push_back(Context->getObjCIdType());
2954 ArgTypes.push_back(Context->getObjCSelType());
2955 for (ObjCMethodDecl::param_iterator PI = DictMethod->param_begin(),
2956 E = DictMethod->param_end(); PI != E; ++PI) {
2957 QualType T = (*PI)->getType();
2958 if (const PointerType* PT = T->getAs<PointerType>()) {
2959 QualType PointeeTy = PT->getPointeeType();
2960 convertToUnqualifiedObjCType(PointeeTy);
2961 T = Context->getPointerType(PointeeTy);
2962 }
2963 ArgTypes.push_back(T);
2964 }
2965
2966 QualType returnType = Exp->getType();
2967 // Get the type, we will need to reference it in a couple spots.
2968 QualType msgSendType = MsgSendFlavor->getType();
2969
2970 // Create a reference to the objc_msgSend() declaration.
2971 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
2972 VK_LValue, SourceLocation());
2973
2974 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
2975 Context->getPointerType(Context->VoidTy),
2976 CK_BitCast, DRE);
2977
2978 // Now do the "normal" pointer to function cast.
2979 QualType castType =
2980 getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
2981 DictMethod->isVariadic());
2982 castType = Context->getPointerType(castType);
2983 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2984 cast);
2985
2986 // Don't forget the parens to enforce the proper binding.
2987 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
2988
2989 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002990 CallExpr *CE = new (Context) CallExpr(*Context, PE, MsgExprs,
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00002991 FT->getResultType(), VK_RValue,
2992 EndLoc);
2993 ReplaceStmt(Exp, CE);
2994 return CE;
2995}
2996
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002997// struct __rw_objc_super {
2998// struct objc_object *object; struct objc_object *superClass;
2999// };
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003000QualType RewriteModernObjC::getSuperStructType() {
3001 if (!SuperStructDecl) {
3002 SuperStructDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
3003 SourceLocation(), SourceLocation(),
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003004 &Context->Idents.get("__rw_objc_super"));
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003005 QualType FieldTypes[2];
3006
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003007 // struct objc_object *object;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003008 FieldTypes[0] = Context->getObjCIdType();
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003009 // struct objc_object *superClass;
3010 FieldTypes[1] = Context->getObjCIdType();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003011
3012 // Create fields
3013 for (unsigned i = 0; i < 2; ++i) {
3014 SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
3015 SourceLocation(),
3016 SourceLocation(), 0,
3017 FieldTypes[i], 0,
3018 /*BitWidth=*/0,
3019 /*Mutable=*/false,
Richard Smithca523302012-06-10 03:12:00 +00003020 ICIS_NoInit));
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003021 }
3022
3023 SuperStructDecl->completeDefinition();
3024 }
3025 return Context->getTagDeclType(SuperStructDecl);
3026}
3027
3028QualType RewriteModernObjC::getConstantStringStructType() {
3029 if (!ConstantStringDecl) {
3030 ConstantStringDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
3031 SourceLocation(), SourceLocation(),
3032 &Context->Idents.get("__NSConstantStringImpl"));
3033 QualType FieldTypes[4];
3034
3035 // struct objc_object *receiver;
3036 FieldTypes[0] = Context->getObjCIdType();
3037 // int flags;
3038 FieldTypes[1] = Context->IntTy;
3039 // char *str;
3040 FieldTypes[2] = Context->getPointerType(Context->CharTy);
3041 // long length;
3042 FieldTypes[3] = Context->LongTy;
3043
3044 // Create fields
3045 for (unsigned i = 0; i < 4; ++i) {
3046 ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
3047 ConstantStringDecl,
3048 SourceLocation(),
3049 SourceLocation(), 0,
3050 FieldTypes[i], 0,
3051 /*BitWidth=*/0,
3052 /*Mutable=*/true,
Richard Smithca523302012-06-10 03:12:00 +00003053 ICIS_NoInit));
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003054 }
3055
3056 ConstantStringDecl->completeDefinition();
3057 }
3058 return Context->getTagDeclType(ConstantStringDecl);
3059}
3060
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +00003061/// getFunctionSourceLocation - returns start location of a function
3062/// definition. Complication arises when function has declared as
3063/// extern "C" or extern "C" {...}
3064static SourceLocation getFunctionSourceLocation (RewriteModernObjC &R,
3065 FunctionDecl *FD) {
3066 if (FD->isExternC() && !FD->isMain()) {
3067 const DeclContext *DC = FD->getDeclContext();
3068 if (const LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(DC))
3069 // if it is extern "C" {...}, return function decl's own location.
3070 if (!LSD->getRBraceLoc().isValid())
3071 return LSD->getExternLoc();
3072 }
3073 if (FD->getStorageClassAsWritten() != SC_None)
3074 R.RewriteBlockLiteralFunctionDecl(FD);
3075 return FD->getTypeSpecStartLoc();
3076}
3077
3078/// SynthMsgSendStretCallExpr - This routine translates message expression
3079/// into a call to objc_msgSend_stret() entry point. Tricky part is that
3080/// nil check on receiver must be performed before calling objc_msgSend_stret.
3081/// MsgSendStretFlavor - function declaration objc_msgSend_stret(...)
3082/// msgSendType - function type of objc_msgSend_stret(...)
3083/// returnType - Result type of the method being synthesized.
3084/// ArgTypes - type of the arguments passed to objc_msgSend_stret, starting with receiver type.
3085/// MsgExprs - list of argument expressions being passed to objc_msgSend_stret,
3086/// starting with receiver.
3087/// Method - Method being rewritten.
3088Expr *RewriteModernObjC::SynthMsgSendStretCallExpr(FunctionDecl *MsgSendStretFlavor,
3089 QualType msgSendType,
3090 QualType returnType,
3091 SmallVectorImpl<QualType> &ArgTypes,
3092 SmallVectorImpl<Expr*> &MsgExprs,
3093 ObjCMethodDecl *Method) {
3094 // Now do the "normal" pointer to function cast.
3095 QualType castType = getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
3096 Method ? Method->isVariadic() : false);
3097 castType = Context->getPointerType(castType);
3098
3099 // build type for containing the objc_msgSend_stret object.
3100 static unsigned stretCount=0;
3101 std::string name = "__Stret"; name += utostr(stretCount);
Fariborz Jahanian2ca5af22012-07-25 21:48:36 +00003102 std::string str =
3103 "extern \"C\" void * __cdecl memset(void *_Dst, int _Val, size_t _Size);\n";
3104 str += "struct "; str += name;
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +00003105 str += " {\n\t";
3106 str += name;
3107 str += "(id receiver, SEL sel";
3108 for (unsigned i = 2; i < ArgTypes.size(); i++) {
Fariborz Jahanian6734ec42012-06-29 19:55:46 +00003109 std::string ArgName = "arg"; ArgName += utostr(i);
3110 ArgTypes[i].getAsStringInternal(ArgName, Context->getPrintingPolicy());
3111 str += ", "; str += ArgName;
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +00003112 }
3113 // could be vararg.
3114 for (unsigned i = ArgTypes.size(); i < MsgExprs.size(); i++) {
Fariborz Jahanian6734ec42012-06-29 19:55:46 +00003115 std::string ArgName = "arg"; ArgName += utostr(i);
3116 MsgExprs[i]->getType().getAsStringInternal(ArgName,
3117 Context->getPrintingPolicy());
3118 str += ", "; str += ArgName;
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +00003119 }
3120
3121 str += ") {\n";
3122 str += "\t if (receiver == 0)\n";
3123 str += "\t memset((void*)&s, 0, sizeof(s));\n";
3124 str += "\t else\n";
3125 str += "\t s = (("; str += castType.getAsString(Context->getPrintingPolicy());
3126 str += ")(void *)objc_msgSend_stret)(receiver, sel";
3127 for (unsigned i = 2; i < ArgTypes.size(); i++) {
3128 str += ", arg"; str += utostr(i);
3129 }
3130 // could be vararg.
3131 for (unsigned i = ArgTypes.size(); i < MsgExprs.size(); i++) {
3132 str += ", arg"; str += utostr(i);
3133 }
3134
3135 str += ");\n";
3136 str += "\t}\n";
3137 str += "\t"; str += returnType.getAsString(Context->getPrintingPolicy());
3138 str += " s;\n";
3139 str += "};\n\n";
Fariborz Jahaniana6e5a6e2012-08-21 18:56:50 +00003140 SourceLocation FunLocStart;
3141 if (CurFunctionDef)
3142 FunLocStart = getFunctionSourceLocation(*this, CurFunctionDef);
3143 else {
3144 assert(CurMethodDef && "SynthMsgSendStretCallExpr - CurMethodDef is null");
3145 FunLocStart = CurMethodDef->getLocStart();
3146 }
3147
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +00003148 InsertText(FunLocStart, str);
3149 ++stretCount;
3150
3151 // AST for __Stretn(receiver, args).s;
3152 IdentifierInfo *ID = &Context->Idents.get(name);
3153 FunctionDecl *FD = FunctionDecl::Create(*Context, TUDecl, SourceLocation(),
3154 SourceLocation(), ID, castType, 0, SC_Extern,
3155 SC_None, false, false);
3156 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, false, castType, VK_RValue,
3157 SourceLocation());
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003158 CallExpr *STCE = new (Context) CallExpr(*Context, DRE, MsgExprs,
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +00003159 castType, VK_LValue, SourceLocation());
3160
3161 FieldDecl *FieldD = FieldDecl::Create(*Context, 0, SourceLocation(),
3162 SourceLocation(),
3163 &Context->Idents.get("s"),
3164 returnType, 0,
3165 /*BitWidth=*/0, /*Mutable=*/true,
3166 ICIS_NoInit);
3167 MemberExpr *ME = new (Context) MemberExpr(STCE, false, FieldD, SourceLocation(),
3168 FieldD->getType(), VK_LValue,
3169 OK_Ordinary);
3170
3171 return ME;
3172}
3173
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003174Stmt *RewriteModernObjC::SynthMessageExpr(ObjCMessageExpr *Exp,
3175 SourceLocation StartLoc,
3176 SourceLocation EndLoc) {
3177 if (!SelGetUidFunctionDecl)
3178 SynthSelGetUidFunctionDecl();
3179 if (!MsgSendFunctionDecl)
3180 SynthMsgSendFunctionDecl();
3181 if (!MsgSendSuperFunctionDecl)
3182 SynthMsgSendSuperFunctionDecl();
3183 if (!MsgSendStretFunctionDecl)
3184 SynthMsgSendStretFunctionDecl();
3185 if (!MsgSendSuperStretFunctionDecl)
3186 SynthMsgSendSuperStretFunctionDecl();
3187 if (!MsgSendFpretFunctionDecl)
3188 SynthMsgSendFpretFunctionDecl();
3189 if (!GetClassFunctionDecl)
3190 SynthGetClassFunctionDecl();
3191 if (!GetSuperClassFunctionDecl)
3192 SynthGetSuperClassFunctionDecl();
3193 if (!GetMetaClassFunctionDecl)
3194 SynthGetMetaClassFunctionDecl();
3195
3196 // default to objc_msgSend().
3197 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
3198 // May need to use objc_msgSend_stret() as well.
3199 FunctionDecl *MsgSendStretFlavor = 0;
3200 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
3201 QualType resultType = mDecl->getResultType();
3202 if (resultType->isRecordType())
3203 MsgSendStretFlavor = MsgSendStretFunctionDecl;
3204 else if (resultType->isRealFloatingType())
3205 MsgSendFlavor = MsgSendFpretFunctionDecl;
3206 }
3207
3208 // Synthesize a call to objc_msgSend().
3209 SmallVector<Expr*, 8> MsgExprs;
3210 switch (Exp->getReceiverKind()) {
3211 case ObjCMessageExpr::SuperClass: {
3212 MsgSendFlavor = MsgSendSuperFunctionDecl;
3213 if (MsgSendStretFlavor)
3214 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
3215 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
3216
3217 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
3218
3219 SmallVector<Expr*, 4> InitExprs;
3220
3221 // set the receiver to self, the first argument to all methods.
3222 InitExprs.push_back(
3223 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3224 CK_BitCast,
3225 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCallf4b88a42012-03-10 09:33:50 +00003226 false,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003227 Context->getObjCIdType(),
3228 VK_RValue,
3229 SourceLocation()))
3230 ); // set the 'receiver'.
3231
3232 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3233 SmallVector<Expr*, 8> ClsExprs;
3234 QualType argType = Context->getPointerType(Context->CharTy);
3235 ClsExprs.push_back(StringLiteral::Create(*Context,
3236 ClassDecl->getIdentifier()->getName(),
3237 StringLiteral::Ascii, false,
3238 argType, SourceLocation()));
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00003239 // (Class)objc_getClass("CurrentClass")
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003240 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
3241 &ClsExprs[0],
3242 ClsExprs.size(),
3243 StartLoc,
3244 EndLoc);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003245 ClsExprs.clear();
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00003246 ClsExprs.push_back(Cls);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003247 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
3248 &ClsExprs[0], ClsExprs.size(),
3249 StartLoc, EndLoc);
3250
3251 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3252 // To turn off a warning, type-cast to 'id'
3253 InitExprs.push_back( // set 'super class', using class_getSuperclass().
3254 NoTypeInfoCStyleCastExpr(Context,
3255 Context->getObjCIdType(),
3256 CK_BitCast, Cls));
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003257 // struct __rw_objc_super
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003258 QualType superType = getSuperStructType();
3259 Expr *SuperRep;
3260
3261 if (LangOpts.MicrosoftExt) {
3262 SynthSuperContructorFunctionDecl();
3263 // Simulate a contructor call...
3264 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
John McCallf4b88a42012-03-10 09:33:50 +00003265 false, superType, VK_LValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003266 SourceLocation());
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003267 SuperRep = new (Context) CallExpr(*Context, DRE, InitExprs,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003268 superType, VK_LValue,
3269 SourceLocation());
3270 // The code for super is a little tricky to prevent collision with
3271 // the structure definition in the header. The rewriter has it's own
3272 // internal definition (__rw_objc_super) that is uses. This is why
3273 // we need the cast below. For example:
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003274 // (struct __rw_objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003275 //
3276 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
3277 Context->getPointerType(SuperRep->getType()),
3278 VK_RValue, OK_Ordinary,
3279 SourceLocation());
3280 SuperRep = NoTypeInfoCStyleCastExpr(Context,
3281 Context->getPointerType(superType),
3282 CK_BitCast, SuperRep);
3283 } else {
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003284 // (struct __rw_objc_super) { <exprs from above> }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003285 InitListExpr *ILE =
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003286 new (Context) InitListExpr(*Context, SourceLocation(), InitExprs,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003287 SourceLocation());
3288 TypeSourceInfo *superTInfo
3289 = Context->getTrivialTypeSourceInfo(superType);
3290 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
3291 superType, VK_LValue,
3292 ILE, false);
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003293 // struct __rw_objc_super *
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003294 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
3295 Context->getPointerType(SuperRep->getType()),
3296 VK_RValue, OK_Ordinary,
3297 SourceLocation());
3298 }
3299 MsgExprs.push_back(SuperRep);
3300 break;
3301 }
3302
3303 case ObjCMessageExpr::Class: {
3304 SmallVector<Expr*, 8> ClsExprs;
3305 QualType argType = Context->getPointerType(Context->CharTy);
3306 ObjCInterfaceDecl *Class
3307 = Exp->getClassReceiver()->getAs<ObjCObjectType>()->getInterface();
3308 IdentifierInfo *clsName = Class->getIdentifier();
3309 ClsExprs.push_back(StringLiteral::Create(*Context,
3310 clsName->getName(),
3311 StringLiteral::Ascii, false,
3312 argType, SourceLocation()));
3313 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
3314 &ClsExprs[0],
3315 ClsExprs.size(),
3316 StartLoc, EndLoc);
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00003317 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
3318 Context->getObjCIdType(),
3319 CK_BitCast, Cls);
3320 MsgExprs.push_back(ArgExpr);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003321 break;
3322 }
3323
3324 case ObjCMessageExpr::SuperInstance:{
3325 MsgSendFlavor = MsgSendSuperFunctionDecl;
3326 if (MsgSendStretFlavor)
3327 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
3328 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
3329 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
3330 SmallVector<Expr*, 4> InitExprs;
3331
3332 InitExprs.push_back(
3333 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3334 CK_BitCast,
3335 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCallf4b88a42012-03-10 09:33:50 +00003336 false,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003337 Context->getObjCIdType(),
3338 VK_RValue, SourceLocation()))
3339 ); // set the 'receiver'.
3340
3341 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3342 SmallVector<Expr*, 8> ClsExprs;
3343 QualType argType = Context->getPointerType(Context->CharTy);
3344 ClsExprs.push_back(StringLiteral::Create(*Context,
3345 ClassDecl->getIdentifier()->getName(),
3346 StringLiteral::Ascii, false, argType,
3347 SourceLocation()));
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00003348 // (Class)objc_getClass("CurrentClass")
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003349 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
3350 &ClsExprs[0],
3351 ClsExprs.size(),
3352 StartLoc, EndLoc);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003353 ClsExprs.clear();
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00003354 ClsExprs.push_back(Cls);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003355 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
3356 &ClsExprs[0], ClsExprs.size(),
3357 StartLoc, EndLoc);
3358
3359 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3360 // To turn off a warning, type-cast to 'id'
3361 InitExprs.push_back(
3362 // set 'super class', using class_getSuperclass().
3363 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3364 CK_BitCast, Cls));
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003365 // struct __rw_objc_super
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003366 QualType superType = getSuperStructType();
3367 Expr *SuperRep;
3368
3369 if (LangOpts.MicrosoftExt) {
3370 SynthSuperContructorFunctionDecl();
3371 // Simulate a contructor call...
3372 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
John McCallf4b88a42012-03-10 09:33:50 +00003373 false, superType, VK_LValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003374 SourceLocation());
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003375 SuperRep = new (Context) CallExpr(*Context, DRE, InitExprs,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003376 superType, VK_LValue, SourceLocation());
3377 // The code for super is a little tricky to prevent collision with
3378 // the structure definition in the header. The rewriter has it's own
3379 // internal definition (__rw_objc_super) that is uses. This is why
3380 // we need the cast below. For example:
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003381 // (struct __rw_objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003382 //
3383 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
3384 Context->getPointerType(SuperRep->getType()),
3385 VK_RValue, OK_Ordinary,
3386 SourceLocation());
3387 SuperRep = NoTypeInfoCStyleCastExpr(Context,
3388 Context->getPointerType(superType),
3389 CK_BitCast, SuperRep);
3390 } else {
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003391 // (struct __rw_objc_super) { <exprs from above> }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003392 InitListExpr *ILE =
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003393 new (Context) InitListExpr(*Context, SourceLocation(), InitExprs,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003394 SourceLocation());
3395 TypeSourceInfo *superTInfo
3396 = Context->getTrivialTypeSourceInfo(superType);
3397 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
3398 superType, VK_RValue, ILE,
3399 false);
3400 }
3401 MsgExprs.push_back(SuperRep);
3402 break;
3403 }
3404
3405 case ObjCMessageExpr::Instance: {
3406 // Remove all type-casts because it may contain objc-style types; e.g.
3407 // Foo<Proto> *.
3408 Expr *recExpr = Exp->getInstanceReceiver();
3409 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
3410 recExpr = CE->getSubExpr();
3411 CastKind CK = recExpr->getType()->isObjCObjectPointerType()
3412 ? CK_BitCast : recExpr->getType()->isBlockPointerType()
3413 ? CK_BlockPointerToObjCPointerCast
3414 : CK_CPointerToObjCPointerCast;
3415
3416 recExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3417 CK, recExpr);
3418 MsgExprs.push_back(recExpr);
3419 break;
3420 }
3421 }
3422
3423 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
3424 SmallVector<Expr*, 8> SelExprs;
3425 QualType argType = Context->getPointerType(Context->CharTy);
3426 SelExprs.push_back(StringLiteral::Create(*Context,
3427 Exp->getSelector().getAsString(),
3428 StringLiteral::Ascii, false,
3429 argType, SourceLocation()));
3430 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
3431 &SelExprs[0], SelExprs.size(),
3432 StartLoc,
3433 EndLoc);
3434 MsgExprs.push_back(SelExp);
3435
3436 // Now push any user supplied arguments.
3437 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
3438 Expr *userExpr = Exp->getArg(i);
3439 // Make all implicit casts explicit...ICE comes in handy:-)
3440 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
3441 // Reuse the ICE type, it is exactly what the doctor ordered.
3442 QualType type = ICE->getType();
3443 if (needToScanForQualifiers(type))
3444 type = Context->getObjCIdType();
3445 // Make sure we convert "type (^)(...)" to "type (*)(...)".
3446 (void)convertBlockPointerToFunctionPointer(type);
3447 const Expr *SubExpr = ICE->IgnoreParenImpCasts();
3448 CastKind CK;
3449 if (SubExpr->getType()->isIntegralType(*Context) &&
3450 type->isBooleanType()) {
3451 CK = CK_IntegralToBoolean;
3452 } else if (type->isObjCObjectPointerType()) {
3453 if (SubExpr->getType()->isBlockPointerType()) {
3454 CK = CK_BlockPointerToObjCPointerCast;
3455 } else if (SubExpr->getType()->isPointerType()) {
3456 CK = CK_CPointerToObjCPointerCast;
3457 } else {
3458 CK = CK_BitCast;
3459 }
3460 } else {
3461 CK = CK_BitCast;
3462 }
3463
3464 userExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, userExpr);
3465 }
3466 // Make id<P...> cast into an 'id' cast.
3467 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
3468 if (CE->getType()->isObjCQualifiedIdType()) {
3469 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
3470 userExpr = CE->getSubExpr();
3471 CastKind CK;
3472 if (userExpr->getType()->isIntegralType(*Context)) {
3473 CK = CK_IntegralToPointer;
3474 } else if (userExpr->getType()->isBlockPointerType()) {
3475 CK = CK_BlockPointerToObjCPointerCast;
3476 } else if (userExpr->getType()->isPointerType()) {
3477 CK = CK_CPointerToObjCPointerCast;
3478 } else {
3479 CK = CK_BitCast;
3480 }
3481 userExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3482 CK, userExpr);
3483 }
3484 }
3485 MsgExprs.push_back(userExpr);
3486 // We've transferred the ownership to MsgExprs. For now, we *don't* null
3487 // out the argument in the original expression (since we aren't deleting
3488 // the ObjCMessageExpr). See RewritePropertyOrImplicitSetter() usage for more info.
3489 //Exp->setArg(i, 0);
3490 }
3491 // Generate the funky cast.
3492 CastExpr *cast;
3493 SmallVector<QualType, 8> ArgTypes;
3494 QualType returnType;
3495
3496 // Push 'id' and 'SEL', the 2 implicit arguments.
3497 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
3498 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
3499 else
3500 ArgTypes.push_back(Context->getObjCIdType());
3501 ArgTypes.push_back(Context->getObjCSelType());
3502 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
3503 // Push any user argument types.
3504 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
3505 E = OMD->param_end(); PI != E; ++PI) {
3506 QualType t = (*PI)->getType()->isObjCQualifiedIdType()
3507 ? Context->getObjCIdType()
3508 : (*PI)->getType();
3509 // Make sure we convert "t (^)(...)" to "t (*)(...)".
3510 (void)convertBlockPointerToFunctionPointer(t);
3511 ArgTypes.push_back(t);
3512 }
3513 returnType = Exp->getType();
3514 convertToUnqualifiedObjCType(returnType);
3515 (void)convertBlockPointerToFunctionPointer(returnType);
3516 } else {
3517 returnType = Context->getObjCIdType();
3518 }
3519 // Get the type, we will need to reference it in a couple spots.
3520 QualType msgSendType = MsgSendFlavor->getType();
3521
3522 // Create a reference to the objc_msgSend() declaration.
John McCallf4b88a42012-03-10 09:33:50 +00003523 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003524 VK_LValue, SourceLocation());
3525
3526 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
3527 // If we don't do this cast, we get the following bizarre warning/note:
3528 // xx.m:13: warning: function called through a non-compatible type
3529 // xx.m:13: note: if this code is reached, the program will abort
3530 cast = NoTypeInfoCStyleCastExpr(Context,
3531 Context->getPointerType(Context->VoidTy),
3532 CK_BitCast, DRE);
3533
3534 // Now do the "normal" pointer to function cast.
3535 QualType castType =
3536 getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
3537 // If we don't have a method decl, force a variadic cast.
3538 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true);
3539 castType = Context->getPointerType(castType);
3540 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
3541 cast);
3542
3543 // Don't forget the parens to enforce the proper binding.
3544 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
3545
3546 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003547 CallExpr *CE = new (Context) CallExpr(*Context, PE, MsgExprs,
3548 FT->getResultType(), VK_RValue, EndLoc);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003549 Stmt *ReplacingStmt = CE;
3550 if (MsgSendStretFlavor) {
3551 // We have the method which returns a struct/union. Must also generate
3552 // call to objc_msgSend_stret and hang both varieties on a conditional
3553 // expression which dictate which one to envoke depending on size of
3554 // method's return type.
3555
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +00003556 Expr *STCE = SynthMsgSendStretCallExpr(MsgSendStretFlavor,
3557 msgSendType, returnType,
3558 ArgTypes, MsgExprs,
3559 Exp->getMethodDecl());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003560
3561 // Build sizeof(returnType)
3562 UnaryExprOrTypeTraitExpr *sizeofExpr =
3563 new (Context) UnaryExprOrTypeTraitExpr(UETT_SizeOf,
3564 Context->getTrivialTypeSourceInfo(returnType),
3565 Context->getSizeType(), SourceLocation(),
3566 SourceLocation());
3567 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
3568 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
3569 // For X86 it is more complicated and some kind of target specific routine
3570 // is needed to decide what to do.
3571 unsigned IntSize =
3572 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
3573 IntegerLiteral *limit = IntegerLiteral::Create(*Context,
3574 llvm::APInt(IntSize, 8),
3575 Context->IntTy,
3576 SourceLocation());
3577 BinaryOperator *lessThanExpr =
3578 new (Context) BinaryOperator(sizeofExpr, limit, BO_LE, Context->IntTy,
Lang Hamesbe9af122012-10-02 04:45:10 +00003579 VK_RValue, OK_Ordinary, SourceLocation(),
3580 false);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003581 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
3582 ConditionalOperator *CondExpr =
3583 new (Context) ConditionalOperator(lessThanExpr,
3584 SourceLocation(), CE,
3585 SourceLocation(), STCE,
3586 returnType, VK_RValue, OK_Ordinary);
3587 ReplacingStmt = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3588 CondExpr);
3589 }
3590 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3591 return ReplacingStmt;
3592}
3593
3594Stmt *RewriteModernObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
3595 Stmt *ReplacingStmt = SynthMessageExpr(Exp, Exp->getLocStart(),
3596 Exp->getLocEnd());
3597
3598 // Now do the actual rewrite.
3599 ReplaceStmt(Exp, ReplacingStmt);
3600
3601 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3602 return ReplacingStmt;
3603}
3604
3605// typedef struct objc_object Protocol;
3606QualType RewriteModernObjC::getProtocolType() {
3607 if (!ProtocolTypeDecl) {
3608 TypeSourceInfo *TInfo
3609 = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
3610 ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
3611 SourceLocation(), SourceLocation(),
3612 &Context->Idents.get("Protocol"),
3613 TInfo);
3614 }
3615 return Context->getTypeDeclType(ProtocolTypeDecl);
3616}
3617
3618/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
3619/// a synthesized/forward data reference (to the protocol's metadata).
3620/// The forward references (and metadata) are generated in
3621/// RewriteModernObjC::HandleTranslationUnit().
3622Stmt *RewriteModernObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00003623 std::string Name = "_OBJC_PROTOCOL_REFERENCE_$_" +
3624 Exp->getProtocol()->getNameAsString();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003625 IdentifierInfo *ID = &Context->Idents.get(Name);
3626 VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
3627 SourceLocation(), ID, getProtocolType(), 0,
3628 SC_Extern, SC_None);
John McCallf4b88a42012-03-10 09:33:50 +00003629 DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, false, getProtocolType(),
3630 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003631 Expr *DerefExpr = new (Context) UnaryOperator(DRE, UO_AddrOf,
3632 Context->getPointerType(DRE->getType()),
3633 VK_RValue, OK_Ordinary, SourceLocation());
3634 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, DerefExpr->getType(),
3635 CK_BitCast,
3636 DerefExpr);
3637 ReplaceStmt(Exp, castExpr);
3638 ProtocolExprDecls.insert(Exp->getProtocol()->getCanonicalDecl());
3639 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3640 return castExpr;
3641
3642}
3643
3644bool RewriteModernObjC::BufferContainsPPDirectives(const char *startBuf,
3645 const char *endBuf) {
3646 while (startBuf < endBuf) {
3647 if (*startBuf == '#') {
3648 // Skip whitespace.
3649 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
3650 ;
3651 if (!strncmp(startBuf, "if", strlen("if")) ||
3652 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
3653 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
3654 !strncmp(startBuf, "define", strlen("define")) ||
3655 !strncmp(startBuf, "undef", strlen("undef")) ||
3656 !strncmp(startBuf, "else", strlen("else")) ||
3657 !strncmp(startBuf, "elif", strlen("elif")) ||
3658 !strncmp(startBuf, "endif", strlen("endif")) ||
3659 !strncmp(startBuf, "pragma", strlen("pragma")) ||
3660 !strncmp(startBuf, "include", strlen("include")) ||
3661 !strncmp(startBuf, "import", strlen("import")) ||
3662 !strncmp(startBuf, "include_next", strlen("include_next")))
3663 return true;
3664 }
3665 startBuf++;
3666 }
3667 return false;
3668}
3669
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003670/// IsTagDefinedInsideClass - This routine checks that a named tagged type
3671/// is defined inside an objective-c class. If so, it returns true.
Fariborz Jahanianb68258f2012-05-01 17:46:45 +00003672bool RewriteModernObjC::IsTagDefinedInsideClass(ObjCContainerDecl *IDecl,
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003673 TagDecl *Tag,
3674 bool &IsNamedDefinition) {
Fariborz Jahanian89585e802012-04-30 19:46:53 +00003675 if (!IDecl)
3676 return false;
3677 SourceLocation TagLocation;
3678 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) {
3679 RD = RD->getDefinition();
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003680 if (!RD || !RD->getDeclName().getAsIdentifierInfo())
Fariborz Jahanian89585e802012-04-30 19:46:53 +00003681 return false;
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003682 IsNamedDefinition = true;
Fariborz Jahanian89585e802012-04-30 19:46:53 +00003683 TagLocation = RD->getLocation();
3684 return Context->getSourceManager().isBeforeInTranslationUnit(
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003685 IDecl->getLocation(), TagLocation);
3686 }
3687 if (EnumDecl *ED = dyn_cast<EnumDecl>(Tag)) {
3688 if (!ED || !ED->getDeclName().getAsIdentifierInfo())
3689 return false;
3690 IsNamedDefinition = true;
3691 TagLocation = ED->getLocation();
3692 return Context->getSourceManager().isBeforeInTranslationUnit(
3693 IDecl->getLocation(), TagLocation);
3694
Fariborz Jahanian89585e802012-04-30 19:46:53 +00003695 }
3696 return false;
3697}
3698
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003699/// RewriteObjCFieldDeclType - This routine rewrites a type into the buffer.
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003700/// It handles elaborated types, as well as enum types in the process.
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003701bool RewriteModernObjC::RewriteObjCFieldDeclType(QualType &Type,
3702 std::string &Result) {
Fariborz Jahanianf5eac482012-05-02 17:34:59 +00003703 if (isa<TypedefType>(Type)) {
3704 Result += "\t";
3705 return false;
3706 }
3707
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003708 if (Type->isArrayType()) {
3709 QualType ElemTy = Context->getBaseElementType(Type);
3710 return RewriteObjCFieldDeclType(ElemTy, Result);
3711 }
3712 else if (Type->isRecordType()) {
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003713 RecordDecl *RD = Type->getAs<RecordType>()->getDecl();
3714 if (RD->isCompleteDefinition()) {
3715 if (RD->isStruct())
3716 Result += "\n\tstruct ";
3717 else if (RD->isUnion())
3718 Result += "\n\tunion ";
3719 else
3720 assert(false && "class not allowed as an ivar type");
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003721
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003722 Result += RD->getName();
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003723 if (GlobalDefinedTags.count(RD)) {
3724 // struct/union is defined globally, use it.
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003725 Result += " ";
3726 return true;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003727 }
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003728 Result += " {\n";
3729 for (RecordDecl::field_iterator i = RD->field_begin(),
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003730 e = RD->field_end(); i != e; ++i) {
David Blaikie581deb32012-06-06 20:45:41 +00003731 FieldDecl *FD = *i;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003732 RewriteObjCFieldDecl(FD, Result);
3733 }
3734 Result += "\t} ";
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003735 return true;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003736 }
3737 }
3738 else if (Type->isEnumeralType()) {
3739 EnumDecl *ED = Type->getAs<EnumType>()->getDecl();
3740 if (ED->isCompleteDefinition()) {
3741 Result += "\n\tenum ";
3742 Result += ED->getName();
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003743 if (GlobalDefinedTags.count(ED)) {
3744 // Enum is globall defined, use it.
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003745 Result += " ";
3746 return true;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003747 }
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003748
3749 Result += " {\n";
3750 for (EnumDecl::enumerator_iterator EC = ED->enumerator_begin(),
3751 ECEnd = ED->enumerator_end(); EC != ECEnd; ++EC) {
3752 Result += "\t"; Result += EC->getName(); Result += " = ";
3753 llvm::APSInt Val = EC->getInitVal();
3754 Result += Val.toString(10);
3755 Result += ",\n";
3756 }
3757 Result += "\t} ";
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003758 return true;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003759 }
3760 }
3761
3762 Result += "\t";
3763 convertObjCTypeToCStyleType(Type);
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003764 return false;
3765}
3766
3767
3768/// RewriteObjCFieldDecl - This routine rewrites a field into the buffer.
3769/// It handles elaborated types, as well as enum types in the process.
3770void RewriteModernObjC::RewriteObjCFieldDecl(FieldDecl *fieldDecl,
3771 std::string &Result) {
3772 QualType Type = fieldDecl->getType();
3773 std::string Name = fieldDecl->getNameAsString();
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003774
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003775 bool EleboratedType = RewriteObjCFieldDeclType(Type, Result);
3776 if (!EleboratedType)
3777 Type.getAsStringInternal(Name, Context->getPrintingPolicy());
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003778 Result += Name;
3779 if (fieldDecl->isBitField()) {
3780 Result += " : "; Result += utostr(fieldDecl->getBitWidthValue(*Context));
3781 }
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003782 else if (EleboratedType && Type->isArrayType()) {
3783 CanQualType CType = Context->getCanonicalType(Type);
3784 while (isa<ArrayType>(CType)) {
3785 if (const ConstantArrayType *CAT = Context->getAsConstantArrayType(CType)) {
3786 Result += "[";
3787 llvm::APInt Dim = CAT->getSize();
3788 Result += utostr(Dim.getZExtValue());
3789 Result += "]";
3790 }
3791 CType = CType->getAs<ArrayType>()->getElementType();
3792 }
3793 }
3794
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003795 Result += ";\n";
3796}
3797
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003798/// RewriteLocallyDefinedNamedAggregates - This routine rewrites locally defined
3799/// named aggregate types into the input buffer.
3800void RewriteModernObjC::RewriteLocallyDefinedNamedAggregates(FieldDecl *fieldDecl,
3801 std::string &Result) {
3802 QualType Type = fieldDecl->getType();
Fariborz Jahanianf5eac482012-05-02 17:34:59 +00003803 if (isa<TypedefType>(Type))
3804 return;
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003805 if (Type->isArrayType())
3806 Type = Context->getBaseElementType(Type);
Fariborz Jahanianb68258f2012-05-01 17:46:45 +00003807 ObjCContainerDecl *IDecl =
3808 dyn_cast<ObjCContainerDecl>(fieldDecl->getDeclContext());
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003809
3810 TagDecl *TD = 0;
3811 if (Type->isRecordType()) {
3812 TD = Type->getAs<RecordType>()->getDecl();
3813 }
3814 else if (Type->isEnumeralType()) {
3815 TD = Type->getAs<EnumType>()->getDecl();
3816 }
3817
3818 if (TD) {
3819 if (GlobalDefinedTags.count(TD))
3820 return;
3821
3822 bool IsNamedDefinition = false;
3823 if (IsTagDefinedInsideClass(IDecl, TD, IsNamedDefinition)) {
3824 RewriteObjCFieldDeclType(Type, Result);
3825 Result += ";";
3826 }
3827 if (IsNamedDefinition)
3828 GlobalDefinedTags.insert(TD);
3829 }
3830
3831}
3832
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003833/// RewriteObjCInternalStruct - Rewrite one internal struct corresponding to
3834/// an objective-c class with ivars.
3835void RewriteModernObjC::RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
3836 std::string &Result) {
3837 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
3838 assert(CDecl->getName() != "" &&
3839 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003840 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003841 SmallVector<ObjCIvarDecl *, 8> IVars;
3842 for (ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
Fariborz Jahanian9a2105b2012-03-06 17:16:27 +00003843 IVD; IVD = IVD->getNextIvar())
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003844 IVars.push_back(IVD);
Fariborz Jahanian9a2105b2012-03-06 17:16:27 +00003845
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003846 SourceLocation LocStart = CDecl->getLocStart();
3847 SourceLocation LocEnd = CDecl->getEndOfDefinitionLoc();
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003848
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003849 const char *startBuf = SM->getCharacterData(LocStart);
3850 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003851
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003852 // If no ivars and no root or if its root, directly or indirectly,
3853 // have no ivars (thus not synthesized) then no need to synthesize this class.
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003854 if ((!CDecl->isThisDeclarationADefinition() || IVars.size() == 0) &&
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003855 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
3856 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
3857 ReplaceText(LocStart, endBuf-startBuf, Result);
3858 return;
3859 }
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003860
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003861 // Insert named struct/union definitions inside class to
3862 // outer scope. This follows semantics of locally defined
3863 // struct/unions in objective-c classes.
3864 for (unsigned i = 0, e = IVars.size(); i < e; i++)
3865 RewriteLocallyDefinedNamedAggregates(IVars[i], Result);
3866
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003867 Result += "\nstruct ";
3868 Result += CDecl->getNameAsString();
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003869 Result += "_IMPL {\n";
3870
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00003871 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003872 Result += "\tstruct "; Result += RCDecl->getNameAsString();
3873 Result += "_IMPL "; Result += RCDecl->getNameAsString();
3874 Result += "_IVARS;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003875 }
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003876
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003877 for (unsigned i = 0, e = IVars.size(); i < e; i++)
3878 RewriteObjCFieldDecl(IVars[i], Result);
Fariborz Jahanian0b17b9a2012-02-12 21:36:23 +00003879
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003880 Result += "};\n";
3881 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
3882 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00003883 // Mark this struct as having been generated.
3884 if (!ObjCSynthesizedStructs.insert(CDecl))
3885 llvm_unreachable("struct already synthesize- RewriteObjCInternalStruct");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003886}
3887
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00003888/// RewriteIvarOffsetSymbols - Rewrite ivar offset symbols of those ivars which
3889/// have been referenced in an ivar access expression.
3890void RewriteModernObjC::RewriteIvarOffsetSymbols(ObjCInterfaceDecl *CDecl,
3891 std::string &Result) {
3892 // write out ivar offset symbols which have been referenced in an ivar
3893 // access expression.
3894 llvm::SmallPtrSet<ObjCIvarDecl *, 8> Ivars = ReferencedIvars[CDecl];
3895 if (Ivars.empty())
3896 return;
3897 for (llvm::SmallPtrSet<ObjCIvarDecl *, 8>::iterator i = Ivars.begin(),
3898 e = Ivars.end(); i != e; i++) {
3899 ObjCIvarDecl *IvarDecl = (*i);
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00003900 Result += "\n";
3901 if (LangOpts.MicrosoftExt)
3902 Result += "__declspec(allocate(\".objc_ivar$B\")) ";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00003903 Result += "extern \"C\" ";
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00003904 if (LangOpts.MicrosoftExt &&
3905 IvarDecl->getAccessControl() != ObjCIvarDecl::Private &&
Fariborz Jahanian297976d2012-03-29 17:51:09 +00003906 IvarDecl->getAccessControl() != ObjCIvarDecl::Package)
3907 Result += "__declspec(dllimport) ";
3908
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00003909 Result += "unsigned long ";
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00003910 WriteInternalIvarName(CDecl, IvarDecl, Result);
3911 Result += ";";
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00003912 }
3913}
3914
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003915//===----------------------------------------------------------------------===//
3916// Meta Data Emission
3917//===----------------------------------------------------------------------===//
3918
3919
3920/// RewriteImplementations - This routine rewrites all method implementations
3921/// and emits meta-data.
3922
3923void RewriteModernObjC::RewriteImplementations() {
3924 int ClsDefCount = ClassImplementation.size();
3925 int CatDefCount = CategoryImplementation.size();
3926
3927 // Rewrite implemented methods
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00003928 for (int i = 0; i < ClsDefCount; i++) {
3929 ObjCImplementationDecl *OIMP = ClassImplementation[i];
3930 ObjCInterfaceDecl *CDecl = OIMP->getClassInterface();
3931 if (CDecl->isImplicitInterfaceDecl())
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +00003932 assert(false &&
3933 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00003934 RewriteImplementationDecl(OIMP);
3935 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003936
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00003937 for (int i = 0; i < CatDefCount; i++) {
3938 ObjCCategoryImplDecl *CIMP = CategoryImplementation[i];
3939 ObjCInterfaceDecl *CDecl = CIMP->getClassInterface();
3940 if (CDecl->isImplicitInterfaceDecl())
3941 assert(false &&
3942 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00003943 RewriteImplementationDecl(CIMP);
3944 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003945}
3946
3947void RewriteModernObjC::RewriteByRefString(std::string &ResultStr,
3948 const std::string &Name,
3949 ValueDecl *VD, bool def) {
3950 assert(BlockByRefDeclNo.count(VD) &&
3951 "RewriteByRefString: ByRef decl missing");
3952 if (def)
3953 ResultStr += "struct ";
3954 ResultStr += "__Block_byref_" + Name +
3955 "_" + utostr(BlockByRefDeclNo[VD]) ;
3956}
3957
3958static bool HasLocalVariableExternalStorage(ValueDecl *VD) {
3959 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
3960 return (Var->isFunctionOrMethodVarDecl() && !Var->hasLocalStorage());
3961 return false;
3962}
3963
3964std::string RewriteModernObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
3965 StringRef funcName,
3966 std::string Tag) {
3967 const FunctionType *AFT = CE->getFunctionType();
3968 QualType RT = AFT->getResultType();
3969 std::string StructRef = "struct " + Tag;
3970 std::string S = "static " + RT.getAsString(Context->getPrintingPolicy()) + " __" +
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00003971 funcName.str() + "_block_func_" + utostr(i);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003972
3973 BlockDecl *BD = CE->getBlockDecl();
3974
3975 if (isa<FunctionNoProtoType>(AFT)) {
3976 // No user-supplied arguments. Still need to pass in a pointer to the
3977 // block (to reference imported block decl refs).
3978 S += "(" + StructRef + " *__cself)";
3979 } else if (BD->param_empty()) {
3980 S += "(" + StructRef + " *__cself)";
3981 } else {
3982 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
3983 assert(FT && "SynthesizeBlockFunc: No function proto");
3984 S += '(';
3985 // first add the implicit argument.
3986 S += StructRef + " *__cself, ";
3987 std::string ParamStr;
3988 for (BlockDecl::param_iterator AI = BD->param_begin(),
3989 E = BD->param_end(); AI != E; ++AI) {
3990 if (AI != BD->param_begin()) S += ", ";
3991 ParamStr = (*AI)->getNameAsString();
3992 QualType QT = (*AI)->getType();
Fariborz Jahanian2610f902012-03-27 16:42:20 +00003993 (void)convertBlockPointerToFunctionPointer(QT);
3994 QT.getAsStringInternal(ParamStr, Context->getPrintingPolicy());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003995 S += ParamStr;
3996 }
3997 if (FT->isVariadic()) {
3998 if (!BD->param_empty()) S += ", ";
3999 S += "...";
4000 }
4001 S += ')';
4002 }
4003 S += " {\n";
4004
4005 // Create local declarations to avoid rewriting all closure decl ref exprs.
4006 // First, emit a declaration for all "by ref" decls.
4007 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
4008 E = BlockByRefDecls.end(); I != E; ++I) {
4009 S += " ";
4010 std::string Name = (*I)->getNameAsString();
4011 std::string TypeString;
4012 RewriteByRefString(TypeString, Name, (*I));
4013 TypeString += " *";
4014 Name = TypeString + Name;
4015 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
4016 }
4017 // Next, emit a declaration for all "by copy" declarations.
4018 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
4019 E = BlockByCopyDecls.end(); I != E; ++I) {
4020 S += " ";
4021 // Handle nested closure invocation. For example:
4022 //
4023 // void (^myImportedClosure)(void);
4024 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
4025 //
4026 // void (^anotherClosure)(void);
4027 // anotherClosure = ^(void) {
4028 // myImportedClosure(); // import and invoke the closure
4029 // };
4030 //
4031 if (isTopLevelBlockPointerType((*I)->getType())) {
4032 RewriteBlockPointerTypeVariable(S, (*I));
4033 S += " = (";
4034 RewriteBlockPointerType(S, (*I)->getType());
4035 S += ")";
4036 S += "__cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
4037 }
4038 else {
4039 std::string Name = (*I)->getNameAsString();
4040 QualType QT = (*I)->getType();
4041 if (HasLocalVariableExternalStorage(*I))
4042 QT = Context->getPointerType(QT);
4043 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
4044 S += Name + " = __cself->" +
4045 (*I)->getNameAsString() + "; // bound by copy\n";
4046 }
4047 }
4048 std::string RewrittenStr = RewrittenBlockExprs[CE];
4049 const char *cstr = RewrittenStr.c_str();
4050 while (*cstr++ != '{') ;
4051 S += cstr;
4052 S += "\n";
4053 return S;
4054}
4055
4056std::string RewriteModernObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
4057 StringRef funcName,
4058 std::string Tag) {
4059 std::string StructRef = "struct " + Tag;
4060 std::string S = "static void __";
4061
4062 S += funcName;
4063 S += "_block_copy_" + utostr(i);
4064 S += "(" + StructRef;
4065 S += "*dst, " + StructRef;
4066 S += "*src) {";
4067 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
4068 E = ImportedBlockDecls.end(); I != E; ++I) {
4069 ValueDecl *VD = (*I);
4070 S += "_Block_object_assign((void*)&dst->";
4071 S += (*I)->getNameAsString();
4072 S += ", (void*)src->";
4073 S += (*I)->getNameAsString();
4074 if (BlockByRefDeclsPtrSet.count((*I)))
4075 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
4076 else if (VD->getType()->isBlockPointerType())
4077 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
4078 else
4079 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
4080 }
4081 S += "}\n";
4082
4083 S += "\nstatic void __";
4084 S += funcName;
4085 S += "_block_dispose_" + utostr(i);
4086 S += "(" + StructRef;
4087 S += "*src) {";
4088 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
4089 E = ImportedBlockDecls.end(); I != E; ++I) {
4090 ValueDecl *VD = (*I);
4091 S += "_Block_object_dispose((void*)src->";
4092 S += (*I)->getNameAsString();
4093 if (BlockByRefDeclsPtrSet.count((*I)))
4094 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
4095 else if (VD->getType()->isBlockPointerType())
4096 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
4097 else
4098 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
4099 }
4100 S += "}\n";
4101 return S;
4102}
4103
4104std::string RewriteModernObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
4105 std::string Desc) {
4106 std::string S = "\nstruct " + Tag;
4107 std::string Constructor = " " + Tag;
4108
4109 S += " {\n struct __block_impl impl;\n";
4110 S += " struct " + Desc;
4111 S += "* Desc;\n";
4112
4113 Constructor += "(void *fp, "; // Invoke function pointer.
4114 Constructor += "struct " + Desc; // Descriptor pointer.
4115 Constructor += " *desc";
4116
4117 if (BlockDeclRefs.size()) {
4118 // Output all "by copy" declarations.
4119 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
4120 E = BlockByCopyDecls.end(); I != E; ++I) {
4121 S += " ";
4122 std::string FieldName = (*I)->getNameAsString();
4123 std::string ArgName = "_" + FieldName;
4124 // Handle nested closure invocation. For example:
4125 //
4126 // void (^myImportedBlock)(void);
4127 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
4128 //
4129 // void (^anotherBlock)(void);
4130 // anotherBlock = ^(void) {
4131 // myImportedBlock(); // import and invoke the closure
4132 // };
4133 //
4134 if (isTopLevelBlockPointerType((*I)->getType())) {
4135 S += "struct __block_impl *";
4136 Constructor += ", void *" + ArgName;
4137 } else {
4138 QualType QT = (*I)->getType();
4139 if (HasLocalVariableExternalStorage(*I))
4140 QT = Context->getPointerType(QT);
4141 QT.getAsStringInternal(FieldName, Context->getPrintingPolicy());
4142 QT.getAsStringInternal(ArgName, Context->getPrintingPolicy());
4143 Constructor += ", " + ArgName;
4144 }
4145 S += FieldName + ";\n";
4146 }
4147 // Output all "by ref" declarations.
4148 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
4149 E = BlockByRefDecls.end(); I != E; ++I) {
4150 S += " ";
4151 std::string FieldName = (*I)->getNameAsString();
4152 std::string ArgName = "_" + FieldName;
4153 {
4154 std::string TypeString;
4155 RewriteByRefString(TypeString, FieldName, (*I));
4156 TypeString += " *";
4157 FieldName = TypeString + FieldName;
4158 ArgName = TypeString + ArgName;
4159 Constructor += ", " + ArgName;
4160 }
4161 S += FieldName + "; // by ref\n";
4162 }
4163 // Finish writing the constructor.
4164 Constructor += ", int flags=0)";
4165 // Initialize all "by copy" arguments.
4166 bool firsTime = true;
4167 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
4168 E = BlockByCopyDecls.end(); I != E; ++I) {
4169 std::string Name = (*I)->getNameAsString();
4170 if (firsTime) {
4171 Constructor += " : ";
4172 firsTime = false;
4173 }
4174 else
4175 Constructor += ", ";
4176 if (isTopLevelBlockPointerType((*I)->getType()))
4177 Constructor += Name + "((struct __block_impl *)_" + Name + ")";
4178 else
4179 Constructor += Name + "(_" + Name + ")";
4180 }
4181 // Initialize all "by ref" arguments.
4182 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
4183 E = BlockByRefDecls.end(); I != E; ++I) {
4184 std::string Name = (*I)->getNameAsString();
4185 if (firsTime) {
4186 Constructor += " : ";
4187 firsTime = false;
4188 }
4189 else
4190 Constructor += ", ";
4191 Constructor += Name + "(_" + Name + "->__forwarding)";
4192 }
4193
4194 Constructor += " {\n";
4195 if (GlobalVarDecl)
4196 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4197 else
4198 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
4199 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
4200
4201 Constructor += " Desc = desc;\n";
4202 } else {
4203 // Finish writing the constructor.
4204 Constructor += ", int flags=0) {\n";
4205 if (GlobalVarDecl)
4206 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4207 else
4208 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
4209 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
4210 Constructor += " Desc = desc;\n";
4211 }
4212 Constructor += " ";
4213 Constructor += "}\n";
4214 S += Constructor;
4215 S += "};\n";
4216 return S;
4217}
4218
4219std::string RewriteModernObjC::SynthesizeBlockDescriptor(std::string DescTag,
4220 std::string ImplTag, int i,
4221 StringRef FunName,
4222 unsigned hasCopy) {
4223 std::string S = "\nstatic struct " + DescTag;
4224
Fariborz Jahanian8b08adb2012-05-03 21:44:12 +00004225 S += " {\n size_t reserved;\n";
4226 S += " size_t Block_size;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004227 if (hasCopy) {
4228 S += " void (*copy)(struct ";
4229 S += ImplTag; S += "*, struct ";
4230 S += ImplTag; S += "*);\n";
4231
4232 S += " void (*dispose)(struct ";
4233 S += ImplTag; S += "*);\n";
4234 }
4235 S += "} ";
4236
4237 S += DescTag + "_DATA = { 0, sizeof(struct ";
4238 S += ImplTag + ")";
4239 if (hasCopy) {
4240 S += ", __" + FunName.str() + "_block_copy_" + utostr(i);
4241 S += ", __" + FunName.str() + "_block_dispose_" + utostr(i);
4242 }
4243 S += "};\n";
4244 return S;
4245}
4246
4247void RewriteModernObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
4248 StringRef FunName) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004249 bool RewriteSC = (GlobalVarDecl &&
4250 !Blocks.empty() &&
4251 GlobalVarDecl->getStorageClass() == SC_Static &&
4252 GlobalVarDecl->getType().getCVRQualifiers());
4253 if (RewriteSC) {
4254 std::string SC(" void __");
4255 SC += GlobalVarDecl->getNameAsString();
4256 SC += "() {}";
4257 InsertText(FunLocStart, SC);
4258 }
4259
4260 // Insert closures that were part of the function.
4261 for (unsigned i = 0, count=0; i < Blocks.size(); i++) {
4262 CollectBlockDeclRefInfo(Blocks[i]);
4263 // Need to copy-in the inner copied-in variables not actually used in this
4264 // block.
4265 for (int j = 0; j < InnerDeclRefsCount[i]; j++) {
John McCallf4b88a42012-03-10 09:33:50 +00004266 DeclRefExpr *Exp = InnerDeclRefs[count++];
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004267 ValueDecl *VD = Exp->getDecl();
4268 BlockDeclRefs.push_back(Exp);
John McCallf4b88a42012-03-10 09:33:50 +00004269 if (!VD->hasAttr<BlocksAttr>()) {
4270 if (!BlockByCopyDeclsPtrSet.count(VD)) {
4271 BlockByCopyDeclsPtrSet.insert(VD);
4272 BlockByCopyDecls.push_back(VD);
4273 }
4274 continue;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004275 }
John McCallf4b88a42012-03-10 09:33:50 +00004276
4277 if (!BlockByRefDeclsPtrSet.count(VD)) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004278 BlockByRefDeclsPtrSet.insert(VD);
4279 BlockByRefDecls.push_back(VD);
4280 }
John McCallf4b88a42012-03-10 09:33:50 +00004281
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004282 // imported objects in the inner blocks not used in the outer
4283 // blocks must be copied/disposed in the outer block as well.
John McCallf4b88a42012-03-10 09:33:50 +00004284 if (VD->getType()->isObjCObjectPointerType() ||
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004285 VD->getType()->isBlockPointerType())
4286 ImportedBlockDecls.insert(VD);
4287 }
4288
4289 std::string ImplTag = "__" + FunName.str() + "_block_impl_" + utostr(i);
4290 std::string DescTag = "__" + FunName.str() + "_block_desc_" + utostr(i);
4291
4292 std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
4293
4294 InsertText(FunLocStart, CI);
4295
4296 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
4297
4298 InsertText(FunLocStart, CF);
4299
4300 if (ImportedBlockDecls.size()) {
4301 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
4302 InsertText(FunLocStart, HF);
4303 }
4304 std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
4305 ImportedBlockDecls.size() > 0);
4306 InsertText(FunLocStart, BD);
4307
4308 BlockDeclRefs.clear();
4309 BlockByRefDecls.clear();
4310 BlockByRefDeclsPtrSet.clear();
4311 BlockByCopyDecls.clear();
4312 BlockByCopyDeclsPtrSet.clear();
4313 ImportedBlockDecls.clear();
4314 }
4315 if (RewriteSC) {
4316 // Must insert any 'const/volatile/static here. Since it has been
4317 // removed as result of rewriting of block literals.
4318 std::string SC;
4319 if (GlobalVarDecl->getStorageClass() == SC_Static)
4320 SC = "static ";
4321 if (GlobalVarDecl->getType().isConstQualified())
4322 SC += "const ";
4323 if (GlobalVarDecl->getType().isVolatileQualified())
4324 SC += "volatile ";
4325 if (GlobalVarDecl->getType().isRestrictQualified())
4326 SC += "restrict ";
4327 InsertText(FunLocStart, SC);
4328 }
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00004329 if (GlobalConstructionExp) {
4330 // extra fancy dance for global literal expression.
4331
4332 // Always the latest block expression on the block stack.
4333 std::string Tag = "__";
4334 Tag += FunName;
4335 Tag += "_block_impl_";
4336 Tag += utostr(Blocks.size()-1);
4337 std::string globalBuf = "static ";
4338 globalBuf += Tag; globalBuf += " ";
4339 std::string SStr;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004340
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00004341 llvm::raw_string_ostream constructorExprBuf(SStr);
Richard Smithd1420c62012-08-16 03:56:14 +00004342 GlobalConstructionExp->printPretty(constructorExprBuf, 0,
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00004343 PrintingPolicy(LangOpts));
4344 globalBuf += constructorExprBuf.str();
4345 globalBuf += ";\n";
4346 InsertText(FunLocStart, globalBuf);
4347 GlobalConstructionExp = 0;
4348 }
4349
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004350 Blocks.clear();
4351 InnerDeclRefsCount.clear();
4352 InnerDeclRefs.clear();
4353 RewrittenBlockExprs.clear();
4354}
4355
4356void RewriteModernObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
Fariborz Jahanian04189532012-04-25 17:56:48 +00004357 SourceLocation FunLocStart =
4358 (!Blocks.empty()) ? getFunctionSourceLocation(*this, FD)
4359 : FD->getTypeSpecStartLoc();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004360 StringRef FuncName = FD->getName();
4361
4362 SynthesizeBlockLiterals(FunLocStart, FuncName);
4363}
4364
4365static void BuildUniqueMethodName(std::string &Name,
4366 ObjCMethodDecl *MD) {
4367 ObjCInterfaceDecl *IFace = MD->getClassInterface();
4368 Name = IFace->getName();
4369 Name += "__" + MD->getSelector().getAsString();
4370 // Convert colons to underscores.
4371 std::string::size_type loc = 0;
4372 while ((loc = Name.find(":", loc)) != std::string::npos)
4373 Name.replace(loc, 1, "_");
4374}
4375
4376void RewriteModernObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
4377 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
4378 //SourceLocation FunLocStart = MD->getLocStart();
4379 SourceLocation FunLocStart = MD->getLocStart();
4380 std::string FuncName;
4381 BuildUniqueMethodName(FuncName, MD);
4382 SynthesizeBlockLiterals(FunLocStart, FuncName);
4383}
4384
4385void RewriteModernObjC::GetBlockDeclRefExprs(Stmt *S) {
4386 for (Stmt::child_range CI = S->children(); CI; ++CI)
4387 if (*CI) {
4388 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
4389 GetBlockDeclRefExprs(CBE->getBody());
4390 else
4391 GetBlockDeclRefExprs(*CI);
4392 }
4393 // Handle specific things.
Fariborz Jahanian0e976812012-04-16 23:00:57 +00004394 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4395 if (DRE->refersToEnclosingLocal()) {
4396 // FIXME: Handle enums.
4397 if (!isa<FunctionDecl>(DRE->getDecl()))
4398 BlockDeclRefs.push_back(DRE);
4399 if (HasLocalVariableExternalStorage(DRE->getDecl()))
4400 BlockDeclRefs.push_back(DRE);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004401 }
Fariborz Jahanian0e976812012-04-16 23:00:57 +00004402 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004403
4404 return;
4405}
4406
4407void RewriteModernObjC::GetInnerBlockDeclRefExprs(Stmt *S,
John McCallf4b88a42012-03-10 09:33:50 +00004408 SmallVector<DeclRefExpr *, 8> &InnerBlockDeclRefs,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004409 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts) {
4410 for (Stmt::child_range CI = S->children(); CI; ++CI)
4411 if (*CI) {
4412 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI)) {
4413 InnerContexts.insert(cast<DeclContext>(CBE->getBlockDecl()));
4414 GetInnerBlockDeclRefExprs(CBE->getBody(),
4415 InnerBlockDeclRefs,
4416 InnerContexts);
4417 }
4418 else
4419 GetInnerBlockDeclRefExprs(*CI,
4420 InnerBlockDeclRefs,
4421 InnerContexts);
4422
4423 }
4424 // Handle specific things.
John McCallf4b88a42012-03-10 09:33:50 +00004425 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4426 if (DRE->refersToEnclosingLocal()) {
4427 if (!isa<FunctionDecl>(DRE->getDecl()) &&
4428 !InnerContexts.count(DRE->getDecl()->getDeclContext()))
4429 InnerBlockDeclRefs.push_back(DRE);
4430 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl()))
4431 if (Var->isFunctionOrMethodVarDecl())
4432 ImportedLocalExternalDecls.insert(Var);
4433 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004434 }
4435
4436 return;
4437}
4438
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00004439/// convertObjCTypeToCStyleType - This routine converts such objc types
4440/// as qualified objects, and blocks to their closest c/c++ types that
4441/// it can. It returns true if input type was modified.
4442bool RewriteModernObjC::convertObjCTypeToCStyleType(QualType &T) {
4443 QualType oldT = T;
4444 convertBlockPointerToFunctionPointer(T);
4445 if (T->isFunctionPointerType()) {
4446 QualType PointeeTy;
4447 if (const PointerType* PT = T->getAs<PointerType>()) {
4448 PointeeTy = PT->getPointeeType();
4449 if (const FunctionType *FT = PointeeTy->getAs<FunctionType>()) {
4450 T = convertFunctionTypeOfBlocks(FT);
4451 T = Context->getPointerType(T);
4452 }
4453 }
4454 }
4455
4456 convertToUnqualifiedObjCType(T);
4457 return T != oldT;
4458}
4459
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004460/// convertFunctionTypeOfBlocks - This routine converts a function type
4461/// whose result type may be a block pointer or whose argument type(s)
4462/// might be block pointers to an equivalent function type replacing
4463/// all block pointers to function pointers.
4464QualType RewriteModernObjC::convertFunctionTypeOfBlocks(const FunctionType *FT) {
4465 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
4466 // FTP will be null for closures that don't take arguments.
4467 // Generate a funky cast.
4468 SmallVector<QualType, 8> ArgTypes;
4469 QualType Res = FT->getResultType();
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00004470 bool modified = convertObjCTypeToCStyleType(Res);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004471
4472 if (FTP) {
4473 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4474 E = FTP->arg_type_end(); I && (I != E); ++I) {
4475 QualType t = *I;
4476 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00004477 if (convertObjCTypeToCStyleType(t))
4478 modified = true;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004479 ArgTypes.push_back(t);
4480 }
4481 }
4482 QualType FuncType;
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00004483 if (modified)
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004484 FuncType = getSimpleFunctionType(Res, &ArgTypes[0], ArgTypes.size());
4485 else FuncType = QualType(FT, 0);
4486 return FuncType;
4487}
4488
4489Stmt *RewriteModernObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
4490 // Navigate to relevant type information.
4491 const BlockPointerType *CPT = 0;
4492
4493 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
4494 CPT = DRE->getType()->getAs<BlockPointerType>();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004495 } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
4496 CPT = MExpr->getType()->getAs<BlockPointerType>();
4497 }
4498 else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
4499 return SynthesizeBlockCall(Exp, PRE->getSubExpr());
4500 }
4501 else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
4502 CPT = IEXPR->getType()->getAs<BlockPointerType>();
4503 else if (const ConditionalOperator *CEXPR =
4504 dyn_cast<ConditionalOperator>(BlockExp)) {
4505 Expr *LHSExp = CEXPR->getLHS();
4506 Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
4507 Expr *RHSExp = CEXPR->getRHS();
4508 Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
4509 Expr *CONDExp = CEXPR->getCond();
4510 ConditionalOperator *CondExpr =
4511 new (Context) ConditionalOperator(CONDExp,
4512 SourceLocation(), cast<Expr>(LHSStmt),
4513 SourceLocation(), cast<Expr>(RHSStmt),
4514 Exp->getType(), VK_RValue, OK_Ordinary);
4515 return CondExpr;
4516 } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
4517 CPT = IRE->getType()->getAs<BlockPointerType>();
4518 } else if (const PseudoObjectExpr *POE
4519 = dyn_cast<PseudoObjectExpr>(BlockExp)) {
4520 CPT = POE->getType()->castAs<BlockPointerType>();
4521 } else {
4522 assert(1 && "RewriteBlockClass: Bad type");
4523 }
4524 assert(CPT && "RewriteBlockClass: Bad type");
4525 const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
4526 assert(FT && "RewriteBlockClass: Bad type");
4527 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
4528 // FTP will be null for closures that don't take arguments.
4529
4530 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
4531 SourceLocation(), SourceLocation(),
4532 &Context->Idents.get("__block_impl"));
4533 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
4534
4535 // Generate a funky cast.
4536 SmallVector<QualType, 8> ArgTypes;
4537
4538 // Push the block argument type.
4539 ArgTypes.push_back(PtrBlock);
4540 if (FTP) {
4541 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4542 E = FTP->arg_type_end(); I && (I != E); ++I) {
4543 QualType t = *I;
4544 // Make sure we convert "t (^)(...)" to "t (*)(...)".
4545 if (!convertBlockPointerToFunctionPointer(t))
4546 convertToUnqualifiedObjCType(t);
4547 ArgTypes.push_back(t);
4548 }
4549 }
4550 // Now do the pointer to function cast.
4551 QualType PtrToFuncCastType
4552 = getSimpleFunctionType(Exp->getType(), &ArgTypes[0], ArgTypes.size());
4553
4554 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
4555
4556 CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock,
4557 CK_BitCast,
4558 const_cast<Expr*>(BlockExp));
4559 // Don't forget the parens to enforce the proper binding.
4560 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4561 BlkCast);
4562 //PE->dump();
4563
4564 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4565 SourceLocation(),
4566 &Context->Idents.get("FuncPtr"),
4567 Context->VoidPtrTy, 0,
4568 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smithca523302012-06-10 03:12:00 +00004569 ICIS_NoInit);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004570 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
4571 FD->getType(), VK_LValue,
4572 OK_Ordinary);
4573
4574
4575 CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType,
4576 CK_BitCast, ME);
4577 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
4578
4579 SmallVector<Expr*, 8> BlkExprs;
4580 // Add the implicit argument.
4581 BlkExprs.push_back(BlkCast);
4582 // Add the user arguments.
4583 for (CallExpr::arg_iterator I = Exp->arg_begin(),
4584 E = Exp->arg_end(); I != E; ++I) {
4585 BlkExprs.push_back(*I);
4586 }
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00004587 CallExpr *CE = new (Context) CallExpr(*Context, PE, BlkExprs,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004588 Exp->getType(), VK_RValue,
4589 SourceLocation());
4590 return CE;
4591}
4592
4593// We need to return the rewritten expression to handle cases where the
John McCallf4b88a42012-03-10 09:33:50 +00004594// DeclRefExpr is embedded in another expression being rewritten.
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004595// For example:
4596//
4597// int main() {
4598// __block Foo *f;
4599// __block int i;
4600//
4601// void (^myblock)() = ^() {
John McCallf4b88a42012-03-10 09:33:50 +00004602// [f test]; // f is a DeclRefExpr embedded in a message (which is being rewritten).
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004603// i = 77;
4604// };
4605//}
John McCallf4b88a42012-03-10 09:33:50 +00004606Stmt *RewriteModernObjC::RewriteBlockDeclRefExpr(DeclRefExpr *DeclRefExp) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004607 // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
4608 // for each DeclRefExp where BYREFVAR is name of the variable.
John McCallf4b88a42012-03-10 09:33:50 +00004609 ValueDecl *VD = DeclRefExp->getDecl();
4610 bool isArrow = DeclRefExp->refersToEnclosingLocal();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004611
4612 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4613 SourceLocation(),
4614 &Context->Idents.get("__forwarding"),
4615 Context->VoidPtrTy, 0,
4616 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smithca523302012-06-10 03:12:00 +00004617 ICIS_NoInit);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004618 MemberExpr *ME = new (Context) MemberExpr(DeclRefExp, isArrow,
4619 FD, SourceLocation(),
4620 FD->getType(), VK_LValue,
4621 OK_Ordinary);
4622
4623 StringRef Name = VD->getName();
4624 FD = FieldDecl::Create(*Context, 0, SourceLocation(), SourceLocation(),
4625 &Context->Idents.get(Name),
4626 Context->VoidPtrTy, 0,
4627 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smithca523302012-06-10 03:12:00 +00004628 ICIS_NoInit);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004629 ME = new (Context) MemberExpr(ME, true, FD, SourceLocation(),
4630 DeclRefExp->getType(), VK_LValue, OK_Ordinary);
4631
4632
4633
4634 // Need parens to enforce precedence.
4635 ParenExpr *PE = new (Context) ParenExpr(DeclRefExp->getExprLoc(),
4636 DeclRefExp->getExprLoc(),
4637 ME);
4638 ReplaceStmt(DeclRefExp, PE);
4639 return PE;
4640}
4641
4642// Rewrites the imported local variable V with external storage
4643// (static, extern, etc.) as *V
4644//
4645Stmt *RewriteModernObjC::RewriteLocalVariableExternalStorage(DeclRefExpr *DRE) {
4646 ValueDecl *VD = DRE->getDecl();
4647 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4648 if (!ImportedLocalExternalDecls.count(Var))
4649 return DRE;
4650 Expr *Exp = new (Context) UnaryOperator(DRE, UO_Deref, DRE->getType(),
4651 VK_LValue, OK_Ordinary,
4652 DRE->getLocation());
4653 // Need parens to enforce precedence.
4654 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4655 Exp);
4656 ReplaceStmt(DRE, PE);
4657 return PE;
4658}
4659
4660void RewriteModernObjC::RewriteCastExpr(CStyleCastExpr *CE) {
4661 SourceLocation LocStart = CE->getLParenLoc();
4662 SourceLocation LocEnd = CE->getRParenLoc();
4663
4664 // Need to avoid trying to rewrite synthesized casts.
4665 if (LocStart.isInvalid())
4666 return;
4667 // Need to avoid trying to rewrite casts contained in macros.
4668 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
4669 return;
4670
4671 const char *startBuf = SM->getCharacterData(LocStart);
4672 const char *endBuf = SM->getCharacterData(LocEnd);
4673 QualType QT = CE->getType();
4674 const Type* TypePtr = QT->getAs<Type>();
4675 if (isa<TypeOfExprType>(TypePtr)) {
4676 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
4677 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
4678 std::string TypeAsString = "(";
4679 RewriteBlockPointerType(TypeAsString, QT);
4680 TypeAsString += ")";
4681 ReplaceText(LocStart, endBuf-startBuf+1, TypeAsString);
4682 return;
4683 }
4684 // advance the location to startArgList.
4685 const char *argPtr = startBuf;
4686
4687 while (*argPtr++ && (argPtr < endBuf)) {
4688 switch (*argPtr) {
4689 case '^':
4690 // Replace the '^' with '*'.
4691 LocStart = LocStart.getLocWithOffset(argPtr-startBuf);
4692 ReplaceText(LocStart, 1, "*");
4693 break;
4694 }
4695 }
4696 return;
4697}
4698
Fariborz Jahanianf1ee6872012-04-10 00:08:18 +00004699void RewriteModernObjC::RewriteImplicitCastObjCExpr(CastExpr *IC) {
4700 CastKind CastKind = IC->getCastKind();
Fariborz Jahanian43aa1c32012-04-16 22:14:01 +00004701 if (CastKind != CK_BlockPointerToObjCPointerCast &&
4702 CastKind != CK_AnyPointerToBlockPointerCast)
4703 return;
Fariborz Jahanianf1ee6872012-04-10 00:08:18 +00004704
Fariborz Jahanian43aa1c32012-04-16 22:14:01 +00004705 QualType QT = IC->getType();
4706 (void)convertBlockPointerToFunctionPointer(QT);
4707 std::string TypeString(QT.getAsString(Context->getPrintingPolicy()));
4708 std::string Str = "(";
4709 Str += TypeString;
4710 Str += ")";
4711 InsertText(IC->getSubExpr()->getLocStart(), &Str[0], Str.size());
4712
Fariborz Jahanianf1ee6872012-04-10 00:08:18 +00004713 return;
4714}
4715
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004716void RewriteModernObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
4717 SourceLocation DeclLoc = FD->getLocation();
4718 unsigned parenCount = 0;
4719
4720 // We have 1 or more arguments that have closure pointers.
4721 const char *startBuf = SM->getCharacterData(DeclLoc);
4722 const char *startArgList = strchr(startBuf, '(');
4723
4724 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
4725
4726 parenCount++;
4727 // advance the location to startArgList.
4728 DeclLoc = DeclLoc.getLocWithOffset(startArgList-startBuf);
4729 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
4730
4731 const char *argPtr = startArgList;
4732
4733 while (*argPtr++ && parenCount) {
4734 switch (*argPtr) {
4735 case '^':
4736 // Replace the '^' with '*'.
4737 DeclLoc = DeclLoc.getLocWithOffset(argPtr-startArgList);
4738 ReplaceText(DeclLoc, 1, "*");
4739 break;
4740 case '(':
4741 parenCount++;
4742 break;
4743 case ')':
4744 parenCount--;
4745 break;
4746 }
4747 }
4748 return;
4749}
4750
4751bool RewriteModernObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
4752 const FunctionProtoType *FTP;
4753 const PointerType *PT = QT->getAs<PointerType>();
4754 if (PT) {
4755 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4756 } else {
4757 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4758 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4759 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4760 }
4761 if (FTP) {
4762 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4763 E = FTP->arg_type_end(); I != E; ++I)
4764 if (isTopLevelBlockPointerType(*I))
4765 return true;
4766 }
4767 return false;
4768}
4769
4770bool RewriteModernObjC::PointerTypeTakesAnyObjCQualifiedType(QualType QT) {
4771 const FunctionProtoType *FTP;
4772 const PointerType *PT = QT->getAs<PointerType>();
4773 if (PT) {
4774 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4775 } else {
4776 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4777 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4778 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4779 }
4780 if (FTP) {
4781 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4782 E = FTP->arg_type_end(); I != E; ++I) {
4783 if ((*I)->isObjCQualifiedIdType())
4784 return true;
4785 if ((*I)->isObjCObjectPointerType() &&
4786 (*I)->getPointeeType()->isObjCQualifiedInterfaceType())
4787 return true;
4788 }
4789
4790 }
4791 return false;
4792}
4793
4794void RewriteModernObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
4795 const char *&RParen) {
4796 const char *argPtr = strchr(Name, '(');
4797 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
4798
4799 LParen = argPtr; // output the start.
4800 argPtr++; // skip past the left paren.
4801 unsigned parenCount = 1;
4802
4803 while (*argPtr && parenCount) {
4804 switch (*argPtr) {
4805 case '(': parenCount++; break;
4806 case ')': parenCount--; break;
4807 default: break;
4808 }
4809 if (parenCount) argPtr++;
4810 }
4811 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
4812 RParen = argPtr; // output the end
4813}
4814
4815void RewriteModernObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
4816 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4817 RewriteBlockPointerFunctionArgs(FD);
4818 return;
4819 }
4820 // Handle Variables and Typedefs.
4821 SourceLocation DeclLoc = ND->getLocation();
4822 QualType DeclT;
4823 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
4824 DeclT = VD->getType();
4825 else if (TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(ND))
4826 DeclT = TDD->getUnderlyingType();
4827 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
4828 DeclT = FD->getType();
4829 else
4830 llvm_unreachable("RewriteBlockPointerDecl(): Decl type not yet handled");
4831
4832 const char *startBuf = SM->getCharacterData(DeclLoc);
4833 const char *endBuf = startBuf;
4834 // scan backward (from the decl location) for the end of the previous decl.
4835 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
4836 startBuf--;
4837 SourceLocation Start = DeclLoc.getLocWithOffset(startBuf-endBuf);
4838 std::string buf;
4839 unsigned OrigLength=0;
4840 // *startBuf != '^' if we are dealing with a pointer to function that
4841 // may take block argument types (which will be handled below).
4842 if (*startBuf == '^') {
4843 // Replace the '^' with '*', computing a negative offset.
4844 buf = '*';
4845 startBuf++;
4846 OrigLength++;
4847 }
4848 while (*startBuf != ')') {
4849 buf += *startBuf;
4850 startBuf++;
4851 OrigLength++;
4852 }
4853 buf += ')';
4854 OrigLength++;
4855
4856 if (PointerTypeTakesAnyBlockArguments(DeclT) ||
4857 PointerTypeTakesAnyObjCQualifiedType(DeclT)) {
4858 // Replace the '^' with '*' for arguments.
4859 // Replace id<P> with id/*<>*/
4860 DeclLoc = ND->getLocation();
4861 startBuf = SM->getCharacterData(DeclLoc);
4862 const char *argListBegin, *argListEnd;
4863 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
4864 while (argListBegin < argListEnd) {
4865 if (*argListBegin == '^')
4866 buf += '*';
4867 else if (*argListBegin == '<') {
4868 buf += "/*";
4869 buf += *argListBegin++;
Dmitri Gribenko1ad23d62012-09-10 21:20:09 +00004870 OrigLength++;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004871 while (*argListBegin != '>') {
4872 buf += *argListBegin++;
4873 OrigLength++;
4874 }
4875 buf += *argListBegin;
4876 buf += "*/";
4877 }
4878 else
4879 buf += *argListBegin;
4880 argListBegin++;
4881 OrigLength++;
4882 }
4883 buf += ')';
4884 OrigLength++;
4885 }
4886 ReplaceText(Start, OrigLength, buf);
4887
4888 return;
4889}
4890
4891
4892/// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
4893/// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
4894/// struct Block_byref_id_object *src) {
4895/// _Block_object_assign (&_dest->object, _src->object,
4896/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4897/// [|BLOCK_FIELD_IS_WEAK]) // object
4898/// _Block_object_assign(&_dest->object, _src->object,
4899/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4900/// [|BLOCK_FIELD_IS_WEAK]) // block
4901/// }
4902/// And:
4903/// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
4904/// _Block_object_dispose(_src->object,
4905/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4906/// [|BLOCK_FIELD_IS_WEAK]) // object
4907/// _Block_object_dispose(_src->object,
4908/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4909/// [|BLOCK_FIELD_IS_WEAK]) // block
4910/// }
4911
4912std::string RewriteModernObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
4913 int flag) {
4914 std::string S;
4915 if (CopyDestroyCache.count(flag))
4916 return S;
4917 CopyDestroyCache.insert(flag);
4918 S = "static void __Block_byref_id_object_copy_";
4919 S += utostr(flag);
4920 S += "(void *dst, void *src) {\n";
4921
4922 // offset into the object pointer is computed as:
4923 // void * + void* + int + int + void* + void *
4924 unsigned IntSize =
4925 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
4926 unsigned VoidPtrSize =
4927 static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
4928
4929 unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/Context->getCharWidth();
4930 S += " _Block_object_assign((char*)dst + ";
4931 S += utostr(offset);
4932 S += ", *(void * *) ((char*)src + ";
4933 S += utostr(offset);
4934 S += "), ";
4935 S += utostr(flag);
4936 S += ");\n}\n";
4937
4938 S += "static void __Block_byref_id_object_dispose_";
4939 S += utostr(flag);
4940 S += "(void *src) {\n";
4941 S += " _Block_object_dispose(*(void * *) ((char*)src + ";
4942 S += utostr(offset);
4943 S += "), ";
4944 S += utostr(flag);
4945 S += ");\n}\n";
4946 return S;
4947}
4948
4949/// RewriteByRefVar - For each __block typex ND variable this routine transforms
4950/// the declaration into:
4951/// struct __Block_byref_ND {
4952/// void *__isa; // NULL for everything except __weak pointers
4953/// struct __Block_byref_ND *__forwarding;
4954/// int32_t __flags;
4955/// int32_t __size;
4956/// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
4957/// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
4958/// typex ND;
4959/// };
4960///
4961/// It then replaces declaration of ND variable with:
4962/// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
4963/// __size=sizeof(struct __Block_byref_ND),
4964/// ND=initializer-if-any};
4965///
4966///
Fariborz Jahanian4fe261c2012-04-24 19:38:45 +00004967void RewriteModernObjC::RewriteByRefVar(VarDecl *ND, bool firstDecl,
4968 bool lastDecl) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004969 int flag = 0;
4970 int isa = 0;
4971 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
4972 if (DeclLoc.isInvalid())
4973 // If type location is missing, it is because of missing type (a warning).
4974 // Use variable's location which is good for this case.
4975 DeclLoc = ND->getLocation();
4976 const char *startBuf = SM->getCharacterData(DeclLoc);
4977 SourceLocation X = ND->getLocEnd();
4978 X = SM->getExpansionLoc(X);
4979 const char *endBuf = SM->getCharacterData(X);
4980 std::string Name(ND->getNameAsString());
4981 std::string ByrefType;
4982 RewriteByRefString(ByrefType, Name, ND, true);
4983 ByrefType += " {\n";
4984 ByrefType += " void *__isa;\n";
4985 RewriteByRefString(ByrefType, Name, ND);
4986 ByrefType += " *__forwarding;\n";
4987 ByrefType += " int __flags;\n";
4988 ByrefType += " int __size;\n";
4989 // Add void *__Block_byref_id_object_copy;
4990 // void *__Block_byref_id_object_dispose; if needed.
4991 QualType Ty = ND->getType();
4992 bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty);
4993 if (HasCopyAndDispose) {
4994 ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
4995 ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
4996 }
4997
4998 QualType T = Ty;
4999 (void)convertBlockPointerToFunctionPointer(T);
5000 T.getAsStringInternal(Name, Context->getPrintingPolicy());
5001
5002 ByrefType += " " + Name + ";\n";
5003 ByrefType += "};\n";
5004 // Insert this type in global scope. It is needed by helper function.
5005 SourceLocation FunLocStart;
5006 if (CurFunctionDef)
Fariborz Jahanianb75f8de2012-04-19 00:50:01 +00005007 FunLocStart = getFunctionSourceLocation(*this, CurFunctionDef);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005008 else {
5009 assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null");
5010 FunLocStart = CurMethodDef->getLocStart();
5011 }
5012 InsertText(FunLocStart, ByrefType);
Fariborz Jahanian8247c4e2012-04-24 16:45:27 +00005013
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005014 if (Ty.isObjCGCWeak()) {
5015 flag |= BLOCK_FIELD_IS_WEAK;
5016 isa = 1;
5017 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005018 if (HasCopyAndDispose) {
5019 flag = BLOCK_BYREF_CALLER;
5020 QualType Ty = ND->getType();
5021 // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
5022 if (Ty->isBlockPointerType())
5023 flag |= BLOCK_FIELD_IS_BLOCK;
5024 else
5025 flag |= BLOCK_FIELD_IS_OBJECT;
5026 std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
5027 if (!HF.empty())
5028 InsertText(FunLocStart, HF);
5029 }
5030
5031 // struct __Block_byref_ND ND =
5032 // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
5033 // initializer-if-any};
5034 bool hasInit = (ND->getInit() != 0);
Fariborz Jahanian104dbf92012-04-11 23:57:12 +00005035 // FIXME. rewriter does not support __block c++ objects which
5036 // require construction.
Fariborz Jahanian65a7c682012-04-26 23:20:25 +00005037 if (hasInit)
5038 if (CXXConstructExpr *CExp = dyn_cast<CXXConstructExpr>(ND->getInit())) {
5039 CXXConstructorDecl *CXXDecl = CExp->getConstructor();
5040 if (CXXDecl && CXXDecl->isDefaultConstructor())
5041 hasInit = false;
5042 }
5043
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005044 unsigned flags = 0;
5045 if (HasCopyAndDispose)
5046 flags |= BLOCK_HAS_COPY_DISPOSE;
5047 Name = ND->getNameAsString();
5048 ByrefType.clear();
5049 RewriteByRefString(ByrefType, Name, ND);
5050 std::string ForwardingCastType("(");
5051 ForwardingCastType += ByrefType + " *)";
Fariborz Jahanian8247c4e2012-04-24 16:45:27 +00005052 ByrefType += " " + Name + " = {(void*)";
5053 ByrefType += utostr(isa);
5054 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
5055 ByrefType += utostr(flags);
5056 ByrefType += ", ";
5057 ByrefType += "sizeof(";
5058 RewriteByRefString(ByrefType, Name, ND);
5059 ByrefType += ")";
5060 if (HasCopyAndDispose) {
5061 ByrefType += ", __Block_byref_id_object_copy_";
5062 ByrefType += utostr(flag);
5063 ByrefType += ", __Block_byref_id_object_dispose_";
5064 ByrefType += utostr(flag);
5065 }
5066
Fariborz Jahanian4fe261c2012-04-24 19:38:45 +00005067 if (!firstDecl) {
5068 // In multiple __block declarations, and for all but 1st declaration,
5069 // find location of the separating comma. This would be start location
5070 // where new text is to be inserted.
5071 DeclLoc = ND->getLocation();
5072 const char *startDeclBuf = SM->getCharacterData(DeclLoc);
5073 const char *commaBuf = startDeclBuf;
5074 while (*commaBuf != ',')
5075 commaBuf--;
5076 assert((*commaBuf == ',') && "RewriteByRefVar: can't find ','");
5077 DeclLoc = DeclLoc.getLocWithOffset(commaBuf - startDeclBuf);
5078 startBuf = commaBuf;
5079 }
5080
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005081 if (!hasInit) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005082 ByrefType += "};\n";
5083 unsigned nameSize = Name.size();
5084 // for block or function pointer declaration. Name is aleady
5085 // part of the declaration.
5086 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType())
5087 nameSize = 1;
5088 ReplaceText(DeclLoc, endBuf-startBuf+nameSize, ByrefType);
5089 }
5090 else {
Fariborz Jahanian8247c4e2012-04-24 16:45:27 +00005091 ByrefType += ", ";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005092 SourceLocation startLoc;
5093 Expr *E = ND->getInit();
5094 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
5095 startLoc = ECE->getLParenLoc();
5096 else
5097 startLoc = E->getLocStart();
5098 startLoc = SM->getExpansionLoc(startLoc);
5099 endBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005100 ReplaceText(DeclLoc, endBuf-startBuf, ByrefType);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005101
Fariborz Jahanian4fe261c2012-04-24 19:38:45 +00005102 const char separator = lastDecl ? ';' : ',';
5103 const char *startInitializerBuf = SM->getCharacterData(startLoc);
5104 const char *separatorBuf = strchr(startInitializerBuf, separator);
5105 assert((*separatorBuf == separator) &&
5106 "RewriteByRefVar: can't find ';' or ','");
5107 SourceLocation separatorLoc =
5108 startLoc.getLocWithOffset(separatorBuf-startInitializerBuf);
5109
5110 InsertText(separatorLoc, lastDecl ? "}" : "};\n");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005111 }
5112 return;
5113}
5114
5115void RewriteModernObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
5116 // Add initializers for any closure decl refs.
5117 GetBlockDeclRefExprs(Exp->getBody());
5118 if (BlockDeclRefs.size()) {
5119 // Unique all "by copy" declarations.
5120 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00005121 if (!BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005122 if (!BlockByCopyDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
5123 BlockByCopyDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
5124 BlockByCopyDecls.push_back(BlockDeclRefs[i]->getDecl());
5125 }
5126 }
5127 // Unique all "by ref" declarations.
5128 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00005129 if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005130 if (!BlockByRefDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
5131 BlockByRefDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
5132 BlockByRefDecls.push_back(BlockDeclRefs[i]->getDecl());
5133 }
5134 }
5135 // Find any imported blocks...they will need special attention.
5136 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00005137 if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005138 BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
5139 BlockDeclRefs[i]->getType()->isBlockPointerType())
5140 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
5141 }
5142}
5143
5144FunctionDecl *RewriteModernObjC::SynthBlockInitFunctionDecl(StringRef name) {
5145 IdentifierInfo *ID = &Context->Idents.get(name);
5146 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
5147 return FunctionDecl::Create(*Context, TUDecl, SourceLocation(),
5148 SourceLocation(), ID, FType, 0, SC_Extern,
5149 SC_None, false, false);
5150}
5151
5152Stmt *RewriteModernObjC::SynthBlockInitExpr(BlockExpr *Exp,
John McCallf4b88a42012-03-10 09:33:50 +00005153 const SmallVector<DeclRefExpr *, 8> &InnerBlockDeclRefs) {
Fariborz Jahaniand13c2c22012-03-22 19:54:39 +00005154
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005155 const BlockDecl *block = Exp->getBlockDecl();
Fariborz Jahaniand13c2c22012-03-22 19:54:39 +00005156
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005157 Blocks.push_back(Exp);
5158
5159 CollectBlockDeclRefInfo(Exp);
5160
5161 // Add inner imported variables now used in current block.
5162 int countOfInnerDecls = 0;
5163 if (!InnerBlockDeclRefs.empty()) {
5164 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++) {
John McCallf4b88a42012-03-10 09:33:50 +00005165 DeclRefExpr *Exp = InnerBlockDeclRefs[i];
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005166 ValueDecl *VD = Exp->getDecl();
John McCallf4b88a42012-03-10 09:33:50 +00005167 if (!VD->hasAttr<BlocksAttr>() && !BlockByCopyDeclsPtrSet.count(VD)) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005168 // We need to save the copied-in variables in nested
5169 // blocks because it is needed at the end for some of the API generations.
5170 // See SynthesizeBlockLiterals routine.
5171 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5172 BlockDeclRefs.push_back(Exp);
5173 BlockByCopyDeclsPtrSet.insert(VD);
5174 BlockByCopyDecls.push_back(VD);
5175 }
John McCallf4b88a42012-03-10 09:33:50 +00005176 if (VD->hasAttr<BlocksAttr>() && !BlockByRefDeclsPtrSet.count(VD)) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005177 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5178 BlockDeclRefs.push_back(Exp);
5179 BlockByRefDeclsPtrSet.insert(VD);
5180 BlockByRefDecls.push_back(VD);
5181 }
5182 }
5183 // Find any imported blocks...they will need special attention.
5184 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00005185 if (InnerBlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005186 InnerBlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
5187 InnerBlockDeclRefs[i]->getType()->isBlockPointerType())
5188 ImportedBlockDecls.insert(InnerBlockDeclRefs[i]->getDecl());
5189 }
5190 InnerDeclRefsCount.push_back(countOfInnerDecls);
5191
5192 std::string FuncName;
5193
5194 if (CurFunctionDef)
5195 FuncName = CurFunctionDef->getNameAsString();
5196 else if (CurMethodDef)
5197 BuildUniqueMethodName(FuncName, CurMethodDef);
5198 else if (GlobalVarDecl)
5199 FuncName = std::string(GlobalVarDecl->getNameAsString());
5200
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00005201 bool GlobalBlockExpr =
5202 block->getDeclContext()->getRedeclContext()->isFileContext();
5203
5204 if (GlobalBlockExpr && !GlobalVarDecl) {
5205 Diags.Report(block->getLocation(), GlobalBlockRewriteFailedDiag);
5206 GlobalBlockExpr = false;
5207 }
5208
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005209 std::string BlockNumber = utostr(Blocks.size()-1);
5210
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005211 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
5212
5213 // Get a pointer to the function type so we can cast appropriately.
5214 QualType BFT = convertFunctionTypeOfBlocks(Exp->getFunctionType());
5215 QualType FType = Context->getPointerType(BFT);
5216
5217 FunctionDecl *FD;
5218 Expr *NewRep;
5219
5220 // Simulate a contructor call...
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00005221 std::string Tag;
5222
5223 if (GlobalBlockExpr)
5224 Tag = "__global_";
5225 else
5226 Tag = "__";
5227 Tag += FuncName + "_block_impl_" + BlockNumber;
5228
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005229 FD = SynthBlockInitFunctionDecl(Tag);
John McCallf4b88a42012-03-10 09:33:50 +00005230 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, false, FType, VK_RValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005231 SourceLocation());
5232
5233 SmallVector<Expr*, 4> InitExprs;
5234
5235 // Initialize the block function.
5236 FD = SynthBlockInitFunctionDecl(Func);
John McCallf4b88a42012-03-10 09:33:50 +00005237 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, false, FD->getType(),
5238 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005239 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
5240 CK_BitCast, Arg);
5241 InitExprs.push_back(castExpr);
5242
5243 // Initialize the block descriptor.
5244 std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
5245
5246 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl,
5247 SourceLocation(), SourceLocation(),
5248 &Context->Idents.get(DescData.c_str()),
5249 Context->VoidPtrTy, 0,
5250 SC_Static, SC_None);
5251 UnaryOperator *DescRefExpr =
John McCallf4b88a42012-03-10 09:33:50 +00005252 new (Context) UnaryOperator(new (Context) DeclRefExpr(NewVD, false,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005253 Context->VoidPtrTy,
5254 VK_LValue,
5255 SourceLocation()),
5256 UO_AddrOf,
5257 Context->getPointerType(Context->VoidPtrTy),
5258 VK_RValue, OK_Ordinary,
5259 SourceLocation());
5260 InitExprs.push_back(DescRefExpr);
5261
5262 // Add initializers for any closure decl refs.
5263 if (BlockDeclRefs.size()) {
5264 Expr *Exp;
5265 // Output all "by copy" declarations.
5266 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
5267 E = BlockByCopyDecls.end(); I != E; ++I) {
5268 if (isObjCType((*I)->getType())) {
5269 // FIXME: Conform to ABI ([[obj retain] autorelease]).
5270 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00005271 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(),
5272 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005273 if (HasLocalVariableExternalStorage(*I)) {
5274 QualType QT = (*I)->getType();
5275 QT = Context->getPointerType(QT);
5276 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
5277 OK_Ordinary, SourceLocation());
5278 }
5279 } else if (isTopLevelBlockPointerType((*I)->getType())) {
5280 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00005281 Arg = new (Context) DeclRefExpr(FD, false, FD->getType(),
5282 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005283 Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
5284 CK_BitCast, Arg);
5285 } else {
5286 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00005287 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(),
5288 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005289 if (HasLocalVariableExternalStorage(*I)) {
5290 QualType QT = (*I)->getType();
5291 QT = Context->getPointerType(QT);
5292 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
5293 OK_Ordinary, SourceLocation());
5294 }
5295
5296 }
5297 InitExprs.push_back(Exp);
5298 }
5299 // Output all "by ref" declarations.
5300 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
5301 E = BlockByRefDecls.end(); I != E; ++I) {
5302 ValueDecl *ND = (*I);
5303 std::string Name(ND->getNameAsString());
5304 std::string RecName;
5305 RewriteByRefString(RecName, Name, ND, true);
5306 IdentifierInfo *II = &Context->Idents.get(RecName.c_str()
5307 + sizeof("struct"));
5308 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
5309 SourceLocation(), SourceLocation(),
5310 II);
5311 assert(RD && "SynthBlockInitExpr(): Can't find RecordDecl");
5312 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
5313
5314 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00005315 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(), VK_LValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005316 SourceLocation());
5317 bool isNestedCapturedVar = false;
5318 if (block)
5319 for (BlockDecl::capture_const_iterator ci = block->capture_begin(),
5320 ce = block->capture_end(); ci != ce; ++ci) {
5321 const VarDecl *variable = ci->getVariable();
5322 if (variable == ND && ci->isNested()) {
5323 assert (ci->isByRef() &&
5324 "SynthBlockInitExpr - captured block variable is not byref");
5325 isNestedCapturedVar = true;
5326 break;
5327 }
5328 }
5329 // captured nested byref variable has its address passed. Do not take
5330 // its address again.
5331 if (!isNestedCapturedVar)
5332 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf,
5333 Context->getPointerType(Exp->getType()),
5334 VK_RValue, OK_Ordinary, SourceLocation());
5335 Exp = NoTypeInfoCStyleCastExpr(Context, castT, CK_BitCast, Exp);
5336 InitExprs.push_back(Exp);
5337 }
5338 }
5339 if (ImportedBlockDecls.size()) {
5340 // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
5341 int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
5342 unsigned IntSize =
5343 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
5344 Expr *FlagExp = IntegerLiteral::Create(*Context, llvm::APInt(IntSize, flag),
5345 Context->IntTy, SourceLocation());
5346 InitExprs.push_back(FlagExp);
5347 }
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00005348 NewRep = new (Context) CallExpr(*Context, DRE, InitExprs,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005349 FType, VK_LValue, SourceLocation());
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00005350
5351 if (GlobalBlockExpr) {
5352 assert (GlobalConstructionExp == 0 &&
5353 "SynthBlockInitExpr - GlobalConstructionExp must be null");
5354 GlobalConstructionExp = NewRep;
5355 NewRep = DRE;
5356 }
5357
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005358 NewRep = new (Context) UnaryOperator(NewRep, UO_AddrOf,
5359 Context->getPointerType(NewRep->getType()),
5360 VK_RValue, OK_Ordinary, SourceLocation());
5361 NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CK_BitCast,
5362 NewRep);
5363 BlockDeclRefs.clear();
5364 BlockByRefDecls.clear();
5365 BlockByRefDeclsPtrSet.clear();
5366 BlockByCopyDecls.clear();
5367 BlockByCopyDeclsPtrSet.clear();
5368 ImportedBlockDecls.clear();
5369 return NewRep;
5370}
5371
5372bool RewriteModernObjC::IsDeclStmtInForeachHeader(DeclStmt *DS) {
5373 if (const ObjCForCollectionStmt * CS =
5374 dyn_cast<ObjCForCollectionStmt>(Stmts.back()))
5375 return CS->getElement() == DS;
5376 return false;
5377}
5378
5379//===----------------------------------------------------------------------===//
5380// Function Body / Expression rewriting
5381//===----------------------------------------------------------------------===//
5382
5383Stmt *RewriteModernObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
5384 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
5385 isa<DoStmt>(S) || isa<ForStmt>(S))
5386 Stmts.push_back(S);
5387 else if (isa<ObjCForCollectionStmt>(S)) {
5388 Stmts.push_back(S);
5389 ObjCBcLabelNo.push_back(++BcLabelCount);
5390 }
5391
5392 // Pseudo-object operations and ivar references need special
5393 // treatment because we're going to recursively rewrite them.
5394 if (PseudoObjectExpr *PseudoOp = dyn_cast<PseudoObjectExpr>(S)) {
5395 if (isa<BinaryOperator>(PseudoOp->getSyntacticForm())) {
5396 return RewritePropertyOrImplicitSetter(PseudoOp);
5397 } else {
5398 return RewritePropertyOrImplicitGetter(PseudoOp);
5399 }
5400 } else if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
5401 return RewriteObjCIvarRefExpr(IvarRefExpr);
5402 }
5403
5404 SourceRange OrigStmtRange = S->getSourceRange();
5405
5406 // Perform a bottom up rewrite of all children.
5407 for (Stmt::child_range CI = S->children(); CI; ++CI)
5408 if (*CI) {
5409 Stmt *childStmt = (*CI);
5410 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(childStmt);
5411 if (newStmt) {
5412 *CI = newStmt;
5413 }
5414 }
5415
5416 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
John McCallf4b88a42012-03-10 09:33:50 +00005417 SmallVector<DeclRefExpr *, 8> InnerBlockDeclRefs;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005418 llvm::SmallPtrSet<const DeclContext *, 8> InnerContexts;
5419 InnerContexts.insert(BE->getBlockDecl());
5420 ImportedLocalExternalDecls.clear();
5421 GetInnerBlockDeclRefExprs(BE->getBody(),
5422 InnerBlockDeclRefs, InnerContexts);
5423 // Rewrite the block body in place.
5424 Stmt *SaveCurrentBody = CurrentBody;
5425 CurrentBody = BE->getBody();
5426 PropParentMap = 0;
5427 // block literal on rhs of a property-dot-sytax assignment
5428 // must be replaced by its synthesize ast so getRewrittenText
5429 // works as expected. In this case, what actually ends up on RHS
5430 // is the blockTranscribed which is the helper function for the
5431 // block literal; as in: self.c = ^() {[ace ARR];};
5432 bool saveDisableReplaceStmt = DisableReplaceStmt;
5433 DisableReplaceStmt = false;
5434 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
5435 DisableReplaceStmt = saveDisableReplaceStmt;
5436 CurrentBody = SaveCurrentBody;
5437 PropParentMap = 0;
5438 ImportedLocalExternalDecls.clear();
5439 // Now we snarf the rewritten text and stash it away for later use.
5440 std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
5441 RewrittenBlockExprs[BE] = Str;
5442
5443 Stmt *blockTranscribed = SynthBlockInitExpr(BE, InnerBlockDeclRefs);
5444
5445 //blockTranscribed->dump();
5446 ReplaceStmt(S, blockTranscribed);
5447 return blockTranscribed;
5448 }
5449 // Handle specific things.
5450 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
5451 return RewriteAtEncode(AtEncode);
5452
5453 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
5454 return RewriteAtSelector(AtSelector);
5455
5456 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
5457 return RewriteObjCStringLiteral(AtString);
Fariborz Jahanian55947042012-03-27 20:17:30 +00005458
5459 if (ObjCBoolLiteralExpr *BoolLitExpr = dyn_cast<ObjCBoolLiteralExpr>(S))
5460 return RewriteObjCBoolLiteralExpr(BoolLitExpr);
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00005461
Patrick Beardeb382ec2012-04-19 00:25:12 +00005462 if (ObjCBoxedExpr *BoxedExpr = dyn_cast<ObjCBoxedExpr>(S))
5463 return RewriteObjCBoxedExpr(BoxedExpr);
Fariborz Jahanian86cff602012-03-30 23:35:47 +00005464
5465 if (ObjCArrayLiteral *ArrayLitExpr = dyn_cast<ObjCArrayLiteral>(S))
5466 return RewriteObjCArrayLiteralExpr(ArrayLitExpr);
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00005467
5468 if (ObjCDictionaryLiteral *DictionaryLitExpr =
5469 dyn_cast<ObjCDictionaryLiteral>(S))
5470 return RewriteObjCDictionaryLiteralExpr(DictionaryLitExpr);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005471
5472 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
5473#if 0
5474 // Before we rewrite it, put the original message expression in a comment.
5475 SourceLocation startLoc = MessExpr->getLocStart();
5476 SourceLocation endLoc = MessExpr->getLocEnd();
5477
5478 const char *startBuf = SM->getCharacterData(startLoc);
5479 const char *endBuf = SM->getCharacterData(endLoc);
5480
5481 std::string messString;
5482 messString += "// ";
5483 messString.append(startBuf, endBuf-startBuf+1);
5484 messString += "\n";
5485
5486 // FIXME: Missing definition of
5487 // InsertText(clang::SourceLocation, char const*, unsigned int).
5488 // InsertText(startLoc, messString.c_str(), messString.size());
5489 // Tried this, but it didn't work either...
5490 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
5491#endif
5492 return RewriteMessageExpr(MessExpr);
5493 }
5494
Fariborz Jahanian042b91d2012-05-23 23:47:20 +00005495 if (ObjCAutoreleasePoolStmt *StmtAutoRelease =
5496 dyn_cast<ObjCAutoreleasePoolStmt>(S)) {
5497 return RewriteObjCAutoreleasePoolStmt(StmtAutoRelease);
5498 }
5499
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005500 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
5501 return RewriteObjCTryStmt(StmtTry);
5502
5503 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
5504 return RewriteObjCSynchronizedStmt(StmtTry);
5505
5506 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
5507 return RewriteObjCThrowStmt(StmtThrow);
5508
5509 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
5510 return RewriteObjCProtocolExpr(ProtocolExp);
5511
5512 if (ObjCForCollectionStmt *StmtForCollection =
5513 dyn_cast<ObjCForCollectionStmt>(S))
5514 return RewriteObjCForCollectionStmt(StmtForCollection,
5515 OrigStmtRange.getEnd());
5516 if (BreakStmt *StmtBreakStmt =
5517 dyn_cast<BreakStmt>(S))
5518 return RewriteBreakStmt(StmtBreakStmt);
5519 if (ContinueStmt *StmtContinueStmt =
5520 dyn_cast<ContinueStmt>(S))
5521 return RewriteContinueStmt(StmtContinueStmt);
5522
5523 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
5524 // and cast exprs.
5525 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
5526 // FIXME: What we're doing here is modifying the type-specifier that
5527 // precedes the first Decl. In the future the DeclGroup should have
5528 // a separate type-specifier that we can rewrite.
5529 // NOTE: We need to avoid rewriting the DeclStmt if it is within
5530 // the context of an ObjCForCollectionStmt. For example:
5531 // NSArray *someArray;
5532 // for (id <FooProtocol> index in someArray) ;
5533 // This is because RewriteObjCForCollectionStmt() does textual rewriting
5534 // and it depends on the original text locations/positions.
5535 if (Stmts.empty() || !IsDeclStmtInForeachHeader(DS))
5536 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
5537
5538 // Blocks rewrite rules.
5539 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
5540 DI != DE; ++DI) {
5541 Decl *SD = *DI;
5542 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
5543 if (isTopLevelBlockPointerType(ND->getType()))
5544 RewriteBlockPointerDecl(ND);
5545 else if (ND->getType()->isFunctionPointerType())
5546 CheckFunctionPointerDecl(ND->getType(), ND);
5547 if (VarDecl *VD = dyn_cast<VarDecl>(SD)) {
5548 if (VD->hasAttr<BlocksAttr>()) {
5549 static unsigned uniqueByrefDeclCount = 0;
5550 assert(!BlockByRefDeclNo.count(ND) &&
5551 "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl");
5552 BlockByRefDeclNo[ND] = uniqueByrefDeclCount++;
Fariborz Jahanian4fe261c2012-04-24 19:38:45 +00005553 RewriteByRefVar(VD, (DI == DS->decl_begin()), ((DI+1) == DE));
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005554 }
5555 else
5556 RewriteTypeOfDecl(VD);
5557 }
5558 }
5559 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(SD)) {
5560 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
5561 RewriteBlockPointerDecl(TD);
5562 else if (TD->getUnderlyingType()->isFunctionPointerType())
5563 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5564 }
5565 }
5566 }
5567
5568 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
5569 RewriteObjCQualifiedInterfaceTypes(CE);
5570
5571 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
5572 isa<DoStmt>(S) || isa<ForStmt>(S)) {
5573 assert(!Stmts.empty() && "Statement stack is empty");
5574 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
5575 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
5576 && "Statement stack mismatch");
5577 Stmts.pop_back();
5578 }
5579 // Handle blocks rewriting.
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005580 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
5581 ValueDecl *VD = DRE->getDecl();
5582 if (VD->hasAttr<BlocksAttr>())
5583 return RewriteBlockDeclRefExpr(DRE);
5584 if (HasLocalVariableExternalStorage(VD))
5585 return RewriteLocalVariableExternalStorage(DRE);
5586 }
5587
5588 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
5589 if (CE->getCallee()->getType()->isBlockPointerType()) {
5590 Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
5591 ReplaceStmt(S, BlockCall);
5592 return BlockCall;
5593 }
5594 }
5595 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
5596 RewriteCastExpr(CE);
5597 }
Fariborz Jahanianf1ee6872012-04-10 00:08:18 +00005598 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
5599 RewriteImplicitCastObjCExpr(ICE);
5600 }
Fariborz Jahanian43aa1c32012-04-16 22:14:01 +00005601#if 0
Fariborz Jahanian653b7cf2012-04-13 18:00:54 +00005602
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005603 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
5604 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(),
5605 ICE->getSubExpr(),
5606 SourceLocation());
5607 // Get the new text.
5608 std::string SStr;
5609 llvm::raw_string_ostream Buf(SStr);
Richard Smithd1420c62012-08-16 03:56:14 +00005610 Replacement->printPretty(Buf);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005611 const std::string &Str = Buf.str();
5612
5613 printf("CAST = %s\n", &Str[0]);
5614 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
5615 delete S;
5616 return Replacement;
5617 }
5618#endif
5619 // Return this stmt unmodified.
5620 return S;
5621}
5622
5623void RewriteModernObjC::RewriteRecordBody(RecordDecl *RD) {
5624 for (RecordDecl::field_iterator i = RD->field_begin(),
5625 e = RD->field_end(); i != e; ++i) {
David Blaikie581deb32012-06-06 20:45:41 +00005626 FieldDecl *FD = *i;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005627 if (isTopLevelBlockPointerType(FD->getType()))
5628 RewriteBlockPointerDecl(FD);
5629 if (FD->getType()->isObjCQualifiedIdType() ||
5630 FD->getType()->isObjCQualifiedInterfaceType())
5631 RewriteObjCQualifiedInterfaceTypes(FD);
5632 }
5633}
5634
5635/// HandleDeclInMainFile - This is called for each top-level decl defined in the
5636/// main file of the input.
5637void RewriteModernObjC::HandleDeclInMainFile(Decl *D) {
5638 switch (D->getKind()) {
5639 case Decl::Function: {
5640 FunctionDecl *FD = cast<FunctionDecl>(D);
5641 if (FD->isOverloadedOperator())
5642 return;
5643
5644 // Since function prototypes don't have ParmDecl's, we check the function
5645 // prototype. This enables us to rewrite function declarations and
5646 // definitions using the same code.
5647 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
5648
Argyrios Kyrtzidis9335df32012-02-12 04:48:45 +00005649 if (!FD->isThisDeclarationADefinition())
5650 break;
5651
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005652 // FIXME: If this should support Obj-C++, support CXXTryStmt
5653 if (CompoundStmt *Body = dyn_cast_or_null<CompoundStmt>(FD->getBody())) {
5654 CurFunctionDef = FD;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005655 CurrentBody = Body;
5656 Body =
5657 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5658 FD->setBody(Body);
5659 CurrentBody = 0;
5660 if (PropParentMap) {
5661 delete PropParentMap;
5662 PropParentMap = 0;
5663 }
5664 // This synthesizes and inserts the block "impl" struct, invoke function,
5665 // and any copy/dispose helper functions.
5666 InsertBlockLiteralsWithinFunction(FD);
5667 CurFunctionDef = 0;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005668 }
5669 break;
5670 }
5671 case Decl::ObjCMethod: {
5672 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(D);
5673 if (CompoundStmt *Body = MD->getCompoundBody()) {
5674 CurMethodDef = MD;
5675 CurrentBody = Body;
5676 Body =
5677 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5678 MD->setBody(Body);
5679 CurrentBody = 0;
5680 if (PropParentMap) {
5681 delete PropParentMap;
5682 PropParentMap = 0;
5683 }
5684 InsertBlockLiteralsWithinMethod(MD);
5685 CurMethodDef = 0;
5686 }
5687 break;
5688 }
5689 case Decl::ObjCImplementation: {
5690 ObjCImplementationDecl *CI = cast<ObjCImplementationDecl>(D);
5691 ClassImplementation.push_back(CI);
5692 break;
5693 }
5694 case Decl::ObjCCategoryImpl: {
5695 ObjCCategoryImplDecl *CI = cast<ObjCCategoryImplDecl>(D);
5696 CategoryImplementation.push_back(CI);
5697 break;
5698 }
5699 case Decl::Var: {
5700 VarDecl *VD = cast<VarDecl>(D);
5701 RewriteObjCQualifiedInterfaceTypes(VD);
5702 if (isTopLevelBlockPointerType(VD->getType()))
5703 RewriteBlockPointerDecl(VD);
5704 else if (VD->getType()->isFunctionPointerType()) {
5705 CheckFunctionPointerDecl(VD->getType(), VD);
5706 if (VD->getInit()) {
5707 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
5708 RewriteCastExpr(CE);
5709 }
5710 }
5711 } else if (VD->getType()->isRecordType()) {
5712 RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
5713 if (RD->isCompleteDefinition())
5714 RewriteRecordBody(RD);
5715 }
5716 if (VD->getInit()) {
5717 GlobalVarDecl = VD;
5718 CurrentBody = VD->getInit();
5719 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
5720 CurrentBody = 0;
5721 if (PropParentMap) {
5722 delete PropParentMap;
5723 PropParentMap = 0;
5724 }
5725 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(), VD->getName());
5726 GlobalVarDecl = 0;
5727
5728 // This is needed for blocks.
5729 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
5730 RewriteCastExpr(CE);
5731 }
5732 }
5733 break;
5734 }
5735 case Decl::TypeAlias:
5736 case Decl::Typedef: {
5737 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
5738 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
5739 RewriteBlockPointerDecl(TD);
5740 else if (TD->getUnderlyingType()->isFunctionPointerType())
5741 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5742 }
5743 break;
5744 }
5745 case Decl::CXXRecord:
5746 case Decl::Record: {
5747 RecordDecl *RD = cast<RecordDecl>(D);
5748 if (RD->isCompleteDefinition())
5749 RewriteRecordBody(RD);
5750 break;
5751 }
5752 default:
5753 break;
5754 }
5755 // Nothing yet.
5756}
5757
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00005758/// Write_ProtocolExprReferencedMetadata - This routine writer out the
5759/// protocol reference symbols in the for of:
5760/// struct _protocol_t *PROTOCOL_REF = &PROTOCOL_METADATA.
5761static void Write_ProtocolExprReferencedMetadata(ASTContext *Context,
5762 ObjCProtocolDecl *PDecl,
5763 std::string &Result) {
5764 // Also output .objc_protorefs$B section and its meta-data.
5765 if (Context->getLangOpts().MicrosoftExt)
Fariborz Jahanianbd78cfa2012-04-27 21:39:49 +00005766 Result += "static ";
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00005767 Result += "struct _protocol_t *";
5768 Result += "_OBJC_PROTOCOL_REFERENCE_$_";
5769 Result += PDecl->getNameAsString();
5770 Result += " = &";
5771 Result += "_OBJC_PROTOCOL_"; Result += PDecl->getNameAsString();
5772 Result += ";\n";
5773}
5774
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005775void RewriteModernObjC::HandleTranslationUnit(ASTContext &C) {
5776 if (Diags.hasErrorOccurred())
5777 return;
5778
5779 RewriteInclude();
5780
5781 // Here's a great place to add any extra declarations that may be needed.
5782 // Write out meta data for each @protocol(<expr>).
5783 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00005784 E = ProtocolExprDecls.end(); I != E; ++I) {
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00005785 RewriteObjCProtocolMetaData(*I, Preamble);
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00005786 Write_ProtocolExprReferencedMetadata(Context, (*I), Preamble);
5787 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005788
5789 InsertText(SM->getLocForStartOfFile(MainFileID), Preamble, false);
Fariborz Jahanian163d3ce2012-05-08 23:54:35 +00005790
5791 if (ClassImplementation.size() || CategoryImplementation.size())
5792 RewriteImplementations();
5793
Fariborz Jahanian57317782012-02-21 23:58:41 +00005794 for (unsigned i = 0, e = ObjCInterfacesSeen.size(); i < e; i++) {
5795 ObjCInterfaceDecl *CDecl = ObjCInterfacesSeen[i];
5796 // Write struct declaration for the class matching its ivar declarations.
5797 // Note that for modern abi, this is postponed until the end of TU
5798 // because class extensions and the implementation might declare their own
5799 // private ivars.
5800 RewriteInterfaceDecl(CDecl);
5801 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005802
5803 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
5804 // we are done.
5805 if (const RewriteBuffer *RewriteBuf =
5806 Rewrite.getRewriteBufferFor(MainFileID)) {
5807 //printf("Changed:\n");
5808 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
5809 } else {
5810 llvm::errs() << "No changes\n";
5811 }
5812
5813 if (ClassImplementation.size() || CategoryImplementation.size() ||
5814 ProtocolExprDecls.size()) {
5815 // Rewrite Objective-c meta data*
5816 std::string ResultStr;
5817 RewriteMetaDataIntoBuffer(ResultStr);
5818 // Emit metadata.
5819 *OutFile << ResultStr;
5820 }
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005821 // Emit ImageInfo;
5822 {
5823 std::string ResultStr;
5824 WriteImageInfo(ResultStr);
5825 *OutFile << ResultStr;
5826 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005827 OutFile->flush();
5828}
5829
5830void RewriteModernObjC::Initialize(ASTContext &context) {
5831 InitializeCommon(context);
5832
Fariborz Jahanian6991bc52012-03-10 17:45:38 +00005833 Preamble += "#ifndef __OBJC2__\n";
5834 Preamble += "#define __OBJC2__\n";
5835 Preamble += "#endif\n";
5836
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005837 // declaring objc_selector outside the parameter list removes a silly
5838 // scope related warning...
5839 if (IsHeader)
5840 Preamble = "#pragma once\n";
5841 Preamble += "struct objc_selector; struct objc_class;\n";
Fariborz Jahaniane2d87bc2012-04-12 23:52:52 +00005842 Preamble += "struct __rw_objc_super { \n\tstruct objc_object *object; ";
5843 Preamble += "\n\tstruct objc_object *superClass; ";
5844 // Add a constructor for creating temporary objects.
5845 Preamble += "\n\t__rw_objc_super(struct objc_object *o, struct objc_object *s) ";
5846 Preamble += ": object(o), superClass(s) {} ";
5847 Preamble += "\n};\n";
5848
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005849 if (LangOpts.MicrosoftExt) {
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00005850 // Define all sections using syntax that makes sense.
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005851 // These are currently generated.
5852 Preamble += "\n#pragma section(\".objc_classlist$B\", long, read, write)\n";
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00005853 Preamble += "#pragma section(\".objc_catlist$B\", long, read, write)\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005854 Preamble += "#pragma section(\".objc_imageinfo$B\", long, read, write)\n";
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00005855 Preamble += "#pragma section(\".objc_nlclslist$B\", long, read, write)\n";
5856 Preamble += "#pragma section(\".objc_nlcatlist$B\", long, read, write)\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005857 // These are generated but not necessary for functionality.
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005858 Preamble += "#pragma section(\".cat_cls_meth$B\", long, read, write)\n";
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00005859 Preamble += "#pragma section(\".inst_meth$B\", long, read, write)\n";
5860 Preamble += "#pragma section(\".cls_meth$B\", long, read, write)\n";
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00005861 Preamble += "#pragma section(\".objc_ivar$B\", long, read, write)\n";
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00005862
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00005863 // These need be generated for performance. Currently they are not,
5864 // using API calls instead.
5865 Preamble += "#pragma section(\".objc_selrefs$B\", long, read, write)\n";
5866 Preamble += "#pragma section(\".objc_classrefs$B\", long, read, write)\n";
5867 Preamble += "#pragma section(\".objc_superrefs$B\", long, read, write)\n";
5868
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005869 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005870 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
5871 Preamble += "typedef struct objc_object Protocol;\n";
5872 Preamble += "#define _REWRITER_typedef_Protocol\n";
5873 Preamble += "#endif\n";
5874 if (LangOpts.MicrosoftExt) {
5875 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
5876 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
Fariborz Jahanian5cf6b6c2012-03-21 23:41:04 +00005877 }
5878 else
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005879 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
Fariborz Jahanian5cf6b6c2012-03-21 23:41:04 +00005880
5881 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend(void);\n";
5882 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSendSuper(void);\n";
5883 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend_stret(void);\n";
5884 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSendSuper_stret(void);\n";
5885 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend_fpret(void);\n";
5886
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00005887 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *objc_getClass";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005888 Preamble += "(const char *);\n";
5889 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *class_getSuperclass";
5890 Preamble += "(struct objc_class *);\n";
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00005891 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *objc_getMetaClass";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005892 Preamble += "(const char *);\n";
Fariborz Jahanian55261af2012-03-19 18:11:32 +00005893 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw( struct objc_object *);\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005894 // @synchronized hooks.
Aaron Ballman2d234d732012-09-06 16:44:16 +00005895 Preamble += "__OBJC_RW_DLLIMPORT int objc_sync_enter( struct objc_object *);\n";
5896 Preamble += "__OBJC_RW_DLLIMPORT int objc_sync_exit( struct objc_object *);\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005897 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
5898 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
5899 Preamble += "struct __objcFastEnumerationState {\n\t";
5900 Preamble += "unsigned long state;\n\t";
5901 Preamble += "void **itemsPtr;\n\t";
5902 Preamble += "unsigned long *mutationsPtr;\n\t";
5903 Preamble += "unsigned long extra[5];\n};\n";
5904 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
5905 Preamble += "#define __FASTENUMERATIONSTATE\n";
5906 Preamble += "#endif\n";
5907 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
5908 Preamble += "struct __NSConstantStringImpl {\n";
5909 Preamble += " int *isa;\n";
5910 Preamble += " int flags;\n";
5911 Preamble += " char *str;\n";
5912 Preamble += " long length;\n";
5913 Preamble += "};\n";
5914 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
5915 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
5916 Preamble += "#else\n";
5917 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
5918 Preamble += "#endif\n";
5919 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
5920 Preamble += "#endif\n";
5921 // Blocks preamble.
5922 Preamble += "#ifndef BLOCK_IMPL\n";
5923 Preamble += "#define BLOCK_IMPL\n";
5924 Preamble += "struct __block_impl {\n";
5925 Preamble += " void *isa;\n";
5926 Preamble += " int Flags;\n";
5927 Preamble += " int Reserved;\n";
5928 Preamble += " void *FuncPtr;\n";
5929 Preamble += "};\n";
5930 Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
5931 Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n";
5932 Preamble += "extern \"C\" __declspec(dllexport) "
5933 "void _Block_object_assign(void *, const void *, const int);\n";
5934 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
5935 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
5936 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
5937 Preamble += "#else\n";
5938 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n";
5939 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n";
5940 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
5941 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
5942 Preamble += "#endif\n";
5943 Preamble += "#endif\n";
5944 if (LangOpts.MicrosoftExt) {
5945 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
5946 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
5947 Preamble += "#ifndef KEEP_ATTRIBUTES\n"; // We use this for clang tests.
5948 Preamble += "#define __attribute__(X)\n";
5949 Preamble += "#endif\n";
Fariborz Jahanian5ce28272012-04-12 16:33:31 +00005950 Preamble += "#ifndef __weak\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005951 Preamble += "#define __weak\n";
Fariborz Jahanian5ce28272012-04-12 16:33:31 +00005952 Preamble += "#endif\n";
5953 Preamble += "#ifndef __block\n";
5954 Preamble += "#define __block\n";
5955 Preamble += "#endif\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005956 }
5957 else {
5958 Preamble += "#define __block\n";
5959 Preamble += "#define __weak\n";
5960 }
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +00005961
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00005962 // Declarations required for modern objective-c array and dictionary literals.
5963 Preamble += "\n#include <stdarg.h>\n";
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00005964 Preamble += "struct __NSContainer_literal {\n";
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00005965 Preamble += " void * *arr;\n";
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00005966 Preamble += " __NSContainer_literal (unsigned int count, ...) {\n";
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00005967 Preamble += "\tva_list marker;\n";
5968 Preamble += "\tva_start(marker, count);\n";
5969 Preamble += "\tarr = new void *[count];\n";
5970 Preamble += "\tfor (unsigned i = 0; i < count; i++)\n";
5971 Preamble += "\t arr[i] = va_arg(marker, void *);\n";
5972 Preamble += "\tva_end( marker );\n";
5973 Preamble += " };\n";
Fariborz Jahanian13a9c022012-05-02 23:53:46 +00005974 Preamble += " ~__NSContainer_literal() {\n";
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00005975 Preamble += "\tdelete[] arr;\n";
5976 Preamble += " }\n";
5977 Preamble += "};\n";
5978
Fariborz Jahanian042b91d2012-05-23 23:47:20 +00005979 // Declaration required for implementation of @autoreleasepool statement.
5980 Preamble += "extern \"C\" __declspec(dllimport) void * objc_autoreleasePoolPush(void);\n";
5981 Preamble += "extern \"C\" __declspec(dllimport) void objc_autoreleasePoolPop(void *);\n\n";
5982 Preamble += "struct __AtAutoreleasePool {\n";
5983 Preamble += " __AtAutoreleasePool() {atautoreleasepoolobj = objc_autoreleasePoolPush();}\n";
5984 Preamble += " ~__AtAutoreleasePool() {objc_autoreleasePoolPop(atautoreleasepoolobj);}\n";
5985 Preamble += " void * atautoreleasepoolobj;\n";
5986 Preamble += "};\n";
5987
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005988 // NOTE! Windows uses LLP64 for 64bit mode. So, cast pointer to long long
5989 // as this avoids warning in any 64bit/32bit compilation model.
5990 Preamble += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long long) &((TYPE *)0)->MEMBER)\n";
5991}
5992
5993/// RewriteIvarOffsetComputation - This rutine synthesizes computation of
5994/// ivar offset.
5995void RewriteModernObjC::RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
5996 std::string &Result) {
5997 if (ivar->isBitField()) {
5998 // FIXME: The hack below doesn't work for bitfields. For now, we simply
5999 // place all bitfields at offset 0.
6000 Result += "0";
6001 } else {
6002 Result += "__OFFSETOFIVAR__(struct ";
6003 Result += ivar->getContainingInterface()->getNameAsString();
6004 if (LangOpts.MicrosoftExt)
6005 Result += "_IMPL";
6006 Result += ", ";
6007 Result += ivar->getNameAsString();
6008 Result += ")";
6009 }
6010}
6011
6012/// WriteModernMetadataDeclarations - Writes out metadata declarations for modern ABI.
6013/// struct _prop_t {
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006014/// const char *name;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006015/// char *attributes;
6016/// }
6017
6018/// struct _prop_list_t {
6019/// uint32_t entsize; // sizeof(struct _prop_t)
6020/// uint32_t count_of_properties;
6021/// struct _prop_t prop_list[count_of_properties];
6022/// }
6023
6024/// struct _protocol_t;
6025
6026/// struct _protocol_list_t {
6027/// long protocol_count; // Note, this is 32/64 bit
6028/// struct _protocol_t * protocol_list[protocol_count];
6029/// }
6030
6031/// struct _objc_method {
6032/// SEL _cmd;
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006033/// const char *method_type;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006034/// char *_imp;
6035/// }
6036
6037/// struct _method_list_t {
6038/// uint32_t entsize; // sizeof(struct _objc_method)
6039/// uint32_t method_count;
6040/// struct _objc_method method_list[method_count];
6041/// }
6042
6043/// struct _protocol_t {
6044/// id isa; // NULL
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006045/// const char *protocol_name;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006046/// const struct _protocol_list_t * protocol_list; // super protocols
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006047/// const struct method_list_t *instance_methods;
6048/// const struct method_list_t *class_methods;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006049/// const struct method_list_t *optionalInstanceMethods;
6050/// const struct method_list_t *optionalClassMethods;
6051/// const struct _prop_list_t * properties;
6052/// const uint32_t size; // sizeof(struct _protocol_t)
6053/// const uint32_t flags; // = 0
6054/// const char ** extendedMethodTypes;
6055/// }
6056
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006057/// struct _ivar_t {
6058/// unsigned long int *offset; // pointer to ivar offset location
Fariborz Jahanianae932952012-02-10 20:47:10 +00006059/// const char *name;
6060/// const char *type;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006061/// uint32_t alignment;
6062/// uint32_t size;
6063/// }
6064
6065/// struct _ivar_list_t {
6066/// uint32 entsize; // sizeof(struct _ivar_t)
6067/// uint32 count;
Fariborz Jahanianae932952012-02-10 20:47:10 +00006068/// struct _ivar_t list[count];
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006069/// }
6070
6071/// struct _class_ro_t {
Fariborz Jahanian249cd102012-03-24 16:53:16 +00006072/// uint32_t flags;
6073/// uint32_t instanceStart;
6074/// uint32_t instanceSize;
6075/// uint32_t reserved; // only when building for 64bit targets
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006076/// const uint8_t *ivarLayout;
6077/// const char *name;
6078/// const struct _method_list_t *baseMethods;
6079/// const struct _protocol_list_t *baseProtocols;
6080/// const struct _ivar_list_t *ivars;
6081/// const uint8_t *weakIvarLayout;
6082/// const struct _prop_list_t *properties;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006083/// }
6084
6085/// struct _class_t {
6086/// struct _class_t *isa;
Fariborz Jahanianfd4ce2c2012-03-20 17:34:50 +00006087/// struct _class_t *superclass;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006088/// void *cache;
6089/// IMP *vtable;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006090/// struct _class_ro_t *ro;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006091/// }
6092
6093/// struct _category_t {
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006094/// const char *name;
Fariborz Jahanian4b2fe6e2012-03-20 21:41:28 +00006095/// struct _class_t *cls;
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006096/// const struct _method_list_t *instance_methods;
6097/// const struct _method_list_t *class_methods;
6098/// const struct _protocol_list_t *protocols;
6099/// const struct _prop_list_t *properties;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006100/// }
6101
6102/// MessageRefTy - LLVM for:
6103/// struct _message_ref_t {
6104/// IMP messenger;
6105/// SEL name;
6106/// };
6107
6108/// SuperMessageRefTy - LLVM for:
6109/// struct _super_message_ref_t {
6110/// SUPER_IMP messenger;
6111/// SEL name;
6112/// };
6113
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00006114static void WriteModernMetadataDeclarations(ASTContext *Context, std::string &Result) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006115 static bool meta_data_declared = false;
6116 if (meta_data_declared)
6117 return;
6118
6119 Result += "\nstruct _prop_t {\n";
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006120 Result += "\tconst char *name;\n";
6121 Result += "\tconst char *attributes;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006122 Result += "};\n";
6123
6124 Result += "\nstruct _protocol_t;\n";
6125
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006126 Result += "\nstruct _objc_method {\n";
6127 Result += "\tstruct objc_selector * _cmd;\n";
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006128 Result += "\tconst char *method_type;\n";
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006129 Result += "\tvoid *_imp;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006130 Result += "};\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006131
6132 Result += "\nstruct _protocol_t {\n";
6133 Result += "\tvoid * isa; // NULL\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006134 Result += "\tconst char *protocol_name;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006135 Result += "\tconst struct _protocol_list_t * protocol_list; // super protocols\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006136 Result += "\tconst struct method_list_t *instance_methods;\n";
6137 Result += "\tconst struct method_list_t *class_methods;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006138 Result += "\tconst struct method_list_t *optionalInstanceMethods;\n";
6139 Result += "\tconst struct method_list_t *optionalClassMethods;\n";
6140 Result += "\tconst struct _prop_list_t * properties;\n";
6141 Result += "\tconst unsigned int size; // sizeof(struct _protocol_t)\n";
6142 Result += "\tconst unsigned int flags; // = 0\n";
6143 Result += "\tconst char ** extendedMethodTypes;\n";
6144 Result += "};\n";
6145
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006146 Result += "\nstruct _ivar_t {\n";
6147 Result += "\tunsigned long int *offset; // pointer to ivar offset location\n";
Fariborz Jahanianae932952012-02-10 20:47:10 +00006148 Result += "\tconst char *name;\n";
6149 Result += "\tconst char *type;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006150 Result += "\tunsigned int alignment;\n";
6151 Result += "\tunsigned int size;\n";
6152 Result += "};\n";
6153
6154 Result += "\nstruct _class_ro_t {\n";
Fariborz Jahanian249cd102012-03-24 16:53:16 +00006155 Result += "\tunsigned int flags;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006156 Result += "\tunsigned int instanceStart;\n";
Fariborz Jahanian249cd102012-03-24 16:53:16 +00006157 Result += "\tunsigned int instanceSize;\n";
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00006158 const llvm::Triple &Triple(Context->getTargetInfo().getTriple());
6159 if (Triple.getArch() == llvm::Triple::x86_64)
Fariborz Jahanian249cd102012-03-24 16:53:16 +00006160 Result += "\tunsigned int reserved;\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006161 Result += "\tconst unsigned char *ivarLayout;\n";
6162 Result += "\tconst char *name;\n";
6163 Result += "\tconst struct _method_list_t *baseMethods;\n";
6164 Result += "\tconst struct _objc_protocol_list *baseProtocols;\n";
6165 Result += "\tconst struct _ivar_list_t *ivars;\n";
6166 Result += "\tconst unsigned char *weakIvarLayout;\n";
6167 Result += "\tconst struct _prop_list_t *properties;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006168 Result += "};\n";
6169
6170 Result += "\nstruct _class_t {\n";
6171 Result += "\tstruct _class_t *isa;\n";
Fariborz Jahanianfd4ce2c2012-03-20 17:34:50 +00006172 Result += "\tstruct _class_t *superclass;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006173 Result += "\tvoid *cache;\n";
6174 Result += "\tvoid *vtable;\n";
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006175 Result += "\tstruct _class_ro_t *ro;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006176 Result += "};\n";
6177
6178 Result += "\nstruct _category_t {\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006179 Result += "\tconst char *name;\n";
Fariborz Jahanian4b2fe6e2012-03-20 21:41:28 +00006180 Result += "\tstruct _class_t *cls;\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006181 Result += "\tconst struct _method_list_t *instance_methods;\n";
6182 Result += "\tconst struct _method_list_t *class_methods;\n";
6183 Result += "\tconst struct _protocol_list_t *protocols;\n";
6184 Result += "\tconst struct _prop_list_t *properties;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006185 Result += "};\n";
6186
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006187 Result += "extern \"C\" __declspec(dllimport) struct objc_cache _objc_empty_cache;\n";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006188 Result += "#pragma warning(disable:4273)\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006189 meta_data_declared = true;
6190}
6191
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006192static void Write_protocol_list_t_TypeDecl(std::string &Result,
6193 long super_protocol_count) {
6194 Result += "struct /*_protocol_list_t*/"; Result += " {\n";
6195 Result += "\tlong protocol_count; // Note, this is 32/64 bit\n";
6196 Result += "\tstruct _protocol_t *super_protocols[";
6197 Result += utostr(super_protocol_count); Result += "];\n";
6198 Result += "}";
6199}
6200
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006201static void Write_method_list_t_TypeDecl(std::string &Result,
6202 unsigned int method_count) {
6203 Result += "struct /*_method_list_t*/"; Result += " {\n";
6204 Result += "\tunsigned int entsize; // sizeof(struct _objc_method)\n";
6205 Result += "\tunsigned int method_count;\n";
6206 Result += "\tstruct _objc_method method_list[";
6207 Result += utostr(method_count); Result += "];\n";
6208 Result += "}";
6209}
6210
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006211static void Write__prop_list_t_TypeDecl(std::string &Result,
6212 unsigned int property_count) {
6213 Result += "struct /*_prop_list_t*/"; Result += " {\n";
6214 Result += "\tunsigned int entsize; // sizeof(struct _prop_t)\n";
6215 Result += "\tunsigned int count_of_properties;\n";
6216 Result += "\tstruct _prop_t prop_list[";
6217 Result += utostr(property_count); Result += "];\n";
6218 Result += "}";
6219}
6220
Fariborz Jahanianae932952012-02-10 20:47:10 +00006221static void Write__ivar_list_t_TypeDecl(std::string &Result,
6222 unsigned int ivar_count) {
6223 Result += "struct /*_ivar_list_t*/"; Result += " {\n";
6224 Result += "\tunsigned int entsize; // sizeof(struct _prop_t)\n";
6225 Result += "\tunsigned int count;\n";
6226 Result += "\tstruct _ivar_t ivar_list[";
6227 Result += utostr(ivar_count); Result += "];\n";
6228 Result += "}";
6229}
6230
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006231static void Write_protocol_list_initializer(ASTContext *Context, std::string &Result,
6232 ArrayRef<ObjCProtocolDecl *> SuperProtocols,
6233 StringRef VarName,
6234 StringRef ProtocolName) {
6235 if (SuperProtocols.size() > 0) {
6236 Result += "\nstatic ";
6237 Write_protocol_list_t_TypeDecl(Result, SuperProtocols.size());
6238 Result += " "; Result += VarName;
6239 Result += ProtocolName;
6240 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6241 Result += "\t"; Result += utostr(SuperProtocols.size()); Result += ",\n";
6242 for (unsigned i = 0, e = SuperProtocols.size(); i < e; i++) {
6243 ObjCProtocolDecl *SuperPD = SuperProtocols[i];
6244 Result += "\t&"; Result += "_OBJC_PROTOCOL_";
6245 Result += SuperPD->getNameAsString();
6246 if (i == e-1)
6247 Result += "\n};\n";
6248 else
6249 Result += ",\n";
6250 }
6251 }
6252}
6253
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006254static void Write_method_list_t_initializer(RewriteModernObjC &RewriteObj,
6255 ASTContext *Context, std::string &Result,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006256 ArrayRef<ObjCMethodDecl *> Methods,
6257 StringRef VarName,
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006258 StringRef TopLevelDeclName,
6259 bool MethodImpl) {
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006260 if (Methods.size() > 0) {
6261 Result += "\nstatic ";
6262 Write_method_list_t_TypeDecl(Result, Methods.size());
6263 Result += " "; Result += VarName;
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006264 Result += TopLevelDeclName;
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006265 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6266 Result += "\t"; Result += "sizeof(_objc_method)"; Result += ",\n";
6267 Result += "\t"; Result += utostr(Methods.size()); Result += ",\n";
6268 for (unsigned i = 0, e = Methods.size(); i < e; i++) {
6269 ObjCMethodDecl *MD = Methods[i];
6270 if (i == 0)
6271 Result += "\t{{(struct objc_selector *)\"";
6272 else
6273 Result += "\t{(struct objc_selector *)\"";
6274 Result += (MD)->getSelector().getAsString(); Result += "\"";
6275 Result += ", ";
6276 std::string MethodTypeString;
6277 Context->getObjCEncodingForMethodDecl(MD, MethodTypeString);
6278 Result += "\""; Result += MethodTypeString; Result += "\"";
6279 Result += ", ";
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006280 if (!MethodImpl)
6281 Result += "0";
6282 else {
6283 Result += "(void *)";
6284 Result += RewriteObj.MethodInternalNames[MD];
6285 }
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006286 if (i == e-1)
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006287 Result += "}}\n";
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006288 else
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006289 Result += "},\n";
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006290 }
6291 Result += "};\n";
6292 }
6293}
6294
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006295static void Write_prop_list_t_initializer(RewriteModernObjC &RewriteObj,
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006296 ASTContext *Context, std::string &Result,
6297 ArrayRef<ObjCPropertyDecl *> Properties,
6298 const Decl *Container,
6299 StringRef VarName,
6300 StringRef ProtocolName) {
6301 if (Properties.size() > 0) {
6302 Result += "\nstatic ";
6303 Write__prop_list_t_TypeDecl(Result, Properties.size());
6304 Result += " "; Result += VarName;
6305 Result += ProtocolName;
6306 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6307 Result += "\t"; Result += "sizeof(_prop_t)"; Result += ",\n";
6308 Result += "\t"; Result += utostr(Properties.size()); Result += ",\n";
6309 for (unsigned i = 0, e = Properties.size(); i < e; i++) {
6310 ObjCPropertyDecl *PropDecl = Properties[i];
6311 if (i == 0)
6312 Result += "\t{{\"";
6313 else
6314 Result += "\t{\"";
6315 Result += PropDecl->getName(); Result += "\",";
6316 std::string PropertyTypeString, QuotePropertyTypeString;
6317 Context->getObjCEncodingForPropertyDecl(PropDecl, Container, PropertyTypeString);
6318 RewriteObj.QuoteDoublequotes(PropertyTypeString, QuotePropertyTypeString);
6319 Result += "\""; Result += QuotePropertyTypeString; Result += "\"";
6320 if (i == e-1)
6321 Result += "}}\n";
6322 else
6323 Result += "},\n";
6324 }
6325 Result += "};\n";
6326 }
6327}
6328
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006329// Metadata flags
6330enum MetaDataDlags {
6331 CLS = 0x0,
6332 CLS_META = 0x1,
6333 CLS_ROOT = 0x2,
6334 OBJC2_CLS_HIDDEN = 0x10,
6335 CLS_EXCEPTION = 0x20,
6336
6337 /// (Obsolete) ARC-specific: this class has a .release_ivars method
6338 CLS_HAS_IVAR_RELEASER = 0x40,
6339 /// class was compiled with -fobjc-arr
6340 CLS_COMPILED_BY_ARC = 0x80 // (1<<7)
6341};
6342
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006343static void Write__class_ro_t_initializer(ASTContext *Context, std::string &Result,
6344 unsigned int flags,
6345 const std::string &InstanceStart,
6346 const std::string &InstanceSize,
6347 ArrayRef<ObjCMethodDecl *>baseMethods,
6348 ArrayRef<ObjCProtocolDecl *>baseProtocols,
6349 ArrayRef<ObjCIvarDecl *>ivars,
6350 ArrayRef<ObjCPropertyDecl *>Properties,
6351 StringRef VarName,
6352 StringRef ClassName) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006353 Result += "\nstatic struct _class_ro_t ";
6354 Result += VarName; Result += ClassName;
6355 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6356 Result += "\t";
6357 Result += llvm::utostr(flags); Result += ", ";
6358 Result += InstanceStart; Result += ", ";
6359 Result += InstanceSize; Result += ", \n";
6360 Result += "\t";
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00006361 const llvm::Triple &Triple(Context->getTargetInfo().getTriple());
6362 if (Triple.getArch() == llvm::Triple::x86_64)
6363 // uint32_t const reserved; // only when building for 64bit targets
6364 Result += "(unsigned int)0, \n\t";
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006365 // const uint8_t * const ivarLayout;
6366 Result += "0, \n\t";
6367 Result += "\""; Result += ClassName; Result += "\",\n\t";
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006368 bool metaclass = ((flags & CLS_META) != 0);
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006369 if (baseMethods.size() > 0) {
6370 Result += "(const struct _method_list_t *)&";
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006371 if (metaclass)
6372 Result += "_OBJC_$_CLASS_METHODS_";
6373 else
6374 Result += "_OBJC_$_INSTANCE_METHODS_";
6375 Result += ClassName;
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006376 Result += ",\n\t";
6377 }
6378 else
6379 Result += "0, \n\t";
6380
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006381 if (!metaclass && baseProtocols.size() > 0) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006382 Result += "(const struct _objc_protocol_list *)&";
6383 Result += "_OBJC_CLASS_PROTOCOLS_$_"; Result += ClassName;
6384 Result += ",\n\t";
6385 }
6386 else
6387 Result += "0, \n\t";
6388
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006389 if (!metaclass && ivars.size() > 0) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006390 Result += "(const struct _ivar_list_t *)&";
6391 Result += "_OBJC_$_INSTANCE_VARIABLES_"; Result += ClassName;
6392 Result += ",\n\t";
6393 }
6394 else
6395 Result += "0, \n\t";
6396
6397 // weakIvarLayout
6398 Result += "0, \n\t";
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006399 if (!metaclass && Properties.size() > 0) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006400 Result += "(const struct _prop_list_t *)&";
Fariborz Jahanianeeabf382012-02-16 21:57:59 +00006401 Result += "_OBJC_$_PROP_LIST_"; Result += ClassName;
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006402 Result += ",\n";
6403 }
6404 else
6405 Result += "0, \n";
6406
6407 Result += "};\n";
6408}
6409
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006410static void Write_class_t(ASTContext *Context, std::string &Result,
6411 StringRef VarName,
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006412 const ObjCInterfaceDecl *CDecl, bool metaclass) {
6413 bool rootClass = (!CDecl->getSuperClass());
6414 const ObjCInterfaceDecl *RootClass = CDecl;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006415
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006416 if (!rootClass) {
6417 // Find the Root class
6418 RootClass = CDecl->getSuperClass();
6419 while (RootClass->getSuperClass()) {
6420 RootClass = RootClass->getSuperClass();
6421 }
6422 }
6423
6424 if (metaclass && rootClass) {
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006425 // Need to handle a case of use of forward declaration.
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00006426 Result += "\n";
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006427 Result += "extern \"C\" ";
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00006428 if (CDecl->getImplementation())
6429 Result += "__declspec(dllexport) ";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006430 else
6431 Result += "__declspec(dllimport) ";
6432
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006433 Result += "struct _class_t OBJC_CLASS_$_";
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006434 Result += CDecl->getNameAsString();
6435 Result += ";\n";
6436 }
6437 // Also, for possibility of 'super' metadata class not having been defined yet.
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006438 if (!rootClass) {
Fariborz Jahanian868e9852012-03-29 19:04:10 +00006439 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00006440 Result += "\n";
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006441 Result += "extern \"C\" ";
Fariborz Jahanian868e9852012-03-29 19:04:10 +00006442 if (SuperClass->getImplementation())
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00006443 Result += "__declspec(dllexport) ";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006444 else
6445 Result += "__declspec(dllimport) ";
6446
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006447 Result += "struct _class_t ";
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00006448 Result += VarName;
Fariborz Jahanian868e9852012-03-29 19:04:10 +00006449 Result += SuperClass->getNameAsString();
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006450 Result += ";\n";
Fariborz Jahanian452eac12012-03-20 21:09:58 +00006451
Fariborz Jahanian868e9852012-03-29 19:04:10 +00006452 if (metaclass && RootClass != SuperClass) {
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006453 Result += "extern \"C\" ";
Fariborz Jahanian452eac12012-03-20 21:09:58 +00006454 if (RootClass->getImplementation())
6455 Result += "__declspec(dllexport) ";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006456 else
6457 Result += "__declspec(dllimport) ";
6458
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006459 Result += "struct _class_t ";
Fariborz Jahanian452eac12012-03-20 21:09:58 +00006460 Result += VarName;
6461 Result += RootClass->getNameAsString();
6462 Result += ";\n";
6463 }
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006464 }
6465
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006466 Result += "\nextern \"C\" __declspec(dllexport) struct _class_t ";
6467 Result += VarName; Result += CDecl->getNameAsString();
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006468 Result += " __attribute__ ((used, section (\"__DATA,__objc_data\"))) = {\n";
6469 Result += "\t";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006470 if (metaclass) {
6471 if (!rootClass) {
6472 Result += "0, // &"; Result += VarName;
6473 Result += RootClass->getNameAsString();
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006474 Result += ",\n\t";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006475 Result += "0, // &"; Result += VarName;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006476 Result += CDecl->getSuperClass()->getNameAsString();
6477 Result += ",\n\t";
6478 }
6479 else {
Fariborz Jahanian452eac12012-03-20 21:09:58 +00006480 Result += "0, // &"; Result += VarName;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006481 Result += CDecl->getNameAsString();
6482 Result += ",\n\t";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006483 Result += "0, // &OBJC_CLASS_$_"; Result += CDecl->getNameAsString();
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006484 Result += ",\n\t";
6485 }
6486 }
6487 else {
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006488 Result += "0, // &OBJC_METACLASS_$_";
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006489 Result += CDecl->getNameAsString();
6490 Result += ",\n\t";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006491 if (!rootClass) {
6492 Result += "0, // &"; Result += VarName;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006493 Result += CDecl->getSuperClass()->getNameAsString();
6494 Result += ",\n\t";
6495 }
6496 else
6497 Result += "0,\n\t";
6498 }
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006499 Result += "0, // (void *)&_objc_empty_cache,\n\t";
6500 Result += "0, // unused, was (void *)&_objc_empty_vtable,\n\t";
6501 if (metaclass)
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006502 Result += "&_OBJC_METACLASS_RO_$_";
6503 else
6504 Result += "&_OBJC_CLASS_RO_$_";
6505 Result += CDecl->getNameAsString();
6506 Result += ",\n};\n";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006507
6508 // Add static function to initialize some of the meta-data fields.
6509 // avoid doing it twice.
6510 if (metaclass)
6511 return;
6512
6513 const ObjCInterfaceDecl *SuperClass =
6514 rootClass ? CDecl : CDecl->getSuperClass();
6515
6516 Result += "static void OBJC_CLASS_SETUP_$_";
6517 Result += CDecl->getNameAsString();
6518 Result += "(void ) {\n";
6519 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
6520 Result += ".isa = "; Result += "&OBJC_METACLASS_$_";
Fariborz Jahanian452eac12012-03-20 21:09:58 +00006521 Result += RootClass->getNameAsString(); Result += ";\n";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006522
6523 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
Fariborz Jahanian452eac12012-03-20 21:09:58 +00006524 Result += ".superclass = ";
6525 if (rootClass)
6526 Result += "&OBJC_CLASS_$_";
6527 else
6528 Result += "&OBJC_METACLASS_$_";
6529
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006530 Result += SuperClass->getNameAsString(); Result += ";\n";
6531
6532 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
6533 Result += ".cache = "; Result += "&_objc_empty_cache"; Result += ";\n";
6534
6535 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6536 Result += ".isa = "; Result += "&OBJC_METACLASS_$_";
6537 Result += CDecl->getNameAsString(); Result += ";\n";
6538
6539 if (!rootClass) {
6540 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6541 Result += ".superclass = "; Result += "&OBJC_CLASS_$_";
6542 Result += SuperClass->getNameAsString(); Result += ";\n";
6543 }
6544
6545 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6546 Result += ".cache = "; Result += "&_objc_empty_cache"; Result += ";\n";
6547 Result += "}\n";
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006548}
6549
Fariborz Jahanian61186122012-02-17 18:40:41 +00006550static void Write_category_t(RewriteModernObjC &RewriteObj, ASTContext *Context,
6551 std::string &Result,
Fariborz Jahaniane0335782012-03-27 18:41:05 +00006552 ObjCCategoryDecl *CatDecl,
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006553 ObjCInterfaceDecl *ClassDecl,
Fariborz Jahanian61186122012-02-17 18:40:41 +00006554 ArrayRef<ObjCMethodDecl *> InstanceMethods,
6555 ArrayRef<ObjCMethodDecl *> ClassMethods,
6556 ArrayRef<ObjCProtocolDecl *> RefedProtocols,
6557 ArrayRef<ObjCPropertyDecl *> ClassProperties) {
Fariborz Jahaniane0335782012-03-27 18:41:05 +00006558 StringRef CatName = CatDecl->getName();
NAKAMURA Takumi20f89392012-03-21 03:21:46 +00006559 StringRef ClassName = ClassDecl->getName();
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00006560 // must declare an extern class object in case this class is not implemented
6561 // in this TU.
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006562 Result += "\n";
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006563 Result += "extern \"C\" ";
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006564 if (ClassDecl->getImplementation())
6565 Result += "__declspec(dllexport) ";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006566 else
6567 Result += "__declspec(dllimport) ";
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006568
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006569 Result += "struct _class_t ";
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00006570 Result += "OBJC_CLASS_$_"; Result += ClassName;
6571 Result += ";\n";
6572
Fariborz Jahanian61186122012-02-17 18:40:41 +00006573 Result += "\nstatic struct _category_t ";
6574 Result += "_OBJC_$_CATEGORY_";
6575 Result += ClassName; Result += "_$_"; Result += CatName;
6576 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = \n";
6577 Result += "{\n";
6578 Result += "\t\""; Result += ClassName; Result += "\",\n";
Fariborz Jahanian4b2fe6e2012-03-20 21:41:28 +00006579 Result += "\t0, // &"; Result += "OBJC_CLASS_$_"; Result += ClassName;
Fariborz Jahanian61186122012-02-17 18:40:41 +00006580 Result += ",\n";
6581 if (InstanceMethods.size() > 0) {
6582 Result += "\t(const struct _method_list_t *)&";
6583 Result += "_OBJC_$_CATEGORY_INSTANCE_METHODS_";
6584 Result += ClassName; Result += "_$_"; Result += CatName;
6585 Result += ",\n";
6586 }
6587 else
6588 Result += "\t0,\n";
6589
6590 if (ClassMethods.size() > 0) {
6591 Result += "\t(const struct _method_list_t *)&";
6592 Result += "_OBJC_$_CATEGORY_CLASS_METHODS_";
6593 Result += ClassName; Result += "_$_"; Result += CatName;
6594 Result += ",\n";
6595 }
6596 else
6597 Result += "\t0,\n";
6598
6599 if (RefedProtocols.size() > 0) {
6600 Result += "\t(const struct _protocol_list_t *)&";
6601 Result += "_OBJC_CATEGORY_PROTOCOLS_$_";
6602 Result += ClassName; Result += "_$_"; Result += CatName;
6603 Result += ",\n";
6604 }
6605 else
6606 Result += "\t0,\n";
6607
6608 if (ClassProperties.size() > 0) {
6609 Result += "\t(const struct _prop_list_t *)&"; Result += "_OBJC_$_PROP_LIST_";
6610 Result += ClassName; Result += "_$_"; Result += CatName;
6611 Result += ",\n";
6612 }
6613 else
6614 Result += "\t0,\n";
6615
6616 Result += "};\n";
Fariborz Jahanian4b2fe6e2012-03-20 21:41:28 +00006617
6618 // Add static function to initialize the class pointer in the category structure.
6619 Result += "static void OBJC_CATEGORY_SETUP_$_";
6620 Result += ClassDecl->getNameAsString();
6621 Result += "_$_";
6622 Result += CatName;
6623 Result += "(void ) {\n";
6624 Result += "\t_OBJC_$_CATEGORY_";
6625 Result += ClassDecl->getNameAsString();
6626 Result += "_$_";
6627 Result += CatName;
6628 Result += ".cls = "; Result += "&OBJC_CLASS_$_"; Result += ClassName;
6629 Result += ";\n}\n";
Fariborz Jahanian61186122012-02-17 18:40:41 +00006630}
6631
Fariborz Jahaniane0adbd82012-02-08 22:23:26 +00006632static void Write__extendedMethodTypes_initializer(RewriteModernObjC &RewriteObj,
6633 ASTContext *Context, std::string &Result,
6634 ArrayRef<ObjCMethodDecl *> Methods,
6635 StringRef VarName,
6636 StringRef ProtocolName) {
6637 if (Methods.size() == 0)
6638 return;
6639
6640 Result += "\nstatic const char *";
6641 Result += VarName; Result += ProtocolName;
6642 Result += " [] __attribute__ ((used, section (\"__DATA,__objc_const\"))) = \n";
6643 Result += "{\n";
6644 for (unsigned i = 0, e = Methods.size(); i < e; i++) {
6645 ObjCMethodDecl *MD = Methods[i];
6646 std::string MethodTypeString, QuoteMethodTypeString;
6647 Context->getObjCEncodingForMethodDecl(MD, MethodTypeString, true);
6648 RewriteObj.QuoteDoublequotes(MethodTypeString, QuoteMethodTypeString);
6649 Result += "\t\""; Result += QuoteMethodTypeString; Result += "\"";
6650 if (i == e-1)
6651 Result += "\n};\n";
6652 else {
6653 Result += ",\n";
6654 }
6655 }
6656}
6657
Fariborz Jahanianacee1c92012-04-11 21:12:36 +00006658static void Write_IvarOffsetVar(RewriteModernObjC &RewriteObj,
6659 ASTContext *Context,
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00006660 std::string &Result,
Fariborz Jahaniandb649232012-02-13 20:59:02 +00006661 ArrayRef<ObjCIvarDecl *> Ivars,
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006662 ObjCInterfaceDecl *CDecl) {
Fariborz Jahaniandb649232012-02-13 20:59:02 +00006663 // FIXME. visibilty of offset symbols may have to be set; for Darwin
6664 // this is what happens:
6665 /**
6666 if (Ivar->getAccessControl() == ObjCIvarDecl::Private ||
6667 Ivar->getAccessControl() == ObjCIvarDecl::Package ||
6668 Class->getVisibility() == HiddenVisibility)
6669 Visibility shoud be: HiddenVisibility;
6670 else
6671 Visibility shoud be: DefaultVisibility;
6672 */
6673
Fariborz Jahanian07e52882012-02-13 21:34:45 +00006674 Result += "\n";
6675 for (unsigned i =0, e = Ivars.size(); i < e; i++) {
6676 ObjCIvarDecl *IvarDecl = Ivars[i];
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00006677 if (Context->getLangOpts().MicrosoftExt)
6678 Result += "__declspec(allocate(\".objc_ivar$B\")) ";
6679
6680 if (!Context->getLangOpts().MicrosoftExt ||
6681 IvarDecl->getAccessControl() == ObjCIvarDecl::Private ||
Fariborz Jahanian117591f2012-03-10 01:34:42 +00006682 IvarDecl->getAccessControl() == ObjCIvarDecl::Package)
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006683 Result += "extern \"C\" unsigned long int ";
Fariborz Jahaniand1c84d32012-03-10 00:53:02 +00006684 else
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006685 Result += "extern \"C\" __declspec(dllexport) unsigned long int ";
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006686 WriteInternalIvarName(CDecl, IvarDecl, Result);
Fariborz Jahanian07e52882012-02-13 21:34:45 +00006687 Result += " __attribute__ ((used, section (\"__DATA,__objc_ivar\")))";
6688 Result += " = ";
Fariborz Jahanianacee1c92012-04-11 21:12:36 +00006689 RewriteObj.RewriteIvarOffsetComputation(IvarDecl, Result);
6690 Result += ";\n";
Fariborz Jahaniandb649232012-02-13 20:59:02 +00006691 }
6692}
6693
Fariborz Jahanianae932952012-02-10 20:47:10 +00006694static void Write__ivar_list_t_initializer(RewriteModernObjC &RewriteObj,
6695 ASTContext *Context, std::string &Result,
6696 ArrayRef<ObjCIvarDecl *> Ivars,
6697 StringRef VarName,
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006698 ObjCInterfaceDecl *CDecl) {
Fariborz Jahanianae932952012-02-10 20:47:10 +00006699 if (Ivars.size() > 0) {
Fariborz Jahanianacee1c92012-04-11 21:12:36 +00006700 Write_IvarOffsetVar(RewriteObj, Context, Result, Ivars, CDecl);
Fariborz Jahanian07e52882012-02-13 21:34:45 +00006701
Fariborz Jahanianae932952012-02-10 20:47:10 +00006702 Result += "\nstatic ";
6703 Write__ivar_list_t_TypeDecl(Result, Ivars.size());
6704 Result += " "; Result += VarName;
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006705 Result += CDecl->getNameAsString();
Fariborz Jahanianae932952012-02-10 20:47:10 +00006706 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6707 Result += "\t"; Result += "sizeof(_ivar_t)"; Result += ",\n";
6708 Result += "\t"; Result += utostr(Ivars.size()); Result += ",\n";
6709 for (unsigned i =0, e = Ivars.size(); i < e; i++) {
6710 ObjCIvarDecl *IvarDecl = Ivars[i];
6711 if (i == 0)
6712 Result += "\t{{";
6713 else
6714 Result += "\t {";
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006715 Result += "(unsigned long int *)&";
6716 WriteInternalIvarName(CDecl, IvarDecl, Result);
Fariborz Jahaniandb649232012-02-13 20:59:02 +00006717 Result += ", ";
Fariborz Jahanianae932952012-02-10 20:47:10 +00006718
6719 Result += "\""; Result += IvarDecl->getName(); Result += "\", ";
6720 std::string IvarTypeString, QuoteIvarTypeString;
6721 Context->getObjCEncodingForType(IvarDecl->getType(), IvarTypeString,
6722 IvarDecl);
6723 RewriteObj.QuoteDoublequotes(IvarTypeString, QuoteIvarTypeString);
6724 Result += "\""; Result += QuoteIvarTypeString; Result += "\", ";
6725
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00006726 // FIXME. this alignment represents the host alignment and need be changed to
6727 // represent the target alignment.
6728 unsigned Align = Context->getTypeAlign(IvarDecl->getType())/8;
6729 Align = llvm::Log2_32(Align);
Fariborz Jahanianae932952012-02-10 20:47:10 +00006730 Result += llvm::utostr(Align); Result += ", ";
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00006731 CharUnits Size = Context->getTypeSizeInChars(IvarDecl->getType());
6732 Result += llvm::utostr(Size.getQuantity());
Fariborz Jahanianae932952012-02-10 20:47:10 +00006733 if (i == e-1)
6734 Result += "}}\n";
6735 else
6736 Result += "},\n";
6737 }
6738 Result += "};\n";
6739 }
6740}
6741
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006742/// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006743void RewriteModernObjC::RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl,
6744 std::string &Result) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006745
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006746 // Do not synthesize the protocol more than once.
6747 if (ObjCSynthesizedProtocols.count(PDecl->getCanonicalDecl()))
6748 return;
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00006749 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006750
6751 if (ObjCProtocolDecl *Def = PDecl->getDefinition())
6752 PDecl = Def;
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006753 // Must write out all protocol definitions in current qualifier list,
6754 // and in their nested qualifiers before writing out current definition.
6755 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
6756 E = PDecl->protocol_end(); I != E; ++I)
6757 RewriteObjCProtocolMetaData(*I, Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006758
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006759 // Construct method lists.
6760 std::vector<ObjCMethodDecl *> InstanceMethods, ClassMethods;
6761 std::vector<ObjCMethodDecl *> OptInstanceMethods, OptClassMethods;
6762 for (ObjCProtocolDecl::instmeth_iterator
6763 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
6764 I != E; ++I) {
6765 ObjCMethodDecl *MD = *I;
6766 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
6767 OptInstanceMethods.push_back(MD);
6768 } else {
6769 InstanceMethods.push_back(MD);
6770 }
6771 }
6772
6773 for (ObjCProtocolDecl::classmeth_iterator
6774 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
6775 I != E; ++I) {
6776 ObjCMethodDecl *MD = *I;
6777 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
6778 OptClassMethods.push_back(MD);
6779 } else {
6780 ClassMethods.push_back(MD);
6781 }
6782 }
Fariborz Jahaniane0adbd82012-02-08 22:23:26 +00006783 std::vector<ObjCMethodDecl *> AllMethods;
6784 for (unsigned i = 0, e = InstanceMethods.size(); i < e; i++)
6785 AllMethods.push_back(InstanceMethods[i]);
6786 for (unsigned i = 0, e = ClassMethods.size(); i < e; i++)
6787 AllMethods.push_back(ClassMethods[i]);
6788 for (unsigned i = 0, e = OptInstanceMethods.size(); i < e; i++)
6789 AllMethods.push_back(OptInstanceMethods[i]);
6790 for (unsigned i = 0, e = OptClassMethods.size(); i < e; i++)
6791 AllMethods.push_back(OptClassMethods[i]);
6792
6793 Write__extendedMethodTypes_initializer(*this, Context, Result,
6794 AllMethods,
6795 "_OBJC_PROTOCOL_METHOD_TYPES_",
6796 PDecl->getNameAsString());
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006797 // Protocol's super protocol list
6798 std::vector<ObjCProtocolDecl *> SuperProtocols;
6799 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
6800 E = PDecl->protocol_end(); I != E; ++I)
6801 SuperProtocols.push_back(*I);
6802
6803 Write_protocol_list_initializer(Context, Result, SuperProtocols,
6804 "_OBJC_PROTOCOL_REFS_",
6805 PDecl->getNameAsString());
6806
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006807 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006808 "_OBJC_PROTOCOL_INSTANCE_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006809 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006810
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006811 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006812 "_OBJC_PROTOCOL_CLASS_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006813 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006814
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006815 Write_method_list_t_initializer(*this, Context, Result, OptInstanceMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006816 "_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006817 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006818
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006819 Write_method_list_t_initializer(*this, Context, Result, OptClassMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006820 "_OBJC_PROTOCOL_OPT_CLASS_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006821 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006822
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006823 // Protocol's property metadata.
6824 std::vector<ObjCPropertyDecl *> ProtocolProperties;
6825 for (ObjCContainerDecl::prop_iterator I = PDecl->prop_begin(),
6826 E = PDecl->prop_end(); I != E; ++I)
David Blaikie581deb32012-06-06 20:45:41 +00006827 ProtocolProperties.push_back(*I);
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006828
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006829 Write_prop_list_t_initializer(*this, Context, Result, ProtocolProperties,
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006830 /* Container */0,
6831 "_OBJC_PROTOCOL_PROPERTIES_",
6832 PDecl->getNameAsString());
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006833
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006834 // Writer out root metadata for current protocol: struct _protocol_t
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00006835 Result += "\n";
6836 if (LangOpts.MicrosoftExt)
Fariborz Jahanian8590d862012-04-14 17:13:08 +00006837 Result += "static ";
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00006838 Result += "struct _protocol_t _OBJC_PROTOCOL_";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006839 Result += PDecl->getNameAsString();
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006840 Result += " __attribute__ ((used, section (\"__DATA,__datacoal_nt,coalesced\"))) = {\n";
6841 Result += "\t0,\n"; // id is; is null
6842 Result += "\t\""; Result += PDecl->getNameAsString(); Result += "\",\n";
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006843 if (SuperProtocols.size() > 0) {
6844 Result += "\t(const struct _protocol_list_t *)&"; Result += "_OBJC_PROTOCOL_REFS_";
6845 Result += PDecl->getNameAsString(); Result += ",\n";
6846 }
6847 else
6848 Result += "\t0,\n";
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006849 if (InstanceMethods.size() > 0) {
6850 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
6851 Result += PDecl->getNameAsString(); Result += ",\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006852 }
6853 else
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006854 Result += "\t0,\n";
6855
6856 if (ClassMethods.size() > 0) {
6857 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_CLASS_METHODS_";
6858 Result += PDecl->getNameAsString(); Result += ",\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006859 }
6860 else
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006861 Result += "\t0,\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006862
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006863 if (OptInstanceMethods.size() > 0) {
6864 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_";
6865 Result += PDecl->getNameAsString(); Result += ",\n";
6866 }
6867 else
6868 Result += "\t0,\n";
6869
6870 if (OptClassMethods.size() > 0) {
6871 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_CLASS_METHODS_";
6872 Result += PDecl->getNameAsString(); Result += ",\n";
6873 }
6874 else
6875 Result += "\t0,\n";
6876
6877 if (ProtocolProperties.size() > 0) {
6878 Result += "\t(const struct _prop_list_t *)&_OBJC_PROTOCOL_PROPERTIES_";
6879 Result += PDecl->getNameAsString(); Result += ",\n";
6880 }
6881 else
6882 Result += "\t0,\n";
6883
6884 Result += "\t"; Result += "sizeof(_protocol_t)"; Result += ",\n";
6885 Result += "\t0,\n";
6886
Fariborz Jahaniane0adbd82012-02-08 22:23:26 +00006887 if (AllMethods.size() > 0) {
6888 Result += "\t(const char **)&"; Result += "_OBJC_PROTOCOL_METHOD_TYPES_";
6889 Result += PDecl->getNameAsString();
6890 Result += "\n};\n";
6891 }
6892 else
6893 Result += "\t0\n};\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00006894
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00006895 if (LangOpts.MicrosoftExt)
Fariborz Jahanian8590d862012-04-14 17:13:08 +00006896 Result += "static ";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00006897 Result += "struct _protocol_t *";
6898 Result += "_OBJC_LABEL_PROTOCOL_$_"; Result += PDecl->getNameAsString();
6899 Result += " = &_OBJC_PROTOCOL_"; Result += PDecl->getNameAsString();
6900 Result += ";\n";
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006901
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006902 // Mark this protocol as having been generated.
6903 if (!ObjCSynthesizedProtocols.insert(PDecl->getCanonicalDecl()))
6904 llvm_unreachable("protocol already synthesized");
6905
6906}
6907
6908void RewriteModernObjC::RewriteObjCProtocolListMetaData(
6909 const ObjCList<ObjCProtocolDecl> &Protocols,
6910 StringRef prefix, StringRef ClassName,
6911 std::string &Result) {
6912 if (Protocols.empty()) return;
6913
6914 for (unsigned i = 0; i != Protocols.size(); i++)
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006915 RewriteObjCProtocolMetaData(Protocols[i], Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006916
6917 // Output the top lovel protocol meta-data for the class.
6918 /* struct _objc_protocol_list {
6919 struct _objc_protocol_list *next;
6920 int protocol_count;
6921 struct _objc_protocol *class_protocols[];
6922 }
6923 */
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00006924 Result += "\n";
6925 if (LangOpts.MicrosoftExt)
6926 Result += "__declspec(allocate(\".cat_cls_meth$B\")) ";
6927 Result += "static struct {\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006928 Result += "\tstruct _objc_protocol_list *next;\n";
6929 Result += "\tint protocol_count;\n";
6930 Result += "\tstruct _objc_protocol *class_protocols[";
6931 Result += utostr(Protocols.size());
6932 Result += "];\n} _OBJC_";
6933 Result += prefix;
6934 Result += "_PROTOCOLS_";
6935 Result += ClassName;
6936 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
6937 "{\n\t0, ";
6938 Result += utostr(Protocols.size());
6939 Result += "\n";
6940
6941 Result += "\t,{&_OBJC_PROTOCOL_";
6942 Result += Protocols[0]->getNameAsString();
6943 Result += " \n";
6944
6945 for (unsigned i = 1; i != Protocols.size(); i++) {
6946 Result += "\t ,&_OBJC_PROTOCOL_";
6947 Result += Protocols[i]->getNameAsString();
6948 Result += "\n";
6949 }
6950 Result += "\t }\n};\n";
6951}
6952
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006953/// hasObjCExceptionAttribute - Return true if this class or any super
6954/// class has the __objc_exception__ attribute.
6955/// FIXME. Move this to ASTContext.cpp as it is also used for IRGen.
6956static bool hasObjCExceptionAttribute(ASTContext &Context,
6957 const ObjCInterfaceDecl *OID) {
6958 if (OID->hasAttr<ObjCExceptionAttr>())
6959 return true;
6960 if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
6961 return hasObjCExceptionAttribute(Context, Super);
6962 return false;
6963}
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006964
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006965void RewriteModernObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
6966 std::string &Result) {
6967 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
6968
6969 // Explicitly declared @interface's are already synthesized.
Fariborz Jahanianae932952012-02-10 20:47:10 +00006970 if (CDecl->isImplicitInterfaceDecl())
6971 assert(false &&
6972 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00006973
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00006974 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanianae932952012-02-10 20:47:10 +00006975 SmallVector<ObjCIvarDecl *, 8> IVars;
6976
6977 for (ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
6978 IVD; IVD = IVD->getNextIvar()) {
6979 // Ignore unnamed bit-fields.
6980 if (!IVD->getDeclName())
6981 continue;
6982 IVars.push_back(IVD);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006983 }
6984
Fariborz Jahanianae932952012-02-10 20:47:10 +00006985 Write__ivar_list_t_initializer(*this, Context, Result, IVars,
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006986 "_OBJC_$_INSTANCE_VARIABLES_",
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006987 CDecl);
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006988
6989 // Build _objc_method_list for class's instance methods if needed
6990 SmallVector<ObjCMethodDecl *, 32>
6991 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
6992
6993 // If any of our property implementations have associated getters or
6994 // setters, produce metadata for them as well.
6995 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
6996 PropEnd = IDecl->propimpl_end();
6997 Prop != PropEnd; ++Prop) {
David Blaikie262bc182012-04-30 02:36:29 +00006998 if (Prop->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006999 continue;
David Blaikie262bc182012-04-30 02:36:29 +00007000 if (!Prop->getPropertyIvarDecl())
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00007001 continue;
David Blaikie262bc182012-04-30 02:36:29 +00007002 ObjCPropertyDecl *PD = Prop->getPropertyDecl();
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00007003 if (!PD)
7004 continue;
7005 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
Fariborz Jahanian301e2e42012-05-03 22:52:13 +00007006 if (mustSynthesizeSetterGetterMethod(IDecl, PD, true /*getter*/))
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00007007 InstanceMethods.push_back(Getter);
7008 if (PD->isReadOnly())
7009 continue;
7010 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
Fariborz Jahanian301e2e42012-05-03 22:52:13 +00007011 if (mustSynthesizeSetterGetterMethod(IDecl, PD, false /*setter*/))
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00007012 InstanceMethods.push_back(Setter);
7013 }
7014
7015 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
7016 "_OBJC_$_INSTANCE_METHODS_",
7017 IDecl->getNameAsString(), true);
7018
7019 SmallVector<ObjCMethodDecl *, 32>
7020 ClassMethods(IDecl->classmeth_begin(), IDecl->classmeth_end());
7021
7022 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
7023 "_OBJC_$_CLASS_METHODS_",
7024 IDecl->getNameAsString(), true);
Fariborz Jahanian0a525342012-02-14 19:31:35 +00007025
7026 // Protocols referenced in class declaration?
7027 // Protocol's super protocol list
7028 std::vector<ObjCProtocolDecl *> RefedProtocols;
7029 const ObjCList<ObjCProtocolDecl> &Protocols = CDecl->getReferencedProtocols();
7030 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
7031 E = Protocols.end();
7032 I != E; ++I) {
7033 RefedProtocols.push_back(*I);
7034 // Must write out all protocol definitions in current qualifier list,
7035 // and in their nested qualifiers before writing out current definition.
7036 RewriteObjCProtocolMetaData(*I, Result);
7037 }
7038
7039 Write_protocol_list_initializer(Context, Result,
7040 RefedProtocols,
7041 "_OBJC_CLASS_PROTOCOLS_$_",
7042 IDecl->getNameAsString());
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00007043
7044 // Protocol's property metadata.
7045 std::vector<ObjCPropertyDecl *> ClassProperties;
7046 for (ObjCContainerDecl::prop_iterator I = CDecl->prop_begin(),
7047 E = CDecl->prop_end(); I != E; ++I)
David Blaikie581deb32012-06-06 20:45:41 +00007048 ClassProperties.push_back(*I);
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00007049
7050 Write_prop_list_t_initializer(*this, Context, Result, ClassProperties,
Fariborz Jahanian2df089d2012-03-22 17:39:35 +00007051 /* Container */IDecl,
Fariborz Jahanianeeabf382012-02-16 21:57:59 +00007052 "_OBJC_$_PROP_LIST_",
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00007053 CDecl->getNameAsString());
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00007054
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00007055
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00007056 // Data for initializing _class_ro_t metaclass meta-data
7057 uint32_t flags = CLS_META;
7058 std::string InstanceSize;
7059 std::string InstanceStart;
7060
7061
7062 bool classIsHidden = CDecl->getVisibility() == HiddenVisibility;
7063 if (classIsHidden)
7064 flags |= OBJC2_CLS_HIDDEN;
7065
7066 if (!CDecl->getSuperClass())
7067 // class is root
7068 flags |= CLS_ROOT;
7069 InstanceSize = "sizeof(struct _class_t)";
7070 InstanceStart = InstanceSize;
7071 Write__class_ro_t_initializer(Context, Result, flags,
7072 InstanceStart, InstanceSize,
7073 ClassMethods,
7074 0,
7075 0,
7076 0,
7077 "_OBJC_METACLASS_RO_$_",
7078 CDecl->getNameAsString());
7079
7080
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00007081 // Data for initializing _class_ro_t meta-data
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00007082 flags = CLS;
7083 if (classIsHidden)
7084 flags |= OBJC2_CLS_HIDDEN;
7085
7086 if (hasObjCExceptionAttribute(*Context, CDecl))
7087 flags |= CLS_EXCEPTION;
7088
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00007089 if (!CDecl->getSuperClass())
7090 // class is root
7091 flags |= CLS_ROOT;
7092
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00007093 InstanceSize.clear();
7094 InstanceStart.clear();
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00007095 if (!ObjCSynthesizedStructs.count(CDecl)) {
7096 InstanceSize = "0";
7097 InstanceStart = "0";
7098 }
7099 else {
7100 InstanceSize = "sizeof(struct ";
7101 InstanceSize += CDecl->getNameAsString();
7102 InstanceSize += "_IMPL)";
7103
7104 ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
7105 if (IVD) {
Fariborz Jahanianacee1c92012-04-11 21:12:36 +00007106 RewriteIvarOffsetComputation(IVD, InstanceStart);
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00007107 }
7108 else
7109 InstanceStart = InstanceSize;
7110 }
7111 Write__class_ro_t_initializer(Context, Result, flags,
7112 InstanceStart, InstanceSize,
7113 InstanceMethods,
7114 RefedProtocols,
7115 IVars,
7116 ClassProperties,
7117 "_OBJC_CLASS_RO_$_",
7118 CDecl->getNameAsString());
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00007119
7120 Write_class_t(Context, Result,
7121 "OBJC_METACLASS_$_",
7122 CDecl, /*metaclass*/true);
7123
7124 Write_class_t(Context, Result,
7125 "OBJC_CLASS_$_",
7126 CDecl, /*metaclass*/false);
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00007127
7128 if (ImplementationIsNonLazy(IDecl))
7129 DefinedNonLazyClasses.push_back(CDecl);
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00007130
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007131}
7132
Fariborz Jahaniane0335782012-03-27 18:41:05 +00007133void RewriteModernObjC::RewriteClassSetupInitHook(std::string &Result) {
7134 int ClsDefCount = ClassImplementation.size();
7135 if (!ClsDefCount)
7136 return;
7137 Result += "#pragma section(\".objc_inithooks$B\", long, read, write)\n";
7138 Result += "__declspec(allocate(\".objc_inithooks$B\")) ";
7139 Result += "static void *OBJC_CLASS_SETUP[] = {\n";
7140 for (int i = 0; i < ClsDefCount; i++) {
7141 ObjCImplementationDecl *IDecl = ClassImplementation[i];
7142 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
7143 Result += "\t(void *)&OBJC_CLASS_SETUP_$_";
7144 Result += CDecl->getName(); Result += ",\n";
7145 }
7146 Result += "};\n";
7147}
7148
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007149void RewriteModernObjC::RewriteMetaDataIntoBuffer(std::string &Result) {
7150 int ClsDefCount = ClassImplementation.size();
7151 int CatDefCount = CategoryImplementation.size();
7152
7153 // For each implemented class, write out all its meta data.
7154 for (int i = 0; i < ClsDefCount; i++)
7155 RewriteObjCClassMetaData(ClassImplementation[i], Result);
7156
Fariborz Jahaniane0335782012-03-27 18:41:05 +00007157 RewriteClassSetupInitHook(Result);
7158
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007159 // For each implemented category, write out all its meta data.
7160 for (int i = 0; i < CatDefCount; i++)
7161 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
7162
Fariborz Jahaniane0335782012-03-27 18:41:05 +00007163 RewriteCategorySetupInitHook(Result);
7164
Fariborz Jahaniandf795672012-02-17 00:06:14 +00007165 if (ClsDefCount > 0) {
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00007166 if (LangOpts.MicrosoftExt)
7167 Result += "__declspec(allocate(\".objc_classlist$B\")) ";
Fariborz Jahaniandf795672012-02-17 00:06:14 +00007168 Result += "static struct _class_t *L_OBJC_LABEL_CLASS_$ [";
7169 Result += llvm::utostr(ClsDefCount); Result += "]";
7170 Result +=
7171 " __attribute__((used, section (\"__DATA, __objc_classlist,"
7172 "regular,no_dead_strip\")))= {\n";
7173 for (int i = 0; i < ClsDefCount; i++) {
7174 Result += "\t&OBJC_CLASS_$_";
7175 Result += ClassImplementation[i]->getNameAsString();
7176 Result += ",\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007177 }
Fariborz Jahaniandf795672012-02-17 00:06:14 +00007178 Result += "};\n";
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00007179
7180 if (!DefinedNonLazyClasses.empty()) {
7181 if (LangOpts.MicrosoftExt)
7182 Result += "__declspec(allocate(\".objc_nlclslist$B\")) \n";
7183 Result += "static struct _class_t *_OBJC_LABEL_NONLAZY_CLASS_$[] = {\n\t";
7184 for (unsigned i = 0, e = DefinedNonLazyClasses.size(); i < e; i++) {
7185 Result += "\t&OBJC_CLASS_$_"; Result += DefinedNonLazyClasses[i]->getNameAsString();
7186 Result += ",\n";
7187 }
7188 Result += "};\n";
7189 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007190 }
Fariborz Jahanian61186122012-02-17 18:40:41 +00007191
7192 if (CatDefCount > 0) {
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00007193 if (LangOpts.MicrosoftExt)
7194 Result += "__declspec(allocate(\".objc_catlist$B\")) ";
Fariborz Jahanian61186122012-02-17 18:40:41 +00007195 Result += "static struct _category_t *L_OBJC_LABEL_CATEGORY_$ [";
7196 Result += llvm::utostr(CatDefCount); Result += "]";
7197 Result +=
7198 " __attribute__((used, section (\"__DATA, __objc_catlist,"
7199 "regular,no_dead_strip\")))= {\n";
7200 for (int i = 0; i < CatDefCount; i++) {
7201 Result += "\t&_OBJC_$_CATEGORY_";
7202 Result +=
7203 CategoryImplementation[i]->getClassInterface()->getNameAsString();
7204 Result += "_$_";
7205 Result += CategoryImplementation[i]->getNameAsString();
7206 Result += ",\n";
7207 }
7208 Result += "};\n";
7209 }
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00007210
7211 if (!DefinedNonLazyCategories.empty()) {
7212 if (LangOpts.MicrosoftExt)
7213 Result += "__declspec(allocate(\".objc_nlcatlist$B\")) \n";
7214 Result += "static struct _category_t *_OBJC_LABEL_NONLAZY_CATEGORY_$[] = {\n\t";
7215 for (unsigned i = 0, e = DefinedNonLazyCategories.size(); i < e; i++) {
7216 Result += "\t&_OBJC_$_CATEGORY_";
7217 Result +=
7218 DefinedNonLazyCategories[i]->getClassInterface()->getNameAsString();
7219 Result += "_$_";
7220 Result += DefinedNonLazyCategories[i]->getNameAsString();
7221 Result += ",\n";
7222 }
7223 Result += "};\n";
7224 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007225}
7226
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00007227void RewriteModernObjC::WriteImageInfo(std::string &Result) {
7228 if (LangOpts.MicrosoftExt)
7229 Result += "__declspec(allocate(\".objc_imageinfo$B\")) \n";
7230
7231 Result += "static struct IMAGE_INFO { unsigned version; unsigned flag; } ";
7232 // version 0, ObjCABI is 2
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00007233 Result += "_OBJC_IMAGE_INFO = { 0, 2 };\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00007234}
7235
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007236/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
7237/// implementation.
7238void RewriteModernObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
7239 std::string &Result) {
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00007240 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007241 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
7242 // Find category declaration for this implementation.
Fariborz Jahanian61186122012-02-17 18:40:41 +00007243 ObjCCategoryDecl *CDecl=0;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007244 for (CDecl = ClassDecl->getCategoryList(); CDecl;
7245 CDecl = CDecl->getNextClassCategory())
7246 if (CDecl->getIdentifier() == IDecl->getIdentifier())
7247 break;
7248
7249 std::string FullCategoryName = ClassDecl->getNameAsString();
Fariborz Jahanian61186122012-02-17 18:40:41 +00007250 FullCategoryName += "_$_";
7251 FullCategoryName += CDecl->getNameAsString();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007252
7253 // Build _objc_method_list for class's instance methods if needed
7254 SmallVector<ObjCMethodDecl *, 32>
7255 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
7256
7257 // If any of our property implementations have associated getters or
7258 // setters, produce metadata for them as well.
7259 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
7260 PropEnd = IDecl->propimpl_end();
7261 Prop != PropEnd; ++Prop) {
David Blaikie262bc182012-04-30 02:36:29 +00007262 if (Prop->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007263 continue;
David Blaikie262bc182012-04-30 02:36:29 +00007264 if (!Prop->getPropertyIvarDecl())
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007265 continue;
David Blaikie262bc182012-04-30 02:36:29 +00007266 ObjCPropertyDecl *PD = Prop->getPropertyDecl();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007267 if (!PD)
7268 continue;
7269 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
7270 InstanceMethods.push_back(Getter);
7271 if (PD->isReadOnly())
7272 continue;
7273 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
7274 InstanceMethods.push_back(Setter);
7275 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007276
Fariborz Jahanian61186122012-02-17 18:40:41 +00007277 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
7278 "_OBJC_$_CATEGORY_INSTANCE_METHODS_",
7279 FullCategoryName, true);
7280
7281 SmallVector<ObjCMethodDecl *, 32>
7282 ClassMethods(IDecl->classmeth_begin(), IDecl->classmeth_end());
7283
7284 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
7285 "_OBJC_$_CATEGORY_CLASS_METHODS_",
7286 FullCategoryName, true);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007287
7288 // Protocols referenced in class declaration?
Fariborz Jahanian61186122012-02-17 18:40:41 +00007289 // Protocol's super protocol list
7290 std::vector<ObjCProtocolDecl *> RefedProtocols;
Argyrios Kyrtzidisa5f44412012-03-13 01:09:41 +00007291 for (ObjCInterfaceDecl::protocol_iterator I = CDecl->protocol_begin(),
7292 E = CDecl->protocol_end();
7293
7294 I != E; ++I) {
Fariborz Jahanian61186122012-02-17 18:40:41 +00007295 RefedProtocols.push_back(*I);
7296 // Must write out all protocol definitions in current qualifier list,
7297 // and in their nested qualifiers before writing out current definition.
7298 RewriteObjCProtocolMetaData(*I, Result);
7299 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007300
Fariborz Jahanian61186122012-02-17 18:40:41 +00007301 Write_protocol_list_initializer(Context, Result,
7302 RefedProtocols,
7303 "_OBJC_CATEGORY_PROTOCOLS_$_",
7304 FullCategoryName);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007305
Fariborz Jahanian61186122012-02-17 18:40:41 +00007306 // Protocol's property metadata.
7307 std::vector<ObjCPropertyDecl *> ClassProperties;
7308 for (ObjCContainerDecl::prop_iterator I = CDecl->prop_begin(),
7309 E = CDecl->prop_end(); I != E; ++I)
David Blaikie581deb32012-06-06 20:45:41 +00007310 ClassProperties.push_back(*I);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007311
Fariborz Jahanian61186122012-02-17 18:40:41 +00007312 Write_prop_list_t_initializer(*this, Context, Result, ClassProperties,
Fariborz Jahanianebfa2722012-05-03 23:19:33 +00007313 /* Container */IDecl,
Fariborz Jahanian61186122012-02-17 18:40:41 +00007314 "_OBJC_$_PROP_LIST_",
7315 FullCategoryName);
7316
7317 Write_category_t(*this, Context, Result,
Fariborz Jahaniane0335782012-03-27 18:41:05 +00007318 CDecl,
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00007319 ClassDecl,
Fariborz Jahanian61186122012-02-17 18:40:41 +00007320 InstanceMethods,
7321 ClassMethods,
7322 RefedProtocols,
7323 ClassProperties);
7324
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00007325 // Determine if this category is also "non-lazy".
7326 if (ImplementationIsNonLazy(IDecl))
7327 DefinedNonLazyCategories.push_back(CDecl);
Fariborz Jahaniane0335782012-03-27 18:41:05 +00007328
7329}
7330
7331void RewriteModernObjC::RewriteCategorySetupInitHook(std::string &Result) {
7332 int CatDefCount = CategoryImplementation.size();
7333 if (!CatDefCount)
7334 return;
7335 Result += "#pragma section(\".objc_inithooks$B\", long, read, write)\n";
7336 Result += "__declspec(allocate(\".objc_inithooks$B\")) ";
7337 Result += "static void *OBJC_CATEGORY_SETUP[] = {\n";
7338 for (int i = 0; i < CatDefCount; i++) {
7339 ObjCCategoryImplDecl *IDecl = CategoryImplementation[i];
7340 ObjCCategoryDecl *CatDecl= IDecl->getCategoryDecl();
7341 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
7342 Result += "\t(void *)&OBJC_CATEGORY_SETUP_$_";
7343 Result += ClassDecl->getName();
7344 Result += "_$_";
7345 Result += CatDecl->getName();
7346 Result += ",\n";
7347 }
7348 Result += "};\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007349}
7350
7351// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
7352/// class methods.
7353template<typename MethodIterator>
7354void RewriteModernObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
7355 MethodIterator MethodEnd,
7356 bool IsInstanceMethod,
7357 StringRef prefix,
7358 StringRef ClassName,
7359 std::string &Result) {
7360 if (MethodBegin == MethodEnd) return;
7361
7362 if (!objc_impl_method) {
7363 /* struct _objc_method {
7364 SEL _cmd;
7365 char *method_types;
7366 void *_imp;
7367 }
7368 */
7369 Result += "\nstruct _objc_method {\n";
7370 Result += "\tSEL _cmd;\n";
7371 Result += "\tchar *method_types;\n";
7372 Result += "\tvoid *_imp;\n";
7373 Result += "};\n";
7374
7375 objc_impl_method = true;
7376 }
7377
7378 // Build _objc_method_list for class's methods if needed
7379
7380 /* struct {
7381 struct _objc_method_list *next_method;
7382 int method_count;
7383 struct _objc_method method_list[];
7384 }
7385 */
7386 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00007387 Result += "\n";
7388 if (LangOpts.MicrosoftExt) {
7389 if (IsInstanceMethod)
7390 Result += "__declspec(allocate(\".inst_meth$B\")) ";
7391 else
7392 Result += "__declspec(allocate(\".cls_meth$B\")) ";
7393 }
7394 Result += "static struct {\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007395 Result += "\tstruct _objc_method_list *next_method;\n";
7396 Result += "\tint method_count;\n";
7397 Result += "\tstruct _objc_method method_list[";
7398 Result += utostr(NumMethods);
7399 Result += "];\n} _OBJC_";
7400 Result += prefix;
7401 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
7402 Result += "_METHODS_";
7403 Result += ClassName;
7404 Result += " __attribute__ ((used, section (\"__OBJC, __";
7405 Result += IsInstanceMethod ? "inst" : "cls";
7406 Result += "_meth\")))= ";
7407 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
7408
7409 Result += "\t,{{(SEL)\"";
7410 Result += (*MethodBegin)->getSelector().getAsString().c_str();
7411 std::string MethodTypeString;
7412 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
7413 Result += "\", \"";
7414 Result += MethodTypeString;
7415 Result += "\", (void *)";
7416 Result += MethodInternalNames[*MethodBegin];
7417 Result += "}\n";
7418 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
7419 Result += "\t ,{(SEL)\"";
7420 Result += (*MethodBegin)->getSelector().getAsString().c_str();
7421 std::string MethodTypeString;
7422 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
7423 Result += "\", \"";
7424 Result += MethodTypeString;
7425 Result += "\", (void *)";
7426 Result += MethodInternalNames[*MethodBegin];
7427 Result += "}\n";
7428 }
7429 Result += "\t }\n};\n";
7430}
7431
7432Stmt *RewriteModernObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) {
7433 SourceRange OldRange = IV->getSourceRange();
7434 Expr *BaseExpr = IV->getBase();
7435
7436 // Rewrite the base, but without actually doing replaces.
7437 {
7438 DisableReplaceStmtScope S(*this);
7439 BaseExpr = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(BaseExpr));
7440 IV->setBase(BaseExpr);
7441 }
7442
7443 ObjCIvarDecl *D = IV->getDecl();
7444
7445 Expr *Replacement = IV;
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007446
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007447 if (BaseExpr->getType()->isObjCObjectPointerType()) {
7448 const ObjCInterfaceType *iFaceDecl =
Fariborz Jahanian163d3ce2012-05-08 23:54:35 +00007449 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007450 assert(iFaceDecl && "RewriteObjCIvarRefExpr - iFaceDecl is null");
7451 // lookup which class implements the instance variable.
7452 ObjCInterfaceDecl *clsDeclared = 0;
7453 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
7454 clsDeclared);
7455 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
7456
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007457 // Build name of symbol holding ivar offset.
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00007458 std::string IvarOffsetName;
7459 WriteInternalIvarName(clsDeclared, D, IvarOffsetName);
7460
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00007461 ReferencedIvars[clsDeclared].insert(D);
7462
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007463 // cast offset to "char *".
7464 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context,
7465 Context->getPointerType(Context->CharTy),
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007466 CK_BitCast,
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007467 BaseExpr);
7468 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
7469 SourceLocation(), &Context->Idents.get(IvarOffsetName),
7470 Context->UnsignedLongTy, 0, SC_Extern, SC_None);
John McCallf4b88a42012-03-10 09:33:50 +00007471 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, false,
7472 Context->UnsignedLongTy, VK_LValue,
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007473 SourceLocation());
7474 BinaryOperator *addExpr =
7475 new (Context) BinaryOperator(castExpr, DRE, BO_Add,
7476 Context->getPointerType(Context->CharTy),
Lang Hamesbe9af122012-10-02 04:45:10 +00007477 VK_RValue, OK_Ordinary, SourceLocation(), false);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007478 // Don't forget the parens to enforce the proper binding.
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007479 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(),
7480 SourceLocation(),
7481 addExpr);
Fariborz Jahanian0d6e22a2012-02-24 17:35:35 +00007482 QualType IvarT = D->getType();
Fariborz Jahanian27fc81b2012-04-27 22:48:54 +00007483
Fariborz Jahanianf5eac482012-05-02 17:34:59 +00007484 if (!isa<TypedefType>(IvarT) && IvarT->isRecordType()) {
Fariborz Jahanian27fc81b2012-04-27 22:48:54 +00007485 RecordDecl *RD = IvarT->getAs<RecordType>()->getDecl();
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00007486 RD = RD->getDefinition();
7487 if (RD && !RD->getDeclName().getAsIdentifierInfo()) {
Fariborz Jahanian27fc81b2012-04-27 22:48:54 +00007488 // decltype(((Foo_IMPL*)0)->bar) *
Fariborz Jahanianf5eac482012-05-02 17:34:59 +00007489 ObjCContainerDecl *CDecl =
7490 dyn_cast<ObjCContainerDecl>(D->getDeclContext());
7491 // ivar in class extensions requires special treatment.
7492 if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(CDecl))
7493 CDecl = CatDecl->getClassInterface();
7494 std::string RecName = CDecl->getName();
Fariborz Jahanian27fc81b2012-04-27 22:48:54 +00007495 RecName += "_IMPL";
7496 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
7497 SourceLocation(), SourceLocation(),
7498 &Context->Idents.get(RecName.c_str()));
7499 QualType PtrStructIMPL = Context->getPointerType(Context->getTagDeclType(RD));
7500 unsigned UnsignedIntSize =
7501 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
7502 Expr *Zero = IntegerLiteral::Create(*Context,
7503 llvm::APInt(UnsignedIntSize, 0),
7504 Context->UnsignedIntTy, SourceLocation());
7505 Zero = NoTypeInfoCStyleCastExpr(Context, PtrStructIMPL, CK_BitCast, Zero);
7506 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
7507 Zero);
7508 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
7509 SourceLocation(),
7510 &Context->Idents.get(D->getNameAsString()),
7511 IvarT, 0,
7512 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smithca523302012-06-10 03:12:00 +00007513 ICIS_NoInit);
Fariborz Jahanian27fc81b2012-04-27 22:48:54 +00007514 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
7515 FD->getType(), VK_LValue,
7516 OK_Ordinary);
7517 IvarT = Context->getDecltypeType(ME, ME->getType());
7518 }
7519 }
Fariborz Jahanian8e0913d2012-02-29 00:26:20 +00007520 convertObjCTypeToCStyleType(IvarT);
Fariborz Jahanian0d6e22a2012-02-24 17:35:35 +00007521 QualType castT = Context->getPointerType(IvarT);
Fariborz Jahanian27fc81b2012-04-27 22:48:54 +00007522
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007523 castExpr = NoTypeInfoCStyleCastExpr(Context,
7524 castT,
7525 CK_BitCast,
7526 PE);
Fariborz Jahanian27fc81b2012-04-27 22:48:54 +00007527
7528
Fariborz Jahanian8e0913d2012-02-29 00:26:20 +00007529 Expr *Exp = new (Context) UnaryOperator(castExpr, UO_Deref, IvarT,
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007530 VK_LValue, OK_Ordinary,
7531 SourceLocation());
7532 PE = new (Context) ParenExpr(OldRange.getBegin(),
7533 OldRange.getEnd(),
7534 Exp);
7535
7536 Replacement = PE;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007537 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007538
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007539 ReplaceStmtWithRange(IV, Replacement, OldRange);
7540 return Replacement;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007541}