blob: 005020dc4cde996cb931c6ecee624cc17ec0cd5b [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();
Fariborz Jahanian96205962012-11-06 17:30:23 +0000281 void RewriteLineDirective(const Decl *D);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000282 void RewriteForwardClassDecl(DeclGroupRef D);
283 void RewriteForwardClassDecl(const llvm::SmallVector<Decl*, 8> &DG);
284 void RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
285 const std::string &typedefString);
286 void RewriteImplementations();
287 void RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
288 ObjCImplementationDecl *IMD,
289 ObjCCategoryImplDecl *CID);
290 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
291 void RewriteImplementationDecl(Decl *Dcl);
292 void RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
293 ObjCMethodDecl *MDecl, std::string &ResultStr);
294 void RewriteTypeIntoString(QualType T, std::string &ResultStr,
295 const FunctionType *&FPRetType);
296 void RewriteByRefString(std::string &ResultStr, const std::string &Name,
297 ValueDecl *VD, bool def=false);
298 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
299 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
300 void RewriteForwardProtocolDecl(DeclGroupRef D);
301 void RewriteForwardProtocolDecl(const llvm::SmallVector<Decl*, 8> &DG);
302 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
303 void RewriteProperty(ObjCPropertyDecl *prop);
304 void RewriteFunctionDecl(FunctionDecl *FD);
305 void RewriteBlockPointerType(std::string& Str, QualType Type);
306 void RewriteBlockPointerTypeVariable(std::string& Str, ValueDecl *VD);
Fariborz Jahanianb75f8de2012-04-19 00:50:01 +0000307 void RewriteBlockLiteralFunctionDecl(FunctionDecl *FD);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000308 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
309 void RewriteTypeOfDecl(VarDecl *VD);
310 void RewriteObjCQualifiedInterfaceTypes(Expr *E);
Fariborz Jahanian163d3ce2012-05-08 23:54:35 +0000311
312 std::string getIvarAccessString(ObjCIvarDecl *D);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000313
314 // Expression Rewriting.
315 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
316 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
317 Stmt *RewritePropertyOrImplicitGetter(PseudoObjectExpr *Pseudo);
318 Stmt *RewritePropertyOrImplicitSetter(PseudoObjectExpr *Pseudo);
319 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
320 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
321 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian55947042012-03-27 20:17:30 +0000322 Stmt *RewriteObjCBoolLiteralExpr(ObjCBoolLiteralExpr *Exp);
Patrick Beardeb382ec2012-04-19 00:25:12 +0000323 Stmt *RewriteObjCBoxedExpr(ObjCBoxedExpr *Exp);
Fariborz Jahanian86cff602012-03-30 23:35:47 +0000324 Stmt *RewriteObjCArrayLiteralExpr(ObjCArrayLiteral *Exp);
Fariborz Jahaniane35abe12012-04-06 22:29:36 +0000325 Stmt *RewriteObjCDictionaryLiteralExpr(ObjCDictionaryLiteral *Exp);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000326 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000327 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
Fariborz Jahanian042b91d2012-05-23 23:47:20 +0000328 Stmt *RewriteObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000329 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
330 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
331 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
332 SourceLocation OrigEnd);
333 Stmt *RewriteBreakStmt(BreakStmt *S);
334 Stmt *RewriteContinueStmt(ContinueStmt *S);
335 void RewriteCastExpr(CStyleCastExpr *CE);
Fariborz Jahanianf1ee6872012-04-10 00:08:18 +0000336 void RewriteImplicitCastObjCExpr(CastExpr *IE);
Fariborz Jahanianb3f904f2012-04-03 17:35:38 +0000337 void RewriteLinkageSpec(LinkageSpecDecl *LSD);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000338
339 // Block rewriting.
340 void RewriteBlocksInFunctionProtoType(QualType funcType, NamedDecl *D);
341
342 // Block specific rewrite rules.
343 void RewriteBlockPointerDecl(NamedDecl *VD);
Fariborz Jahanian4fe261c2012-04-24 19:38:45 +0000344 void RewriteByRefVar(VarDecl *VD, bool firstDecl, bool lastDecl);
John McCallf4b88a42012-03-10 09:33:50 +0000345 Stmt *RewriteBlockDeclRefExpr(DeclRefExpr *VD);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000346 Stmt *RewriteLocalVariableExternalStorage(DeclRefExpr *DRE);
347 void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
348
349 void RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
350 std::string &Result);
351
Fariborz Jahanian15f87772012-02-28 22:45:07 +0000352 void RewriteObjCFieldDecl(FieldDecl *fieldDecl, std::string &Result);
Fariborz Jahanianb68258f2012-05-01 17:46:45 +0000353 bool IsTagDefinedInsideClass(ObjCContainerDecl *IDecl, TagDecl *Tag,
Fariborz Jahanian8fba8942012-04-30 23:20:30 +0000354 bool &IsNamedDefinition);
355 void RewriteLocallyDefinedNamedAggregates(FieldDecl *fieldDecl,
356 std::string &Result);
Fariborz Jahanian15f87772012-02-28 22:45:07 +0000357
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +0000358 bool RewriteObjCFieldDeclType(QualType &Type, std::string &Result);
359
Fariborz Jahanian72c88f12012-02-22 18:13:25 +0000360 void RewriteIvarOffsetSymbols(ObjCInterfaceDecl *CDecl,
361 std::string &Result);
362
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000363 virtual void Initialize(ASTContext &context);
364
Benjamin Kramer48d798c2012-06-02 10:20:41 +0000365 // Misc. AST transformation routines. Sometimes they end up calling
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000366 // rewriting routines on the new ASTs.
367 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
368 Expr **args, unsigned nargs,
369 SourceLocation StartLoc=SourceLocation(),
370 SourceLocation EndLoc=SourceLocation());
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +0000371
372 Expr *SynthMsgSendStretCallExpr(FunctionDecl *MsgSendStretFlavor,
373 QualType msgSendType,
374 QualType returnType,
375 SmallVectorImpl<QualType> &ArgTypes,
376 SmallVectorImpl<Expr*> &MsgExprs,
377 ObjCMethodDecl *Method);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000378
379 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp,
380 SourceLocation StartLoc=SourceLocation(),
381 SourceLocation EndLoc=SourceLocation());
382
383 void SynthCountByEnumWithState(std::string &buf);
384 void SynthMsgSendFunctionDecl();
385 void SynthMsgSendSuperFunctionDecl();
386 void SynthMsgSendStretFunctionDecl();
387 void SynthMsgSendFpretFunctionDecl();
388 void SynthMsgSendSuperStretFunctionDecl();
389 void SynthGetClassFunctionDecl();
390 void SynthGetMetaClassFunctionDecl();
391 void SynthGetSuperClassFunctionDecl();
392 void SynthSelGetUidFunctionDecl();
393 void SynthSuperContructorFunctionDecl();
394
395 // Rewriting metadata
396 template<typename MethodIterator>
397 void RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
398 MethodIterator MethodEnd,
399 bool IsInstanceMethod,
400 StringRef prefix,
401 StringRef ClassName,
402 std::string &Result);
Fariborz Jahanianda9624a2012-02-08 19:53:58 +0000403 void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
404 std::string &Result);
Fariborz Jahanianb4ee8802012-04-30 16:57:52 +0000405 void RewriteObjCProtocolListMetaData(
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000406 const ObjCList<ObjCProtocolDecl> &Prots,
407 StringRef prefix, StringRef ClassName, std::string &Result);
Fariborz Jahanianb4ee8802012-04-30 16:57:52 +0000408 void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000409 std::string &Result);
Fariborz Jahanianb4ee8802012-04-30 16:57:52 +0000410 void RewriteClassSetupInitHook(std::string &Result);
Fariborz Jahaniane0335782012-03-27 18:41:05 +0000411
Fariborz Jahanianb4ee8802012-04-30 16:57:52 +0000412 void RewriteMetaDataIntoBuffer(std::string &Result);
413 void WriteImageInfo(std::string &Result);
414 void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000415 std::string &Result);
Fariborz Jahanianb4ee8802012-04-30 16:57:52 +0000416 void RewriteCategorySetupInitHook(std::string &Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000417
418 // Rewriting ivar
Fariborz Jahanianb4ee8802012-04-30 16:57:52 +0000419 void RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000420 std::string &Result);
Fariborz Jahanianb4ee8802012-04-30 16:57:52 +0000421 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000422
423
424 std::string SynthesizeByrefCopyDestroyHelper(VarDecl *VD, int flag);
425 std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
426 StringRef funcName, std::string Tag);
427 std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
428 StringRef funcName, std::string Tag);
429 std::string SynthesizeBlockImpl(BlockExpr *CE,
430 std::string Tag, std::string Desc);
431 std::string SynthesizeBlockDescriptor(std::string DescTag,
432 std::string ImplTag,
433 int i, StringRef funcName,
434 unsigned hasCopy);
435 Stmt *SynthesizeBlockCall(CallExpr *Exp, const Expr* BlockExp);
436 void SynthesizeBlockLiterals(SourceLocation FunLocStart,
437 StringRef FunName);
438 FunctionDecl *SynthBlockInitFunctionDecl(StringRef name);
439 Stmt *SynthBlockInitExpr(BlockExpr *Exp,
John McCallf4b88a42012-03-10 09:33:50 +0000440 const SmallVector<DeclRefExpr *, 8> &InnerBlockDeclRefs);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000441
442 // Misc. helper routines.
443 QualType getProtocolType();
444 void WarnAboutReturnGotoStmts(Stmt *S);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000445 void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
446 void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
447 void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
448
449 bool IsDeclStmtInForeachHeader(DeclStmt *DS);
450 void CollectBlockDeclRefInfo(BlockExpr *Exp);
451 void GetBlockDeclRefExprs(Stmt *S);
452 void GetInnerBlockDeclRefExprs(Stmt *S,
John McCallf4b88a42012-03-10 09:33:50 +0000453 SmallVector<DeclRefExpr *, 8> &InnerBlockDeclRefs,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000454 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts);
455
456 // We avoid calling Type::isBlockPointerType(), since it operates on the
457 // canonical type. We only care if the top-level type is a closure pointer.
458 bool isTopLevelBlockPointerType(QualType T) {
459 return isa<BlockPointerType>(T);
460 }
461
462 /// convertBlockPointerToFunctionPointer - Converts a block-pointer type
463 /// to a function pointer type and upon success, returns true; false
464 /// otherwise.
465 bool convertBlockPointerToFunctionPointer(QualType &T) {
466 if (isTopLevelBlockPointerType(T)) {
467 const BlockPointerType *BPT = T->getAs<BlockPointerType>();
468 T = Context->getPointerType(BPT->getPointeeType());
469 return true;
470 }
471 return false;
472 }
473
Fariborz Jahanian164d6f82012-02-13 18:57:49 +0000474 bool convertObjCTypeToCStyleType(QualType &T);
475
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000476 bool needToScanForQualifiers(QualType T);
477 QualType getSuperStructType();
478 QualType getConstantStringStructType();
479 QualType convertFunctionTypeOfBlocks(const FunctionType *FT);
480 bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf);
481
482 void convertToUnqualifiedObjCType(QualType &T) {
Fariborz Jahaniane35abe12012-04-06 22:29:36 +0000483 if (T->isObjCQualifiedIdType()) {
484 bool isConst = T.isConstQualified();
485 T = isConst ? Context->getObjCIdType().withConst()
486 : Context->getObjCIdType();
487 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000488 else if (T->isObjCQualifiedClassType())
489 T = Context->getObjCClassType();
490 else if (T->isObjCObjectPointerType() &&
491 T->getPointeeType()->isObjCQualifiedInterfaceType()) {
492 if (const ObjCObjectPointerType * OBJPT =
493 T->getAsObjCInterfacePointerType()) {
494 const ObjCInterfaceType *IFaceT = OBJPT->getInterfaceType();
495 T = QualType(IFaceT, 0);
496 T = Context->getPointerType(T);
497 }
498 }
499 }
500
501 // FIXME: This predicate seems like it would be useful to add to ASTContext.
502 bool isObjCType(QualType T) {
503 if (!LangOpts.ObjC1 && !LangOpts.ObjC2)
504 return false;
505
506 QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
507
508 if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
509 OCT == Context->getCanonicalType(Context->getObjCClassType()))
510 return true;
511
512 if (const PointerType *PT = OCT->getAs<PointerType>()) {
513 if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
514 PT->getPointeeType()->isObjCQualifiedIdType())
515 return true;
516 }
517 return false;
518 }
519 bool PointerTypeTakesAnyBlockArguments(QualType QT);
520 bool PointerTypeTakesAnyObjCQualifiedType(QualType QT);
521 void GetExtentOfArgList(const char *Name, const char *&LParen,
522 const char *&RParen);
523
524 void QuoteDoublequotes(std::string &From, std::string &To) {
525 for (unsigned i = 0; i < From.length(); i++) {
526 if (From[i] == '"')
527 To += "\\\"";
528 else
529 To += From[i];
530 }
531 }
532
533 QualType getSimpleFunctionType(QualType result,
534 const QualType *args,
535 unsigned numArgs,
536 bool variadic = false) {
537 if (result == Context->getObjCInstanceType())
538 result = Context->getObjCIdType();
539 FunctionProtoType::ExtProtoInfo fpi;
540 fpi.Variadic = variadic;
541 return Context->getFunctionType(result, args, numArgs, fpi);
542 }
543
544 // Helper function: create a CStyleCastExpr with trivial type source info.
545 CStyleCastExpr* NoTypeInfoCStyleCastExpr(ASTContext *Ctx, QualType Ty,
546 CastKind Kind, Expr *E) {
547 TypeSourceInfo *TInfo = Ctx->getTrivialTypeSourceInfo(Ty, SourceLocation());
548 return CStyleCastExpr::Create(*Ctx, Ty, VK_RValue, Kind, E, 0, TInfo,
549 SourceLocation(), SourceLocation());
550 }
Fariborz Jahanian88f7f752012-03-14 23:18:19 +0000551
552 bool ImplementationIsNonLazy(const ObjCImplDecl *OD) const {
553 IdentifierInfo* II = &Context->Idents.get("load");
554 Selector LoadSel = Context->Selectors.getSelector(0, &II);
555 return OD->getClassMethod(LoadSel) != 0;
556 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000557 };
558
559}
560
561void RewriteModernObjC::RewriteBlocksInFunctionProtoType(QualType funcType,
562 NamedDecl *D) {
563 if (const FunctionProtoType *fproto
564 = dyn_cast<FunctionProtoType>(funcType.IgnoreParens())) {
565 for (FunctionProtoType::arg_type_iterator I = fproto->arg_type_begin(),
566 E = fproto->arg_type_end(); I && (I != E); ++I)
567 if (isTopLevelBlockPointerType(*I)) {
568 // All the args are checked/rewritten. Don't call twice!
569 RewriteBlockPointerDecl(D);
570 break;
571 }
572 }
573}
574
575void RewriteModernObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
576 const PointerType *PT = funcType->getAs<PointerType>();
577 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
578 RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND);
579}
580
581static bool IsHeaderFile(const std::string &Filename) {
582 std::string::size_type DotPos = Filename.rfind('.');
583
584 if (DotPos == std::string::npos) {
585 // no file extension
586 return false;
587 }
588
589 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
590 // C header: .h
591 // C++ header: .hh or .H;
592 return Ext == "h" || Ext == "hh" || Ext == "H";
593}
594
595RewriteModernObjC::RewriteModernObjC(std::string inFile, raw_ostream* OS,
596 DiagnosticsEngine &D, const LangOptions &LOpts,
597 bool silenceMacroWarn)
598 : Diags(D), LangOpts(LOpts), InFileName(inFile), OutFile(OS),
599 SilenceRewriteMacroWarning(silenceMacroWarn) {
600 IsHeader = IsHeaderFile(inFile);
601 RewriteFailedDiag = Diags.getCustomDiagID(DiagnosticsEngine::Warning,
602 "rewriting sub-expression within a macro (may not be correct)");
Fariborz Jahaniand13c2c22012-03-22 19:54:39 +0000603 // FIXME. This should be an error. But if block is not called, it is OK. And it
604 // may break including some headers.
605 GlobalBlockRewriteFailedDiag = Diags.getCustomDiagID(DiagnosticsEngine::Warning,
606 "rewriting block literal declared in global scope is not implemented");
607
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000608 TryFinallyContainsReturnDiag = Diags.getCustomDiagID(
609 DiagnosticsEngine::Warning,
610 "rewriter doesn't support user-specified control flow semantics "
611 "for @try/@finally (code may not execute properly)");
612}
613
614ASTConsumer *clang::CreateModernObjCRewriter(const std::string& InFile,
615 raw_ostream* OS,
616 DiagnosticsEngine &Diags,
617 const LangOptions &LOpts,
618 bool SilenceRewriteMacroWarning) {
619 return new RewriteModernObjC(InFile, OS, Diags, LOpts, SilenceRewriteMacroWarning);
620}
621
622void RewriteModernObjC::InitializeCommon(ASTContext &context) {
623 Context = &context;
624 SM = &Context->getSourceManager();
625 TUDecl = Context->getTranslationUnitDecl();
626 MsgSendFunctionDecl = 0;
627 MsgSendSuperFunctionDecl = 0;
628 MsgSendStretFunctionDecl = 0;
629 MsgSendSuperStretFunctionDecl = 0;
630 MsgSendFpretFunctionDecl = 0;
631 GetClassFunctionDecl = 0;
632 GetMetaClassFunctionDecl = 0;
633 GetSuperClassFunctionDecl = 0;
634 SelGetUidFunctionDecl = 0;
635 CFStringFunctionDecl = 0;
636 ConstantStringClassReference = 0;
637 NSStringRecord = 0;
638 CurMethodDef = 0;
639 CurFunctionDef = 0;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000640 GlobalVarDecl = 0;
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +0000641 GlobalConstructionExp = 0;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000642 SuperStructDecl = 0;
643 ProtocolTypeDecl = 0;
644 ConstantStringDecl = 0;
645 BcLabelCount = 0;
646 SuperContructorFunctionDecl = 0;
647 NumObjCStringLiterals = 0;
648 PropParentMap = 0;
649 CurrentBody = 0;
650 DisableReplaceStmt = false;
651 objc_impl_method = false;
652
653 // Get the ID and start/end of the main file.
654 MainFileID = SM->getMainFileID();
655 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
656 MainFileStart = MainBuf->getBufferStart();
657 MainFileEnd = MainBuf->getBufferEnd();
658
David Blaikie4e4d0842012-03-11 07:00:24 +0000659 Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOpts());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000660}
661
662//===----------------------------------------------------------------------===//
663// Top Level Driver Code
664//===----------------------------------------------------------------------===//
665
666void RewriteModernObjC::HandleTopLevelSingleDecl(Decl *D) {
667 if (Diags.hasErrorOccurred())
668 return;
669
670 // Two cases: either the decl could be in the main file, or it could be in a
671 // #included file. If the former, rewrite it now. If the later, check to see
672 // if we rewrote the #include/#import.
673 SourceLocation Loc = D->getLocation();
674 Loc = SM->getExpansionLoc(Loc);
675
676 // If this is for a builtin, ignore it.
677 if (Loc.isInvalid()) return;
678
679 // Look for built-in declarations that we need to refer during the rewrite.
680 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
681 RewriteFunctionDecl(FD);
682 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
683 // declared in <Foundation/NSString.h>
684 if (FVD->getName() == "_NSConstantStringClassReference") {
685 ConstantStringClassReference = FVD;
686 return;
687 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000688 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
689 RewriteCategoryDecl(CD);
690 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
691 if (PD->isThisDeclarationADefinition())
692 RewriteProtocolDecl(PD);
693 } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) {
Fariborz Jahanian8e86b2d2012-04-04 17:16:15 +0000694 // FIXME. This will not work in all situations and leaving it out
695 // is harmless.
696 // RewriteLinkageSpec(LSD);
697
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000698 // Recurse into linkage specifications
699 for (DeclContext::decl_iterator DI = LSD->decls_begin(),
700 DIEnd = LSD->decls_end();
701 DI != DIEnd; ) {
702 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>((*DI))) {
703 if (!IFace->isThisDeclarationADefinition()) {
704 SmallVector<Decl *, 8> DG;
705 SourceLocation StartLoc = IFace->getLocStart();
706 do {
707 if (isa<ObjCInterfaceDecl>(*DI) &&
708 !cast<ObjCInterfaceDecl>(*DI)->isThisDeclarationADefinition() &&
709 StartLoc == (*DI)->getLocStart())
710 DG.push_back(*DI);
711 else
712 break;
713
714 ++DI;
715 } while (DI != DIEnd);
716 RewriteForwardClassDecl(DG);
717 continue;
718 }
Fariborz Jahanianb3f904f2012-04-03 17:35:38 +0000719 else {
720 // Keep track of all interface declarations seen.
721 ObjCInterfacesSeen.push_back(IFace);
722 ++DI;
723 continue;
724 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000725 }
726
727 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>((*DI))) {
728 if (!Proto->isThisDeclarationADefinition()) {
729 SmallVector<Decl *, 8> DG;
730 SourceLocation StartLoc = Proto->getLocStart();
731 do {
732 if (isa<ObjCProtocolDecl>(*DI) &&
733 !cast<ObjCProtocolDecl>(*DI)->isThisDeclarationADefinition() &&
734 StartLoc == (*DI)->getLocStart())
735 DG.push_back(*DI);
736 else
737 break;
738
739 ++DI;
740 } while (DI != DIEnd);
741 RewriteForwardProtocolDecl(DG);
742 continue;
743 }
744 }
745
746 HandleTopLevelSingleDecl(*DI);
747 ++DI;
748 }
749 }
750 // If we have a decl in the main file, see if we should rewrite it.
751 if (SM->isFromMainFile(Loc))
752 return HandleDeclInMainFile(D);
753}
754
755//===----------------------------------------------------------------------===//
756// Syntactic (non-AST) Rewriting Code
757//===----------------------------------------------------------------------===//
758
759void RewriteModernObjC::RewriteInclude() {
760 SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID);
761 StringRef MainBuf = SM->getBufferData(MainFileID);
762 const char *MainBufStart = MainBuf.begin();
763 const char *MainBufEnd = MainBuf.end();
764 size_t ImportLen = strlen("import");
765
766 // Loop over the whole file, looking for includes.
767 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
768 if (*BufPtr == '#') {
769 if (++BufPtr == MainBufEnd)
770 return;
771 while (*BufPtr == ' ' || *BufPtr == '\t')
772 if (++BufPtr == MainBufEnd)
773 return;
774 if (!strncmp(BufPtr, "import", ImportLen)) {
775 // replace import with include
776 SourceLocation ImportLoc =
777 LocStart.getLocWithOffset(BufPtr-MainBufStart);
778 ReplaceText(ImportLoc, ImportLen, "include");
779 BufPtr += ImportLen;
780 }
781 }
782 }
783}
784
Fariborz Jahanian163d3ce2012-05-08 23:54:35 +0000785static void WriteInternalIvarName(const ObjCInterfaceDecl *IDecl,
786 ObjCIvarDecl *IvarDecl, std::string &Result) {
787 Result += "OBJC_IVAR_$_";
788 Result += IDecl->getName();
789 Result += "$";
790 Result += IvarDecl->getName();
791}
792
793std::string
794RewriteModernObjC::getIvarAccessString(ObjCIvarDecl *D) {
795 const ObjCInterfaceDecl *ClassDecl = D->getContainingInterface();
796
797 // Build name of symbol holding ivar offset.
798 std::string IvarOffsetName;
799 WriteInternalIvarName(ClassDecl, D, IvarOffsetName);
800
801
802 std::string S = "(*(";
803 QualType IvarT = D->getType();
804
805 if (!isa<TypedefType>(IvarT) && IvarT->isRecordType()) {
806 RecordDecl *RD = IvarT->getAs<RecordType>()->getDecl();
807 RD = RD->getDefinition();
808 if (RD && !RD->getDeclName().getAsIdentifierInfo()) {
809 // decltype(((Foo_IMPL*)0)->bar) *
810 ObjCContainerDecl *CDecl =
811 dyn_cast<ObjCContainerDecl>(D->getDeclContext());
812 // ivar in class extensions requires special treatment.
813 if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(CDecl))
814 CDecl = CatDecl->getClassInterface();
815 std::string RecName = CDecl->getName();
816 RecName += "_IMPL";
817 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
818 SourceLocation(), SourceLocation(),
819 &Context->Idents.get(RecName.c_str()));
820 QualType PtrStructIMPL = Context->getPointerType(Context->getTagDeclType(RD));
821 unsigned UnsignedIntSize =
822 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
823 Expr *Zero = IntegerLiteral::Create(*Context,
824 llvm::APInt(UnsignedIntSize, 0),
825 Context->UnsignedIntTy, SourceLocation());
826 Zero = NoTypeInfoCStyleCastExpr(Context, PtrStructIMPL, CK_BitCast, Zero);
827 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
828 Zero);
829 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
830 SourceLocation(),
831 &Context->Idents.get(D->getNameAsString()),
832 IvarT, 0,
833 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smithca523302012-06-10 03:12:00 +0000834 ICIS_NoInit);
Fariborz Jahanian163d3ce2012-05-08 23:54:35 +0000835 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
836 FD->getType(), VK_LValue,
837 OK_Ordinary);
838 IvarT = Context->getDecltypeType(ME, ME->getType());
839 }
840 }
841 convertObjCTypeToCStyleType(IvarT);
842 QualType castT = Context->getPointerType(IvarT);
843 std::string TypeString(castT.getAsString(Context->getPrintingPolicy()));
844 S += TypeString;
845 S += ")";
846
847 // ((char *)self + IVAR_OFFSET_SYMBOL_NAME)
848 S += "((char *)self + ";
849 S += IvarOffsetName;
850 S += "))";
851 ReferencedIvars[const_cast<ObjCInterfaceDecl *>(ClassDecl)].insert(D);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000852 return S;
853}
854
Fariborz Jahanian301e2e42012-05-03 22:52:13 +0000855/// mustSynthesizeSetterGetterMethod - returns true if setter or getter has not
856/// been found in the class implementation. In this case, it must be synthesized.
857static bool mustSynthesizeSetterGetterMethod(ObjCImplementationDecl *IMP,
858 ObjCPropertyDecl *PD,
859 bool getter) {
860 return getter ? !IMP->getInstanceMethod(PD->getGetterName())
861 : !IMP->getInstanceMethod(PD->getSetterName());
862
863}
864
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000865void RewriteModernObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
866 ObjCImplementationDecl *IMD,
867 ObjCCategoryImplDecl *CID) {
868 static bool objcGetPropertyDefined = false;
869 static bool objcSetPropertyDefined = false;
Fariborz Jahanian301e2e42012-05-03 22:52:13 +0000870 SourceLocation startGetterSetterLoc;
871
872 if (PID->getLocStart().isValid()) {
873 SourceLocation startLoc = PID->getLocStart();
874 InsertText(startLoc, "// ");
875 const char *startBuf = SM->getCharacterData(startLoc);
876 assert((*startBuf == '@') && "bogus @synthesize location");
877 const char *semiBuf = strchr(startBuf, ';');
878 assert((*semiBuf == ';') && "@synthesize: can't find ';'");
879 startGetterSetterLoc = startLoc.getLocWithOffset(semiBuf-startBuf+1);
880 }
881 else
882 startGetterSetterLoc = IMD ? IMD->getLocEnd() : CID->getLocEnd();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000883
884 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
885 return; // FIXME: is this correct?
886
887 // Generate the 'getter' function.
888 ObjCPropertyDecl *PD = PID->getPropertyDecl();
889 ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
890
891 if (!OID)
892 return;
893 unsigned Attributes = PD->getPropertyAttributes();
Fariborz Jahanian301e2e42012-05-03 22:52:13 +0000894 if (mustSynthesizeSetterGetterMethod(IMD, PD, true /*getter*/)) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000895 bool GenGetProperty = !(Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic) &&
896 (Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
897 ObjCPropertyDecl::OBJC_PR_copy));
898 std::string Getr;
899 if (GenGetProperty && !objcGetPropertyDefined) {
900 objcGetPropertyDefined = true;
901 // FIXME. Is this attribute correct in all cases?
902 Getr = "\nextern \"C\" __declspec(dllimport) "
903 "id objc_getProperty(id, SEL, long, bool);\n";
904 }
905 RewriteObjCMethodDecl(OID->getContainingInterface(),
906 PD->getGetterMethodDecl(), Getr);
907 Getr += "{ ";
908 // Synthesize an explicit cast to gain access to the ivar.
909 // See objc-act.c:objc_synthesize_new_getter() for details.
910 if (GenGetProperty) {
911 // return objc_getProperty(self, _cmd, offsetof(ClassDecl, OID), 1)
912 Getr += "typedef ";
913 const FunctionType *FPRetType = 0;
914 RewriteTypeIntoString(PD->getGetterMethodDecl()->getResultType(), Getr,
915 FPRetType);
916 Getr += " _TYPE";
917 if (FPRetType) {
918 Getr += ")"; // close the precedence "scope" for "*".
919
920 // Now, emit the argument types (if any).
921 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)){
922 Getr += "(";
923 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
924 if (i) Getr += ", ";
925 std::string ParamStr = FT->getArgType(i).getAsString(
926 Context->getPrintingPolicy());
927 Getr += ParamStr;
928 }
929 if (FT->isVariadic()) {
930 if (FT->getNumArgs()) Getr += ", ";
931 Getr += "...";
932 }
933 Getr += ")";
934 } else
935 Getr += "()";
936 }
937 Getr += ";\n";
938 Getr += "return (_TYPE)";
939 Getr += "objc_getProperty(self, _cmd, ";
940 RewriteIvarOffsetComputation(OID, Getr);
941 Getr += ", 1)";
942 }
943 else
944 Getr += "return " + getIvarAccessString(OID);
945 Getr += "; }";
Fariborz Jahanian301e2e42012-05-03 22:52:13 +0000946 InsertText(startGetterSetterLoc, Getr);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000947 }
948
Fariborz Jahanian301e2e42012-05-03 22:52:13 +0000949 if (PD->isReadOnly() ||
950 !mustSynthesizeSetterGetterMethod(IMD, PD, false /*setter*/))
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000951 return;
952
953 // Generate the 'setter' function.
954 std::string Setr;
955 bool GenSetProperty = Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
956 ObjCPropertyDecl::OBJC_PR_copy);
957 if (GenSetProperty && !objcSetPropertyDefined) {
958 objcSetPropertyDefined = true;
959 // FIXME. Is this attribute correct in all cases?
960 Setr = "\nextern \"C\" __declspec(dllimport) "
961 "void objc_setProperty (id, SEL, long, id, bool, bool);\n";
962 }
963
964 RewriteObjCMethodDecl(OID->getContainingInterface(),
965 PD->getSetterMethodDecl(), Setr);
966 Setr += "{ ";
967 // Synthesize an explicit cast to initialize the ivar.
968 // See objc-act.c:objc_synthesize_new_setter() for details.
969 if (GenSetProperty) {
970 Setr += "objc_setProperty (self, _cmd, ";
971 RewriteIvarOffsetComputation(OID, Setr);
972 Setr += ", (id)";
973 Setr += PD->getName();
974 Setr += ", ";
975 if (Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic)
976 Setr += "0, ";
977 else
978 Setr += "1, ";
979 if (Attributes & ObjCPropertyDecl::OBJC_PR_copy)
980 Setr += "1)";
981 else
982 Setr += "0)";
983 }
984 else {
985 Setr += getIvarAccessString(OID) + " = ";
986 Setr += PD->getName();
987 }
Fariborz Jahanian301e2e42012-05-03 22:52:13 +0000988 Setr += "; }\n";
989 InsertText(startGetterSetterLoc, Setr);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000990}
991
992static void RewriteOneForwardClassDecl(ObjCInterfaceDecl *ForwardDecl,
993 std::string &typedefString) {
994 typedefString += "#ifndef _REWRITER_typedef_";
995 typedefString += ForwardDecl->getNameAsString();
996 typedefString += "\n";
997 typedefString += "#define _REWRITER_typedef_";
998 typedefString += ForwardDecl->getNameAsString();
999 typedefString += "\n";
1000 typedefString += "typedef struct objc_object ";
1001 typedefString += ForwardDecl->getNameAsString();
Fariborz Jahanianc38503b2012-03-12 23:58:28 +00001002 // typedef struct { } _objc_exc_Classname;
1003 typedefString += ";\ntypedef struct {} _objc_exc_";
1004 typedefString += ForwardDecl->getNameAsString();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001005 typedefString += ";\n#endif\n";
1006}
1007
1008void RewriteModernObjC::RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
1009 const std::string &typedefString) {
1010 SourceLocation startLoc = ClassDecl->getLocStart();
1011 const char *startBuf = SM->getCharacterData(startLoc);
1012 const char *semiPtr = strchr(startBuf, ';');
1013 // Replace the @class with typedefs corresponding to the classes.
1014 ReplaceText(startLoc, semiPtr-startBuf+1, typedefString);
1015}
1016
1017void RewriteModernObjC::RewriteForwardClassDecl(DeclGroupRef D) {
1018 std::string typedefString;
1019 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
1020 ObjCInterfaceDecl *ForwardDecl = cast<ObjCInterfaceDecl>(*I);
1021 if (I == D.begin()) {
1022 // Translate to typedef's that forward reference structs with the same name
1023 // as the class. As a convenience, we include the original declaration
1024 // as a comment.
1025 typedefString += "// @class ";
1026 typedefString += ForwardDecl->getNameAsString();
1027 typedefString += ";\n";
1028 }
1029 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
1030 }
1031 DeclGroupRef::iterator I = D.begin();
1032 RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(*I), typedefString);
1033}
1034
1035void RewriteModernObjC::RewriteForwardClassDecl(
1036 const llvm::SmallVector<Decl*, 8> &D) {
1037 std::string typedefString;
1038 for (unsigned i = 0; i < D.size(); i++) {
1039 ObjCInterfaceDecl *ForwardDecl = cast<ObjCInterfaceDecl>(D[i]);
1040 if (i == 0) {
1041 typedefString += "// @class ";
1042 typedefString += ForwardDecl->getNameAsString();
1043 typedefString += ";\n";
1044 }
1045 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
1046 }
1047 RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(D[0]), typedefString);
1048}
1049
1050void RewriteModernObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
1051 // When method is a synthesized one, such as a getter/setter there is
1052 // nothing to rewrite.
1053 if (Method->isImplicit())
1054 return;
1055 SourceLocation LocStart = Method->getLocStart();
1056 SourceLocation LocEnd = Method->getLocEnd();
1057
1058 if (SM->getExpansionLineNumber(LocEnd) >
1059 SM->getExpansionLineNumber(LocStart)) {
1060 InsertText(LocStart, "#if 0\n");
1061 ReplaceText(LocEnd, 1, ";\n#endif\n");
1062 } else {
1063 InsertText(LocStart, "// ");
1064 }
1065}
1066
1067void RewriteModernObjC::RewriteProperty(ObjCPropertyDecl *prop) {
1068 SourceLocation Loc = prop->getAtLoc();
1069
1070 ReplaceText(Loc, 0, "// ");
1071 // FIXME: handle properties that are declared across multiple lines.
1072}
1073
1074void RewriteModernObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
1075 SourceLocation LocStart = CatDecl->getLocStart();
1076
1077 // FIXME: handle category headers that are declared across multiple lines.
Fariborz Jahanianb68258f2012-05-01 17:46:45 +00001078 if (CatDecl->getIvarRBraceLoc().isValid()) {
1079 ReplaceText(LocStart, 1, "/** ");
1080 ReplaceText(CatDecl->getIvarRBraceLoc(), 1, "**/ ");
1081 }
1082 else {
Fariborz Jahaniand2aea122012-02-19 19:00:05 +00001083 ReplaceText(LocStart, 0, "// ");
Fariborz Jahanianb68258f2012-05-01 17:46:45 +00001084 }
Fariborz Jahanianaf300292012-02-20 20:09:20 +00001085
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001086 for (ObjCCategoryDecl::prop_iterator I = CatDecl->prop_begin(),
1087 E = CatDecl->prop_end(); I != E; ++I)
David Blaikie581deb32012-06-06 20:45:41 +00001088 RewriteProperty(*I);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001089
1090 for (ObjCCategoryDecl::instmeth_iterator
1091 I = CatDecl->instmeth_begin(), E = CatDecl->instmeth_end();
1092 I != E; ++I)
1093 RewriteMethodDeclaration(*I);
1094 for (ObjCCategoryDecl::classmeth_iterator
1095 I = CatDecl->classmeth_begin(), E = CatDecl->classmeth_end();
1096 I != E; ++I)
1097 RewriteMethodDeclaration(*I);
1098
1099 // Lastly, comment out the @end.
1100 ReplaceText(CatDecl->getAtEndRange().getBegin(),
1101 strlen("@end"), "/* @end */");
1102}
1103
1104void RewriteModernObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
1105 SourceLocation LocStart = PDecl->getLocStart();
1106 assert(PDecl->isThisDeclarationADefinition());
1107
1108 // FIXME: handle protocol headers that are declared across multiple lines.
1109 ReplaceText(LocStart, 0, "// ");
1110
1111 for (ObjCProtocolDecl::instmeth_iterator
1112 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
1113 I != E; ++I)
1114 RewriteMethodDeclaration(*I);
1115 for (ObjCProtocolDecl::classmeth_iterator
1116 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
1117 I != E; ++I)
1118 RewriteMethodDeclaration(*I);
1119
1120 for (ObjCInterfaceDecl::prop_iterator I = PDecl->prop_begin(),
1121 E = PDecl->prop_end(); I != E; ++I)
David Blaikie581deb32012-06-06 20:45:41 +00001122 RewriteProperty(*I);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001123
1124 // Lastly, comment out the @end.
1125 SourceLocation LocEnd = PDecl->getAtEndRange().getBegin();
1126 ReplaceText(LocEnd, strlen("@end"), "/* @end */");
1127
1128 // Must comment out @optional/@required
1129 const char *startBuf = SM->getCharacterData(LocStart);
1130 const char *endBuf = SM->getCharacterData(LocEnd);
1131 for (const char *p = startBuf; p < endBuf; p++) {
1132 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
1133 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
1134 ReplaceText(OptionalLoc, strlen("@optional"), "/* @optional */");
1135
1136 }
1137 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
1138 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
1139 ReplaceText(OptionalLoc, strlen("@required"), "/* @required */");
1140
1141 }
1142 }
1143}
1144
1145void RewriteModernObjC::RewriteForwardProtocolDecl(DeclGroupRef D) {
1146 SourceLocation LocStart = (*D.begin())->getLocStart();
1147 if (LocStart.isInvalid())
1148 llvm_unreachable("Invalid SourceLocation");
1149 // FIXME: handle forward protocol that are declared across multiple lines.
1150 ReplaceText(LocStart, 0, "// ");
1151}
1152
1153void
1154RewriteModernObjC::RewriteForwardProtocolDecl(const llvm::SmallVector<Decl*, 8> &DG) {
1155 SourceLocation LocStart = DG[0]->getLocStart();
1156 if (LocStart.isInvalid())
1157 llvm_unreachable("Invalid SourceLocation");
1158 // FIXME: handle forward protocol that are declared across multiple lines.
1159 ReplaceText(LocStart, 0, "// ");
1160}
1161
Fariborz Jahanianb3f904f2012-04-03 17:35:38 +00001162void
1163RewriteModernObjC::RewriteLinkageSpec(LinkageSpecDecl *LSD) {
1164 SourceLocation LocStart = LSD->getExternLoc();
1165 if (LocStart.isInvalid())
1166 llvm_unreachable("Invalid extern SourceLocation");
1167
1168 ReplaceText(LocStart, 0, "// ");
1169 if (!LSD->hasBraces())
1170 return;
1171 // FIXME. We don't rewrite well if '{' is not on same line as 'extern'.
1172 SourceLocation LocRBrace = LSD->getRBraceLoc();
1173 if (LocRBrace.isInvalid())
1174 llvm_unreachable("Invalid rbrace SourceLocation");
1175 ReplaceText(LocRBrace, 0, "// ");
1176}
1177
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001178void RewriteModernObjC::RewriteTypeIntoString(QualType T, std::string &ResultStr,
1179 const FunctionType *&FPRetType) {
1180 if (T->isObjCQualifiedIdType())
1181 ResultStr += "id";
1182 else if (T->isFunctionPointerType() ||
1183 T->isBlockPointerType()) {
1184 // needs special handling, since pointer-to-functions have special
1185 // syntax (where a decaration models use).
1186 QualType retType = T;
1187 QualType PointeeTy;
1188 if (const PointerType* PT = retType->getAs<PointerType>())
1189 PointeeTy = PT->getPointeeType();
1190 else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>())
1191 PointeeTy = BPT->getPointeeType();
1192 if ((FPRetType = PointeeTy->getAs<FunctionType>())) {
1193 ResultStr += FPRetType->getResultType().getAsString(
1194 Context->getPrintingPolicy());
1195 ResultStr += "(*";
1196 }
1197 } else
1198 ResultStr += T.getAsString(Context->getPrintingPolicy());
1199}
1200
1201void RewriteModernObjC::RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
1202 ObjCMethodDecl *OMD,
1203 std::string &ResultStr) {
1204 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
1205 const FunctionType *FPRetType = 0;
1206 ResultStr += "\nstatic ";
1207 RewriteTypeIntoString(OMD->getResultType(), ResultStr, FPRetType);
1208 ResultStr += " ";
1209
1210 // Unique method name
1211 std::string NameStr;
1212
1213 if (OMD->isInstanceMethod())
1214 NameStr += "_I_";
1215 else
1216 NameStr += "_C_";
1217
1218 NameStr += IDecl->getNameAsString();
1219 NameStr += "_";
1220
1221 if (ObjCCategoryImplDecl *CID =
1222 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
1223 NameStr += CID->getNameAsString();
1224 NameStr += "_";
1225 }
1226 // Append selector names, replacing ':' with '_'
1227 {
1228 std::string selString = OMD->getSelector().getAsString();
1229 int len = selString.size();
1230 for (int i = 0; i < len; i++)
1231 if (selString[i] == ':')
1232 selString[i] = '_';
1233 NameStr += selString;
1234 }
1235 // Remember this name for metadata emission
1236 MethodInternalNames[OMD] = NameStr;
1237 ResultStr += NameStr;
1238
1239 // Rewrite arguments
1240 ResultStr += "(";
1241
1242 // invisible arguments
1243 if (OMD->isInstanceMethod()) {
1244 QualType selfTy = Context->getObjCInterfaceType(IDecl);
1245 selfTy = Context->getPointerType(selfTy);
1246 if (!LangOpts.MicrosoftExt) {
1247 if (ObjCSynthesizedStructs.count(const_cast<ObjCInterfaceDecl*>(IDecl)))
1248 ResultStr += "struct ";
1249 }
1250 // When rewriting for Microsoft, explicitly omit the structure name.
1251 ResultStr += IDecl->getNameAsString();
1252 ResultStr += " *";
1253 }
1254 else
1255 ResultStr += Context->getObjCClassType().getAsString(
1256 Context->getPrintingPolicy());
1257
1258 ResultStr += " self, ";
1259 ResultStr += Context->getObjCSelType().getAsString(Context->getPrintingPolicy());
1260 ResultStr += " _cmd";
1261
1262 // Method arguments.
1263 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
1264 E = OMD->param_end(); PI != E; ++PI) {
1265 ParmVarDecl *PDecl = *PI;
1266 ResultStr += ", ";
1267 if (PDecl->getType()->isObjCQualifiedIdType()) {
1268 ResultStr += "id ";
1269 ResultStr += PDecl->getNameAsString();
1270 } else {
1271 std::string Name = PDecl->getNameAsString();
1272 QualType QT = PDecl->getType();
1273 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian2610f902012-03-27 16:42:20 +00001274 (void)convertBlockPointerToFunctionPointer(QT);
1275 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001276 ResultStr += Name;
1277 }
1278 }
1279 if (OMD->isVariadic())
1280 ResultStr += ", ...";
1281 ResultStr += ") ";
1282
1283 if (FPRetType) {
1284 ResultStr += ")"; // close the precedence "scope" for "*".
1285
1286 // Now, emit the argument types (if any).
1287 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
1288 ResultStr += "(";
1289 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
1290 if (i) ResultStr += ", ";
1291 std::string ParamStr = FT->getArgType(i).getAsString(
1292 Context->getPrintingPolicy());
1293 ResultStr += ParamStr;
1294 }
1295 if (FT->isVariadic()) {
1296 if (FT->getNumArgs()) ResultStr += ", ";
1297 ResultStr += "...";
1298 }
1299 ResultStr += ")";
1300 } else {
1301 ResultStr += "()";
1302 }
1303 }
1304}
1305void RewriteModernObjC::RewriteImplementationDecl(Decl *OID) {
1306 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
1307 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
1308
Fariborz Jahaniand2aea122012-02-19 19:00:05 +00001309 if (IMD) {
Fariborz Jahanianb68258f2012-05-01 17:46:45 +00001310 if (IMD->getIvarRBraceLoc().isValid()) {
1311 ReplaceText(IMD->getLocStart(), 1, "/** ");
1312 ReplaceText(IMD->getIvarRBraceLoc(), 1, "**/ ");
Fariborz Jahaniand2aea122012-02-19 19:00:05 +00001313 }
Fariborz Jahanianb68258f2012-05-01 17:46:45 +00001314 else {
1315 InsertText(IMD->getLocStart(), "// ");
1316 }
Fariborz Jahaniand2aea122012-02-19 19:00:05 +00001317 }
1318 else
1319 InsertText(CID->getLocStart(), "// ");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001320
1321 for (ObjCCategoryImplDecl::instmeth_iterator
1322 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
1323 E = IMD ? IMD->instmeth_end() : CID->instmeth_end();
1324 I != E; ++I) {
1325 std::string ResultStr;
1326 ObjCMethodDecl *OMD = *I;
1327 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
1328 SourceLocation LocStart = OMD->getLocStart();
1329 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
1330
1331 const char *startBuf = SM->getCharacterData(LocStart);
1332 const char *endBuf = SM->getCharacterData(LocEnd);
1333 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
1334 }
1335
1336 for (ObjCCategoryImplDecl::classmeth_iterator
1337 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
1338 E = IMD ? IMD->classmeth_end() : CID->classmeth_end();
1339 I != E; ++I) {
1340 std::string ResultStr;
1341 ObjCMethodDecl *OMD = *I;
1342 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
1343 SourceLocation LocStart = OMD->getLocStart();
1344 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
1345
1346 const char *startBuf = SM->getCharacterData(LocStart);
1347 const char *endBuf = SM->getCharacterData(LocEnd);
1348 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
1349 }
1350 for (ObjCCategoryImplDecl::propimpl_iterator
1351 I = IMD ? IMD->propimpl_begin() : CID->propimpl_begin(),
1352 E = IMD ? IMD->propimpl_end() : CID->propimpl_end();
1353 I != E; ++I) {
David Blaikie581deb32012-06-06 20:45:41 +00001354 RewritePropertyImplDecl(*I, IMD, CID);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001355 }
1356
1357 InsertText(IMD ? IMD->getLocEnd() : CID->getLocEnd(), "// ");
1358}
1359
1360void RewriteModernObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00001361 // Do not synthesize more than once.
1362 if (ObjCSynthesizedStructs.count(ClassDecl))
1363 return;
1364 // Make sure super class's are written before current class is written.
1365 ObjCInterfaceDecl *SuperClass = ClassDecl->getSuperClass();
1366 while (SuperClass) {
1367 RewriteInterfaceDecl(SuperClass);
1368 SuperClass = SuperClass->getSuperClass();
1369 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001370 std::string ResultStr;
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +00001371 if (!ObjCWrittenInterfaces.count(ClassDecl->getCanonicalDecl())) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001372 // we haven't seen a forward decl - generate a typedef.
Fariborz Jahanianc38503b2012-03-12 23:58:28 +00001373 RewriteOneForwardClassDecl(ClassDecl, ResultStr);
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00001374 RewriteIvarOffsetSymbols(ClassDecl, ResultStr);
1375
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001376 RewriteObjCInternalStruct(ClassDecl, ResultStr);
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +00001377 // Mark this typedef as having been written into its c++ equivalent.
1378 ObjCWrittenInterfaces.insert(ClassDecl->getCanonicalDecl());
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001379
1380 for (ObjCInterfaceDecl::prop_iterator I = ClassDecl->prop_begin(),
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001381 E = ClassDecl->prop_end(); I != E; ++I)
David Blaikie581deb32012-06-06 20:45:41 +00001382 RewriteProperty(*I);
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001383 for (ObjCInterfaceDecl::instmeth_iterator
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001384 I = ClassDecl->instmeth_begin(), E = ClassDecl->instmeth_end();
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001385 I != E; ++I)
1386 RewriteMethodDeclaration(*I);
1387 for (ObjCInterfaceDecl::classmeth_iterator
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001388 I = ClassDecl->classmeth_begin(), E = ClassDecl->classmeth_end();
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001389 I != E; ++I)
1390 RewriteMethodDeclaration(*I);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001391
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001392 // Lastly, comment out the @end.
1393 ReplaceText(ClassDecl->getAtEndRange().getBegin(), strlen("@end"),
1394 "/* @end */");
1395 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001396}
1397
1398Stmt *RewriteModernObjC::RewritePropertyOrImplicitSetter(PseudoObjectExpr *PseudoOp) {
1399 SourceRange OldRange = PseudoOp->getSourceRange();
1400
1401 // We just magically know some things about the structure of this
1402 // expression.
1403 ObjCMessageExpr *OldMsg =
1404 cast<ObjCMessageExpr>(PseudoOp->getSemanticExpr(
1405 PseudoOp->getNumSemanticExprs() - 1));
1406
1407 // Because the rewriter doesn't allow us to rewrite rewritten code,
1408 // we need to suppress rewriting the sub-statements.
Fariborz Jahanian88ec6102012-04-10 22:06:54 +00001409 Expr *Base;
1410 SmallVector<Expr*, 2> Args;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001411 {
1412 DisableReplaceStmtScope S(*this);
1413
1414 // Rebuild the base expression if we have one.
1415 Base = 0;
1416 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1417 Base = OldMsg->getInstanceReceiver();
1418 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1419 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1420 }
Fariborz Jahanian88ec6102012-04-10 22:06:54 +00001421
1422 unsigned numArgs = OldMsg->getNumArgs();
1423 for (unsigned i = 0; i < numArgs; i++) {
1424 Expr *Arg = OldMsg->getArg(i);
1425 if (isa<OpaqueValueExpr>(Arg))
1426 Arg = cast<OpaqueValueExpr>(Arg)->getSourceExpr();
1427 Arg = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Arg));
1428 Args.push_back(Arg);
1429 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001430 }
1431
1432 // TODO: avoid this copy.
1433 SmallVector<SourceLocation, 1> SelLocs;
1434 OldMsg->getSelectorLocs(SelLocs);
1435
1436 ObjCMessageExpr *NewMsg = 0;
1437 switch (OldMsg->getReceiverKind()) {
1438 case ObjCMessageExpr::Class:
1439 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1440 OldMsg->getValueKind(),
1441 OldMsg->getLeftLoc(),
1442 OldMsg->getClassReceiverTypeInfo(),
1443 OldMsg->getSelector(),
1444 SelLocs,
1445 OldMsg->getMethodDecl(),
Fariborz Jahanian88ec6102012-04-10 22:06:54 +00001446 Args,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001447 OldMsg->getRightLoc(),
1448 OldMsg->isImplicit());
1449 break;
1450
1451 case ObjCMessageExpr::Instance:
1452 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1453 OldMsg->getValueKind(),
1454 OldMsg->getLeftLoc(),
1455 Base,
1456 OldMsg->getSelector(),
1457 SelLocs,
1458 OldMsg->getMethodDecl(),
Fariborz Jahanian88ec6102012-04-10 22:06:54 +00001459 Args,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001460 OldMsg->getRightLoc(),
1461 OldMsg->isImplicit());
1462 break;
1463
1464 case ObjCMessageExpr::SuperClass:
1465 case ObjCMessageExpr::SuperInstance:
1466 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1467 OldMsg->getValueKind(),
1468 OldMsg->getLeftLoc(),
1469 OldMsg->getSuperLoc(),
1470 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1471 OldMsg->getSuperType(),
1472 OldMsg->getSelector(),
1473 SelLocs,
1474 OldMsg->getMethodDecl(),
Fariborz Jahanian88ec6102012-04-10 22:06:54 +00001475 Args,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001476 OldMsg->getRightLoc(),
1477 OldMsg->isImplicit());
1478 break;
1479 }
1480
1481 Stmt *Replacement = SynthMessageExpr(NewMsg);
1482 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1483 return Replacement;
1484}
1485
1486Stmt *RewriteModernObjC::RewritePropertyOrImplicitGetter(PseudoObjectExpr *PseudoOp) {
1487 SourceRange OldRange = PseudoOp->getSourceRange();
1488
1489 // We just magically know some things about the structure of this
1490 // expression.
1491 ObjCMessageExpr *OldMsg =
1492 cast<ObjCMessageExpr>(PseudoOp->getResultExpr()->IgnoreImplicit());
1493
1494 // Because the rewriter doesn't allow us to rewrite rewritten code,
1495 // we need to suppress rewriting the sub-statements.
1496 Expr *Base = 0;
Fariborz Jahanian88ec6102012-04-10 22:06:54 +00001497 SmallVector<Expr*, 1> Args;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001498 {
1499 DisableReplaceStmtScope S(*this);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001500 // Rebuild the base expression if we have one.
1501 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1502 Base = OldMsg->getInstanceReceiver();
1503 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1504 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1505 }
Fariborz Jahanian88ec6102012-04-10 22:06:54 +00001506 unsigned numArgs = OldMsg->getNumArgs();
1507 for (unsigned i = 0; i < numArgs; i++) {
1508 Expr *Arg = OldMsg->getArg(i);
1509 if (isa<OpaqueValueExpr>(Arg))
1510 Arg = cast<OpaqueValueExpr>(Arg)->getSourceExpr();
1511 Arg = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Arg));
1512 Args.push_back(Arg);
1513 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001514 }
1515
1516 // Intentionally empty.
1517 SmallVector<SourceLocation, 1> SelLocs;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001518
1519 ObjCMessageExpr *NewMsg = 0;
1520 switch (OldMsg->getReceiverKind()) {
1521 case ObjCMessageExpr::Class:
1522 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1523 OldMsg->getValueKind(),
1524 OldMsg->getLeftLoc(),
1525 OldMsg->getClassReceiverTypeInfo(),
1526 OldMsg->getSelector(),
1527 SelLocs,
1528 OldMsg->getMethodDecl(),
1529 Args,
1530 OldMsg->getRightLoc(),
1531 OldMsg->isImplicit());
1532 break;
1533
1534 case ObjCMessageExpr::Instance:
1535 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1536 OldMsg->getValueKind(),
1537 OldMsg->getLeftLoc(),
1538 Base,
1539 OldMsg->getSelector(),
1540 SelLocs,
1541 OldMsg->getMethodDecl(),
1542 Args,
1543 OldMsg->getRightLoc(),
1544 OldMsg->isImplicit());
1545 break;
1546
1547 case ObjCMessageExpr::SuperClass:
1548 case ObjCMessageExpr::SuperInstance:
1549 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1550 OldMsg->getValueKind(),
1551 OldMsg->getLeftLoc(),
1552 OldMsg->getSuperLoc(),
1553 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1554 OldMsg->getSuperType(),
1555 OldMsg->getSelector(),
1556 SelLocs,
1557 OldMsg->getMethodDecl(),
1558 Args,
1559 OldMsg->getRightLoc(),
1560 OldMsg->isImplicit());
1561 break;
1562 }
1563
1564 Stmt *Replacement = SynthMessageExpr(NewMsg);
1565 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1566 return Replacement;
1567}
1568
1569/// SynthCountByEnumWithState - To print:
1570/// ((unsigned int (*)
1571/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1572/// (void *)objc_msgSend)((id)l_collection,
1573/// sel_registerName(
1574/// "countByEnumeratingWithState:objects:count:"),
1575/// &enumState,
1576/// (id *)__rw_items, (unsigned int)16)
1577///
1578void RewriteModernObjC::SynthCountByEnumWithState(std::string &buf) {
1579 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1580 "id *, unsigned int))(void *)objc_msgSend)";
1581 buf += "\n\t\t";
1582 buf += "((id)l_collection,\n\t\t";
1583 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1584 buf += "\n\t\t";
1585 buf += "&enumState, "
1586 "(id *)__rw_items, (unsigned int)16)";
1587}
1588
1589/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1590/// statement to exit to its outer synthesized loop.
1591///
1592Stmt *RewriteModernObjC::RewriteBreakStmt(BreakStmt *S) {
1593 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1594 return S;
1595 // replace break with goto __break_label
1596 std::string buf;
1597
1598 SourceLocation startLoc = S->getLocStart();
1599 buf = "goto __break_label_";
1600 buf += utostr(ObjCBcLabelNo.back());
1601 ReplaceText(startLoc, strlen("break"), buf);
1602
1603 return 0;
1604}
1605
1606/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1607/// statement to continue with its inner synthesized loop.
1608///
1609Stmt *RewriteModernObjC::RewriteContinueStmt(ContinueStmt *S) {
1610 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1611 return S;
1612 // replace continue with goto __continue_label
1613 std::string buf;
1614
1615 SourceLocation startLoc = S->getLocStart();
1616 buf = "goto __continue_label_";
1617 buf += utostr(ObjCBcLabelNo.back());
1618 ReplaceText(startLoc, strlen("continue"), buf);
1619
1620 return 0;
1621}
1622
1623/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
1624/// It rewrites:
1625/// for ( type elem in collection) { stmts; }
1626
1627/// Into:
1628/// {
1629/// type elem;
1630/// struct __objcFastEnumerationState enumState = { 0 };
1631/// id __rw_items[16];
1632/// id l_collection = (id)collection;
1633/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1634/// objects:__rw_items count:16];
1635/// if (limit) {
1636/// unsigned long startMutations = *enumState.mutationsPtr;
1637/// do {
1638/// unsigned long counter = 0;
1639/// do {
1640/// if (startMutations != *enumState.mutationsPtr)
1641/// objc_enumerationMutation(l_collection);
1642/// elem = (type)enumState.itemsPtr[counter++];
1643/// stmts;
1644/// __continue_label: ;
1645/// } while (counter < limit);
1646/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1647/// objects:__rw_items count:16]);
1648/// elem = nil;
1649/// __break_label: ;
1650/// }
1651/// else
1652/// elem = nil;
1653/// }
1654///
1655Stmt *RewriteModernObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
1656 SourceLocation OrigEnd) {
1657 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
1658 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
1659 "ObjCForCollectionStmt Statement stack mismatch");
1660 assert(!ObjCBcLabelNo.empty() &&
1661 "ObjCForCollectionStmt - Label No stack empty");
1662
1663 SourceLocation startLoc = S->getLocStart();
1664 const char *startBuf = SM->getCharacterData(startLoc);
1665 StringRef elementName;
1666 std::string elementTypeAsString;
1667 std::string buf;
1668 buf = "\n{\n\t";
1669 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1670 // type elem;
1671 NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
1672 QualType ElementType = cast<ValueDecl>(D)->getType();
1673 if (ElementType->isObjCQualifiedIdType() ||
1674 ElementType->isObjCQualifiedInterfaceType())
1675 // Simply use 'id' for all qualified types.
1676 elementTypeAsString = "id";
1677 else
1678 elementTypeAsString = ElementType.getAsString(Context->getPrintingPolicy());
1679 buf += elementTypeAsString;
1680 buf += " ";
1681 elementName = D->getName();
1682 buf += elementName;
1683 buf += ";\n\t";
1684 }
1685 else {
1686 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
1687 elementName = DR->getDecl()->getName();
1688 ValueDecl *VD = cast<ValueDecl>(DR->getDecl());
1689 if (VD->getType()->isObjCQualifiedIdType() ||
1690 VD->getType()->isObjCQualifiedInterfaceType())
1691 // Simply use 'id' for all qualified types.
1692 elementTypeAsString = "id";
1693 else
1694 elementTypeAsString = VD->getType().getAsString(Context->getPrintingPolicy());
1695 }
1696
1697 // struct __objcFastEnumerationState enumState = { 0 };
1698 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1699 // id __rw_items[16];
1700 buf += "id __rw_items[16];\n\t";
1701 // id l_collection = (id)
1702 buf += "id l_collection = (id)";
1703 // Find start location of 'collection' the hard way!
1704 const char *startCollectionBuf = startBuf;
1705 startCollectionBuf += 3; // skip 'for'
1706 startCollectionBuf = strchr(startCollectionBuf, '(');
1707 startCollectionBuf++; // skip '('
1708 // find 'in' and skip it.
1709 while (*startCollectionBuf != ' ' ||
1710 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1711 (*(startCollectionBuf+3) != ' ' &&
1712 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1713 startCollectionBuf++;
1714 startCollectionBuf += 3;
1715
1716 // Replace: "for (type element in" with string constructed thus far.
1717 ReplaceText(startLoc, startCollectionBuf - startBuf, buf);
1718 // Replace ')' in for '(' type elem in collection ')' with ';'
1719 SourceLocation rightParenLoc = S->getRParenLoc();
1720 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1721 SourceLocation lparenLoc = startLoc.getLocWithOffset(rparenBuf-startBuf);
1722 buf = ";\n\t";
1723
1724 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1725 // objects:__rw_items count:16];
1726 // which is synthesized into:
1727 // unsigned int limit =
1728 // ((unsigned int (*)
1729 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1730 // (void *)objc_msgSend)((id)l_collection,
1731 // sel_registerName(
1732 // "countByEnumeratingWithState:objects:count:"),
1733 // (struct __objcFastEnumerationState *)&state,
1734 // (id *)__rw_items, (unsigned int)16);
1735 buf += "unsigned long limit =\n\t\t";
1736 SynthCountByEnumWithState(buf);
1737 buf += ";\n\t";
1738 /// if (limit) {
1739 /// unsigned long startMutations = *enumState.mutationsPtr;
1740 /// do {
1741 /// unsigned long counter = 0;
1742 /// do {
1743 /// if (startMutations != *enumState.mutationsPtr)
1744 /// objc_enumerationMutation(l_collection);
1745 /// elem = (type)enumState.itemsPtr[counter++];
1746 buf += "if (limit) {\n\t";
1747 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1748 buf += "do {\n\t\t";
1749 buf += "unsigned long counter = 0;\n\t\t";
1750 buf += "do {\n\t\t\t";
1751 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1752 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1753 buf += elementName;
1754 buf += " = (";
1755 buf += elementTypeAsString;
1756 buf += ")enumState.itemsPtr[counter++];";
1757 // Replace ')' in for '(' type elem in collection ')' with all of these.
1758 ReplaceText(lparenLoc, 1, buf);
1759
1760 /// __continue_label: ;
1761 /// } while (counter < limit);
1762 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1763 /// objects:__rw_items count:16]);
1764 /// elem = nil;
1765 /// __break_label: ;
1766 /// }
1767 /// else
1768 /// elem = nil;
1769 /// }
1770 ///
1771 buf = ";\n\t";
1772 buf += "__continue_label_";
1773 buf += utostr(ObjCBcLabelNo.back());
1774 buf += ": ;";
1775 buf += "\n\t\t";
1776 buf += "} while (counter < limit);\n\t";
1777 buf += "} while (limit = ";
1778 SynthCountByEnumWithState(buf);
1779 buf += ");\n\t";
1780 buf += elementName;
1781 buf += " = ((";
1782 buf += elementTypeAsString;
1783 buf += ")0);\n\t";
1784 buf += "__break_label_";
1785 buf += utostr(ObjCBcLabelNo.back());
1786 buf += ": ;\n\t";
1787 buf += "}\n\t";
1788 buf += "else\n\t\t";
1789 buf += elementName;
1790 buf += " = ((";
1791 buf += elementTypeAsString;
1792 buf += ")0);\n\t";
1793 buf += "}\n";
1794
1795 // Insert all these *after* the statement body.
1796 // FIXME: If this should support Obj-C++, support CXXTryStmt
1797 if (isa<CompoundStmt>(S->getBody())) {
1798 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(1);
1799 InsertText(endBodyLoc, buf);
1800 } else {
1801 /* Need to treat single statements specially. For example:
1802 *
1803 * for (A *a in b) if (stuff()) break;
1804 * for (A *a in b) xxxyy;
1805 *
1806 * The following code simply scans ahead to the semi to find the actual end.
1807 */
1808 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1809 const char *semiBuf = strchr(stmtBuf, ';');
1810 assert(semiBuf && "Can't find ';'");
1811 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(semiBuf-stmtBuf+1);
1812 InsertText(endBodyLoc, buf);
1813 }
1814 Stmts.pop_back();
1815 ObjCBcLabelNo.pop_back();
1816 return 0;
1817}
1818
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001819static void Write_RethrowObject(std::string &buf) {
1820 buf += "{ struct _FIN { _FIN(id reth) : rethrow(reth) {}\n";
1821 buf += "\t~_FIN() { if (rethrow) objc_exception_throw(rethrow); }\n";
1822 buf += "\tid rethrow;\n";
1823 buf += "\t} _fin_force_rethow(_rethrow);";
1824}
1825
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001826/// RewriteObjCSynchronizedStmt -
1827/// This routine rewrites @synchronized(expr) stmt;
1828/// into:
1829/// objc_sync_enter(expr);
1830/// @try stmt @finally { objc_sync_exit(expr); }
1831///
1832Stmt *RewriteModernObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
1833 // Get the start location and compute the semi location.
1834 SourceLocation startLoc = S->getLocStart();
1835 const char *startBuf = SM->getCharacterData(startLoc);
1836
1837 assert((*startBuf == '@') && "bogus @synchronized location");
1838
1839 std::string buf;
Fariborz Jahanian22e2f852012-03-17 17:46:02 +00001840 buf = "{ id _rethrow = 0; id _sync_obj = ";
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001841
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001842 const char *lparenBuf = startBuf;
1843 while (*lparenBuf != '(') lparenBuf++;
1844 ReplaceText(startLoc, lparenBuf-startBuf+1, buf);
Fariborz Jahanian22e2f852012-03-17 17:46:02 +00001845
1846 buf = "; objc_sync_enter(_sync_obj);\n";
1847 buf += "try {\n\tstruct _SYNC_EXIT { _SYNC_EXIT(id arg) : sync_exit(arg) {}";
1848 buf += "\n\t~_SYNC_EXIT() {objc_sync_exit(sync_exit);}";
1849 buf += "\n\tid sync_exit;";
1850 buf += "\n\t} _sync_exit(_sync_obj);\n";
1851
1852 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1853 // the sync expression is typically a message expression that's already
1854 // been rewritten! (which implies the SourceLocation's are invalid).
1855 SourceLocation RParenExprLoc = S->getSynchBody()->getLocStart();
1856 const char *RParenExprLocBuf = SM->getCharacterData(RParenExprLoc);
1857 while (*RParenExprLocBuf != ')') RParenExprLocBuf--;
1858 RParenExprLoc = startLoc.getLocWithOffset(RParenExprLocBuf-startBuf);
1859
1860 SourceLocation LBranceLoc = S->getSynchBody()->getLocStart();
1861 const char *LBraceLocBuf = SM->getCharacterData(LBranceLoc);
1862 assert (*LBraceLocBuf == '{');
1863 ReplaceText(RParenExprLoc, (LBraceLocBuf - SM->getCharacterData(RParenExprLoc) + 1), buf);
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001864
Fariborz Jahanianb655bf02012-03-16 21:43:45 +00001865 SourceLocation startRBraceLoc = S->getSynchBody()->getLocEnd();
Matt Beaumont-Gay9ab511c2012-03-16 22:20:39 +00001866 assert((*SM->getCharacterData(startRBraceLoc) == '}') &&
1867 "bogus @synchronized block");
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001868
1869 buf = "} catch (id e) {_rethrow = e;}\n";
1870 Write_RethrowObject(buf);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001871 buf += "}\n";
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001872 buf += "}\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001873
Fariborz Jahanianb655bf02012-03-16 21:43:45 +00001874 ReplaceText(startRBraceLoc, 1, buf);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001875
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001876 return 0;
1877}
1878
1879void RewriteModernObjC::WarnAboutReturnGotoStmts(Stmt *S)
1880{
1881 // Perform a bottom up traversal of all children.
1882 for (Stmt::child_range CI = S->children(); CI; ++CI)
1883 if (*CI)
1884 WarnAboutReturnGotoStmts(*CI);
1885
1886 if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
1887 Diags.Report(Context->getFullLoc(S->getLocStart()),
1888 TryFinallyContainsReturnDiag);
1889 }
1890 return;
1891}
1892
Fariborz Jahanian042b91d2012-05-23 23:47:20 +00001893Stmt *RewriteModernObjC::RewriteObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S) {
1894 SourceLocation startLoc = S->getAtLoc();
1895 ReplaceText(startLoc, strlen("@autoreleasepool"), "/* @autoreleasepool */");
Fariborz Jahanianc9b72b62012-05-24 22:59:56 +00001896 ReplaceText(S->getSubStmt()->getLocStart(), 1,
1897 "{ __AtAutoreleasePool __autoreleasepool; ");
Fariborz Jahanian042b91d2012-05-23 23:47:20 +00001898
1899 return 0;
1900}
1901
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001902Stmt *RewriteModernObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Fariborz Jahanianb1228182012-03-15 22:42:15 +00001903 ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt();
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001904 bool noCatch = S->getNumCatchStmts() == 0;
Fariborz Jahanianb1228182012-03-15 22:42:15 +00001905 std::string buf;
1906
1907 if (finalStmt) {
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001908 if (noCatch)
1909 buf = "{ id volatile _rethrow = 0;\n";
1910 else {
1911 buf = "{ id volatile _rethrow = 0;\ntry {\n";
1912 }
Fariborz Jahanianb1228182012-03-15 22:42:15 +00001913 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001914 // Get the start location and compute the semi location.
1915 SourceLocation startLoc = S->getLocStart();
1916 const char *startBuf = SM->getCharacterData(startLoc);
1917
1918 assert((*startBuf == '@') && "bogus @try location");
Fariborz Jahanianb1228182012-03-15 22:42:15 +00001919 if (finalStmt)
1920 ReplaceText(startLoc, 1, buf);
1921 else
1922 // @try -> try
1923 ReplaceText(startLoc, 1, "");
1924
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001925 for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I) {
1926 ObjCAtCatchStmt *Catch = S->getCatchStmt(I);
Fariborz Jahanian4c148812012-03-15 20:11:10 +00001927 VarDecl *catchDecl = Catch->getCatchParamDecl();
Fariborz Jahanianc38503b2012-03-12 23:58:28 +00001928
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001929 startLoc = Catch->getLocStart();
Fariborz Jahanian4c148812012-03-15 20:11:10 +00001930 bool AtRemoved = false;
1931 if (catchDecl) {
1932 QualType t = catchDecl->getType();
1933 if (const ObjCObjectPointerType *Ptr = t->getAs<ObjCObjectPointerType>()) {
1934 // Should be a pointer to a class.
1935 ObjCInterfaceDecl *IDecl = Ptr->getObjectType()->getInterface();
1936 if (IDecl) {
1937 std::string Result;
1938 startBuf = SM->getCharacterData(startLoc);
1939 assert((*startBuf == '@') && "bogus @catch location");
1940 SourceLocation rParenLoc = Catch->getRParenLoc();
1941 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1942
1943 // _objc_exc_Foo *_e as argument to catch.
1944 Result = "catch (_objc_exc_"; Result += IDecl->getNameAsString();
1945 Result += " *_"; Result += catchDecl->getNameAsString();
1946 Result += ")";
1947 ReplaceText(startLoc, rParenBuf-startBuf+1, Result);
1948 // Foo *e = (Foo *)_e;
1949 Result.clear();
1950 Result = "{ ";
1951 Result += IDecl->getNameAsString();
1952 Result += " *"; Result += catchDecl->getNameAsString();
1953 Result += " = ("; Result += IDecl->getNameAsString(); Result += "*)";
1954 Result += "_"; Result += catchDecl->getNameAsString();
1955
1956 Result += "; ";
1957 SourceLocation lBraceLoc = Catch->getCatchBody()->getLocStart();
1958 ReplaceText(lBraceLoc, 1, Result);
1959 AtRemoved = true;
1960 }
1961 }
1962 }
1963 if (!AtRemoved)
1964 // @catch -> catch
1965 ReplaceText(startLoc, 1, "");
Fariborz Jahanianc38503b2012-03-12 23:58:28 +00001966
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001967 }
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001968 if (finalStmt) {
1969 buf.clear();
1970 if (noCatch)
1971 buf = "catch (id e) {_rethrow = e;}\n";
1972 else
1973 buf = "}\ncatch (id e) {_rethrow = e;}\n";
1974
1975 SourceLocation startFinalLoc = finalStmt->getLocStart();
1976 ReplaceText(startFinalLoc, 8, buf);
1977 Stmt *body = finalStmt->getFinallyBody();
1978 SourceLocation startFinalBodyLoc = body->getLocStart();
1979 buf.clear();
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001980 Write_RethrowObject(buf);
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001981 ReplaceText(startFinalBodyLoc, 1, buf);
1982
1983 SourceLocation endFinalBodyLoc = body->getLocEnd();
1984 ReplaceText(endFinalBodyLoc, 1, "}\n}");
Fariborz Jahanian22e2f852012-03-17 17:46:02 +00001985 // Now check for any return/continue/go statements within the @try.
1986 WarnAboutReturnGotoStmts(S->getTryBody());
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001987 }
1988
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001989 return 0;
1990}
1991
1992// This can't be done with ReplaceStmt(S, ThrowExpr), since
1993// the throw expression is typically a message expression that's already
1994// been rewritten! (which implies the SourceLocation's are invalid).
1995Stmt *RewriteModernObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
1996 // Get the start location and compute the semi location.
1997 SourceLocation startLoc = S->getLocStart();
1998 const char *startBuf = SM->getCharacterData(startLoc);
1999
2000 assert((*startBuf == '@') && "bogus @throw location");
2001
2002 std::string buf;
2003 /* void objc_exception_throw(id) __attribute__((noreturn)); */
2004 if (S->getThrowExpr())
2005 buf = "objc_exception_throw(";
Fariborz Jahanian40539462012-03-16 16:52:06 +00002006 else
2007 buf = "throw";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002008
2009 // handle "@ throw" correctly.
2010 const char *wBuf = strchr(startBuf, 'w');
2011 assert((*wBuf == 'w') && "@throw: can't find 'w'");
2012 ReplaceText(startLoc, wBuf-startBuf+1, buf);
2013
2014 const char *semiBuf = strchr(startBuf, ';');
2015 assert((*semiBuf == ';') && "@throw: can't find ';'");
2016 SourceLocation semiLoc = startLoc.getLocWithOffset(semiBuf-startBuf);
Fariborz Jahanian40539462012-03-16 16:52:06 +00002017 if (S->getThrowExpr())
2018 ReplaceText(semiLoc, 1, ");");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002019 return 0;
2020}
2021
2022Stmt *RewriteModernObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
2023 // Create a new string expression.
2024 QualType StrType = Context->getPointerType(Context->CharTy);
2025 std::string StrEncoding;
2026 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
2027 Expr *Replacement = StringLiteral::Create(*Context, StrEncoding,
2028 StringLiteral::Ascii, false,
2029 StrType, SourceLocation());
2030 ReplaceStmt(Exp, Replacement);
2031
2032 // Replace this subexpr in the parent.
2033 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2034 return Replacement;
2035}
2036
2037Stmt *RewriteModernObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
2038 if (!SelGetUidFunctionDecl)
2039 SynthSelGetUidFunctionDecl();
2040 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
2041 // Create a call to sel_registerName("selName").
2042 SmallVector<Expr*, 8> SelExprs;
2043 QualType argType = Context->getPointerType(Context->CharTy);
2044 SelExprs.push_back(StringLiteral::Create(*Context,
2045 Exp->getSelector().getAsString(),
2046 StringLiteral::Ascii, false,
2047 argType, SourceLocation()));
2048 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2049 &SelExprs[0], SelExprs.size());
2050 ReplaceStmt(Exp, SelExp);
2051 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2052 return SelExp;
2053}
2054
2055CallExpr *RewriteModernObjC::SynthesizeCallToFunctionDecl(
2056 FunctionDecl *FD, Expr **args, unsigned nargs, SourceLocation StartLoc,
2057 SourceLocation EndLoc) {
2058 // Get the type, we will need to reference it in a couple spots.
2059 QualType msgSendType = FD->getType();
2060
2061 // Create a reference to the objc_msgSend() declaration.
2062 DeclRefExpr *DRE =
John McCallf4b88a42012-03-10 09:33:50 +00002063 new (Context) DeclRefExpr(FD, false, msgSendType, VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002064
2065 // Now, we cast the reference to a pointer to the objc_msgSend type.
2066 QualType pToFunc = Context->getPointerType(msgSendType);
2067 ImplicitCastExpr *ICE =
2068 ImplicitCastExpr::Create(*Context, pToFunc, CK_FunctionToPointerDecay,
2069 DRE, 0, VK_RValue);
2070
2071 const FunctionType *FT = msgSendType->getAs<FunctionType>();
2072
2073 CallExpr *Exp =
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002074 new (Context) CallExpr(*Context, ICE, llvm::makeArrayRef(args, nargs),
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002075 FT->getCallResultType(*Context),
2076 VK_RValue, EndLoc);
2077 return Exp;
2078}
2079
2080static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
2081 const char *&startRef, const char *&endRef) {
2082 while (startBuf < endBuf) {
2083 if (*startBuf == '<')
2084 startRef = startBuf; // mark the start.
2085 if (*startBuf == '>') {
2086 if (startRef && *startRef == '<') {
2087 endRef = startBuf; // mark the end.
2088 return true;
2089 }
2090 return false;
2091 }
2092 startBuf++;
2093 }
2094 return false;
2095}
2096
2097static void scanToNextArgument(const char *&argRef) {
2098 int angle = 0;
2099 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
2100 if (*argRef == '<')
2101 angle++;
2102 else if (*argRef == '>')
2103 angle--;
2104 argRef++;
2105 }
2106 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
2107}
2108
2109bool RewriteModernObjC::needToScanForQualifiers(QualType T) {
2110 if (T->isObjCQualifiedIdType())
2111 return true;
2112 if (const PointerType *PT = T->getAs<PointerType>()) {
2113 if (PT->getPointeeType()->isObjCQualifiedIdType())
2114 return true;
2115 }
2116 if (T->isObjCObjectPointerType()) {
2117 T = T->getPointeeType();
2118 return T->isObjCQualifiedInterfaceType();
2119 }
2120 if (T->isArrayType()) {
2121 QualType ElemTy = Context->getBaseElementType(T);
2122 return needToScanForQualifiers(ElemTy);
2123 }
2124 return false;
2125}
2126
2127void RewriteModernObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
2128 QualType Type = E->getType();
2129 if (needToScanForQualifiers(Type)) {
2130 SourceLocation Loc, EndLoc;
2131
2132 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
2133 Loc = ECE->getLParenLoc();
2134 EndLoc = ECE->getRParenLoc();
2135 } else {
2136 Loc = E->getLocStart();
2137 EndLoc = E->getLocEnd();
2138 }
2139 // This will defend against trying to rewrite synthesized expressions.
2140 if (Loc.isInvalid() || EndLoc.isInvalid())
2141 return;
2142
2143 const char *startBuf = SM->getCharacterData(Loc);
2144 const char *endBuf = SM->getCharacterData(EndLoc);
2145 const char *startRef = 0, *endRef = 0;
2146 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2147 // Get the locations of the startRef, endRef.
2148 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-startBuf);
2149 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-startBuf+1);
2150 // Comment out the protocol references.
2151 InsertText(LessLoc, "/*");
2152 InsertText(GreaterLoc, "*/");
2153 }
2154 }
2155}
2156
2157void RewriteModernObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
2158 SourceLocation Loc;
2159 QualType Type;
2160 const FunctionProtoType *proto = 0;
2161 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
2162 Loc = VD->getLocation();
2163 Type = VD->getType();
2164 }
2165 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
2166 Loc = FD->getLocation();
2167 // Check for ObjC 'id' and class types that have been adorned with protocol
2168 // information (id<p>, C<p>*). The protocol references need to be rewritten!
2169 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2170 assert(funcType && "missing function type");
2171 proto = dyn_cast<FunctionProtoType>(funcType);
2172 if (!proto)
2173 return;
2174 Type = proto->getResultType();
2175 }
2176 else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
2177 Loc = FD->getLocation();
2178 Type = FD->getType();
2179 }
2180 else
2181 return;
2182
2183 if (needToScanForQualifiers(Type)) {
2184 // Since types are unique, we need to scan the buffer.
2185
2186 const char *endBuf = SM->getCharacterData(Loc);
2187 const char *startBuf = endBuf;
2188 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
2189 startBuf--; // scan backward (from the decl location) for return type.
2190 const char *startRef = 0, *endRef = 0;
2191 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2192 // Get the locations of the startRef, endRef.
2193 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-endBuf);
2194 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-endBuf+1);
2195 // Comment out the protocol references.
2196 InsertText(LessLoc, "/*");
2197 InsertText(GreaterLoc, "*/");
2198 }
2199 }
2200 if (!proto)
2201 return; // most likely, was a variable
2202 // Now check arguments.
2203 const char *startBuf = SM->getCharacterData(Loc);
2204 const char *startFuncBuf = startBuf;
2205 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
2206 if (needToScanForQualifiers(proto->getArgType(i))) {
2207 // Since types are unique, we need to scan the buffer.
2208
2209 const char *endBuf = startBuf;
2210 // scan forward (from the decl location) for argument types.
2211 scanToNextArgument(endBuf);
2212 const char *startRef = 0, *endRef = 0;
2213 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2214 // Get the locations of the startRef, endRef.
2215 SourceLocation LessLoc =
2216 Loc.getLocWithOffset(startRef-startFuncBuf);
2217 SourceLocation GreaterLoc =
2218 Loc.getLocWithOffset(endRef-startFuncBuf+1);
2219 // Comment out the protocol references.
2220 InsertText(LessLoc, "/*");
2221 InsertText(GreaterLoc, "*/");
2222 }
2223 startBuf = ++endBuf;
2224 }
2225 else {
2226 // If the function name is derived from a macro expansion, then the
2227 // argument buffer will not follow the name. Need to speak with Chris.
2228 while (*startBuf && *startBuf != ')' && *startBuf != ',')
2229 startBuf++; // scan forward (from the decl location) for argument types.
2230 startBuf++;
2231 }
2232 }
2233}
2234
2235void RewriteModernObjC::RewriteTypeOfDecl(VarDecl *ND) {
2236 QualType QT = ND->getType();
2237 const Type* TypePtr = QT->getAs<Type>();
2238 if (!isa<TypeOfExprType>(TypePtr))
2239 return;
2240 while (isa<TypeOfExprType>(TypePtr)) {
2241 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
2242 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
2243 TypePtr = QT->getAs<Type>();
2244 }
2245 // FIXME. This will not work for multiple declarators; as in:
2246 // __typeof__(a) b,c,d;
2247 std::string TypeAsString(QT.getAsString(Context->getPrintingPolicy()));
2248 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
2249 const char *startBuf = SM->getCharacterData(DeclLoc);
2250 if (ND->getInit()) {
2251 std::string Name(ND->getNameAsString());
2252 TypeAsString += " " + Name + " = ";
2253 Expr *E = ND->getInit();
2254 SourceLocation startLoc;
2255 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
2256 startLoc = ECE->getLParenLoc();
2257 else
2258 startLoc = E->getLocStart();
2259 startLoc = SM->getExpansionLoc(startLoc);
2260 const char *endBuf = SM->getCharacterData(startLoc);
2261 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
2262 }
2263 else {
2264 SourceLocation X = ND->getLocEnd();
2265 X = SM->getExpansionLoc(X);
2266 const char *endBuf = SM->getCharacterData(X);
2267 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
2268 }
2269}
2270
2271// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
2272void RewriteModernObjC::SynthSelGetUidFunctionDecl() {
2273 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
2274 SmallVector<QualType, 16> ArgTys;
2275 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2276 QualType getFuncType =
2277 getSimpleFunctionType(Context->getObjCSelType(), &ArgTys[0], ArgTys.size());
2278 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2279 SourceLocation(),
2280 SourceLocation(),
2281 SelGetUidIdent, getFuncType, 0,
2282 SC_Extern,
2283 SC_None, false);
2284}
2285
2286void RewriteModernObjC::RewriteFunctionDecl(FunctionDecl *FD) {
2287 // declared in <objc/objc.h>
2288 if (FD->getIdentifier() &&
2289 FD->getName() == "sel_registerName") {
2290 SelGetUidFunctionDecl = FD;
2291 return;
2292 }
2293 RewriteObjCQualifiedInterfaceTypes(FD);
2294}
2295
2296void RewriteModernObjC::RewriteBlockPointerType(std::string& Str, QualType Type) {
2297 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
2298 const char *argPtr = TypeString.c_str();
2299 if (!strchr(argPtr, '^')) {
2300 Str += TypeString;
2301 return;
2302 }
2303 while (*argPtr) {
2304 Str += (*argPtr == '^' ? '*' : *argPtr);
2305 argPtr++;
2306 }
2307}
2308
2309// FIXME. Consolidate this routine with RewriteBlockPointerType.
2310void RewriteModernObjC::RewriteBlockPointerTypeVariable(std::string& Str,
2311 ValueDecl *VD) {
2312 QualType Type = VD->getType();
2313 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
2314 const char *argPtr = TypeString.c_str();
2315 int paren = 0;
2316 while (*argPtr) {
2317 switch (*argPtr) {
2318 case '(':
2319 Str += *argPtr;
2320 paren++;
2321 break;
2322 case ')':
2323 Str += *argPtr;
2324 paren--;
2325 break;
2326 case '^':
2327 Str += '*';
2328 if (paren == 1)
2329 Str += VD->getNameAsString();
2330 break;
2331 default:
2332 Str += *argPtr;
2333 break;
2334 }
2335 argPtr++;
2336 }
2337}
2338
Fariborz Jahanianb75f8de2012-04-19 00:50:01 +00002339void RewriteModernObjC::RewriteBlockLiteralFunctionDecl(FunctionDecl *FD) {
2340 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
2341 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2342 const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(funcType);
2343 if (!proto)
2344 return;
2345 QualType Type = proto->getResultType();
2346 std::string FdStr = Type.getAsString(Context->getPrintingPolicy());
2347 FdStr += " ";
2348 FdStr += FD->getName();
2349 FdStr += "(";
2350 unsigned numArgs = proto->getNumArgs();
2351 for (unsigned i = 0; i < numArgs; i++) {
2352 QualType ArgType = proto->getArgType(i);
2353 RewriteBlockPointerType(FdStr, ArgType);
2354 if (i+1 < numArgs)
2355 FdStr += ", ";
2356 }
Fariborz Jahanianb5863da2012-04-19 16:30:28 +00002357 if (FD->isVariadic()) {
2358 FdStr += (numArgs > 0) ? ", ...);\n" : "...);\n";
2359 }
2360 else
2361 FdStr += ");\n";
Fariborz Jahanianb75f8de2012-04-19 00:50:01 +00002362 InsertText(FunLocStart, FdStr);
2363}
2364
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002365// SynthSuperContructorFunctionDecl - id __rw_objc_super(id obj, id super);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002366void RewriteModernObjC::SynthSuperContructorFunctionDecl() {
2367 if (SuperContructorFunctionDecl)
2368 return;
2369 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
2370 SmallVector<QualType, 16> ArgTys;
2371 QualType argT = Context->getObjCIdType();
2372 assert(!argT.isNull() && "Can't find 'id' type");
2373 ArgTys.push_back(argT);
2374 ArgTys.push_back(argT);
2375 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2376 &ArgTys[0], ArgTys.size());
2377 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2378 SourceLocation(),
2379 SourceLocation(),
2380 msgSendIdent, msgSendType, 0,
2381 SC_Extern,
2382 SC_None, false);
2383}
2384
2385// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
2386void RewriteModernObjC::SynthMsgSendFunctionDecl() {
2387 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
2388 SmallVector<QualType, 16> ArgTys;
2389 QualType argT = Context->getObjCIdType();
2390 assert(!argT.isNull() && "Can't find 'id' type");
2391 ArgTys.push_back(argT);
2392 argT = Context->getObjCSelType();
2393 assert(!argT.isNull() && "Can't find 'SEL' type");
2394 ArgTys.push_back(argT);
2395 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2396 &ArgTys[0], ArgTys.size(),
2397 true /*isVariadic*/);
2398 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2399 SourceLocation(),
2400 SourceLocation(),
2401 msgSendIdent, msgSendType, 0,
2402 SC_Extern,
2403 SC_None, false);
2404}
2405
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002406// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(void);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002407void RewriteModernObjC::SynthMsgSendSuperFunctionDecl() {
2408 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002409 SmallVector<QualType, 2> ArgTys;
2410 ArgTys.push_back(Context->VoidTy);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002411 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002412 &ArgTys[0], 1,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002413 true /*isVariadic*/);
2414 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2415 SourceLocation(),
2416 SourceLocation(),
2417 msgSendIdent, msgSendType, 0,
2418 SC_Extern,
2419 SC_None, false);
2420}
2421
2422// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
2423void RewriteModernObjC::SynthMsgSendStretFunctionDecl() {
2424 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
2425 SmallVector<QualType, 16> ArgTys;
2426 QualType argT = Context->getObjCIdType();
2427 assert(!argT.isNull() && "Can't find 'id' type");
2428 ArgTys.push_back(argT);
2429 argT = Context->getObjCSelType();
2430 assert(!argT.isNull() && "Can't find 'SEL' type");
2431 ArgTys.push_back(argT);
2432 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2433 &ArgTys[0], ArgTys.size(),
2434 true /*isVariadic*/);
2435 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2436 SourceLocation(),
2437 SourceLocation(),
2438 msgSendIdent, msgSendType, 0,
2439 SC_Extern,
2440 SC_None, false);
2441}
2442
2443// SynthMsgSendSuperStretFunctionDecl -
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002444// id objc_msgSendSuper_stret(void);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002445void RewriteModernObjC::SynthMsgSendSuperStretFunctionDecl() {
2446 IdentifierInfo *msgSendIdent =
2447 &Context->Idents.get("objc_msgSendSuper_stret");
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002448 SmallVector<QualType, 2> ArgTys;
2449 ArgTys.push_back(Context->VoidTy);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002450 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002451 &ArgTys[0], 1,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002452 true /*isVariadic*/);
2453 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2454 SourceLocation(),
2455 SourceLocation(),
2456 msgSendIdent, msgSendType, 0,
2457 SC_Extern,
2458 SC_None, false);
2459}
2460
2461// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
2462void RewriteModernObjC::SynthMsgSendFpretFunctionDecl() {
2463 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
2464 SmallVector<QualType, 16> ArgTys;
2465 QualType argT = Context->getObjCIdType();
2466 assert(!argT.isNull() && "Can't find 'id' type");
2467 ArgTys.push_back(argT);
2468 argT = Context->getObjCSelType();
2469 assert(!argT.isNull() && "Can't find 'SEL' type");
2470 ArgTys.push_back(argT);
2471 QualType msgSendType = getSimpleFunctionType(Context->DoubleTy,
2472 &ArgTys[0], ArgTys.size(),
2473 true /*isVariadic*/);
2474 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2475 SourceLocation(),
2476 SourceLocation(),
2477 msgSendIdent, msgSendType, 0,
2478 SC_Extern,
2479 SC_None, false);
2480}
2481
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00002482// SynthGetClassFunctionDecl - Class objc_getClass(const char *name);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002483void RewriteModernObjC::SynthGetClassFunctionDecl() {
2484 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
2485 SmallVector<QualType, 16> ArgTys;
2486 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00002487 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002488 &ArgTys[0], ArgTys.size());
2489 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2490 SourceLocation(),
2491 SourceLocation(),
2492 getClassIdent, getClassType, 0,
2493 SC_Extern,
2494 SC_None, false);
2495}
2496
2497// SynthGetSuperClassFunctionDecl - Class class_getSuperclass(Class cls);
2498void RewriteModernObjC::SynthGetSuperClassFunctionDecl() {
2499 IdentifierInfo *getSuperClassIdent =
2500 &Context->Idents.get("class_getSuperclass");
2501 SmallVector<QualType, 16> ArgTys;
2502 ArgTys.push_back(Context->getObjCClassType());
2503 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
2504 &ArgTys[0], ArgTys.size());
2505 GetSuperClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2506 SourceLocation(),
2507 SourceLocation(),
2508 getSuperClassIdent,
2509 getClassType, 0,
2510 SC_Extern,
2511 SC_None,
2512 false);
2513}
2514
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00002515// SynthGetMetaClassFunctionDecl - Class objc_getMetaClass(const char *name);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002516void RewriteModernObjC::SynthGetMetaClassFunctionDecl() {
2517 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
2518 SmallVector<QualType, 16> ArgTys;
2519 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00002520 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002521 &ArgTys[0], ArgTys.size());
2522 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2523 SourceLocation(),
2524 SourceLocation(),
2525 getClassIdent, getClassType, 0,
2526 SC_Extern,
2527 SC_None, false);
2528}
2529
2530Stmt *RewriteModernObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
2531 QualType strType = getConstantStringStructType();
2532
2533 std::string S = "__NSConstantStringImpl_";
2534
2535 std::string tmpName = InFileName;
2536 unsigned i;
2537 for (i=0; i < tmpName.length(); i++) {
2538 char c = tmpName.at(i);
2539 // replace any non alphanumeric characters with '_'.
2540 if (!isalpha(c) && (c < '0' || c > '9'))
2541 tmpName[i] = '_';
2542 }
2543 S += tmpName;
2544 S += "_";
2545 S += utostr(NumObjCStringLiterals++);
2546
2547 Preamble += "static __NSConstantStringImpl " + S;
2548 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2549 Preamble += "0x000007c8,"; // utf8_str
2550 // The pretty printer for StringLiteral handles escape characters properly.
2551 std::string prettyBufS;
2552 llvm::raw_string_ostream prettyBuf(prettyBufS);
Richard Smithd1420c62012-08-16 03:56:14 +00002553 Exp->getString()->printPretty(prettyBuf, 0, PrintingPolicy(LangOpts));
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002554 Preamble += prettyBuf.str();
2555 Preamble += ",";
2556 Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
2557
2558 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
2559 SourceLocation(), &Context->Idents.get(S),
2560 strType, 0, SC_Static, SC_None);
John McCallf4b88a42012-03-10 09:33:50 +00002561 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, false, strType, VK_LValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002562 SourceLocation());
2563 Expr *Unop = new (Context) UnaryOperator(DRE, UO_AddrOf,
2564 Context->getPointerType(DRE->getType()),
2565 VK_RValue, OK_Ordinary,
2566 SourceLocation());
2567 // cast to NSConstantString *
2568 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Exp->getType(),
2569 CK_CPointerToObjCPointerCast, Unop);
2570 ReplaceStmt(Exp, cast);
2571 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2572 return cast;
2573}
2574
Fariborz Jahanian55947042012-03-27 20:17:30 +00002575Stmt *RewriteModernObjC::RewriteObjCBoolLiteralExpr(ObjCBoolLiteralExpr *Exp) {
2576 unsigned IntSize =
2577 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
2578
2579 Expr *FlagExp = IntegerLiteral::Create(*Context,
2580 llvm::APInt(IntSize, Exp->getValue()),
2581 Context->IntTy, Exp->getLocation());
2582 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Context->ObjCBuiltinBoolTy,
2583 CK_BitCast, FlagExp);
2584 ParenExpr *PE = new (Context) ParenExpr(Exp->getLocation(), Exp->getExprLoc(),
2585 cast);
2586 ReplaceStmt(Exp, PE);
2587 return PE;
2588}
2589
Patrick Beardeb382ec2012-04-19 00:25:12 +00002590Stmt *RewriteModernObjC::RewriteObjCBoxedExpr(ObjCBoxedExpr *Exp) {
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002591 // synthesize declaration of helper functions needed in this routine.
2592 if (!SelGetUidFunctionDecl)
2593 SynthSelGetUidFunctionDecl();
2594 // use objc_msgSend() for all.
2595 if (!MsgSendFunctionDecl)
2596 SynthMsgSendFunctionDecl();
2597 if (!GetClassFunctionDecl)
2598 SynthGetClassFunctionDecl();
2599
2600 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2601 SourceLocation StartLoc = Exp->getLocStart();
2602 SourceLocation EndLoc = Exp->getLocEnd();
2603
2604 // Synthesize a call to objc_msgSend().
2605 SmallVector<Expr*, 4> MsgExprs;
2606 SmallVector<Expr*, 4> ClsExprs;
2607 QualType argType = Context->getPointerType(Context->CharTy);
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002608
Patrick Beardeb382ec2012-04-19 00:25:12 +00002609 // Create a call to objc_getClass("<BoxingClass>"). It will be the 1st argument.
2610 ObjCMethodDecl *BoxingMethod = Exp->getBoxingMethod();
2611 ObjCInterfaceDecl *BoxingClass = BoxingMethod->getClassInterface();
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002612
Patrick Beardeb382ec2012-04-19 00:25:12 +00002613 IdentifierInfo *clsName = BoxingClass->getIdentifier();
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002614 ClsExprs.push_back(StringLiteral::Create(*Context,
2615 clsName->getName(),
2616 StringLiteral::Ascii, false,
2617 argType, SourceLocation()));
2618 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2619 &ClsExprs[0],
2620 ClsExprs.size(),
2621 StartLoc, EndLoc);
2622 MsgExprs.push_back(Cls);
2623
Patrick Beardeb382ec2012-04-19 00:25:12 +00002624 // Create a call to sel_registerName("<BoxingMethod>:"), etc.
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002625 // it will be the 2nd argument.
2626 SmallVector<Expr*, 4> SelExprs;
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002627 SelExprs.push_back(StringLiteral::Create(*Context,
Patrick Beardeb382ec2012-04-19 00:25:12 +00002628 BoxingMethod->getSelector().getAsString(),
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002629 StringLiteral::Ascii, false,
2630 argType, SourceLocation()));
2631 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2632 &SelExprs[0], SelExprs.size(),
2633 StartLoc, EndLoc);
2634 MsgExprs.push_back(SelExp);
2635
Patrick Beardeb382ec2012-04-19 00:25:12 +00002636 // User provided sub-expression is the 3rd, and last, argument.
2637 Expr *subExpr = Exp->getSubExpr();
2638 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(subExpr)) {
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002639 QualType type = ICE->getType();
2640 const Expr *SubExpr = ICE->IgnoreParenImpCasts();
2641 CastKind CK = CK_BitCast;
2642 if (SubExpr->getType()->isIntegralType(*Context) && type->isBooleanType())
2643 CK = CK_IntegralToBoolean;
Patrick Beardeb382ec2012-04-19 00:25:12 +00002644 subExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, subExpr);
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002645 }
Patrick Beardeb382ec2012-04-19 00:25:12 +00002646 MsgExprs.push_back(subExpr);
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002647
2648 SmallVector<QualType, 4> ArgTypes;
2649 ArgTypes.push_back(Context->getObjCIdType());
2650 ArgTypes.push_back(Context->getObjCSelType());
Patrick Beardeb382ec2012-04-19 00:25:12 +00002651 for (ObjCMethodDecl::param_iterator PI = BoxingMethod->param_begin(),
2652 E = BoxingMethod->param_end(); PI != E; ++PI)
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002653 ArgTypes.push_back((*PI)->getType());
Patrick Beardeb382ec2012-04-19 00:25:12 +00002654
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002655 QualType returnType = Exp->getType();
2656 // Get the type, we will need to reference it in a couple spots.
2657 QualType msgSendType = MsgSendFlavor->getType();
2658
2659 // Create a reference to the objc_msgSend() declaration.
2660 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
2661 VK_LValue, SourceLocation());
2662
2663 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
Patrick Beardeb382ec2012-04-19 00:25:12 +00002664 Context->getPointerType(Context->VoidTy),
2665 CK_BitCast, DRE);
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002666
2667 // Now do the "normal" pointer to function cast.
2668 QualType castType =
Patrick Beardeb382ec2012-04-19 00:25:12 +00002669 getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
2670 BoxingMethod->isVariadic());
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002671 castType = Context->getPointerType(castType);
2672 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2673 cast);
2674
2675 // Don't forget the parens to enforce the proper binding.
2676 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
2677
2678 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002679 CallExpr *CE = new (Context) CallExpr(*Context, PE, MsgExprs,
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002680 FT->getResultType(), VK_RValue,
2681 EndLoc);
2682 ReplaceStmt(Exp, CE);
2683 return CE;
2684}
2685
Fariborz Jahanian86cff602012-03-30 23:35:47 +00002686Stmt *RewriteModernObjC::RewriteObjCArrayLiteralExpr(ObjCArrayLiteral *Exp) {
2687 // synthesize declaration of helper functions needed in this routine.
2688 if (!SelGetUidFunctionDecl)
2689 SynthSelGetUidFunctionDecl();
2690 // use objc_msgSend() for all.
2691 if (!MsgSendFunctionDecl)
2692 SynthMsgSendFunctionDecl();
2693 if (!GetClassFunctionDecl)
2694 SynthGetClassFunctionDecl();
2695
2696 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2697 SourceLocation StartLoc = Exp->getLocStart();
2698 SourceLocation EndLoc = Exp->getLocEnd();
2699
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00002700 // Build the expression: __NSContainer_literal(int, ...).arr
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00002701 QualType IntQT = Context->IntTy;
2702 QualType NSArrayFType =
2703 getSimpleFunctionType(Context->VoidTy, &IntQT, 1, true);
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00002704 std::string NSArrayFName("__NSContainer_literal");
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00002705 FunctionDecl *NSArrayFD = SynthBlockInitFunctionDecl(NSArrayFName);
2706 DeclRefExpr *NSArrayDRE =
2707 new (Context) DeclRefExpr(NSArrayFD, false, NSArrayFType, VK_RValue,
2708 SourceLocation());
2709
2710 SmallVector<Expr*, 16> InitExprs;
2711 unsigned NumElements = Exp->getNumElements();
2712 unsigned UnsignedIntSize =
2713 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
2714 Expr *count = IntegerLiteral::Create(*Context,
2715 llvm::APInt(UnsignedIntSize, NumElements),
2716 Context->UnsignedIntTy, SourceLocation());
2717 InitExprs.push_back(count);
2718 for (unsigned i = 0; i < NumElements; i++)
2719 InitExprs.push_back(Exp->getElement(i));
2720 Expr *NSArrayCallExpr =
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002721 new (Context) CallExpr(*Context, NSArrayDRE, InitExprs,
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00002722 NSArrayFType, VK_LValue, SourceLocation());
2723
2724 FieldDecl *ARRFD = FieldDecl::Create(*Context, 0, SourceLocation(),
2725 SourceLocation(),
2726 &Context->Idents.get("arr"),
2727 Context->getPointerType(Context->VoidPtrTy), 0,
2728 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smithca523302012-06-10 03:12:00 +00002729 ICIS_NoInit);
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00002730 MemberExpr *ArrayLiteralME =
2731 new (Context) MemberExpr(NSArrayCallExpr, false, ARRFD,
2732 SourceLocation(),
2733 ARRFD->getType(), VK_LValue,
2734 OK_Ordinary);
2735 QualType ConstIdT = Context->getObjCIdType().withConst();
2736 CStyleCastExpr * ArrayLiteralObjects =
2737 NoTypeInfoCStyleCastExpr(Context,
2738 Context->getPointerType(ConstIdT),
2739 CK_BitCast,
2740 ArrayLiteralME);
2741
Fariborz Jahanian86cff602012-03-30 23:35:47 +00002742 // Synthesize a call to objc_msgSend().
2743 SmallVector<Expr*, 32> MsgExprs;
2744 SmallVector<Expr*, 4> ClsExprs;
2745 QualType argType = Context->getPointerType(Context->CharTy);
2746 QualType expType = Exp->getType();
2747
2748 // Create a call to objc_getClass("NSArray"). It will be th 1st argument.
2749 ObjCInterfaceDecl *Class =
2750 expType->getPointeeType()->getAs<ObjCObjectType>()->getInterface();
2751
2752 IdentifierInfo *clsName = Class->getIdentifier();
2753 ClsExprs.push_back(StringLiteral::Create(*Context,
2754 clsName->getName(),
2755 StringLiteral::Ascii, false,
2756 argType, SourceLocation()));
2757 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2758 &ClsExprs[0],
2759 ClsExprs.size(),
2760 StartLoc, EndLoc);
2761 MsgExprs.push_back(Cls);
2762
2763 // Create a call to sel_registerName("arrayWithObjects:count:").
2764 // it will be the 2nd argument.
2765 SmallVector<Expr*, 4> SelExprs;
2766 ObjCMethodDecl *ArrayMethod = Exp->getArrayWithObjectsMethod();
2767 SelExprs.push_back(StringLiteral::Create(*Context,
2768 ArrayMethod->getSelector().getAsString(),
2769 StringLiteral::Ascii, false,
2770 argType, SourceLocation()));
2771 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2772 &SelExprs[0], SelExprs.size(),
2773 StartLoc, EndLoc);
2774 MsgExprs.push_back(SelExp);
2775
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00002776 // (const id [])objects
2777 MsgExprs.push_back(ArrayLiteralObjects);
Fariborz Jahanian86cff602012-03-30 23:35:47 +00002778
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00002779 // (NSUInteger)cnt
2780 Expr *cnt = IntegerLiteral::Create(*Context,
2781 llvm::APInt(UnsignedIntSize, NumElements),
2782 Context->UnsignedIntTy, SourceLocation());
2783 MsgExprs.push_back(cnt);
Fariborz Jahanian86cff602012-03-30 23:35:47 +00002784
2785
2786 SmallVector<QualType, 4> ArgTypes;
2787 ArgTypes.push_back(Context->getObjCIdType());
2788 ArgTypes.push_back(Context->getObjCSelType());
2789 for (ObjCMethodDecl::param_iterator PI = ArrayMethod->param_begin(),
2790 E = ArrayMethod->param_end(); PI != E; ++PI)
2791 ArgTypes.push_back((*PI)->getType());
2792
2793 QualType returnType = Exp->getType();
2794 // Get the type, we will need to reference it in a couple spots.
2795 QualType msgSendType = MsgSendFlavor->getType();
2796
2797 // Create a reference to the objc_msgSend() declaration.
2798 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
2799 VK_LValue, SourceLocation());
2800
2801 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
2802 Context->getPointerType(Context->VoidTy),
2803 CK_BitCast, DRE);
2804
2805 // Now do the "normal" pointer to function cast.
2806 QualType castType =
2807 getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
2808 ArrayMethod->isVariadic());
2809 castType = Context->getPointerType(castType);
2810 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2811 cast);
2812
2813 // Don't forget the parens to enforce the proper binding.
2814 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
2815
2816 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002817 CallExpr *CE = new (Context) CallExpr(*Context, PE, MsgExprs,
Fariborz Jahanian86cff602012-03-30 23:35:47 +00002818 FT->getResultType(), VK_RValue,
2819 EndLoc);
2820 ReplaceStmt(Exp, CE);
2821 return CE;
2822}
2823
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00002824Stmt *RewriteModernObjC::RewriteObjCDictionaryLiteralExpr(ObjCDictionaryLiteral *Exp) {
2825 // synthesize declaration of helper functions needed in this routine.
2826 if (!SelGetUidFunctionDecl)
2827 SynthSelGetUidFunctionDecl();
2828 // use objc_msgSend() for all.
2829 if (!MsgSendFunctionDecl)
2830 SynthMsgSendFunctionDecl();
2831 if (!GetClassFunctionDecl)
2832 SynthGetClassFunctionDecl();
2833
2834 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2835 SourceLocation StartLoc = Exp->getLocStart();
2836 SourceLocation EndLoc = Exp->getLocEnd();
2837
2838 // Build the expression: __NSContainer_literal(int, ...).arr
2839 QualType IntQT = Context->IntTy;
2840 QualType NSDictFType =
2841 getSimpleFunctionType(Context->VoidTy, &IntQT, 1, true);
2842 std::string NSDictFName("__NSContainer_literal");
2843 FunctionDecl *NSDictFD = SynthBlockInitFunctionDecl(NSDictFName);
2844 DeclRefExpr *NSDictDRE =
2845 new (Context) DeclRefExpr(NSDictFD, false, NSDictFType, VK_RValue,
2846 SourceLocation());
2847
2848 SmallVector<Expr*, 16> KeyExprs;
2849 SmallVector<Expr*, 16> ValueExprs;
2850
2851 unsigned NumElements = Exp->getNumElements();
2852 unsigned UnsignedIntSize =
2853 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
2854 Expr *count = IntegerLiteral::Create(*Context,
2855 llvm::APInt(UnsignedIntSize, NumElements),
2856 Context->UnsignedIntTy, SourceLocation());
2857 KeyExprs.push_back(count);
2858 ValueExprs.push_back(count);
2859 for (unsigned i = 0; i < NumElements; i++) {
2860 ObjCDictionaryElement Element = Exp->getKeyValueElement(i);
2861 KeyExprs.push_back(Element.Key);
2862 ValueExprs.push_back(Element.Value);
2863 }
2864
2865 // (const id [])objects
2866 Expr *NSValueCallExpr =
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002867 new (Context) CallExpr(*Context, NSDictDRE, ValueExprs,
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00002868 NSDictFType, VK_LValue, SourceLocation());
2869
2870 FieldDecl *ARRFD = FieldDecl::Create(*Context, 0, SourceLocation(),
2871 SourceLocation(),
2872 &Context->Idents.get("arr"),
2873 Context->getPointerType(Context->VoidPtrTy), 0,
2874 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smithca523302012-06-10 03:12:00 +00002875 ICIS_NoInit);
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00002876 MemberExpr *DictLiteralValueME =
2877 new (Context) MemberExpr(NSValueCallExpr, false, ARRFD,
2878 SourceLocation(),
2879 ARRFD->getType(), VK_LValue,
2880 OK_Ordinary);
2881 QualType ConstIdT = Context->getObjCIdType().withConst();
2882 CStyleCastExpr * DictValueObjects =
2883 NoTypeInfoCStyleCastExpr(Context,
2884 Context->getPointerType(ConstIdT),
2885 CK_BitCast,
2886 DictLiteralValueME);
2887 // (const id <NSCopying> [])keys
2888 Expr *NSKeyCallExpr =
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002889 new (Context) CallExpr(*Context, NSDictDRE, KeyExprs,
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00002890 NSDictFType, VK_LValue, SourceLocation());
2891
2892 MemberExpr *DictLiteralKeyME =
2893 new (Context) MemberExpr(NSKeyCallExpr, false, ARRFD,
2894 SourceLocation(),
2895 ARRFD->getType(), VK_LValue,
2896 OK_Ordinary);
2897
2898 CStyleCastExpr * DictKeyObjects =
2899 NoTypeInfoCStyleCastExpr(Context,
2900 Context->getPointerType(ConstIdT),
2901 CK_BitCast,
2902 DictLiteralKeyME);
2903
2904
2905
2906 // Synthesize a call to objc_msgSend().
2907 SmallVector<Expr*, 32> MsgExprs;
2908 SmallVector<Expr*, 4> ClsExprs;
2909 QualType argType = Context->getPointerType(Context->CharTy);
2910 QualType expType = Exp->getType();
2911
2912 // Create a call to objc_getClass("NSArray"). It will be th 1st argument.
2913 ObjCInterfaceDecl *Class =
2914 expType->getPointeeType()->getAs<ObjCObjectType>()->getInterface();
2915
2916 IdentifierInfo *clsName = Class->getIdentifier();
2917 ClsExprs.push_back(StringLiteral::Create(*Context,
2918 clsName->getName(),
2919 StringLiteral::Ascii, false,
2920 argType, SourceLocation()));
2921 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2922 &ClsExprs[0],
2923 ClsExprs.size(),
2924 StartLoc, EndLoc);
2925 MsgExprs.push_back(Cls);
2926
2927 // Create a call to sel_registerName("arrayWithObjects:count:").
2928 // it will be the 2nd argument.
2929 SmallVector<Expr*, 4> SelExprs;
2930 ObjCMethodDecl *DictMethod = Exp->getDictWithObjectsMethod();
2931 SelExprs.push_back(StringLiteral::Create(*Context,
2932 DictMethod->getSelector().getAsString(),
2933 StringLiteral::Ascii, false,
2934 argType, SourceLocation()));
2935 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2936 &SelExprs[0], SelExprs.size(),
2937 StartLoc, EndLoc);
2938 MsgExprs.push_back(SelExp);
2939
2940 // (const id [])objects
2941 MsgExprs.push_back(DictValueObjects);
2942
2943 // (const id <NSCopying> [])keys
2944 MsgExprs.push_back(DictKeyObjects);
2945
2946 // (NSUInteger)cnt
2947 Expr *cnt = IntegerLiteral::Create(*Context,
2948 llvm::APInt(UnsignedIntSize, NumElements),
2949 Context->UnsignedIntTy, SourceLocation());
2950 MsgExprs.push_back(cnt);
2951
2952
2953 SmallVector<QualType, 8> ArgTypes;
2954 ArgTypes.push_back(Context->getObjCIdType());
2955 ArgTypes.push_back(Context->getObjCSelType());
2956 for (ObjCMethodDecl::param_iterator PI = DictMethod->param_begin(),
2957 E = DictMethod->param_end(); PI != E; ++PI) {
2958 QualType T = (*PI)->getType();
2959 if (const PointerType* PT = T->getAs<PointerType>()) {
2960 QualType PointeeTy = PT->getPointeeType();
2961 convertToUnqualifiedObjCType(PointeeTy);
2962 T = Context->getPointerType(PointeeTy);
2963 }
2964 ArgTypes.push_back(T);
2965 }
2966
2967 QualType returnType = Exp->getType();
2968 // Get the type, we will need to reference it in a couple spots.
2969 QualType msgSendType = MsgSendFlavor->getType();
2970
2971 // Create a reference to the objc_msgSend() declaration.
2972 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
2973 VK_LValue, SourceLocation());
2974
2975 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
2976 Context->getPointerType(Context->VoidTy),
2977 CK_BitCast, DRE);
2978
2979 // Now do the "normal" pointer to function cast.
2980 QualType castType =
2981 getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
2982 DictMethod->isVariadic());
2983 castType = Context->getPointerType(castType);
2984 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2985 cast);
2986
2987 // Don't forget the parens to enforce the proper binding.
2988 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
2989
2990 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002991 CallExpr *CE = new (Context) CallExpr(*Context, PE, MsgExprs,
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00002992 FT->getResultType(), VK_RValue,
2993 EndLoc);
2994 ReplaceStmt(Exp, CE);
2995 return CE;
2996}
2997
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002998// struct __rw_objc_super {
2999// struct objc_object *object; struct objc_object *superClass;
3000// };
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003001QualType RewriteModernObjC::getSuperStructType() {
3002 if (!SuperStructDecl) {
3003 SuperStructDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
3004 SourceLocation(), SourceLocation(),
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003005 &Context->Idents.get("__rw_objc_super"));
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003006 QualType FieldTypes[2];
3007
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003008 // struct objc_object *object;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003009 FieldTypes[0] = Context->getObjCIdType();
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003010 // struct objc_object *superClass;
3011 FieldTypes[1] = Context->getObjCIdType();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003012
3013 // Create fields
3014 for (unsigned i = 0; i < 2; ++i) {
3015 SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
3016 SourceLocation(),
3017 SourceLocation(), 0,
3018 FieldTypes[i], 0,
3019 /*BitWidth=*/0,
3020 /*Mutable=*/false,
Richard Smithca523302012-06-10 03:12:00 +00003021 ICIS_NoInit));
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003022 }
3023
3024 SuperStructDecl->completeDefinition();
3025 }
3026 return Context->getTagDeclType(SuperStructDecl);
3027}
3028
3029QualType RewriteModernObjC::getConstantStringStructType() {
3030 if (!ConstantStringDecl) {
3031 ConstantStringDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
3032 SourceLocation(), SourceLocation(),
3033 &Context->Idents.get("__NSConstantStringImpl"));
3034 QualType FieldTypes[4];
3035
3036 // struct objc_object *receiver;
3037 FieldTypes[0] = Context->getObjCIdType();
3038 // int flags;
3039 FieldTypes[1] = Context->IntTy;
3040 // char *str;
3041 FieldTypes[2] = Context->getPointerType(Context->CharTy);
3042 // long length;
3043 FieldTypes[3] = Context->LongTy;
3044
3045 // Create fields
3046 for (unsigned i = 0; i < 4; ++i) {
3047 ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
3048 ConstantStringDecl,
3049 SourceLocation(),
3050 SourceLocation(), 0,
3051 FieldTypes[i], 0,
3052 /*BitWidth=*/0,
3053 /*Mutable=*/true,
Richard Smithca523302012-06-10 03:12:00 +00003054 ICIS_NoInit));
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003055 }
3056
3057 ConstantStringDecl->completeDefinition();
3058 }
3059 return Context->getTagDeclType(ConstantStringDecl);
3060}
3061
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +00003062/// getFunctionSourceLocation - returns start location of a function
3063/// definition. Complication arises when function has declared as
3064/// extern "C" or extern "C" {...}
3065static SourceLocation getFunctionSourceLocation (RewriteModernObjC &R,
3066 FunctionDecl *FD) {
3067 if (FD->isExternC() && !FD->isMain()) {
3068 const DeclContext *DC = FD->getDeclContext();
3069 if (const LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(DC))
3070 // if it is extern "C" {...}, return function decl's own location.
3071 if (!LSD->getRBraceLoc().isValid())
3072 return LSD->getExternLoc();
3073 }
3074 if (FD->getStorageClassAsWritten() != SC_None)
3075 R.RewriteBlockLiteralFunctionDecl(FD);
3076 return FD->getTypeSpecStartLoc();
3077}
3078
Fariborz Jahanian96205962012-11-06 17:30:23 +00003079void RewriteModernObjC::RewriteLineDirective(const Decl *D) {
3080
3081 SourceLocation Location = D->getLocation();
3082
3083 if (Location.isFileID()) {
3084 std::string LineString("#line ");
3085 PresumedLoc PLoc = SM->getPresumedLoc(Location);
3086 LineString += utostr(PLoc.getLine());
3087 LineString += " \"";
3088 LineString += PLoc.getFilename();
3089 if (isa<ObjCMethodDecl>(D))
3090 LineString += "\"";
3091 else LineString += "\"\n";
3092
3093 Location = D->getLocStart();
3094 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
3095 if (FD->isExternC() && !FD->isMain()) {
3096 const DeclContext *DC = FD->getDeclContext();
3097 if (const LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(DC))
3098 // if it is extern "C" {...}, return function decl's own location.
3099 if (!LSD->getRBraceLoc().isValid())
3100 Location = LSD->getExternLoc();
3101 }
3102 }
3103 InsertText(Location, LineString);
3104 }
3105}
3106
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +00003107/// SynthMsgSendStretCallExpr - This routine translates message expression
3108/// into a call to objc_msgSend_stret() entry point. Tricky part is that
3109/// nil check on receiver must be performed before calling objc_msgSend_stret.
3110/// MsgSendStretFlavor - function declaration objc_msgSend_stret(...)
3111/// msgSendType - function type of objc_msgSend_stret(...)
3112/// returnType - Result type of the method being synthesized.
3113/// ArgTypes - type of the arguments passed to objc_msgSend_stret, starting with receiver type.
3114/// MsgExprs - list of argument expressions being passed to objc_msgSend_stret,
3115/// starting with receiver.
3116/// Method - Method being rewritten.
3117Expr *RewriteModernObjC::SynthMsgSendStretCallExpr(FunctionDecl *MsgSendStretFlavor,
3118 QualType msgSendType,
3119 QualType returnType,
3120 SmallVectorImpl<QualType> &ArgTypes,
3121 SmallVectorImpl<Expr*> &MsgExprs,
3122 ObjCMethodDecl *Method) {
3123 // Now do the "normal" pointer to function cast.
3124 QualType castType = getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
3125 Method ? Method->isVariadic() : false);
3126 castType = Context->getPointerType(castType);
3127
3128 // build type for containing the objc_msgSend_stret object.
3129 static unsigned stretCount=0;
3130 std::string name = "__Stret"; name += utostr(stretCount);
Fariborz Jahanian2ca5af22012-07-25 21:48:36 +00003131 std::string str =
3132 "extern \"C\" void * __cdecl memset(void *_Dst, int _Val, size_t _Size);\n";
3133 str += "struct "; str += name;
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +00003134 str += " {\n\t";
3135 str += name;
3136 str += "(id receiver, SEL sel";
3137 for (unsigned i = 2; i < ArgTypes.size(); i++) {
Fariborz Jahanian6734ec42012-06-29 19:55:46 +00003138 std::string ArgName = "arg"; ArgName += utostr(i);
3139 ArgTypes[i].getAsStringInternal(ArgName, Context->getPrintingPolicy());
3140 str += ", "; str += ArgName;
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +00003141 }
3142 // could be vararg.
3143 for (unsigned i = ArgTypes.size(); i < MsgExprs.size(); i++) {
Fariborz Jahanian6734ec42012-06-29 19:55:46 +00003144 std::string ArgName = "arg"; ArgName += utostr(i);
3145 MsgExprs[i]->getType().getAsStringInternal(ArgName,
3146 Context->getPrintingPolicy());
3147 str += ", "; str += ArgName;
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +00003148 }
3149
3150 str += ") {\n";
3151 str += "\t if (receiver == 0)\n";
3152 str += "\t memset((void*)&s, 0, sizeof(s));\n";
3153 str += "\t else\n";
3154 str += "\t s = (("; str += castType.getAsString(Context->getPrintingPolicy());
3155 str += ")(void *)objc_msgSend_stret)(receiver, sel";
3156 for (unsigned i = 2; i < ArgTypes.size(); i++) {
3157 str += ", arg"; str += utostr(i);
3158 }
3159 // could be vararg.
3160 for (unsigned i = ArgTypes.size(); i < MsgExprs.size(); i++) {
3161 str += ", arg"; str += utostr(i);
3162 }
3163
3164 str += ");\n";
3165 str += "\t}\n";
3166 str += "\t"; str += returnType.getAsString(Context->getPrintingPolicy());
3167 str += " s;\n";
3168 str += "};\n\n";
Fariborz Jahaniana6e5a6e2012-08-21 18:56:50 +00003169 SourceLocation FunLocStart;
3170 if (CurFunctionDef)
3171 FunLocStart = getFunctionSourceLocation(*this, CurFunctionDef);
3172 else {
3173 assert(CurMethodDef && "SynthMsgSendStretCallExpr - CurMethodDef is null");
3174 FunLocStart = CurMethodDef->getLocStart();
3175 }
3176
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +00003177 InsertText(FunLocStart, str);
3178 ++stretCount;
3179
3180 // AST for __Stretn(receiver, args).s;
3181 IdentifierInfo *ID = &Context->Idents.get(name);
3182 FunctionDecl *FD = FunctionDecl::Create(*Context, TUDecl, SourceLocation(),
3183 SourceLocation(), ID, castType, 0, SC_Extern,
3184 SC_None, false, false);
3185 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, false, castType, VK_RValue,
3186 SourceLocation());
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003187 CallExpr *STCE = new (Context) CallExpr(*Context, DRE, MsgExprs,
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +00003188 castType, VK_LValue, SourceLocation());
3189
3190 FieldDecl *FieldD = FieldDecl::Create(*Context, 0, SourceLocation(),
3191 SourceLocation(),
3192 &Context->Idents.get("s"),
3193 returnType, 0,
3194 /*BitWidth=*/0, /*Mutable=*/true,
3195 ICIS_NoInit);
3196 MemberExpr *ME = new (Context) MemberExpr(STCE, false, FieldD, SourceLocation(),
3197 FieldD->getType(), VK_LValue,
3198 OK_Ordinary);
3199
3200 return ME;
3201}
3202
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003203Stmt *RewriteModernObjC::SynthMessageExpr(ObjCMessageExpr *Exp,
3204 SourceLocation StartLoc,
3205 SourceLocation EndLoc) {
3206 if (!SelGetUidFunctionDecl)
3207 SynthSelGetUidFunctionDecl();
3208 if (!MsgSendFunctionDecl)
3209 SynthMsgSendFunctionDecl();
3210 if (!MsgSendSuperFunctionDecl)
3211 SynthMsgSendSuperFunctionDecl();
3212 if (!MsgSendStretFunctionDecl)
3213 SynthMsgSendStretFunctionDecl();
3214 if (!MsgSendSuperStretFunctionDecl)
3215 SynthMsgSendSuperStretFunctionDecl();
3216 if (!MsgSendFpretFunctionDecl)
3217 SynthMsgSendFpretFunctionDecl();
3218 if (!GetClassFunctionDecl)
3219 SynthGetClassFunctionDecl();
3220 if (!GetSuperClassFunctionDecl)
3221 SynthGetSuperClassFunctionDecl();
3222 if (!GetMetaClassFunctionDecl)
3223 SynthGetMetaClassFunctionDecl();
3224
3225 // default to objc_msgSend().
3226 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
3227 // May need to use objc_msgSend_stret() as well.
3228 FunctionDecl *MsgSendStretFlavor = 0;
3229 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
3230 QualType resultType = mDecl->getResultType();
3231 if (resultType->isRecordType())
3232 MsgSendStretFlavor = MsgSendStretFunctionDecl;
3233 else if (resultType->isRealFloatingType())
3234 MsgSendFlavor = MsgSendFpretFunctionDecl;
3235 }
3236
3237 // Synthesize a call to objc_msgSend().
3238 SmallVector<Expr*, 8> MsgExprs;
3239 switch (Exp->getReceiverKind()) {
3240 case ObjCMessageExpr::SuperClass: {
3241 MsgSendFlavor = MsgSendSuperFunctionDecl;
3242 if (MsgSendStretFlavor)
3243 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
3244 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
3245
3246 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
3247
3248 SmallVector<Expr*, 4> InitExprs;
3249
3250 // set the receiver to self, the first argument to all methods.
3251 InitExprs.push_back(
3252 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3253 CK_BitCast,
3254 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCallf4b88a42012-03-10 09:33:50 +00003255 false,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003256 Context->getObjCIdType(),
3257 VK_RValue,
3258 SourceLocation()))
3259 ); // set the 'receiver'.
3260
3261 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3262 SmallVector<Expr*, 8> ClsExprs;
3263 QualType argType = Context->getPointerType(Context->CharTy);
3264 ClsExprs.push_back(StringLiteral::Create(*Context,
3265 ClassDecl->getIdentifier()->getName(),
3266 StringLiteral::Ascii, false,
3267 argType, SourceLocation()));
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00003268 // (Class)objc_getClass("CurrentClass")
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003269 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
3270 &ClsExprs[0],
3271 ClsExprs.size(),
3272 StartLoc,
3273 EndLoc);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003274 ClsExprs.clear();
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00003275 ClsExprs.push_back(Cls);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003276 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
3277 &ClsExprs[0], ClsExprs.size(),
3278 StartLoc, EndLoc);
3279
3280 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3281 // To turn off a warning, type-cast to 'id'
3282 InitExprs.push_back( // set 'super class', using class_getSuperclass().
3283 NoTypeInfoCStyleCastExpr(Context,
3284 Context->getObjCIdType(),
3285 CK_BitCast, Cls));
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003286 // struct __rw_objc_super
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003287 QualType superType = getSuperStructType();
3288 Expr *SuperRep;
3289
3290 if (LangOpts.MicrosoftExt) {
3291 SynthSuperContructorFunctionDecl();
3292 // Simulate a contructor call...
3293 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
John McCallf4b88a42012-03-10 09:33:50 +00003294 false, superType, VK_LValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003295 SourceLocation());
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003296 SuperRep = new (Context) CallExpr(*Context, DRE, InitExprs,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003297 superType, VK_LValue,
3298 SourceLocation());
3299 // The code for super is a little tricky to prevent collision with
3300 // the structure definition in the header. The rewriter has it's own
3301 // internal definition (__rw_objc_super) that is uses. This is why
3302 // we need the cast below. For example:
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003303 // (struct __rw_objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003304 //
3305 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
3306 Context->getPointerType(SuperRep->getType()),
3307 VK_RValue, OK_Ordinary,
3308 SourceLocation());
3309 SuperRep = NoTypeInfoCStyleCastExpr(Context,
3310 Context->getPointerType(superType),
3311 CK_BitCast, SuperRep);
3312 } else {
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003313 // (struct __rw_objc_super) { <exprs from above> }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003314 InitListExpr *ILE =
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003315 new (Context) InitListExpr(*Context, SourceLocation(), InitExprs,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003316 SourceLocation());
3317 TypeSourceInfo *superTInfo
3318 = Context->getTrivialTypeSourceInfo(superType);
3319 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
3320 superType, VK_LValue,
3321 ILE, false);
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003322 // struct __rw_objc_super *
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003323 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
3324 Context->getPointerType(SuperRep->getType()),
3325 VK_RValue, OK_Ordinary,
3326 SourceLocation());
3327 }
3328 MsgExprs.push_back(SuperRep);
3329 break;
3330 }
3331
3332 case ObjCMessageExpr::Class: {
3333 SmallVector<Expr*, 8> ClsExprs;
3334 QualType argType = Context->getPointerType(Context->CharTy);
3335 ObjCInterfaceDecl *Class
3336 = Exp->getClassReceiver()->getAs<ObjCObjectType>()->getInterface();
3337 IdentifierInfo *clsName = Class->getIdentifier();
3338 ClsExprs.push_back(StringLiteral::Create(*Context,
3339 clsName->getName(),
3340 StringLiteral::Ascii, false,
3341 argType, SourceLocation()));
3342 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
3343 &ClsExprs[0],
3344 ClsExprs.size(),
3345 StartLoc, EndLoc);
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00003346 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
3347 Context->getObjCIdType(),
3348 CK_BitCast, Cls);
3349 MsgExprs.push_back(ArgExpr);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003350 break;
3351 }
3352
3353 case ObjCMessageExpr::SuperInstance:{
3354 MsgSendFlavor = MsgSendSuperFunctionDecl;
3355 if (MsgSendStretFlavor)
3356 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
3357 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
3358 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
3359 SmallVector<Expr*, 4> InitExprs;
3360
3361 InitExprs.push_back(
3362 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3363 CK_BitCast,
3364 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCallf4b88a42012-03-10 09:33:50 +00003365 false,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003366 Context->getObjCIdType(),
3367 VK_RValue, SourceLocation()))
3368 ); // set the 'receiver'.
3369
3370 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3371 SmallVector<Expr*, 8> ClsExprs;
3372 QualType argType = Context->getPointerType(Context->CharTy);
3373 ClsExprs.push_back(StringLiteral::Create(*Context,
3374 ClassDecl->getIdentifier()->getName(),
3375 StringLiteral::Ascii, false, argType,
3376 SourceLocation()));
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00003377 // (Class)objc_getClass("CurrentClass")
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003378 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
3379 &ClsExprs[0],
3380 ClsExprs.size(),
3381 StartLoc, EndLoc);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003382 ClsExprs.clear();
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00003383 ClsExprs.push_back(Cls);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003384 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
3385 &ClsExprs[0], ClsExprs.size(),
3386 StartLoc, EndLoc);
3387
3388 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3389 // To turn off a warning, type-cast to 'id'
3390 InitExprs.push_back(
3391 // set 'super class', using class_getSuperclass().
3392 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3393 CK_BitCast, Cls));
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003394 // struct __rw_objc_super
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003395 QualType superType = getSuperStructType();
3396 Expr *SuperRep;
3397
3398 if (LangOpts.MicrosoftExt) {
3399 SynthSuperContructorFunctionDecl();
3400 // Simulate a contructor call...
3401 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
John McCallf4b88a42012-03-10 09:33:50 +00003402 false, superType, VK_LValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003403 SourceLocation());
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003404 SuperRep = new (Context) CallExpr(*Context, DRE, InitExprs,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003405 superType, VK_LValue, SourceLocation());
3406 // The code for super is a little tricky to prevent collision with
3407 // the structure definition in the header. The rewriter has it's own
3408 // internal definition (__rw_objc_super) that is uses. This is why
3409 // we need the cast below. For example:
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003410 // (struct __rw_objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003411 //
3412 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
3413 Context->getPointerType(SuperRep->getType()),
3414 VK_RValue, OK_Ordinary,
3415 SourceLocation());
3416 SuperRep = NoTypeInfoCStyleCastExpr(Context,
3417 Context->getPointerType(superType),
3418 CK_BitCast, SuperRep);
3419 } else {
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003420 // (struct __rw_objc_super) { <exprs from above> }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003421 InitListExpr *ILE =
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003422 new (Context) InitListExpr(*Context, SourceLocation(), InitExprs,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003423 SourceLocation());
3424 TypeSourceInfo *superTInfo
3425 = Context->getTrivialTypeSourceInfo(superType);
3426 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
3427 superType, VK_RValue, ILE,
3428 false);
3429 }
3430 MsgExprs.push_back(SuperRep);
3431 break;
3432 }
3433
3434 case ObjCMessageExpr::Instance: {
3435 // Remove all type-casts because it may contain objc-style types; e.g.
3436 // Foo<Proto> *.
3437 Expr *recExpr = Exp->getInstanceReceiver();
3438 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
3439 recExpr = CE->getSubExpr();
3440 CastKind CK = recExpr->getType()->isObjCObjectPointerType()
3441 ? CK_BitCast : recExpr->getType()->isBlockPointerType()
3442 ? CK_BlockPointerToObjCPointerCast
3443 : CK_CPointerToObjCPointerCast;
3444
3445 recExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3446 CK, recExpr);
3447 MsgExprs.push_back(recExpr);
3448 break;
3449 }
3450 }
3451
3452 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
3453 SmallVector<Expr*, 8> SelExprs;
3454 QualType argType = Context->getPointerType(Context->CharTy);
3455 SelExprs.push_back(StringLiteral::Create(*Context,
3456 Exp->getSelector().getAsString(),
3457 StringLiteral::Ascii, false,
3458 argType, SourceLocation()));
3459 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
3460 &SelExprs[0], SelExprs.size(),
3461 StartLoc,
3462 EndLoc);
3463 MsgExprs.push_back(SelExp);
3464
3465 // Now push any user supplied arguments.
3466 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
3467 Expr *userExpr = Exp->getArg(i);
3468 // Make all implicit casts explicit...ICE comes in handy:-)
3469 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
3470 // Reuse the ICE type, it is exactly what the doctor ordered.
3471 QualType type = ICE->getType();
3472 if (needToScanForQualifiers(type))
3473 type = Context->getObjCIdType();
3474 // Make sure we convert "type (^)(...)" to "type (*)(...)".
3475 (void)convertBlockPointerToFunctionPointer(type);
3476 const Expr *SubExpr = ICE->IgnoreParenImpCasts();
3477 CastKind CK;
3478 if (SubExpr->getType()->isIntegralType(*Context) &&
3479 type->isBooleanType()) {
3480 CK = CK_IntegralToBoolean;
3481 } else if (type->isObjCObjectPointerType()) {
3482 if (SubExpr->getType()->isBlockPointerType()) {
3483 CK = CK_BlockPointerToObjCPointerCast;
3484 } else if (SubExpr->getType()->isPointerType()) {
3485 CK = CK_CPointerToObjCPointerCast;
3486 } else {
3487 CK = CK_BitCast;
3488 }
3489 } else {
3490 CK = CK_BitCast;
3491 }
3492
3493 userExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, userExpr);
3494 }
3495 // Make id<P...> cast into an 'id' cast.
3496 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
3497 if (CE->getType()->isObjCQualifiedIdType()) {
3498 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
3499 userExpr = CE->getSubExpr();
3500 CastKind CK;
3501 if (userExpr->getType()->isIntegralType(*Context)) {
3502 CK = CK_IntegralToPointer;
3503 } else if (userExpr->getType()->isBlockPointerType()) {
3504 CK = CK_BlockPointerToObjCPointerCast;
3505 } else if (userExpr->getType()->isPointerType()) {
3506 CK = CK_CPointerToObjCPointerCast;
3507 } else {
3508 CK = CK_BitCast;
3509 }
3510 userExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3511 CK, userExpr);
3512 }
3513 }
3514 MsgExprs.push_back(userExpr);
3515 // We've transferred the ownership to MsgExprs. For now, we *don't* null
3516 // out the argument in the original expression (since we aren't deleting
3517 // the ObjCMessageExpr). See RewritePropertyOrImplicitSetter() usage for more info.
3518 //Exp->setArg(i, 0);
3519 }
3520 // Generate the funky cast.
3521 CastExpr *cast;
3522 SmallVector<QualType, 8> ArgTypes;
3523 QualType returnType;
3524
3525 // Push 'id' and 'SEL', the 2 implicit arguments.
3526 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
3527 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
3528 else
3529 ArgTypes.push_back(Context->getObjCIdType());
3530 ArgTypes.push_back(Context->getObjCSelType());
3531 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
3532 // Push any user argument types.
3533 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
3534 E = OMD->param_end(); PI != E; ++PI) {
3535 QualType t = (*PI)->getType()->isObjCQualifiedIdType()
3536 ? Context->getObjCIdType()
3537 : (*PI)->getType();
3538 // Make sure we convert "t (^)(...)" to "t (*)(...)".
3539 (void)convertBlockPointerToFunctionPointer(t);
3540 ArgTypes.push_back(t);
3541 }
3542 returnType = Exp->getType();
3543 convertToUnqualifiedObjCType(returnType);
3544 (void)convertBlockPointerToFunctionPointer(returnType);
3545 } else {
3546 returnType = Context->getObjCIdType();
3547 }
3548 // Get the type, we will need to reference it in a couple spots.
3549 QualType msgSendType = MsgSendFlavor->getType();
3550
3551 // Create a reference to the objc_msgSend() declaration.
John McCallf4b88a42012-03-10 09:33:50 +00003552 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003553 VK_LValue, SourceLocation());
3554
3555 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
3556 // If we don't do this cast, we get the following bizarre warning/note:
3557 // xx.m:13: warning: function called through a non-compatible type
3558 // xx.m:13: note: if this code is reached, the program will abort
3559 cast = NoTypeInfoCStyleCastExpr(Context,
3560 Context->getPointerType(Context->VoidTy),
3561 CK_BitCast, DRE);
3562
3563 // Now do the "normal" pointer to function cast.
3564 QualType castType =
3565 getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
3566 // If we don't have a method decl, force a variadic cast.
3567 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true);
3568 castType = Context->getPointerType(castType);
3569 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
3570 cast);
3571
3572 // Don't forget the parens to enforce the proper binding.
3573 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
3574
3575 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003576 CallExpr *CE = new (Context) CallExpr(*Context, PE, MsgExprs,
3577 FT->getResultType(), VK_RValue, EndLoc);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003578 Stmt *ReplacingStmt = CE;
3579 if (MsgSendStretFlavor) {
3580 // We have the method which returns a struct/union. Must also generate
3581 // call to objc_msgSend_stret and hang both varieties on a conditional
3582 // expression which dictate which one to envoke depending on size of
3583 // method's return type.
3584
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +00003585 Expr *STCE = SynthMsgSendStretCallExpr(MsgSendStretFlavor,
3586 msgSendType, returnType,
3587 ArgTypes, MsgExprs,
3588 Exp->getMethodDecl());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003589
3590 // Build sizeof(returnType)
3591 UnaryExprOrTypeTraitExpr *sizeofExpr =
3592 new (Context) UnaryExprOrTypeTraitExpr(UETT_SizeOf,
3593 Context->getTrivialTypeSourceInfo(returnType),
3594 Context->getSizeType(), SourceLocation(),
3595 SourceLocation());
3596 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
3597 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
3598 // For X86 it is more complicated and some kind of target specific routine
3599 // is needed to decide what to do.
3600 unsigned IntSize =
3601 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
3602 IntegerLiteral *limit = IntegerLiteral::Create(*Context,
3603 llvm::APInt(IntSize, 8),
3604 Context->IntTy,
3605 SourceLocation());
3606 BinaryOperator *lessThanExpr =
3607 new (Context) BinaryOperator(sizeofExpr, limit, BO_LE, Context->IntTy,
Lang Hamesbe9af122012-10-02 04:45:10 +00003608 VK_RValue, OK_Ordinary, SourceLocation(),
3609 false);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003610 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
3611 ConditionalOperator *CondExpr =
3612 new (Context) ConditionalOperator(lessThanExpr,
3613 SourceLocation(), CE,
3614 SourceLocation(), STCE,
3615 returnType, VK_RValue, OK_Ordinary);
3616 ReplacingStmt = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3617 CondExpr);
3618 }
3619 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3620 return ReplacingStmt;
3621}
3622
3623Stmt *RewriteModernObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
3624 Stmt *ReplacingStmt = SynthMessageExpr(Exp, Exp->getLocStart(),
3625 Exp->getLocEnd());
3626
3627 // Now do the actual rewrite.
3628 ReplaceStmt(Exp, ReplacingStmt);
3629
3630 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3631 return ReplacingStmt;
3632}
3633
3634// typedef struct objc_object Protocol;
3635QualType RewriteModernObjC::getProtocolType() {
3636 if (!ProtocolTypeDecl) {
3637 TypeSourceInfo *TInfo
3638 = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
3639 ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
3640 SourceLocation(), SourceLocation(),
3641 &Context->Idents.get("Protocol"),
3642 TInfo);
3643 }
3644 return Context->getTypeDeclType(ProtocolTypeDecl);
3645}
3646
3647/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
3648/// a synthesized/forward data reference (to the protocol's metadata).
3649/// The forward references (and metadata) are generated in
3650/// RewriteModernObjC::HandleTranslationUnit().
3651Stmt *RewriteModernObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00003652 std::string Name = "_OBJC_PROTOCOL_REFERENCE_$_" +
3653 Exp->getProtocol()->getNameAsString();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003654 IdentifierInfo *ID = &Context->Idents.get(Name);
3655 VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
3656 SourceLocation(), ID, getProtocolType(), 0,
3657 SC_Extern, SC_None);
John McCallf4b88a42012-03-10 09:33:50 +00003658 DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, false, getProtocolType(),
3659 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003660 Expr *DerefExpr = new (Context) UnaryOperator(DRE, UO_AddrOf,
3661 Context->getPointerType(DRE->getType()),
3662 VK_RValue, OK_Ordinary, SourceLocation());
3663 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, DerefExpr->getType(),
3664 CK_BitCast,
3665 DerefExpr);
3666 ReplaceStmt(Exp, castExpr);
3667 ProtocolExprDecls.insert(Exp->getProtocol()->getCanonicalDecl());
3668 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3669 return castExpr;
3670
3671}
3672
3673bool RewriteModernObjC::BufferContainsPPDirectives(const char *startBuf,
3674 const char *endBuf) {
3675 while (startBuf < endBuf) {
3676 if (*startBuf == '#') {
3677 // Skip whitespace.
3678 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
3679 ;
3680 if (!strncmp(startBuf, "if", strlen("if")) ||
3681 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
3682 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
3683 !strncmp(startBuf, "define", strlen("define")) ||
3684 !strncmp(startBuf, "undef", strlen("undef")) ||
3685 !strncmp(startBuf, "else", strlen("else")) ||
3686 !strncmp(startBuf, "elif", strlen("elif")) ||
3687 !strncmp(startBuf, "endif", strlen("endif")) ||
3688 !strncmp(startBuf, "pragma", strlen("pragma")) ||
3689 !strncmp(startBuf, "include", strlen("include")) ||
3690 !strncmp(startBuf, "import", strlen("import")) ||
3691 !strncmp(startBuf, "include_next", strlen("include_next")))
3692 return true;
3693 }
3694 startBuf++;
3695 }
3696 return false;
3697}
3698
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003699/// IsTagDefinedInsideClass - This routine checks that a named tagged type
3700/// is defined inside an objective-c class. If so, it returns true.
Fariborz Jahanianb68258f2012-05-01 17:46:45 +00003701bool RewriteModernObjC::IsTagDefinedInsideClass(ObjCContainerDecl *IDecl,
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003702 TagDecl *Tag,
3703 bool &IsNamedDefinition) {
Fariborz Jahanian89585e802012-04-30 19:46:53 +00003704 if (!IDecl)
3705 return false;
3706 SourceLocation TagLocation;
3707 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) {
3708 RD = RD->getDefinition();
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003709 if (!RD || !RD->getDeclName().getAsIdentifierInfo())
Fariborz Jahanian89585e802012-04-30 19:46:53 +00003710 return false;
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003711 IsNamedDefinition = true;
Fariborz Jahanian89585e802012-04-30 19:46:53 +00003712 TagLocation = RD->getLocation();
3713 return Context->getSourceManager().isBeforeInTranslationUnit(
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003714 IDecl->getLocation(), TagLocation);
3715 }
3716 if (EnumDecl *ED = dyn_cast<EnumDecl>(Tag)) {
3717 if (!ED || !ED->getDeclName().getAsIdentifierInfo())
3718 return false;
3719 IsNamedDefinition = true;
3720 TagLocation = ED->getLocation();
3721 return Context->getSourceManager().isBeforeInTranslationUnit(
3722 IDecl->getLocation(), TagLocation);
3723
Fariborz Jahanian89585e802012-04-30 19:46:53 +00003724 }
3725 return false;
3726}
3727
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003728/// RewriteObjCFieldDeclType - This routine rewrites a type into the buffer.
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003729/// It handles elaborated types, as well as enum types in the process.
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003730bool RewriteModernObjC::RewriteObjCFieldDeclType(QualType &Type,
3731 std::string &Result) {
Fariborz Jahanianf5eac482012-05-02 17:34:59 +00003732 if (isa<TypedefType>(Type)) {
3733 Result += "\t";
3734 return false;
3735 }
3736
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003737 if (Type->isArrayType()) {
3738 QualType ElemTy = Context->getBaseElementType(Type);
3739 return RewriteObjCFieldDeclType(ElemTy, Result);
3740 }
3741 else if (Type->isRecordType()) {
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003742 RecordDecl *RD = Type->getAs<RecordType>()->getDecl();
3743 if (RD->isCompleteDefinition()) {
3744 if (RD->isStruct())
3745 Result += "\n\tstruct ";
3746 else if (RD->isUnion())
3747 Result += "\n\tunion ";
3748 else
3749 assert(false && "class not allowed as an ivar type");
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003750
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003751 Result += RD->getName();
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003752 if (GlobalDefinedTags.count(RD)) {
3753 // struct/union is defined globally, use it.
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003754 Result += " ";
3755 return true;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003756 }
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003757 Result += " {\n";
3758 for (RecordDecl::field_iterator i = RD->field_begin(),
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003759 e = RD->field_end(); i != e; ++i) {
David Blaikie581deb32012-06-06 20:45:41 +00003760 FieldDecl *FD = *i;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003761 RewriteObjCFieldDecl(FD, Result);
3762 }
3763 Result += "\t} ";
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003764 return true;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003765 }
3766 }
3767 else if (Type->isEnumeralType()) {
3768 EnumDecl *ED = Type->getAs<EnumType>()->getDecl();
3769 if (ED->isCompleteDefinition()) {
3770 Result += "\n\tenum ";
3771 Result += ED->getName();
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003772 if (GlobalDefinedTags.count(ED)) {
3773 // Enum is globall defined, use it.
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003774 Result += " ";
3775 return true;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003776 }
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003777
3778 Result += " {\n";
3779 for (EnumDecl::enumerator_iterator EC = ED->enumerator_begin(),
3780 ECEnd = ED->enumerator_end(); EC != ECEnd; ++EC) {
3781 Result += "\t"; Result += EC->getName(); Result += " = ";
3782 llvm::APSInt Val = EC->getInitVal();
3783 Result += Val.toString(10);
3784 Result += ",\n";
3785 }
3786 Result += "\t} ";
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003787 return true;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003788 }
3789 }
3790
3791 Result += "\t";
3792 convertObjCTypeToCStyleType(Type);
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003793 return false;
3794}
3795
3796
3797/// RewriteObjCFieldDecl - This routine rewrites a field into the buffer.
3798/// It handles elaborated types, as well as enum types in the process.
3799void RewriteModernObjC::RewriteObjCFieldDecl(FieldDecl *fieldDecl,
3800 std::string &Result) {
3801 QualType Type = fieldDecl->getType();
3802 std::string Name = fieldDecl->getNameAsString();
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003803
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003804 bool EleboratedType = RewriteObjCFieldDeclType(Type, Result);
3805 if (!EleboratedType)
3806 Type.getAsStringInternal(Name, Context->getPrintingPolicy());
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003807 Result += Name;
3808 if (fieldDecl->isBitField()) {
3809 Result += " : "; Result += utostr(fieldDecl->getBitWidthValue(*Context));
3810 }
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003811 else if (EleboratedType && Type->isArrayType()) {
3812 CanQualType CType = Context->getCanonicalType(Type);
3813 while (isa<ArrayType>(CType)) {
3814 if (const ConstantArrayType *CAT = Context->getAsConstantArrayType(CType)) {
3815 Result += "[";
3816 llvm::APInt Dim = CAT->getSize();
3817 Result += utostr(Dim.getZExtValue());
3818 Result += "]";
3819 }
3820 CType = CType->getAs<ArrayType>()->getElementType();
3821 }
3822 }
3823
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003824 Result += ";\n";
3825}
3826
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003827/// RewriteLocallyDefinedNamedAggregates - This routine rewrites locally defined
3828/// named aggregate types into the input buffer.
3829void RewriteModernObjC::RewriteLocallyDefinedNamedAggregates(FieldDecl *fieldDecl,
3830 std::string &Result) {
3831 QualType Type = fieldDecl->getType();
Fariborz Jahanianf5eac482012-05-02 17:34:59 +00003832 if (isa<TypedefType>(Type))
3833 return;
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003834 if (Type->isArrayType())
3835 Type = Context->getBaseElementType(Type);
Fariborz Jahanianb68258f2012-05-01 17:46:45 +00003836 ObjCContainerDecl *IDecl =
3837 dyn_cast<ObjCContainerDecl>(fieldDecl->getDeclContext());
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003838
3839 TagDecl *TD = 0;
3840 if (Type->isRecordType()) {
3841 TD = Type->getAs<RecordType>()->getDecl();
3842 }
3843 else if (Type->isEnumeralType()) {
3844 TD = Type->getAs<EnumType>()->getDecl();
3845 }
3846
3847 if (TD) {
3848 if (GlobalDefinedTags.count(TD))
3849 return;
3850
3851 bool IsNamedDefinition = false;
3852 if (IsTagDefinedInsideClass(IDecl, TD, IsNamedDefinition)) {
3853 RewriteObjCFieldDeclType(Type, Result);
3854 Result += ";";
3855 }
3856 if (IsNamedDefinition)
3857 GlobalDefinedTags.insert(TD);
3858 }
3859
3860}
3861
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003862/// RewriteObjCInternalStruct - Rewrite one internal struct corresponding to
3863/// an objective-c class with ivars.
3864void RewriteModernObjC::RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
3865 std::string &Result) {
3866 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
3867 assert(CDecl->getName() != "" &&
3868 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003869 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003870 SmallVector<ObjCIvarDecl *, 8> IVars;
3871 for (ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
Fariborz Jahanian9a2105b2012-03-06 17:16:27 +00003872 IVD; IVD = IVD->getNextIvar())
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003873 IVars.push_back(IVD);
Fariborz Jahanian9a2105b2012-03-06 17:16:27 +00003874
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003875 SourceLocation LocStart = CDecl->getLocStart();
3876 SourceLocation LocEnd = CDecl->getEndOfDefinitionLoc();
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003877
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003878 const char *startBuf = SM->getCharacterData(LocStart);
3879 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003880
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003881 // If no ivars and no root or if its root, directly or indirectly,
3882 // have no ivars (thus not synthesized) then no need to synthesize this class.
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003883 if ((!CDecl->isThisDeclarationADefinition() || IVars.size() == 0) &&
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003884 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
3885 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
3886 ReplaceText(LocStart, endBuf-startBuf, Result);
3887 return;
3888 }
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003889
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003890 // Insert named struct/union definitions inside class to
3891 // outer scope. This follows semantics of locally defined
3892 // struct/unions in objective-c classes.
3893 for (unsigned i = 0, e = IVars.size(); i < e; i++)
3894 RewriteLocallyDefinedNamedAggregates(IVars[i], Result);
3895
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003896 Result += "\nstruct ";
3897 Result += CDecl->getNameAsString();
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003898 Result += "_IMPL {\n";
3899
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00003900 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003901 Result += "\tstruct "; Result += RCDecl->getNameAsString();
3902 Result += "_IMPL "; Result += RCDecl->getNameAsString();
3903 Result += "_IVARS;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003904 }
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003905
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003906 for (unsigned i = 0, e = IVars.size(); i < e; i++)
3907 RewriteObjCFieldDecl(IVars[i], Result);
Fariborz Jahanian0b17b9a2012-02-12 21:36:23 +00003908
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003909 Result += "};\n";
3910 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
3911 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00003912 // Mark this struct as having been generated.
3913 if (!ObjCSynthesizedStructs.insert(CDecl))
3914 llvm_unreachable("struct already synthesize- RewriteObjCInternalStruct");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003915}
3916
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00003917/// RewriteIvarOffsetSymbols - Rewrite ivar offset symbols of those ivars which
3918/// have been referenced in an ivar access expression.
3919void RewriteModernObjC::RewriteIvarOffsetSymbols(ObjCInterfaceDecl *CDecl,
3920 std::string &Result) {
3921 // write out ivar offset symbols which have been referenced in an ivar
3922 // access expression.
3923 llvm::SmallPtrSet<ObjCIvarDecl *, 8> Ivars = ReferencedIvars[CDecl];
3924 if (Ivars.empty())
3925 return;
3926 for (llvm::SmallPtrSet<ObjCIvarDecl *, 8>::iterator i = Ivars.begin(),
3927 e = Ivars.end(); i != e; i++) {
3928 ObjCIvarDecl *IvarDecl = (*i);
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00003929 Result += "\n";
3930 if (LangOpts.MicrosoftExt)
3931 Result += "__declspec(allocate(\".objc_ivar$B\")) ";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00003932 Result += "extern \"C\" ";
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00003933 if (LangOpts.MicrosoftExt &&
3934 IvarDecl->getAccessControl() != ObjCIvarDecl::Private &&
Fariborz Jahanian297976d2012-03-29 17:51:09 +00003935 IvarDecl->getAccessControl() != ObjCIvarDecl::Package)
3936 Result += "__declspec(dllimport) ";
3937
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00003938 Result += "unsigned long ";
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00003939 WriteInternalIvarName(CDecl, IvarDecl, Result);
3940 Result += ";";
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00003941 }
3942}
3943
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003944//===----------------------------------------------------------------------===//
3945// Meta Data Emission
3946//===----------------------------------------------------------------------===//
3947
3948
3949/// RewriteImplementations - This routine rewrites all method implementations
3950/// and emits meta-data.
3951
3952void RewriteModernObjC::RewriteImplementations() {
3953 int ClsDefCount = ClassImplementation.size();
3954 int CatDefCount = CategoryImplementation.size();
3955
3956 // Rewrite implemented methods
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00003957 for (int i = 0; i < ClsDefCount; i++) {
3958 ObjCImplementationDecl *OIMP = ClassImplementation[i];
3959 ObjCInterfaceDecl *CDecl = OIMP->getClassInterface();
3960 if (CDecl->isImplicitInterfaceDecl())
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +00003961 assert(false &&
3962 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00003963 RewriteImplementationDecl(OIMP);
3964 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003965
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00003966 for (int i = 0; i < CatDefCount; i++) {
3967 ObjCCategoryImplDecl *CIMP = CategoryImplementation[i];
3968 ObjCInterfaceDecl *CDecl = CIMP->getClassInterface();
3969 if (CDecl->isImplicitInterfaceDecl())
3970 assert(false &&
3971 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00003972 RewriteImplementationDecl(CIMP);
3973 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003974}
3975
3976void RewriteModernObjC::RewriteByRefString(std::string &ResultStr,
3977 const std::string &Name,
3978 ValueDecl *VD, bool def) {
3979 assert(BlockByRefDeclNo.count(VD) &&
3980 "RewriteByRefString: ByRef decl missing");
3981 if (def)
3982 ResultStr += "struct ";
3983 ResultStr += "__Block_byref_" + Name +
3984 "_" + utostr(BlockByRefDeclNo[VD]) ;
3985}
3986
3987static bool HasLocalVariableExternalStorage(ValueDecl *VD) {
3988 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
3989 return (Var->isFunctionOrMethodVarDecl() && !Var->hasLocalStorage());
3990 return false;
3991}
3992
3993std::string RewriteModernObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
3994 StringRef funcName,
3995 std::string Tag) {
3996 const FunctionType *AFT = CE->getFunctionType();
3997 QualType RT = AFT->getResultType();
3998 std::string StructRef = "struct " + Tag;
3999 std::string S = "static " + RT.getAsString(Context->getPrintingPolicy()) + " __" +
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00004000 funcName.str() + "_block_func_" + utostr(i);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004001
4002 BlockDecl *BD = CE->getBlockDecl();
4003
4004 if (isa<FunctionNoProtoType>(AFT)) {
4005 // No user-supplied arguments. Still need to pass in a pointer to the
4006 // block (to reference imported block decl refs).
4007 S += "(" + StructRef + " *__cself)";
4008 } else if (BD->param_empty()) {
4009 S += "(" + StructRef + " *__cself)";
4010 } else {
4011 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
4012 assert(FT && "SynthesizeBlockFunc: No function proto");
4013 S += '(';
4014 // first add the implicit argument.
4015 S += StructRef + " *__cself, ";
4016 std::string ParamStr;
4017 for (BlockDecl::param_iterator AI = BD->param_begin(),
4018 E = BD->param_end(); AI != E; ++AI) {
4019 if (AI != BD->param_begin()) S += ", ";
4020 ParamStr = (*AI)->getNameAsString();
4021 QualType QT = (*AI)->getType();
Fariborz Jahanian2610f902012-03-27 16:42:20 +00004022 (void)convertBlockPointerToFunctionPointer(QT);
4023 QT.getAsStringInternal(ParamStr, Context->getPrintingPolicy());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004024 S += ParamStr;
4025 }
4026 if (FT->isVariadic()) {
4027 if (!BD->param_empty()) S += ", ";
4028 S += "...";
4029 }
4030 S += ')';
4031 }
4032 S += " {\n";
4033
4034 // Create local declarations to avoid rewriting all closure decl ref exprs.
4035 // First, emit a declaration for all "by ref" decls.
4036 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
4037 E = BlockByRefDecls.end(); I != E; ++I) {
4038 S += " ";
4039 std::string Name = (*I)->getNameAsString();
4040 std::string TypeString;
4041 RewriteByRefString(TypeString, Name, (*I));
4042 TypeString += " *";
4043 Name = TypeString + Name;
4044 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
4045 }
4046 // Next, emit a declaration for all "by copy" declarations.
4047 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
4048 E = BlockByCopyDecls.end(); I != E; ++I) {
4049 S += " ";
4050 // Handle nested closure invocation. For example:
4051 //
4052 // void (^myImportedClosure)(void);
4053 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
4054 //
4055 // void (^anotherClosure)(void);
4056 // anotherClosure = ^(void) {
4057 // myImportedClosure(); // import and invoke the closure
4058 // };
4059 //
4060 if (isTopLevelBlockPointerType((*I)->getType())) {
4061 RewriteBlockPointerTypeVariable(S, (*I));
4062 S += " = (";
4063 RewriteBlockPointerType(S, (*I)->getType());
4064 S += ")";
4065 S += "__cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
4066 }
4067 else {
4068 std::string Name = (*I)->getNameAsString();
4069 QualType QT = (*I)->getType();
4070 if (HasLocalVariableExternalStorage(*I))
4071 QT = Context->getPointerType(QT);
4072 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
4073 S += Name + " = __cself->" +
4074 (*I)->getNameAsString() + "; // bound by copy\n";
4075 }
4076 }
4077 std::string RewrittenStr = RewrittenBlockExprs[CE];
4078 const char *cstr = RewrittenStr.c_str();
4079 while (*cstr++ != '{') ;
4080 S += cstr;
4081 S += "\n";
4082 return S;
4083}
4084
4085std::string RewriteModernObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
4086 StringRef funcName,
4087 std::string Tag) {
4088 std::string StructRef = "struct " + Tag;
4089 std::string S = "static void __";
4090
4091 S += funcName;
4092 S += "_block_copy_" + utostr(i);
4093 S += "(" + StructRef;
4094 S += "*dst, " + StructRef;
4095 S += "*src) {";
4096 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
4097 E = ImportedBlockDecls.end(); I != E; ++I) {
4098 ValueDecl *VD = (*I);
4099 S += "_Block_object_assign((void*)&dst->";
4100 S += (*I)->getNameAsString();
4101 S += ", (void*)src->";
4102 S += (*I)->getNameAsString();
4103 if (BlockByRefDeclsPtrSet.count((*I)))
4104 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
4105 else if (VD->getType()->isBlockPointerType())
4106 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
4107 else
4108 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
4109 }
4110 S += "}\n";
4111
4112 S += "\nstatic void __";
4113 S += funcName;
4114 S += "_block_dispose_" + utostr(i);
4115 S += "(" + StructRef;
4116 S += "*src) {";
4117 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
4118 E = ImportedBlockDecls.end(); I != E; ++I) {
4119 ValueDecl *VD = (*I);
4120 S += "_Block_object_dispose((void*)src->";
4121 S += (*I)->getNameAsString();
4122 if (BlockByRefDeclsPtrSet.count((*I)))
4123 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
4124 else if (VD->getType()->isBlockPointerType())
4125 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
4126 else
4127 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
4128 }
4129 S += "}\n";
4130 return S;
4131}
4132
4133std::string RewriteModernObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
4134 std::string Desc) {
4135 std::string S = "\nstruct " + Tag;
4136 std::string Constructor = " " + Tag;
4137
4138 S += " {\n struct __block_impl impl;\n";
4139 S += " struct " + Desc;
4140 S += "* Desc;\n";
4141
4142 Constructor += "(void *fp, "; // Invoke function pointer.
4143 Constructor += "struct " + Desc; // Descriptor pointer.
4144 Constructor += " *desc";
4145
4146 if (BlockDeclRefs.size()) {
4147 // Output all "by copy" declarations.
4148 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
4149 E = BlockByCopyDecls.end(); I != E; ++I) {
4150 S += " ";
4151 std::string FieldName = (*I)->getNameAsString();
4152 std::string ArgName = "_" + FieldName;
4153 // Handle nested closure invocation. For example:
4154 //
4155 // void (^myImportedBlock)(void);
4156 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
4157 //
4158 // void (^anotherBlock)(void);
4159 // anotherBlock = ^(void) {
4160 // myImportedBlock(); // import and invoke the closure
4161 // };
4162 //
4163 if (isTopLevelBlockPointerType((*I)->getType())) {
4164 S += "struct __block_impl *";
4165 Constructor += ", void *" + ArgName;
4166 } else {
4167 QualType QT = (*I)->getType();
4168 if (HasLocalVariableExternalStorage(*I))
4169 QT = Context->getPointerType(QT);
4170 QT.getAsStringInternal(FieldName, Context->getPrintingPolicy());
4171 QT.getAsStringInternal(ArgName, Context->getPrintingPolicy());
4172 Constructor += ", " + ArgName;
4173 }
4174 S += FieldName + ";\n";
4175 }
4176 // Output all "by ref" declarations.
4177 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
4178 E = BlockByRefDecls.end(); I != E; ++I) {
4179 S += " ";
4180 std::string FieldName = (*I)->getNameAsString();
4181 std::string ArgName = "_" + FieldName;
4182 {
4183 std::string TypeString;
4184 RewriteByRefString(TypeString, FieldName, (*I));
4185 TypeString += " *";
4186 FieldName = TypeString + FieldName;
4187 ArgName = TypeString + ArgName;
4188 Constructor += ", " + ArgName;
4189 }
4190 S += FieldName + "; // by ref\n";
4191 }
4192 // Finish writing the constructor.
4193 Constructor += ", int flags=0)";
4194 // Initialize all "by copy" arguments.
4195 bool firsTime = true;
4196 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
4197 E = BlockByCopyDecls.end(); I != E; ++I) {
4198 std::string Name = (*I)->getNameAsString();
4199 if (firsTime) {
4200 Constructor += " : ";
4201 firsTime = false;
4202 }
4203 else
4204 Constructor += ", ";
4205 if (isTopLevelBlockPointerType((*I)->getType()))
4206 Constructor += Name + "((struct __block_impl *)_" + Name + ")";
4207 else
4208 Constructor += Name + "(_" + Name + ")";
4209 }
4210 // Initialize all "by ref" arguments.
4211 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
4212 E = BlockByRefDecls.end(); I != E; ++I) {
4213 std::string Name = (*I)->getNameAsString();
4214 if (firsTime) {
4215 Constructor += " : ";
4216 firsTime = false;
4217 }
4218 else
4219 Constructor += ", ";
4220 Constructor += Name + "(_" + Name + "->__forwarding)";
4221 }
4222
4223 Constructor += " {\n";
4224 if (GlobalVarDecl)
4225 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4226 else
4227 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
4228 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
4229
4230 Constructor += " Desc = desc;\n";
4231 } else {
4232 // Finish writing the constructor.
4233 Constructor += ", int flags=0) {\n";
4234 if (GlobalVarDecl)
4235 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4236 else
4237 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
4238 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
4239 Constructor += " Desc = desc;\n";
4240 }
4241 Constructor += " ";
4242 Constructor += "}\n";
4243 S += Constructor;
4244 S += "};\n";
4245 return S;
4246}
4247
4248std::string RewriteModernObjC::SynthesizeBlockDescriptor(std::string DescTag,
4249 std::string ImplTag, int i,
4250 StringRef FunName,
4251 unsigned hasCopy) {
4252 std::string S = "\nstatic struct " + DescTag;
4253
Fariborz Jahanian8b08adb2012-05-03 21:44:12 +00004254 S += " {\n size_t reserved;\n";
4255 S += " size_t Block_size;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004256 if (hasCopy) {
4257 S += " void (*copy)(struct ";
4258 S += ImplTag; S += "*, struct ";
4259 S += ImplTag; S += "*);\n";
4260
4261 S += " void (*dispose)(struct ";
4262 S += ImplTag; S += "*);\n";
4263 }
4264 S += "} ";
4265
4266 S += DescTag + "_DATA = { 0, sizeof(struct ";
4267 S += ImplTag + ")";
4268 if (hasCopy) {
4269 S += ", __" + FunName.str() + "_block_copy_" + utostr(i);
4270 S += ", __" + FunName.str() + "_block_dispose_" + utostr(i);
4271 }
4272 S += "};\n";
4273 return S;
4274}
4275
4276void RewriteModernObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
4277 StringRef FunName) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004278 bool RewriteSC = (GlobalVarDecl &&
4279 !Blocks.empty() &&
4280 GlobalVarDecl->getStorageClass() == SC_Static &&
4281 GlobalVarDecl->getType().getCVRQualifiers());
4282 if (RewriteSC) {
4283 std::string SC(" void __");
4284 SC += GlobalVarDecl->getNameAsString();
4285 SC += "() {}";
4286 InsertText(FunLocStart, SC);
4287 }
4288
4289 // Insert closures that were part of the function.
4290 for (unsigned i = 0, count=0; i < Blocks.size(); i++) {
4291 CollectBlockDeclRefInfo(Blocks[i]);
4292 // Need to copy-in the inner copied-in variables not actually used in this
4293 // block.
4294 for (int j = 0; j < InnerDeclRefsCount[i]; j++) {
John McCallf4b88a42012-03-10 09:33:50 +00004295 DeclRefExpr *Exp = InnerDeclRefs[count++];
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004296 ValueDecl *VD = Exp->getDecl();
4297 BlockDeclRefs.push_back(Exp);
John McCallf4b88a42012-03-10 09:33:50 +00004298 if (!VD->hasAttr<BlocksAttr>()) {
4299 if (!BlockByCopyDeclsPtrSet.count(VD)) {
4300 BlockByCopyDeclsPtrSet.insert(VD);
4301 BlockByCopyDecls.push_back(VD);
4302 }
4303 continue;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004304 }
John McCallf4b88a42012-03-10 09:33:50 +00004305
4306 if (!BlockByRefDeclsPtrSet.count(VD)) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004307 BlockByRefDeclsPtrSet.insert(VD);
4308 BlockByRefDecls.push_back(VD);
4309 }
John McCallf4b88a42012-03-10 09:33:50 +00004310
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004311 // imported objects in the inner blocks not used in the outer
4312 // blocks must be copied/disposed in the outer block as well.
John McCallf4b88a42012-03-10 09:33:50 +00004313 if (VD->getType()->isObjCObjectPointerType() ||
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004314 VD->getType()->isBlockPointerType())
4315 ImportedBlockDecls.insert(VD);
4316 }
4317
4318 std::string ImplTag = "__" + FunName.str() + "_block_impl_" + utostr(i);
4319 std::string DescTag = "__" + FunName.str() + "_block_desc_" + utostr(i);
4320
4321 std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
4322
4323 InsertText(FunLocStart, CI);
4324
4325 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
4326
4327 InsertText(FunLocStart, CF);
4328
4329 if (ImportedBlockDecls.size()) {
4330 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
4331 InsertText(FunLocStart, HF);
4332 }
4333 std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
4334 ImportedBlockDecls.size() > 0);
4335 InsertText(FunLocStart, BD);
4336
4337 BlockDeclRefs.clear();
4338 BlockByRefDecls.clear();
4339 BlockByRefDeclsPtrSet.clear();
4340 BlockByCopyDecls.clear();
4341 BlockByCopyDeclsPtrSet.clear();
4342 ImportedBlockDecls.clear();
4343 }
4344 if (RewriteSC) {
4345 // Must insert any 'const/volatile/static here. Since it has been
4346 // removed as result of rewriting of block literals.
4347 std::string SC;
4348 if (GlobalVarDecl->getStorageClass() == SC_Static)
4349 SC = "static ";
4350 if (GlobalVarDecl->getType().isConstQualified())
4351 SC += "const ";
4352 if (GlobalVarDecl->getType().isVolatileQualified())
4353 SC += "volatile ";
4354 if (GlobalVarDecl->getType().isRestrictQualified())
4355 SC += "restrict ";
4356 InsertText(FunLocStart, SC);
4357 }
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00004358 if (GlobalConstructionExp) {
4359 // extra fancy dance for global literal expression.
4360
4361 // Always the latest block expression on the block stack.
4362 std::string Tag = "__";
4363 Tag += FunName;
4364 Tag += "_block_impl_";
4365 Tag += utostr(Blocks.size()-1);
4366 std::string globalBuf = "static ";
4367 globalBuf += Tag; globalBuf += " ";
4368 std::string SStr;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004369
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00004370 llvm::raw_string_ostream constructorExprBuf(SStr);
Richard Smithd1420c62012-08-16 03:56:14 +00004371 GlobalConstructionExp->printPretty(constructorExprBuf, 0,
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00004372 PrintingPolicy(LangOpts));
4373 globalBuf += constructorExprBuf.str();
4374 globalBuf += ";\n";
4375 InsertText(FunLocStart, globalBuf);
4376 GlobalConstructionExp = 0;
4377 }
4378
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004379 Blocks.clear();
4380 InnerDeclRefsCount.clear();
4381 InnerDeclRefs.clear();
4382 RewrittenBlockExprs.clear();
4383}
4384
4385void RewriteModernObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
Fariborz Jahanian04189532012-04-25 17:56:48 +00004386 SourceLocation FunLocStart =
4387 (!Blocks.empty()) ? getFunctionSourceLocation(*this, FD)
4388 : FD->getTypeSpecStartLoc();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004389 StringRef FuncName = FD->getName();
4390
4391 SynthesizeBlockLiterals(FunLocStart, FuncName);
4392}
4393
4394static void BuildUniqueMethodName(std::string &Name,
4395 ObjCMethodDecl *MD) {
4396 ObjCInterfaceDecl *IFace = MD->getClassInterface();
4397 Name = IFace->getName();
4398 Name += "__" + MD->getSelector().getAsString();
4399 // Convert colons to underscores.
4400 std::string::size_type loc = 0;
4401 while ((loc = Name.find(":", loc)) != std::string::npos)
4402 Name.replace(loc, 1, "_");
4403}
4404
4405void RewriteModernObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
4406 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
4407 //SourceLocation FunLocStart = MD->getLocStart();
4408 SourceLocation FunLocStart = MD->getLocStart();
4409 std::string FuncName;
4410 BuildUniqueMethodName(FuncName, MD);
4411 SynthesizeBlockLiterals(FunLocStart, FuncName);
4412}
4413
4414void RewriteModernObjC::GetBlockDeclRefExprs(Stmt *S) {
4415 for (Stmt::child_range CI = S->children(); CI; ++CI)
4416 if (*CI) {
4417 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
4418 GetBlockDeclRefExprs(CBE->getBody());
4419 else
4420 GetBlockDeclRefExprs(*CI);
4421 }
4422 // Handle specific things.
Fariborz Jahanian0e976812012-04-16 23:00:57 +00004423 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4424 if (DRE->refersToEnclosingLocal()) {
4425 // FIXME: Handle enums.
4426 if (!isa<FunctionDecl>(DRE->getDecl()))
4427 BlockDeclRefs.push_back(DRE);
4428 if (HasLocalVariableExternalStorage(DRE->getDecl()))
4429 BlockDeclRefs.push_back(DRE);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004430 }
Fariborz Jahanian0e976812012-04-16 23:00:57 +00004431 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004432
4433 return;
4434}
4435
4436void RewriteModernObjC::GetInnerBlockDeclRefExprs(Stmt *S,
John McCallf4b88a42012-03-10 09:33:50 +00004437 SmallVector<DeclRefExpr *, 8> &InnerBlockDeclRefs,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004438 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts) {
4439 for (Stmt::child_range CI = S->children(); CI; ++CI)
4440 if (*CI) {
4441 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI)) {
4442 InnerContexts.insert(cast<DeclContext>(CBE->getBlockDecl()));
4443 GetInnerBlockDeclRefExprs(CBE->getBody(),
4444 InnerBlockDeclRefs,
4445 InnerContexts);
4446 }
4447 else
4448 GetInnerBlockDeclRefExprs(*CI,
4449 InnerBlockDeclRefs,
4450 InnerContexts);
4451
4452 }
4453 // Handle specific things.
John McCallf4b88a42012-03-10 09:33:50 +00004454 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4455 if (DRE->refersToEnclosingLocal()) {
4456 if (!isa<FunctionDecl>(DRE->getDecl()) &&
4457 !InnerContexts.count(DRE->getDecl()->getDeclContext()))
4458 InnerBlockDeclRefs.push_back(DRE);
4459 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl()))
4460 if (Var->isFunctionOrMethodVarDecl())
4461 ImportedLocalExternalDecls.insert(Var);
4462 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004463 }
4464
4465 return;
4466}
4467
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00004468/// convertObjCTypeToCStyleType - This routine converts such objc types
4469/// as qualified objects, and blocks to their closest c/c++ types that
4470/// it can. It returns true if input type was modified.
4471bool RewriteModernObjC::convertObjCTypeToCStyleType(QualType &T) {
4472 QualType oldT = T;
4473 convertBlockPointerToFunctionPointer(T);
4474 if (T->isFunctionPointerType()) {
4475 QualType PointeeTy;
4476 if (const PointerType* PT = T->getAs<PointerType>()) {
4477 PointeeTy = PT->getPointeeType();
4478 if (const FunctionType *FT = PointeeTy->getAs<FunctionType>()) {
4479 T = convertFunctionTypeOfBlocks(FT);
4480 T = Context->getPointerType(T);
4481 }
4482 }
4483 }
4484
4485 convertToUnqualifiedObjCType(T);
4486 return T != oldT;
4487}
4488
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004489/// convertFunctionTypeOfBlocks - This routine converts a function type
4490/// whose result type may be a block pointer or whose argument type(s)
4491/// might be block pointers to an equivalent function type replacing
4492/// all block pointers to function pointers.
4493QualType RewriteModernObjC::convertFunctionTypeOfBlocks(const FunctionType *FT) {
4494 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
4495 // FTP will be null for closures that don't take arguments.
4496 // Generate a funky cast.
4497 SmallVector<QualType, 8> ArgTypes;
4498 QualType Res = FT->getResultType();
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00004499 bool modified = convertObjCTypeToCStyleType(Res);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004500
4501 if (FTP) {
4502 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4503 E = FTP->arg_type_end(); I && (I != E); ++I) {
4504 QualType t = *I;
4505 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00004506 if (convertObjCTypeToCStyleType(t))
4507 modified = true;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004508 ArgTypes.push_back(t);
4509 }
4510 }
4511 QualType FuncType;
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00004512 if (modified)
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004513 FuncType = getSimpleFunctionType(Res, &ArgTypes[0], ArgTypes.size());
4514 else FuncType = QualType(FT, 0);
4515 return FuncType;
4516}
4517
4518Stmt *RewriteModernObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
4519 // Navigate to relevant type information.
4520 const BlockPointerType *CPT = 0;
4521
4522 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
4523 CPT = DRE->getType()->getAs<BlockPointerType>();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004524 } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
4525 CPT = MExpr->getType()->getAs<BlockPointerType>();
4526 }
4527 else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
4528 return SynthesizeBlockCall(Exp, PRE->getSubExpr());
4529 }
4530 else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
4531 CPT = IEXPR->getType()->getAs<BlockPointerType>();
4532 else if (const ConditionalOperator *CEXPR =
4533 dyn_cast<ConditionalOperator>(BlockExp)) {
4534 Expr *LHSExp = CEXPR->getLHS();
4535 Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
4536 Expr *RHSExp = CEXPR->getRHS();
4537 Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
4538 Expr *CONDExp = CEXPR->getCond();
4539 ConditionalOperator *CondExpr =
4540 new (Context) ConditionalOperator(CONDExp,
4541 SourceLocation(), cast<Expr>(LHSStmt),
4542 SourceLocation(), cast<Expr>(RHSStmt),
4543 Exp->getType(), VK_RValue, OK_Ordinary);
4544 return CondExpr;
4545 } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
4546 CPT = IRE->getType()->getAs<BlockPointerType>();
4547 } else if (const PseudoObjectExpr *POE
4548 = dyn_cast<PseudoObjectExpr>(BlockExp)) {
4549 CPT = POE->getType()->castAs<BlockPointerType>();
4550 } else {
4551 assert(1 && "RewriteBlockClass: Bad type");
4552 }
4553 assert(CPT && "RewriteBlockClass: Bad type");
4554 const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
4555 assert(FT && "RewriteBlockClass: Bad type");
4556 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
4557 // FTP will be null for closures that don't take arguments.
4558
4559 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
4560 SourceLocation(), SourceLocation(),
4561 &Context->Idents.get("__block_impl"));
4562 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
4563
4564 // Generate a funky cast.
4565 SmallVector<QualType, 8> ArgTypes;
4566
4567 // Push the block argument type.
4568 ArgTypes.push_back(PtrBlock);
4569 if (FTP) {
4570 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4571 E = FTP->arg_type_end(); I && (I != E); ++I) {
4572 QualType t = *I;
4573 // Make sure we convert "t (^)(...)" to "t (*)(...)".
4574 if (!convertBlockPointerToFunctionPointer(t))
4575 convertToUnqualifiedObjCType(t);
4576 ArgTypes.push_back(t);
4577 }
4578 }
4579 // Now do the pointer to function cast.
4580 QualType PtrToFuncCastType
4581 = getSimpleFunctionType(Exp->getType(), &ArgTypes[0], ArgTypes.size());
4582
4583 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
4584
4585 CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock,
4586 CK_BitCast,
4587 const_cast<Expr*>(BlockExp));
4588 // Don't forget the parens to enforce the proper binding.
4589 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4590 BlkCast);
4591 //PE->dump();
4592
4593 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4594 SourceLocation(),
4595 &Context->Idents.get("FuncPtr"),
4596 Context->VoidPtrTy, 0,
4597 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smithca523302012-06-10 03:12:00 +00004598 ICIS_NoInit);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004599 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
4600 FD->getType(), VK_LValue,
4601 OK_Ordinary);
4602
4603
4604 CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType,
4605 CK_BitCast, ME);
4606 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
4607
4608 SmallVector<Expr*, 8> BlkExprs;
4609 // Add the implicit argument.
4610 BlkExprs.push_back(BlkCast);
4611 // Add the user arguments.
4612 for (CallExpr::arg_iterator I = Exp->arg_begin(),
4613 E = Exp->arg_end(); I != E; ++I) {
4614 BlkExprs.push_back(*I);
4615 }
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00004616 CallExpr *CE = new (Context) CallExpr(*Context, PE, BlkExprs,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004617 Exp->getType(), VK_RValue,
4618 SourceLocation());
4619 return CE;
4620}
4621
4622// We need to return the rewritten expression to handle cases where the
John McCallf4b88a42012-03-10 09:33:50 +00004623// DeclRefExpr is embedded in another expression being rewritten.
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004624// For example:
4625//
4626// int main() {
4627// __block Foo *f;
4628// __block int i;
4629//
4630// void (^myblock)() = ^() {
John McCallf4b88a42012-03-10 09:33:50 +00004631// [f test]; // f is a DeclRefExpr embedded in a message (which is being rewritten).
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004632// i = 77;
4633// };
4634//}
John McCallf4b88a42012-03-10 09:33:50 +00004635Stmt *RewriteModernObjC::RewriteBlockDeclRefExpr(DeclRefExpr *DeclRefExp) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004636 // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
4637 // for each DeclRefExp where BYREFVAR is name of the variable.
John McCallf4b88a42012-03-10 09:33:50 +00004638 ValueDecl *VD = DeclRefExp->getDecl();
4639 bool isArrow = DeclRefExp->refersToEnclosingLocal();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004640
4641 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4642 SourceLocation(),
4643 &Context->Idents.get("__forwarding"),
4644 Context->VoidPtrTy, 0,
4645 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smithca523302012-06-10 03:12:00 +00004646 ICIS_NoInit);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004647 MemberExpr *ME = new (Context) MemberExpr(DeclRefExp, isArrow,
4648 FD, SourceLocation(),
4649 FD->getType(), VK_LValue,
4650 OK_Ordinary);
4651
4652 StringRef Name = VD->getName();
4653 FD = FieldDecl::Create(*Context, 0, SourceLocation(), SourceLocation(),
4654 &Context->Idents.get(Name),
4655 Context->VoidPtrTy, 0,
4656 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smithca523302012-06-10 03:12:00 +00004657 ICIS_NoInit);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004658 ME = new (Context) MemberExpr(ME, true, FD, SourceLocation(),
4659 DeclRefExp->getType(), VK_LValue, OK_Ordinary);
4660
4661
4662
4663 // Need parens to enforce precedence.
4664 ParenExpr *PE = new (Context) ParenExpr(DeclRefExp->getExprLoc(),
4665 DeclRefExp->getExprLoc(),
4666 ME);
4667 ReplaceStmt(DeclRefExp, PE);
4668 return PE;
4669}
4670
4671// Rewrites the imported local variable V with external storage
4672// (static, extern, etc.) as *V
4673//
4674Stmt *RewriteModernObjC::RewriteLocalVariableExternalStorage(DeclRefExpr *DRE) {
4675 ValueDecl *VD = DRE->getDecl();
4676 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4677 if (!ImportedLocalExternalDecls.count(Var))
4678 return DRE;
4679 Expr *Exp = new (Context) UnaryOperator(DRE, UO_Deref, DRE->getType(),
4680 VK_LValue, OK_Ordinary,
4681 DRE->getLocation());
4682 // Need parens to enforce precedence.
4683 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4684 Exp);
4685 ReplaceStmt(DRE, PE);
4686 return PE;
4687}
4688
4689void RewriteModernObjC::RewriteCastExpr(CStyleCastExpr *CE) {
4690 SourceLocation LocStart = CE->getLParenLoc();
4691 SourceLocation LocEnd = CE->getRParenLoc();
4692
4693 // Need to avoid trying to rewrite synthesized casts.
4694 if (LocStart.isInvalid())
4695 return;
4696 // Need to avoid trying to rewrite casts contained in macros.
4697 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
4698 return;
4699
4700 const char *startBuf = SM->getCharacterData(LocStart);
4701 const char *endBuf = SM->getCharacterData(LocEnd);
4702 QualType QT = CE->getType();
4703 const Type* TypePtr = QT->getAs<Type>();
4704 if (isa<TypeOfExprType>(TypePtr)) {
4705 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
4706 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
4707 std::string TypeAsString = "(";
4708 RewriteBlockPointerType(TypeAsString, QT);
4709 TypeAsString += ")";
4710 ReplaceText(LocStart, endBuf-startBuf+1, TypeAsString);
4711 return;
4712 }
4713 // advance the location to startArgList.
4714 const char *argPtr = startBuf;
4715
4716 while (*argPtr++ && (argPtr < endBuf)) {
4717 switch (*argPtr) {
4718 case '^':
4719 // Replace the '^' with '*'.
4720 LocStart = LocStart.getLocWithOffset(argPtr-startBuf);
4721 ReplaceText(LocStart, 1, "*");
4722 break;
4723 }
4724 }
4725 return;
4726}
4727
Fariborz Jahanianf1ee6872012-04-10 00:08:18 +00004728void RewriteModernObjC::RewriteImplicitCastObjCExpr(CastExpr *IC) {
4729 CastKind CastKind = IC->getCastKind();
Fariborz Jahanian43aa1c32012-04-16 22:14:01 +00004730 if (CastKind != CK_BlockPointerToObjCPointerCast &&
4731 CastKind != CK_AnyPointerToBlockPointerCast)
4732 return;
Fariborz Jahanianf1ee6872012-04-10 00:08:18 +00004733
Fariborz Jahanian43aa1c32012-04-16 22:14:01 +00004734 QualType QT = IC->getType();
4735 (void)convertBlockPointerToFunctionPointer(QT);
4736 std::string TypeString(QT.getAsString(Context->getPrintingPolicy()));
4737 std::string Str = "(";
4738 Str += TypeString;
4739 Str += ")";
4740 InsertText(IC->getSubExpr()->getLocStart(), &Str[0], Str.size());
4741
Fariborz Jahanianf1ee6872012-04-10 00:08:18 +00004742 return;
4743}
4744
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004745void RewriteModernObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
4746 SourceLocation DeclLoc = FD->getLocation();
4747 unsigned parenCount = 0;
4748
4749 // We have 1 or more arguments that have closure pointers.
4750 const char *startBuf = SM->getCharacterData(DeclLoc);
4751 const char *startArgList = strchr(startBuf, '(');
4752
4753 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
4754
4755 parenCount++;
4756 // advance the location to startArgList.
4757 DeclLoc = DeclLoc.getLocWithOffset(startArgList-startBuf);
4758 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
4759
4760 const char *argPtr = startArgList;
4761
4762 while (*argPtr++ && parenCount) {
4763 switch (*argPtr) {
4764 case '^':
4765 // Replace the '^' with '*'.
4766 DeclLoc = DeclLoc.getLocWithOffset(argPtr-startArgList);
4767 ReplaceText(DeclLoc, 1, "*");
4768 break;
4769 case '(':
4770 parenCount++;
4771 break;
4772 case ')':
4773 parenCount--;
4774 break;
4775 }
4776 }
4777 return;
4778}
4779
4780bool RewriteModernObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
4781 const FunctionProtoType *FTP;
4782 const PointerType *PT = QT->getAs<PointerType>();
4783 if (PT) {
4784 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4785 } else {
4786 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4787 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4788 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4789 }
4790 if (FTP) {
4791 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4792 E = FTP->arg_type_end(); I != E; ++I)
4793 if (isTopLevelBlockPointerType(*I))
4794 return true;
4795 }
4796 return false;
4797}
4798
4799bool RewriteModernObjC::PointerTypeTakesAnyObjCQualifiedType(QualType QT) {
4800 const FunctionProtoType *FTP;
4801 const PointerType *PT = QT->getAs<PointerType>();
4802 if (PT) {
4803 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4804 } else {
4805 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4806 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4807 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4808 }
4809 if (FTP) {
4810 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4811 E = FTP->arg_type_end(); I != E; ++I) {
4812 if ((*I)->isObjCQualifiedIdType())
4813 return true;
4814 if ((*I)->isObjCObjectPointerType() &&
4815 (*I)->getPointeeType()->isObjCQualifiedInterfaceType())
4816 return true;
4817 }
4818
4819 }
4820 return false;
4821}
4822
4823void RewriteModernObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
4824 const char *&RParen) {
4825 const char *argPtr = strchr(Name, '(');
4826 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
4827
4828 LParen = argPtr; // output the start.
4829 argPtr++; // skip past the left paren.
4830 unsigned parenCount = 1;
4831
4832 while (*argPtr && parenCount) {
4833 switch (*argPtr) {
4834 case '(': parenCount++; break;
4835 case ')': parenCount--; break;
4836 default: break;
4837 }
4838 if (parenCount) argPtr++;
4839 }
4840 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
4841 RParen = argPtr; // output the end
4842}
4843
4844void RewriteModernObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
4845 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4846 RewriteBlockPointerFunctionArgs(FD);
4847 return;
4848 }
4849 // Handle Variables and Typedefs.
4850 SourceLocation DeclLoc = ND->getLocation();
4851 QualType DeclT;
4852 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
4853 DeclT = VD->getType();
4854 else if (TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(ND))
4855 DeclT = TDD->getUnderlyingType();
4856 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
4857 DeclT = FD->getType();
4858 else
4859 llvm_unreachable("RewriteBlockPointerDecl(): Decl type not yet handled");
4860
4861 const char *startBuf = SM->getCharacterData(DeclLoc);
4862 const char *endBuf = startBuf;
4863 // scan backward (from the decl location) for the end of the previous decl.
4864 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
4865 startBuf--;
4866 SourceLocation Start = DeclLoc.getLocWithOffset(startBuf-endBuf);
4867 std::string buf;
4868 unsigned OrigLength=0;
4869 // *startBuf != '^' if we are dealing with a pointer to function that
4870 // may take block argument types (which will be handled below).
4871 if (*startBuf == '^') {
4872 // Replace the '^' with '*', computing a negative offset.
4873 buf = '*';
4874 startBuf++;
4875 OrigLength++;
4876 }
4877 while (*startBuf != ')') {
4878 buf += *startBuf;
4879 startBuf++;
4880 OrigLength++;
4881 }
4882 buf += ')';
4883 OrigLength++;
4884
4885 if (PointerTypeTakesAnyBlockArguments(DeclT) ||
4886 PointerTypeTakesAnyObjCQualifiedType(DeclT)) {
4887 // Replace the '^' with '*' for arguments.
4888 // Replace id<P> with id/*<>*/
4889 DeclLoc = ND->getLocation();
4890 startBuf = SM->getCharacterData(DeclLoc);
4891 const char *argListBegin, *argListEnd;
4892 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
4893 while (argListBegin < argListEnd) {
4894 if (*argListBegin == '^')
4895 buf += '*';
4896 else if (*argListBegin == '<') {
4897 buf += "/*";
4898 buf += *argListBegin++;
Dmitri Gribenko1ad23d62012-09-10 21:20:09 +00004899 OrigLength++;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004900 while (*argListBegin != '>') {
4901 buf += *argListBegin++;
4902 OrigLength++;
4903 }
4904 buf += *argListBegin;
4905 buf += "*/";
4906 }
4907 else
4908 buf += *argListBegin;
4909 argListBegin++;
4910 OrigLength++;
4911 }
4912 buf += ')';
4913 OrigLength++;
4914 }
4915 ReplaceText(Start, OrigLength, buf);
4916
4917 return;
4918}
4919
4920
4921/// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
4922/// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
4923/// struct Block_byref_id_object *src) {
4924/// _Block_object_assign (&_dest->object, _src->object,
4925/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4926/// [|BLOCK_FIELD_IS_WEAK]) // object
4927/// _Block_object_assign(&_dest->object, _src->object,
4928/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4929/// [|BLOCK_FIELD_IS_WEAK]) // block
4930/// }
4931/// And:
4932/// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
4933/// _Block_object_dispose(_src->object,
4934/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4935/// [|BLOCK_FIELD_IS_WEAK]) // object
4936/// _Block_object_dispose(_src->object,
4937/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4938/// [|BLOCK_FIELD_IS_WEAK]) // block
4939/// }
4940
4941std::string RewriteModernObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
4942 int flag) {
4943 std::string S;
4944 if (CopyDestroyCache.count(flag))
4945 return S;
4946 CopyDestroyCache.insert(flag);
4947 S = "static void __Block_byref_id_object_copy_";
4948 S += utostr(flag);
4949 S += "(void *dst, void *src) {\n";
4950
4951 // offset into the object pointer is computed as:
4952 // void * + void* + int + int + void* + void *
4953 unsigned IntSize =
4954 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
4955 unsigned VoidPtrSize =
4956 static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
4957
4958 unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/Context->getCharWidth();
4959 S += " _Block_object_assign((char*)dst + ";
4960 S += utostr(offset);
4961 S += ", *(void * *) ((char*)src + ";
4962 S += utostr(offset);
4963 S += "), ";
4964 S += utostr(flag);
4965 S += ");\n}\n";
4966
4967 S += "static void __Block_byref_id_object_dispose_";
4968 S += utostr(flag);
4969 S += "(void *src) {\n";
4970 S += " _Block_object_dispose(*(void * *) ((char*)src + ";
4971 S += utostr(offset);
4972 S += "), ";
4973 S += utostr(flag);
4974 S += ");\n}\n";
4975 return S;
4976}
4977
4978/// RewriteByRefVar - For each __block typex ND variable this routine transforms
4979/// the declaration into:
4980/// struct __Block_byref_ND {
4981/// void *__isa; // NULL for everything except __weak pointers
4982/// struct __Block_byref_ND *__forwarding;
4983/// int32_t __flags;
4984/// int32_t __size;
4985/// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
4986/// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
4987/// typex ND;
4988/// };
4989///
4990/// It then replaces declaration of ND variable with:
4991/// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
4992/// __size=sizeof(struct __Block_byref_ND),
4993/// ND=initializer-if-any};
4994///
4995///
Fariborz Jahanian4fe261c2012-04-24 19:38:45 +00004996void RewriteModernObjC::RewriteByRefVar(VarDecl *ND, bool firstDecl,
4997 bool lastDecl) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004998 int flag = 0;
4999 int isa = 0;
5000 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
5001 if (DeclLoc.isInvalid())
5002 // If type location is missing, it is because of missing type (a warning).
5003 // Use variable's location which is good for this case.
5004 DeclLoc = ND->getLocation();
5005 const char *startBuf = SM->getCharacterData(DeclLoc);
5006 SourceLocation X = ND->getLocEnd();
5007 X = SM->getExpansionLoc(X);
5008 const char *endBuf = SM->getCharacterData(X);
5009 std::string Name(ND->getNameAsString());
5010 std::string ByrefType;
5011 RewriteByRefString(ByrefType, Name, ND, true);
5012 ByrefType += " {\n";
5013 ByrefType += " void *__isa;\n";
5014 RewriteByRefString(ByrefType, Name, ND);
5015 ByrefType += " *__forwarding;\n";
5016 ByrefType += " int __flags;\n";
5017 ByrefType += " int __size;\n";
5018 // Add void *__Block_byref_id_object_copy;
5019 // void *__Block_byref_id_object_dispose; if needed.
5020 QualType Ty = ND->getType();
5021 bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty);
5022 if (HasCopyAndDispose) {
5023 ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
5024 ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
5025 }
5026
5027 QualType T = Ty;
5028 (void)convertBlockPointerToFunctionPointer(T);
5029 T.getAsStringInternal(Name, Context->getPrintingPolicy());
5030
5031 ByrefType += " " + Name + ";\n";
5032 ByrefType += "};\n";
5033 // Insert this type in global scope. It is needed by helper function.
5034 SourceLocation FunLocStart;
5035 if (CurFunctionDef)
Fariborz Jahanianb75f8de2012-04-19 00:50:01 +00005036 FunLocStart = getFunctionSourceLocation(*this, CurFunctionDef);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005037 else {
5038 assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null");
5039 FunLocStart = CurMethodDef->getLocStart();
5040 }
5041 InsertText(FunLocStart, ByrefType);
Fariborz Jahanian8247c4e2012-04-24 16:45:27 +00005042
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005043 if (Ty.isObjCGCWeak()) {
5044 flag |= BLOCK_FIELD_IS_WEAK;
5045 isa = 1;
5046 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005047 if (HasCopyAndDispose) {
5048 flag = BLOCK_BYREF_CALLER;
5049 QualType Ty = ND->getType();
5050 // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
5051 if (Ty->isBlockPointerType())
5052 flag |= BLOCK_FIELD_IS_BLOCK;
5053 else
5054 flag |= BLOCK_FIELD_IS_OBJECT;
5055 std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
5056 if (!HF.empty())
5057 InsertText(FunLocStart, HF);
5058 }
5059
5060 // struct __Block_byref_ND ND =
5061 // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
5062 // initializer-if-any};
5063 bool hasInit = (ND->getInit() != 0);
Fariborz Jahanian104dbf92012-04-11 23:57:12 +00005064 // FIXME. rewriter does not support __block c++ objects which
5065 // require construction.
Fariborz Jahanian65a7c682012-04-26 23:20:25 +00005066 if (hasInit)
5067 if (CXXConstructExpr *CExp = dyn_cast<CXXConstructExpr>(ND->getInit())) {
5068 CXXConstructorDecl *CXXDecl = CExp->getConstructor();
5069 if (CXXDecl && CXXDecl->isDefaultConstructor())
5070 hasInit = false;
5071 }
5072
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005073 unsigned flags = 0;
5074 if (HasCopyAndDispose)
5075 flags |= BLOCK_HAS_COPY_DISPOSE;
5076 Name = ND->getNameAsString();
5077 ByrefType.clear();
5078 RewriteByRefString(ByrefType, Name, ND);
5079 std::string ForwardingCastType("(");
5080 ForwardingCastType += ByrefType + " *)";
Fariborz Jahanian8247c4e2012-04-24 16:45:27 +00005081 ByrefType += " " + Name + " = {(void*)";
5082 ByrefType += utostr(isa);
5083 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
5084 ByrefType += utostr(flags);
5085 ByrefType += ", ";
5086 ByrefType += "sizeof(";
5087 RewriteByRefString(ByrefType, Name, ND);
5088 ByrefType += ")";
5089 if (HasCopyAndDispose) {
5090 ByrefType += ", __Block_byref_id_object_copy_";
5091 ByrefType += utostr(flag);
5092 ByrefType += ", __Block_byref_id_object_dispose_";
5093 ByrefType += utostr(flag);
5094 }
5095
Fariborz Jahanian4fe261c2012-04-24 19:38:45 +00005096 if (!firstDecl) {
5097 // In multiple __block declarations, and for all but 1st declaration,
5098 // find location of the separating comma. This would be start location
5099 // where new text is to be inserted.
5100 DeclLoc = ND->getLocation();
5101 const char *startDeclBuf = SM->getCharacterData(DeclLoc);
5102 const char *commaBuf = startDeclBuf;
5103 while (*commaBuf != ',')
5104 commaBuf--;
5105 assert((*commaBuf == ',') && "RewriteByRefVar: can't find ','");
5106 DeclLoc = DeclLoc.getLocWithOffset(commaBuf - startDeclBuf);
5107 startBuf = commaBuf;
5108 }
5109
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005110 if (!hasInit) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005111 ByrefType += "};\n";
5112 unsigned nameSize = Name.size();
5113 // for block or function pointer declaration. Name is aleady
5114 // part of the declaration.
5115 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType())
5116 nameSize = 1;
5117 ReplaceText(DeclLoc, endBuf-startBuf+nameSize, ByrefType);
5118 }
5119 else {
Fariborz Jahanian8247c4e2012-04-24 16:45:27 +00005120 ByrefType += ", ";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005121 SourceLocation startLoc;
5122 Expr *E = ND->getInit();
5123 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
5124 startLoc = ECE->getLParenLoc();
5125 else
5126 startLoc = E->getLocStart();
5127 startLoc = SM->getExpansionLoc(startLoc);
5128 endBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005129 ReplaceText(DeclLoc, endBuf-startBuf, ByrefType);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005130
Fariborz Jahanian4fe261c2012-04-24 19:38:45 +00005131 const char separator = lastDecl ? ';' : ',';
5132 const char *startInitializerBuf = SM->getCharacterData(startLoc);
5133 const char *separatorBuf = strchr(startInitializerBuf, separator);
5134 assert((*separatorBuf == separator) &&
5135 "RewriteByRefVar: can't find ';' or ','");
5136 SourceLocation separatorLoc =
5137 startLoc.getLocWithOffset(separatorBuf-startInitializerBuf);
5138
5139 InsertText(separatorLoc, lastDecl ? "}" : "};\n");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005140 }
5141 return;
5142}
5143
5144void RewriteModernObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
5145 // Add initializers for any closure decl refs.
5146 GetBlockDeclRefExprs(Exp->getBody());
5147 if (BlockDeclRefs.size()) {
5148 // Unique all "by copy" declarations.
5149 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00005150 if (!BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005151 if (!BlockByCopyDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
5152 BlockByCopyDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
5153 BlockByCopyDecls.push_back(BlockDeclRefs[i]->getDecl());
5154 }
5155 }
5156 // Unique all "by ref" declarations.
5157 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00005158 if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005159 if (!BlockByRefDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
5160 BlockByRefDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
5161 BlockByRefDecls.push_back(BlockDeclRefs[i]->getDecl());
5162 }
5163 }
5164 // Find any imported blocks...they will need special attention.
5165 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00005166 if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005167 BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
5168 BlockDeclRefs[i]->getType()->isBlockPointerType())
5169 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
5170 }
5171}
5172
5173FunctionDecl *RewriteModernObjC::SynthBlockInitFunctionDecl(StringRef name) {
5174 IdentifierInfo *ID = &Context->Idents.get(name);
5175 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
5176 return FunctionDecl::Create(*Context, TUDecl, SourceLocation(),
5177 SourceLocation(), ID, FType, 0, SC_Extern,
5178 SC_None, false, false);
5179}
5180
5181Stmt *RewriteModernObjC::SynthBlockInitExpr(BlockExpr *Exp,
John McCallf4b88a42012-03-10 09:33:50 +00005182 const SmallVector<DeclRefExpr *, 8> &InnerBlockDeclRefs) {
Fariborz Jahaniand13c2c22012-03-22 19:54:39 +00005183
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005184 const BlockDecl *block = Exp->getBlockDecl();
Fariborz Jahaniand13c2c22012-03-22 19:54:39 +00005185
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005186 Blocks.push_back(Exp);
5187
5188 CollectBlockDeclRefInfo(Exp);
5189
5190 // Add inner imported variables now used in current block.
5191 int countOfInnerDecls = 0;
5192 if (!InnerBlockDeclRefs.empty()) {
5193 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++) {
John McCallf4b88a42012-03-10 09:33:50 +00005194 DeclRefExpr *Exp = InnerBlockDeclRefs[i];
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005195 ValueDecl *VD = Exp->getDecl();
John McCallf4b88a42012-03-10 09:33:50 +00005196 if (!VD->hasAttr<BlocksAttr>() && !BlockByCopyDeclsPtrSet.count(VD)) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005197 // We need to save the copied-in variables in nested
5198 // blocks because it is needed at the end for some of the API generations.
5199 // See SynthesizeBlockLiterals routine.
5200 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5201 BlockDeclRefs.push_back(Exp);
5202 BlockByCopyDeclsPtrSet.insert(VD);
5203 BlockByCopyDecls.push_back(VD);
5204 }
John McCallf4b88a42012-03-10 09:33:50 +00005205 if (VD->hasAttr<BlocksAttr>() && !BlockByRefDeclsPtrSet.count(VD)) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005206 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5207 BlockDeclRefs.push_back(Exp);
5208 BlockByRefDeclsPtrSet.insert(VD);
5209 BlockByRefDecls.push_back(VD);
5210 }
5211 }
5212 // Find any imported blocks...they will need special attention.
5213 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00005214 if (InnerBlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005215 InnerBlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
5216 InnerBlockDeclRefs[i]->getType()->isBlockPointerType())
5217 ImportedBlockDecls.insert(InnerBlockDeclRefs[i]->getDecl());
5218 }
5219 InnerDeclRefsCount.push_back(countOfInnerDecls);
5220
5221 std::string FuncName;
5222
5223 if (CurFunctionDef)
5224 FuncName = CurFunctionDef->getNameAsString();
5225 else if (CurMethodDef)
5226 BuildUniqueMethodName(FuncName, CurMethodDef);
5227 else if (GlobalVarDecl)
5228 FuncName = std::string(GlobalVarDecl->getNameAsString());
5229
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00005230 bool GlobalBlockExpr =
5231 block->getDeclContext()->getRedeclContext()->isFileContext();
5232
5233 if (GlobalBlockExpr && !GlobalVarDecl) {
5234 Diags.Report(block->getLocation(), GlobalBlockRewriteFailedDiag);
5235 GlobalBlockExpr = false;
5236 }
5237
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005238 std::string BlockNumber = utostr(Blocks.size()-1);
5239
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005240 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
5241
5242 // Get a pointer to the function type so we can cast appropriately.
5243 QualType BFT = convertFunctionTypeOfBlocks(Exp->getFunctionType());
5244 QualType FType = Context->getPointerType(BFT);
5245
5246 FunctionDecl *FD;
5247 Expr *NewRep;
5248
5249 // Simulate a contructor call...
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00005250 std::string Tag;
5251
5252 if (GlobalBlockExpr)
5253 Tag = "__global_";
5254 else
5255 Tag = "__";
5256 Tag += FuncName + "_block_impl_" + BlockNumber;
5257
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005258 FD = SynthBlockInitFunctionDecl(Tag);
John McCallf4b88a42012-03-10 09:33:50 +00005259 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, false, FType, VK_RValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005260 SourceLocation());
5261
5262 SmallVector<Expr*, 4> InitExprs;
5263
5264 // Initialize the block function.
5265 FD = SynthBlockInitFunctionDecl(Func);
John McCallf4b88a42012-03-10 09:33:50 +00005266 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, false, FD->getType(),
5267 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005268 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
5269 CK_BitCast, Arg);
5270 InitExprs.push_back(castExpr);
5271
5272 // Initialize the block descriptor.
5273 std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
5274
5275 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl,
5276 SourceLocation(), SourceLocation(),
5277 &Context->Idents.get(DescData.c_str()),
5278 Context->VoidPtrTy, 0,
5279 SC_Static, SC_None);
5280 UnaryOperator *DescRefExpr =
John McCallf4b88a42012-03-10 09:33:50 +00005281 new (Context) UnaryOperator(new (Context) DeclRefExpr(NewVD, false,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005282 Context->VoidPtrTy,
5283 VK_LValue,
5284 SourceLocation()),
5285 UO_AddrOf,
5286 Context->getPointerType(Context->VoidPtrTy),
5287 VK_RValue, OK_Ordinary,
5288 SourceLocation());
5289 InitExprs.push_back(DescRefExpr);
5290
5291 // Add initializers for any closure decl refs.
5292 if (BlockDeclRefs.size()) {
5293 Expr *Exp;
5294 // Output all "by copy" declarations.
5295 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
5296 E = BlockByCopyDecls.end(); I != E; ++I) {
5297 if (isObjCType((*I)->getType())) {
5298 // FIXME: Conform to ABI ([[obj retain] autorelease]).
5299 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00005300 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(),
5301 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005302 if (HasLocalVariableExternalStorage(*I)) {
5303 QualType QT = (*I)->getType();
5304 QT = Context->getPointerType(QT);
5305 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
5306 OK_Ordinary, SourceLocation());
5307 }
5308 } else if (isTopLevelBlockPointerType((*I)->getType())) {
5309 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00005310 Arg = new (Context) DeclRefExpr(FD, false, FD->getType(),
5311 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005312 Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
5313 CK_BitCast, Arg);
5314 } else {
5315 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00005316 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(),
5317 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005318 if (HasLocalVariableExternalStorage(*I)) {
5319 QualType QT = (*I)->getType();
5320 QT = Context->getPointerType(QT);
5321 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
5322 OK_Ordinary, SourceLocation());
5323 }
5324
5325 }
5326 InitExprs.push_back(Exp);
5327 }
5328 // Output all "by ref" declarations.
5329 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
5330 E = BlockByRefDecls.end(); I != E; ++I) {
5331 ValueDecl *ND = (*I);
5332 std::string Name(ND->getNameAsString());
5333 std::string RecName;
5334 RewriteByRefString(RecName, Name, ND, true);
5335 IdentifierInfo *II = &Context->Idents.get(RecName.c_str()
5336 + sizeof("struct"));
5337 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
5338 SourceLocation(), SourceLocation(),
5339 II);
5340 assert(RD && "SynthBlockInitExpr(): Can't find RecordDecl");
5341 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
5342
5343 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00005344 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(), VK_LValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005345 SourceLocation());
5346 bool isNestedCapturedVar = false;
5347 if (block)
5348 for (BlockDecl::capture_const_iterator ci = block->capture_begin(),
5349 ce = block->capture_end(); ci != ce; ++ci) {
5350 const VarDecl *variable = ci->getVariable();
5351 if (variable == ND && ci->isNested()) {
5352 assert (ci->isByRef() &&
5353 "SynthBlockInitExpr - captured block variable is not byref");
5354 isNestedCapturedVar = true;
5355 break;
5356 }
5357 }
5358 // captured nested byref variable has its address passed. Do not take
5359 // its address again.
5360 if (!isNestedCapturedVar)
5361 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf,
5362 Context->getPointerType(Exp->getType()),
5363 VK_RValue, OK_Ordinary, SourceLocation());
5364 Exp = NoTypeInfoCStyleCastExpr(Context, castT, CK_BitCast, Exp);
5365 InitExprs.push_back(Exp);
5366 }
5367 }
5368 if (ImportedBlockDecls.size()) {
5369 // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
5370 int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
5371 unsigned IntSize =
5372 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
5373 Expr *FlagExp = IntegerLiteral::Create(*Context, llvm::APInt(IntSize, flag),
5374 Context->IntTy, SourceLocation());
5375 InitExprs.push_back(FlagExp);
5376 }
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00005377 NewRep = new (Context) CallExpr(*Context, DRE, InitExprs,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005378 FType, VK_LValue, SourceLocation());
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00005379
5380 if (GlobalBlockExpr) {
5381 assert (GlobalConstructionExp == 0 &&
5382 "SynthBlockInitExpr - GlobalConstructionExp must be null");
5383 GlobalConstructionExp = NewRep;
5384 NewRep = DRE;
5385 }
5386
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005387 NewRep = new (Context) UnaryOperator(NewRep, UO_AddrOf,
5388 Context->getPointerType(NewRep->getType()),
5389 VK_RValue, OK_Ordinary, SourceLocation());
5390 NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CK_BitCast,
5391 NewRep);
5392 BlockDeclRefs.clear();
5393 BlockByRefDecls.clear();
5394 BlockByRefDeclsPtrSet.clear();
5395 BlockByCopyDecls.clear();
5396 BlockByCopyDeclsPtrSet.clear();
5397 ImportedBlockDecls.clear();
5398 return NewRep;
5399}
5400
5401bool RewriteModernObjC::IsDeclStmtInForeachHeader(DeclStmt *DS) {
5402 if (const ObjCForCollectionStmt * CS =
5403 dyn_cast<ObjCForCollectionStmt>(Stmts.back()))
5404 return CS->getElement() == DS;
5405 return false;
5406}
5407
5408//===----------------------------------------------------------------------===//
5409// Function Body / Expression rewriting
5410//===----------------------------------------------------------------------===//
5411
5412Stmt *RewriteModernObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
5413 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
5414 isa<DoStmt>(S) || isa<ForStmt>(S))
5415 Stmts.push_back(S);
5416 else if (isa<ObjCForCollectionStmt>(S)) {
5417 Stmts.push_back(S);
5418 ObjCBcLabelNo.push_back(++BcLabelCount);
5419 }
5420
5421 // Pseudo-object operations and ivar references need special
5422 // treatment because we're going to recursively rewrite them.
5423 if (PseudoObjectExpr *PseudoOp = dyn_cast<PseudoObjectExpr>(S)) {
5424 if (isa<BinaryOperator>(PseudoOp->getSyntacticForm())) {
5425 return RewritePropertyOrImplicitSetter(PseudoOp);
5426 } else {
5427 return RewritePropertyOrImplicitGetter(PseudoOp);
5428 }
5429 } else if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
5430 return RewriteObjCIvarRefExpr(IvarRefExpr);
5431 }
5432
5433 SourceRange OrigStmtRange = S->getSourceRange();
5434
5435 // Perform a bottom up rewrite of all children.
5436 for (Stmt::child_range CI = S->children(); CI; ++CI)
5437 if (*CI) {
5438 Stmt *childStmt = (*CI);
5439 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(childStmt);
5440 if (newStmt) {
5441 *CI = newStmt;
5442 }
5443 }
5444
5445 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
John McCallf4b88a42012-03-10 09:33:50 +00005446 SmallVector<DeclRefExpr *, 8> InnerBlockDeclRefs;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005447 llvm::SmallPtrSet<const DeclContext *, 8> InnerContexts;
5448 InnerContexts.insert(BE->getBlockDecl());
5449 ImportedLocalExternalDecls.clear();
5450 GetInnerBlockDeclRefExprs(BE->getBody(),
5451 InnerBlockDeclRefs, InnerContexts);
5452 // Rewrite the block body in place.
5453 Stmt *SaveCurrentBody = CurrentBody;
5454 CurrentBody = BE->getBody();
5455 PropParentMap = 0;
5456 // block literal on rhs of a property-dot-sytax assignment
5457 // must be replaced by its synthesize ast so getRewrittenText
5458 // works as expected. In this case, what actually ends up on RHS
5459 // is the blockTranscribed which is the helper function for the
5460 // block literal; as in: self.c = ^() {[ace ARR];};
5461 bool saveDisableReplaceStmt = DisableReplaceStmt;
5462 DisableReplaceStmt = false;
5463 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
5464 DisableReplaceStmt = saveDisableReplaceStmt;
5465 CurrentBody = SaveCurrentBody;
5466 PropParentMap = 0;
5467 ImportedLocalExternalDecls.clear();
5468 // Now we snarf the rewritten text and stash it away for later use.
5469 std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
5470 RewrittenBlockExprs[BE] = Str;
5471
5472 Stmt *blockTranscribed = SynthBlockInitExpr(BE, InnerBlockDeclRefs);
5473
5474 //blockTranscribed->dump();
5475 ReplaceStmt(S, blockTranscribed);
5476 return blockTranscribed;
5477 }
5478 // Handle specific things.
5479 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
5480 return RewriteAtEncode(AtEncode);
5481
5482 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
5483 return RewriteAtSelector(AtSelector);
5484
5485 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
5486 return RewriteObjCStringLiteral(AtString);
Fariborz Jahanian55947042012-03-27 20:17:30 +00005487
5488 if (ObjCBoolLiteralExpr *BoolLitExpr = dyn_cast<ObjCBoolLiteralExpr>(S))
5489 return RewriteObjCBoolLiteralExpr(BoolLitExpr);
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00005490
Patrick Beardeb382ec2012-04-19 00:25:12 +00005491 if (ObjCBoxedExpr *BoxedExpr = dyn_cast<ObjCBoxedExpr>(S))
5492 return RewriteObjCBoxedExpr(BoxedExpr);
Fariborz Jahanian86cff602012-03-30 23:35:47 +00005493
5494 if (ObjCArrayLiteral *ArrayLitExpr = dyn_cast<ObjCArrayLiteral>(S))
5495 return RewriteObjCArrayLiteralExpr(ArrayLitExpr);
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00005496
5497 if (ObjCDictionaryLiteral *DictionaryLitExpr =
5498 dyn_cast<ObjCDictionaryLiteral>(S))
5499 return RewriteObjCDictionaryLiteralExpr(DictionaryLitExpr);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005500
5501 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
5502#if 0
5503 // Before we rewrite it, put the original message expression in a comment.
5504 SourceLocation startLoc = MessExpr->getLocStart();
5505 SourceLocation endLoc = MessExpr->getLocEnd();
5506
5507 const char *startBuf = SM->getCharacterData(startLoc);
5508 const char *endBuf = SM->getCharacterData(endLoc);
5509
5510 std::string messString;
5511 messString += "// ";
5512 messString.append(startBuf, endBuf-startBuf+1);
5513 messString += "\n";
5514
5515 // FIXME: Missing definition of
5516 // InsertText(clang::SourceLocation, char const*, unsigned int).
5517 // InsertText(startLoc, messString.c_str(), messString.size());
5518 // Tried this, but it didn't work either...
5519 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
5520#endif
5521 return RewriteMessageExpr(MessExpr);
5522 }
5523
Fariborz Jahanian042b91d2012-05-23 23:47:20 +00005524 if (ObjCAutoreleasePoolStmt *StmtAutoRelease =
5525 dyn_cast<ObjCAutoreleasePoolStmt>(S)) {
5526 return RewriteObjCAutoreleasePoolStmt(StmtAutoRelease);
5527 }
5528
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005529 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
5530 return RewriteObjCTryStmt(StmtTry);
5531
5532 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
5533 return RewriteObjCSynchronizedStmt(StmtTry);
5534
5535 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
5536 return RewriteObjCThrowStmt(StmtThrow);
5537
5538 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
5539 return RewriteObjCProtocolExpr(ProtocolExp);
5540
5541 if (ObjCForCollectionStmt *StmtForCollection =
5542 dyn_cast<ObjCForCollectionStmt>(S))
5543 return RewriteObjCForCollectionStmt(StmtForCollection,
5544 OrigStmtRange.getEnd());
5545 if (BreakStmt *StmtBreakStmt =
5546 dyn_cast<BreakStmt>(S))
5547 return RewriteBreakStmt(StmtBreakStmt);
5548 if (ContinueStmt *StmtContinueStmt =
5549 dyn_cast<ContinueStmt>(S))
5550 return RewriteContinueStmt(StmtContinueStmt);
5551
5552 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
5553 // and cast exprs.
5554 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
5555 // FIXME: What we're doing here is modifying the type-specifier that
5556 // precedes the first Decl. In the future the DeclGroup should have
5557 // a separate type-specifier that we can rewrite.
5558 // NOTE: We need to avoid rewriting the DeclStmt if it is within
5559 // the context of an ObjCForCollectionStmt. For example:
5560 // NSArray *someArray;
5561 // for (id <FooProtocol> index in someArray) ;
5562 // This is because RewriteObjCForCollectionStmt() does textual rewriting
5563 // and it depends on the original text locations/positions.
5564 if (Stmts.empty() || !IsDeclStmtInForeachHeader(DS))
5565 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
5566
5567 // Blocks rewrite rules.
5568 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
5569 DI != DE; ++DI) {
5570 Decl *SD = *DI;
5571 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
5572 if (isTopLevelBlockPointerType(ND->getType()))
5573 RewriteBlockPointerDecl(ND);
5574 else if (ND->getType()->isFunctionPointerType())
5575 CheckFunctionPointerDecl(ND->getType(), ND);
5576 if (VarDecl *VD = dyn_cast<VarDecl>(SD)) {
5577 if (VD->hasAttr<BlocksAttr>()) {
5578 static unsigned uniqueByrefDeclCount = 0;
5579 assert(!BlockByRefDeclNo.count(ND) &&
5580 "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl");
5581 BlockByRefDeclNo[ND] = uniqueByrefDeclCount++;
Fariborz Jahanian4fe261c2012-04-24 19:38:45 +00005582 RewriteByRefVar(VD, (DI == DS->decl_begin()), ((DI+1) == DE));
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005583 }
5584 else
5585 RewriteTypeOfDecl(VD);
5586 }
5587 }
5588 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(SD)) {
5589 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
5590 RewriteBlockPointerDecl(TD);
5591 else if (TD->getUnderlyingType()->isFunctionPointerType())
5592 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5593 }
5594 }
5595 }
5596
5597 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
5598 RewriteObjCQualifiedInterfaceTypes(CE);
5599
5600 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
5601 isa<DoStmt>(S) || isa<ForStmt>(S)) {
5602 assert(!Stmts.empty() && "Statement stack is empty");
5603 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
5604 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
5605 && "Statement stack mismatch");
5606 Stmts.pop_back();
5607 }
5608 // Handle blocks rewriting.
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005609 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
5610 ValueDecl *VD = DRE->getDecl();
5611 if (VD->hasAttr<BlocksAttr>())
5612 return RewriteBlockDeclRefExpr(DRE);
5613 if (HasLocalVariableExternalStorage(VD))
5614 return RewriteLocalVariableExternalStorage(DRE);
5615 }
5616
5617 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
5618 if (CE->getCallee()->getType()->isBlockPointerType()) {
5619 Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
5620 ReplaceStmt(S, BlockCall);
5621 return BlockCall;
5622 }
5623 }
5624 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
5625 RewriteCastExpr(CE);
5626 }
Fariborz Jahanianf1ee6872012-04-10 00:08:18 +00005627 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
5628 RewriteImplicitCastObjCExpr(ICE);
5629 }
Fariborz Jahanian43aa1c32012-04-16 22:14:01 +00005630#if 0
Fariborz Jahanian653b7cf2012-04-13 18:00:54 +00005631
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005632 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
5633 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(),
5634 ICE->getSubExpr(),
5635 SourceLocation());
5636 // Get the new text.
5637 std::string SStr;
5638 llvm::raw_string_ostream Buf(SStr);
Richard Smithd1420c62012-08-16 03:56:14 +00005639 Replacement->printPretty(Buf);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005640 const std::string &Str = Buf.str();
5641
5642 printf("CAST = %s\n", &Str[0]);
5643 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
5644 delete S;
5645 return Replacement;
5646 }
5647#endif
5648 // Return this stmt unmodified.
5649 return S;
5650}
5651
5652void RewriteModernObjC::RewriteRecordBody(RecordDecl *RD) {
5653 for (RecordDecl::field_iterator i = RD->field_begin(),
5654 e = RD->field_end(); i != e; ++i) {
David Blaikie581deb32012-06-06 20:45:41 +00005655 FieldDecl *FD = *i;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005656 if (isTopLevelBlockPointerType(FD->getType()))
5657 RewriteBlockPointerDecl(FD);
5658 if (FD->getType()->isObjCQualifiedIdType() ||
5659 FD->getType()->isObjCQualifiedInterfaceType())
5660 RewriteObjCQualifiedInterfaceTypes(FD);
5661 }
5662}
5663
5664/// HandleDeclInMainFile - This is called for each top-level decl defined in the
5665/// main file of the input.
5666void RewriteModernObjC::HandleDeclInMainFile(Decl *D) {
5667 switch (D->getKind()) {
5668 case Decl::Function: {
5669 FunctionDecl *FD = cast<FunctionDecl>(D);
5670 if (FD->isOverloadedOperator())
5671 return;
5672
5673 // Since function prototypes don't have ParmDecl's, we check the function
5674 // prototype. This enables us to rewrite function declarations and
5675 // definitions using the same code.
5676 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
5677
Argyrios Kyrtzidis9335df32012-02-12 04:48:45 +00005678 if (!FD->isThisDeclarationADefinition())
5679 break;
5680
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005681 // FIXME: If this should support Obj-C++, support CXXTryStmt
5682 if (CompoundStmt *Body = dyn_cast_or_null<CompoundStmt>(FD->getBody())) {
5683 CurFunctionDef = FD;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005684 CurrentBody = Body;
5685 Body =
5686 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5687 FD->setBody(Body);
5688 CurrentBody = 0;
5689 if (PropParentMap) {
5690 delete PropParentMap;
5691 PropParentMap = 0;
5692 }
5693 // This synthesizes and inserts the block "impl" struct, invoke function,
5694 // and any copy/dispose helper functions.
5695 InsertBlockLiteralsWithinFunction(FD);
Fariborz Jahanian96205962012-11-06 17:30:23 +00005696 RewriteLineDirective(D);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005697 CurFunctionDef = 0;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005698 }
5699 break;
5700 }
5701 case Decl::ObjCMethod: {
5702 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(D);
5703 if (CompoundStmt *Body = MD->getCompoundBody()) {
5704 CurMethodDef = MD;
5705 CurrentBody = Body;
5706 Body =
5707 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5708 MD->setBody(Body);
5709 CurrentBody = 0;
5710 if (PropParentMap) {
5711 delete PropParentMap;
5712 PropParentMap = 0;
5713 }
5714 InsertBlockLiteralsWithinMethod(MD);
Fariborz Jahanian96205962012-11-06 17:30:23 +00005715 RewriteLineDirective(D);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005716 CurMethodDef = 0;
5717 }
5718 break;
5719 }
5720 case Decl::ObjCImplementation: {
5721 ObjCImplementationDecl *CI = cast<ObjCImplementationDecl>(D);
5722 ClassImplementation.push_back(CI);
5723 break;
5724 }
5725 case Decl::ObjCCategoryImpl: {
5726 ObjCCategoryImplDecl *CI = cast<ObjCCategoryImplDecl>(D);
5727 CategoryImplementation.push_back(CI);
5728 break;
5729 }
5730 case Decl::Var: {
5731 VarDecl *VD = cast<VarDecl>(D);
5732 RewriteObjCQualifiedInterfaceTypes(VD);
5733 if (isTopLevelBlockPointerType(VD->getType()))
5734 RewriteBlockPointerDecl(VD);
5735 else if (VD->getType()->isFunctionPointerType()) {
5736 CheckFunctionPointerDecl(VD->getType(), VD);
5737 if (VD->getInit()) {
5738 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
5739 RewriteCastExpr(CE);
5740 }
5741 }
5742 } else if (VD->getType()->isRecordType()) {
5743 RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
5744 if (RD->isCompleteDefinition())
5745 RewriteRecordBody(RD);
5746 }
5747 if (VD->getInit()) {
5748 GlobalVarDecl = VD;
5749 CurrentBody = VD->getInit();
5750 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
5751 CurrentBody = 0;
5752 if (PropParentMap) {
5753 delete PropParentMap;
5754 PropParentMap = 0;
5755 }
5756 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(), VD->getName());
5757 GlobalVarDecl = 0;
5758
5759 // This is needed for blocks.
5760 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
5761 RewriteCastExpr(CE);
5762 }
5763 }
5764 break;
5765 }
5766 case Decl::TypeAlias:
5767 case Decl::Typedef: {
5768 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
5769 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
5770 RewriteBlockPointerDecl(TD);
5771 else if (TD->getUnderlyingType()->isFunctionPointerType())
5772 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5773 }
5774 break;
5775 }
5776 case Decl::CXXRecord:
5777 case Decl::Record: {
5778 RecordDecl *RD = cast<RecordDecl>(D);
5779 if (RD->isCompleteDefinition())
5780 RewriteRecordBody(RD);
5781 break;
5782 }
5783 default:
5784 break;
5785 }
5786 // Nothing yet.
5787}
5788
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00005789/// Write_ProtocolExprReferencedMetadata - This routine writer out the
5790/// protocol reference symbols in the for of:
5791/// struct _protocol_t *PROTOCOL_REF = &PROTOCOL_METADATA.
5792static void Write_ProtocolExprReferencedMetadata(ASTContext *Context,
5793 ObjCProtocolDecl *PDecl,
5794 std::string &Result) {
5795 // Also output .objc_protorefs$B section and its meta-data.
5796 if (Context->getLangOpts().MicrosoftExt)
Fariborz Jahanianbd78cfa2012-04-27 21:39:49 +00005797 Result += "static ";
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00005798 Result += "struct _protocol_t *";
5799 Result += "_OBJC_PROTOCOL_REFERENCE_$_";
5800 Result += PDecl->getNameAsString();
5801 Result += " = &";
5802 Result += "_OBJC_PROTOCOL_"; Result += PDecl->getNameAsString();
5803 Result += ";\n";
5804}
5805
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005806void RewriteModernObjC::HandleTranslationUnit(ASTContext &C) {
5807 if (Diags.hasErrorOccurred())
5808 return;
5809
5810 RewriteInclude();
5811
5812 // Here's a great place to add any extra declarations that may be needed.
5813 // Write out meta data for each @protocol(<expr>).
5814 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00005815 E = ProtocolExprDecls.end(); I != E; ++I) {
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00005816 RewriteObjCProtocolMetaData(*I, Preamble);
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00005817 Write_ProtocolExprReferencedMetadata(Context, (*I), Preamble);
5818 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005819
5820 InsertText(SM->getLocForStartOfFile(MainFileID), Preamble, false);
Fariborz Jahanian163d3ce2012-05-08 23:54:35 +00005821
5822 if (ClassImplementation.size() || CategoryImplementation.size())
5823 RewriteImplementations();
5824
Fariborz Jahanian57317782012-02-21 23:58:41 +00005825 for (unsigned i = 0, e = ObjCInterfacesSeen.size(); i < e; i++) {
5826 ObjCInterfaceDecl *CDecl = ObjCInterfacesSeen[i];
5827 // Write struct declaration for the class matching its ivar declarations.
5828 // Note that for modern abi, this is postponed until the end of TU
5829 // because class extensions and the implementation might declare their own
5830 // private ivars.
5831 RewriteInterfaceDecl(CDecl);
5832 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005833
5834 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
5835 // we are done.
5836 if (const RewriteBuffer *RewriteBuf =
5837 Rewrite.getRewriteBufferFor(MainFileID)) {
5838 //printf("Changed:\n");
5839 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
5840 } else {
5841 llvm::errs() << "No changes\n";
5842 }
5843
5844 if (ClassImplementation.size() || CategoryImplementation.size() ||
5845 ProtocolExprDecls.size()) {
5846 // Rewrite Objective-c meta data*
5847 std::string ResultStr;
5848 RewriteMetaDataIntoBuffer(ResultStr);
5849 // Emit metadata.
5850 *OutFile << ResultStr;
5851 }
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005852 // Emit ImageInfo;
5853 {
5854 std::string ResultStr;
5855 WriteImageInfo(ResultStr);
5856 *OutFile << ResultStr;
5857 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005858 OutFile->flush();
5859}
5860
5861void RewriteModernObjC::Initialize(ASTContext &context) {
5862 InitializeCommon(context);
5863
Fariborz Jahanian6991bc52012-03-10 17:45:38 +00005864 Preamble += "#ifndef __OBJC2__\n";
5865 Preamble += "#define __OBJC2__\n";
5866 Preamble += "#endif\n";
5867
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005868 // declaring objc_selector outside the parameter list removes a silly
5869 // scope related warning...
5870 if (IsHeader)
5871 Preamble = "#pragma once\n";
5872 Preamble += "struct objc_selector; struct objc_class;\n";
Fariborz Jahaniane2d87bc2012-04-12 23:52:52 +00005873 Preamble += "struct __rw_objc_super { \n\tstruct objc_object *object; ";
5874 Preamble += "\n\tstruct objc_object *superClass; ";
5875 // Add a constructor for creating temporary objects.
5876 Preamble += "\n\t__rw_objc_super(struct objc_object *o, struct objc_object *s) ";
5877 Preamble += ": object(o), superClass(s) {} ";
5878 Preamble += "\n};\n";
5879
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005880 if (LangOpts.MicrosoftExt) {
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00005881 // Define all sections using syntax that makes sense.
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005882 // These are currently generated.
5883 Preamble += "\n#pragma section(\".objc_classlist$B\", long, read, write)\n";
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00005884 Preamble += "#pragma section(\".objc_catlist$B\", long, read, write)\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005885 Preamble += "#pragma section(\".objc_imageinfo$B\", long, read, write)\n";
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00005886 Preamble += "#pragma section(\".objc_nlclslist$B\", long, read, write)\n";
5887 Preamble += "#pragma section(\".objc_nlcatlist$B\", long, read, write)\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005888 // These are generated but not necessary for functionality.
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005889 Preamble += "#pragma section(\".cat_cls_meth$B\", long, read, write)\n";
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00005890 Preamble += "#pragma section(\".inst_meth$B\", long, read, write)\n";
5891 Preamble += "#pragma section(\".cls_meth$B\", long, read, write)\n";
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00005892 Preamble += "#pragma section(\".objc_ivar$B\", long, read, write)\n";
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00005893
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00005894 // These need be generated for performance. Currently they are not,
5895 // using API calls instead.
5896 Preamble += "#pragma section(\".objc_selrefs$B\", long, read, write)\n";
5897 Preamble += "#pragma section(\".objc_classrefs$B\", long, read, write)\n";
5898 Preamble += "#pragma section(\".objc_superrefs$B\", long, read, write)\n";
5899
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005900 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005901 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
5902 Preamble += "typedef struct objc_object Protocol;\n";
5903 Preamble += "#define _REWRITER_typedef_Protocol\n";
5904 Preamble += "#endif\n";
5905 if (LangOpts.MicrosoftExt) {
5906 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
5907 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
Fariborz Jahanian5cf6b6c2012-03-21 23:41:04 +00005908 }
5909 else
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005910 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
Fariborz Jahanian5cf6b6c2012-03-21 23:41:04 +00005911
5912 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend(void);\n";
5913 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSendSuper(void);\n";
5914 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend_stret(void);\n";
5915 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSendSuper_stret(void);\n";
5916 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend_fpret(void);\n";
5917
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00005918 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *objc_getClass";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005919 Preamble += "(const char *);\n";
5920 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *class_getSuperclass";
5921 Preamble += "(struct objc_class *);\n";
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00005922 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *objc_getMetaClass";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005923 Preamble += "(const char *);\n";
Fariborz Jahanian55261af2012-03-19 18:11:32 +00005924 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw( struct objc_object *);\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005925 // @synchronized hooks.
Aaron Ballman2d234d732012-09-06 16:44:16 +00005926 Preamble += "__OBJC_RW_DLLIMPORT int objc_sync_enter( struct objc_object *);\n";
5927 Preamble += "__OBJC_RW_DLLIMPORT int objc_sync_exit( struct objc_object *);\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005928 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
5929 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
5930 Preamble += "struct __objcFastEnumerationState {\n\t";
5931 Preamble += "unsigned long state;\n\t";
5932 Preamble += "void **itemsPtr;\n\t";
5933 Preamble += "unsigned long *mutationsPtr;\n\t";
5934 Preamble += "unsigned long extra[5];\n};\n";
5935 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
5936 Preamble += "#define __FASTENUMERATIONSTATE\n";
5937 Preamble += "#endif\n";
5938 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
5939 Preamble += "struct __NSConstantStringImpl {\n";
5940 Preamble += " int *isa;\n";
5941 Preamble += " int flags;\n";
5942 Preamble += " char *str;\n";
5943 Preamble += " long length;\n";
5944 Preamble += "};\n";
5945 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
5946 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
5947 Preamble += "#else\n";
5948 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
5949 Preamble += "#endif\n";
5950 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
5951 Preamble += "#endif\n";
5952 // Blocks preamble.
5953 Preamble += "#ifndef BLOCK_IMPL\n";
5954 Preamble += "#define BLOCK_IMPL\n";
5955 Preamble += "struct __block_impl {\n";
5956 Preamble += " void *isa;\n";
5957 Preamble += " int Flags;\n";
5958 Preamble += " int Reserved;\n";
5959 Preamble += " void *FuncPtr;\n";
5960 Preamble += "};\n";
5961 Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
5962 Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n";
5963 Preamble += "extern \"C\" __declspec(dllexport) "
5964 "void _Block_object_assign(void *, const void *, const int);\n";
5965 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
5966 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
5967 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
5968 Preamble += "#else\n";
5969 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n";
5970 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n";
5971 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
5972 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
5973 Preamble += "#endif\n";
5974 Preamble += "#endif\n";
5975 if (LangOpts.MicrosoftExt) {
5976 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
5977 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
5978 Preamble += "#ifndef KEEP_ATTRIBUTES\n"; // We use this for clang tests.
5979 Preamble += "#define __attribute__(X)\n";
5980 Preamble += "#endif\n";
Fariborz Jahanian5ce28272012-04-12 16:33:31 +00005981 Preamble += "#ifndef __weak\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005982 Preamble += "#define __weak\n";
Fariborz Jahanian5ce28272012-04-12 16:33:31 +00005983 Preamble += "#endif\n";
5984 Preamble += "#ifndef __block\n";
5985 Preamble += "#define __block\n";
5986 Preamble += "#endif\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005987 }
5988 else {
5989 Preamble += "#define __block\n";
5990 Preamble += "#define __weak\n";
5991 }
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +00005992
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00005993 // Declarations required for modern objective-c array and dictionary literals.
5994 Preamble += "\n#include <stdarg.h>\n";
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00005995 Preamble += "struct __NSContainer_literal {\n";
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00005996 Preamble += " void * *arr;\n";
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00005997 Preamble += " __NSContainer_literal (unsigned int count, ...) {\n";
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00005998 Preamble += "\tva_list marker;\n";
5999 Preamble += "\tva_start(marker, count);\n";
6000 Preamble += "\tarr = new void *[count];\n";
6001 Preamble += "\tfor (unsigned i = 0; i < count; i++)\n";
6002 Preamble += "\t arr[i] = va_arg(marker, void *);\n";
6003 Preamble += "\tva_end( marker );\n";
6004 Preamble += " };\n";
Fariborz Jahanian13a9c022012-05-02 23:53:46 +00006005 Preamble += " ~__NSContainer_literal() {\n";
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00006006 Preamble += "\tdelete[] arr;\n";
6007 Preamble += " }\n";
6008 Preamble += "};\n";
6009
Fariborz Jahanian042b91d2012-05-23 23:47:20 +00006010 // Declaration required for implementation of @autoreleasepool statement.
6011 Preamble += "extern \"C\" __declspec(dllimport) void * objc_autoreleasePoolPush(void);\n";
6012 Preamble += "extern \"C\" __declspec(dllimport) void objc_autoreleasePoolPop(void *);\n\n";
6013 Preamble += "struct __AtAutoreleasePool {\n";
6014 Preamble += " __AtAutoreleasePool() {atautoreleasepoolobj = objc_autoreleasePoolPush();}\n";
6015 Preamble += " ~__AtAutoreleasePool() {objc_autoreleasePoolPop(atautoreleasepoolobj);}\n";
6016 Preamble += " void * atautoreleasepoolobj;\n";
6017 Preamble += "};\n";
6018
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006019 // NOTE! Windows uses LLP64 for 64bit mode. So, cast pointer to long long
6020 // as this avoids warning in any 64bit/32bit compilation model.
6021 Preamble += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long long) &((TYPE *)0)->MEMBER)\n";
6022}
6023
6024/// RewriteIvarOffsetComputation - This rutine synthesizes computation of
6025/// ivar offset.
6026void RewriteModernObjC::RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
6027 std::string &Result) {
6028 if (ivar->isBitField()) {
6029 // FIXME: The hack below doesn't work for bitfields. For now, we simply
6030 // place all bitfields at offset 0.
6031 Result += "0";
6032 } else {
6033 Result += "__OFFSETOFIVAR__(struct ";
6034 Result += ivar->getContainingInterface()->getNameAsString();
6035 if (LangOpts.MicrosoftExt)
6036 Result += "_IMPL";
6037 Result += ", ";
6038 Result += ivar->getNameAsString();
6039 Result += ")";
6040 }
6041}
6042
6043/// WriteModernMetadataDeclarations - Writes out metadata declarations for modern ABI.
6044/// struct _prop_t {
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006045/// const char *name;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006046/// char *attributes;
6047/// }
6048
6049/// struct _prop_list_t {
6050/// uint32_t entsize; // sizeof(struct _prop_t)
6051/// uint32_t count_of_properties;
6052/// struct _prop_t prop_list[count_of_properties];
6053/// }
6054
6055/// struct _protocol_t;
6056
6057/// struct _protocol_list_t {
6058/// long protocol_count; // Note, this is 32/64 bit
6059/// struct _protocol_t * protocol_list[protocol_count];
6060/// }
6061
6062/// struct _objc_method {
6063/// SEL _cmd;
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006064/// const char *method_type;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006065/// char *_imp;
6066/// }
6067
6068/// struct _method_list_t {
6069/// uint32_t entsize; // sizeof(struct _objc_method)
6070/// uint32_t method_count;
6071/// struct _objc_method method_list[method_count];
6072/// }
6073
6074/// struct _protocol_t {
6075/// id isa; // NULL
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006076/// const char *protocol_name;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006077/// const struct _protocol_list_t * protocol_list; // super protocols
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006078/// const struct method_list_t *instance_methods;
6079/// const struct method_list_t *class_methods;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006080/// const struct method_list_t *optionalInstanceMethods;
6081/// const struct method_list_t *optionalClassMethods;
6082/// const struct _prop_list_t * properties;
6083/// const uint32_t size; // sizeof(struct _protocol_t)
6084/// const uint32_t flags; // = 0
6085/// const char ** extendedMethodTypes;
6086/// }
6087
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006088/// struct _ivar_t {
6089/// unsigned long int *offset; // pointer to ivar offset location
Fariborz Jahanianae932952012-02-10 20:47:10 +00006090/// const char *name;
6091/// const char *type;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006092/// uint32_t alignment;
6093/// uint32_t size;
6094/// }
6095
6096/// struct _ivar_list_t {
6097/// uint32 entsize; // sizeof(struct _ivar_t)
6098/// uint32 count;
Fariborz Jahanianae932952012-02-10 20:47:10 +00006099/// struct _ivar_t list[count];
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006100/// }
6101
6102/// struct _class_ro_t {
Fariborz Jahanian249cd102012-03-24 16:53:16 +00006103/// uint32_t flags;
6104/// uint32_t instanceStart;
6105/// uint32_t instanceSize;
6106/// uint32_t reserved; // only when building for 64bit targets
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006107/// const uint8_t *ivarLayout;
6108/// const char *name;
6109/// const struct _method_list_t *baseMethods;
6110/// const struct _protocol_list_t *baseProtocols;
6111/// const struct _ivar_list_t *ivars;
6112/// const uint8_t *weakIvarLayout;
6113/// const struct _prop_list_t *properties;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006114/// }
6115
6116/// struct _class_t {
6117/// struct _class_t *isa;
Fariborz Jahanianfd4ce2c2012-03-20 17:34:50 +00006118/// struct _class_t *superclass;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006119/// void *cache;
6120/// IMP *vtable;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006121/// struct _class_ro_t *ro;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006122/// }
6123
6124/// struct _category_t {
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006125/// const char *name;
Fariborz Jahanian4b2fe6e2012-03-20 21:41:28 +00006126/// struct _class_t *cls;
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006127/// const struct _method_list_t *instance_methods;
6128/// const struct _method_list_t *class_methods;
6129/// const struct _protocol_list_t *protocols;
6130/// const struct _prop_list_t *properties;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006131/// }
6132
6133/// MessageRefTy - LLVM for:
6134/// struct _message_ref_t {
6135/// IMP messenger;
6136/// SEL name;
6137/// };
6138
6139/// SuperMessageRefTy - LLVM for:
6140/// struct _super_message_ref_t {
6141/// SUPER_IMP messenger;
6142/// SEL name;
6143/// };
6144
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00006145static void WriteModernMetadataDeclarations(ASTContext *Context, std::string &Result) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006146 static bool meta_data_declared = false;
6147 if (meta_data_declared)
6148 return;
6149
6150 Result += "\nstruct _prop_t {\n";
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006151 Result += "\tconst char *name;\n";
6152 Result += "\tconst char *attributes;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006153 Result += "};\n";
6154
6155 Result += "\nstruct _protocol_t;\n";
6156
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006157 Result += "\nstruct _objc_method {\n";
6158 Result += "\tstruct objc_selector * _cmd;\n";
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006159 Result += "\tconst char *method_type;\n";
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006160 Result += "\tvoid *_imp;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006161 Result += "};\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006162
6163 Result += "\nstruct _protocol_t {\n";
6164 Result += "\tvoid * isa; // NULL\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006165 Result += "\tconst char *protocol_name;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006166 Result += "\tconst struct _protocol_list_t * protocol_list; // super protocols\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006167 Result += "\tconst struct method_list_t *instance_methods;\n";
6168 Result += "\tconst struct method_list_t *class_methods;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006169 Result += "\tconst struct method_list_t *optionalInstanceMethods;\n";
6170 Result += "\tconst struct method_list_t *optionalClassMethods;\n";
6171 Result += "\tconst struct _prop_list_t * properties;\n";
6172 Result += "\tconst unsigned int size; // sizeof(struct _protocol_t)\n";
6173 Result += "\tconst unsigned int flags; // = 0\n";
6174 Result += "\tconst char ** extendedMethodTypes;\n";
6175 Result += "};\n";
6176
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006177 Result += "\nstruct _ivar_t {\n";
6178 Result += "\tunsigned long int *offset; // pointer to ivar offset location\n";
Fariborz Jahanianae932952012-02-10 20:47:10 +00006179 Result += "\tconst char *name;\n";
6180 Result += "\tconst char *type;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006181 Result += "\tunsigned int alignment;\n";
6182 Result += "\tunsigned int size;\n";
6183 Result += "};\n";
6184
6185 Result += "\nstruct _class_ro_t {\n";
Fariborz Jahanian249cd102012-03-24 16:53:16 +00006186 Result += "\tunsigned int flags;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006187 Result += "\tunsigned int instanceStart;\n";
Fariborz Jahanian249cd102012-03-24 16:53:16 +00006188 Result += "\tunsigned int instanceSize;\n";
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00006189 const llvm::Triple &Triple(Context->getTargetInfo().getTriple());
6190 if (Triple.getArch() == llvm::Triple::x86_64)
Fariborz Jahanian249cd102012-03-24 16:53:16 +00006191 Result += "\tunsigned int reserved;\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006192 Result += "\tconst unsigned char *ivarLayout;\n";
6193 Result += "\tconst char *name;\n";
6194 Result += "\tconst struct _method_list_t *baseMethods;\n";
6195 Result += "\tconst struct _objc_protocol_list *baseProtocols;\n";
6196 Result += "\tconst struct _ivar_list_t *ivars;\n";
6197 Result += "\tconst unsigned char *weakIvarLayout;\n";
6198 Result += "\tconst struct _prop_list_t *properties;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006199 Result += "};\n";
6200
6201 Result += "\nstruct _class_t {\n";
6202 Result += "\tstruct _class_t *isa;\n";
Fariborz Jahanianfd4ce2c2012-03-20 17:34:50 +00006203 Result += "\tstruct _class_t *superclass;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006204 Result += "\tvoid *cache;\n";
6205 Result += "\tvoid *vtable;\n";
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006206 Result += "\tstruct _class_ro_t *ro;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006207 Result += "};\n";
6208
6209 Result += "\nstruct _category_t {\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006210 Result += "\tconst char *name;\n";
Fariborz Jahanian4b2fe6e2012-03-20 21:41:28 +00006211 Result += "\tstruct _class_t *cls;\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006212 Result += "\tconst struct _method_list_t *instance_methods;\n";
6213 Result += "\tconst struct _method_list_t *class_methods;\n";
6214 Result += "\tconst struct _protocol_list_t *protocols;\n";
6215 Result += "\tconst struct _prop_list_t *properties;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006216 Result += "};\n";
6217
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006218 Result += "extern \"C\" __declspec(dllimport) struct objc_cache _objc_empty_cache;\n";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006219 Result += "#pragma warning(disable:4273)\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006220 meta_data_declared = true;
6221}
6222
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006223static void Write_protocol_list_t_TypeDecl(std::string &Result,
6224 long super_protocol_count) {
6225 Result += "struct /*_protocol_list_t*/"; Result += " {\n";
6226 Result += "\tlong protocol_count; // Note, this is 32/64 bit\n";
6227 Result += "\tstruct _protocol_t *super_protocols[";
6228 Result += utostr(super_protocol_count); Result += "];\n";
6229 Result += "}";
6230}
6231
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006232static void Write_method_list_t_TypeDecl(std::string &Result,
6233 unsigned int method_count) {
6234 Result += "struct /*_method_list_t*/"; Result += " {\n";
6235 Result += "\tunsigned int entsize; // sizeof(struct _objc_method)\n";
6236 Result += "\tunsigned int method_count;\n";
6237 Result += "\tstruct _objc_method method_list[";
6238 Result += utostr(method_count); Result += "];\n";
6239 Result += "}";
6240}
6241
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006242static void Write__prop_list_t_TypeDecl(std::string &Result,
6243 unsigned int property_count) {
6244 Result += "struct /*_prop_list_t*/"; Result += " {\n";
6245 Result += "\tunsigned int entsize; // sizeof(struct _prop_t)\n";
6246 Result += "\tunsigned int count_of_properties;\n";
6247 Result += "\tstruct _prop_t prop_list[";
6248 Result += utostr(property_count); Result += "];\n";
6249 Result += "}";
6250}
6251
Fariborz Jahanianae932952012-02-10 20:47:10 +00006252static void Write__ivar_list_t_TypeDecl(std::string &Result,
6253 unsigned int ivar_count) {
6254 Result += "struct /*_ivar_list_t*/"; Result += " {\n";
6255 Result += "\tunsigned int entsize; // sizeof(struct _prop_t)\n";
6256 Result += "\tunsigned int count;\n";
6257 Result += "\tstruct _ivar_t ivar_list[";
6258 Result += utostr(ivar_count); Result += "];\n";
6259 Result += "}";
6260}
6261
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006262static void Write_protocol_list_initializer(ASTContext *Context, std::string &Result,
6263 ArrayRef<ObjCProtocolDecl *> SuperProtocols,
6264 StringRef VarName,
6265 StringRef ProtocolName) {
6266 if (SuperProtocols.size() > 0) {
6267 Result += "\nstatic ";
6268 Write_protocol_list_t_TypeDecl(Result, SuperProtocols.size());
6269 Result += " "; Result += VarName;
6270 Result += ProtocolName;
6271 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6272 Result += "\t"; Result += utostr(SuperProtocols.size()); Result += ",\n";
6273 for (unsigned i = 0, e = SuperProtocols.size(); i < e; i++) {
6274 ObjCProtocolDecl *SuperPD = SuperProtocols[i];
6275 Result += "\t&"; Result += "_OBJC_PROTOCOL_";
6276 Result += SuperPD->getNameAsString();
6277 if (i == e-1)
6278 Result += "\n};\n";
6279 else
6280 Result += ",\n";
6281 }
6282 }
6283}
6284
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006285static void Write_method_list_t_initializer(RewriteModernObjC &RewriteObj,
6286 ASTContext *Context, std::string &Result,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006287 ArrayRef<ObjCMethodDecl *> Methods,
6288 StringRef VarName,
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006289 StringRef TopLevelDeclName,
6290 bool MethodImpl) {
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006291 if (Methods.size() > 0) {
6292 Result += "\nstatic ";
6293 Write_method_list_t_TypeDecl(Result, Methods.size());
6294 Result += " "; Result += VarName;
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006295 Result += TopLevelDeclName;
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006296 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6297 Result += "\t"; Result += "sizeof(_objc_method)"; Result += ",\n";
6298 Result += "\t"; Result += utostr(Methods.size()); Result += ",\n";
6299 for (unsigned i = 0, e = Methods.size(); i < e; i++) {
6300 ObjCMethodDecl *MD = Methods[i];
6301 if (i == 0)
6302 Result += "\t{{(struct objc_selector *)\"";
6303 else
6304 Result += "\t{(struct objc_selector *)\"";
6305 Result += (MD)->getSelector().getAsString(); Result += "\"";
6306 Result += ", ";
6307 std::string MethodTypeString;
6308 Context->getObjCEncodingForMethodDecl(MD, MethodTypeString);
6309 Result += "\""; Result += MethodTypeString; Result += "\"";
6310 Result += ", ";
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006311 if (!MethodImpl)
6312 Result += "0";
6313 else {
6314 Result += "(void *)";
6315 Result += RewriteObj.MethodInternalNames[MD];
6316 }
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006317 if (i == e-1)
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006318 Result += "}}\n";
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006319 else
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006320 Result += "},\n";
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006321 }
6322 Result += "};\n";
6323 }
6324}
6325
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006326static void Write_prop_list_t_initializer(RewriteModernObjC &RewriteObj,
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006327 ASTContext *Context, std::string &Result,
6328 ArrayRef<ObjCPropertyDecl *> Properties,
6329 const Decl *Container,
6330 StringRef VarName,
6331 StringRef ProtocolName) {
6332 if (Properties.size() > 0) {
6333 Result += "\nstatic ";
6334 Write__prop_list_t_TypeDecl(Result, Properties.size());
6335 Result += " "; Result += VarName;
6336 Result += ProtocolName;
6337 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6338 Result += "\t"; Result += "sizeof(_prop_t)"; Result += ",\n";
6339 Result += "\t"; Result += utostr(Properties.size()); Result += ",\n";
6340 for (unsigned i = 0, e = Properties.size(); i < e; i++) {
6341 ObjCPropertyDecl *PropDecl = Properties[i];
6342 if (i == 0)
6343 Result += "\t{{\"";
6344 else
6345 Result += "\t{\"";
6346 Result += PropDecl->getName(); Result += "\",";
6347 std::string PropertyTypeString, QuotePropertyTypeString;
6348 Context->getObjCEncodingForPropertyDecl(PropDecl, Container, PropertyTypeString);
6349 RewriteObj.QuoteDoublequotes(PropertyTypeString, QuotePropertyTypeString);
6350 Result += "\""; Result += QuotePropertyTypeString; Result += "\"";
6351 if (i == e-1)
6352 Result += "}}\n";
6353 else
6354 Result += "},\n";
6355 }
6356 Result += "};\n";
6357 }
6358}
6359
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006360// Metadata flags
6361enum MetaDataDlags {
6362 CLS = 0x0,
6363 CLS_META = 0x1,
6364 CLS_ROOT = 0x2,
6365 OBJC2_CLS_HIDDEN = 0x10,
6366 CLS_EXCEPTION = 0x20,
6367
6368 /// (Obsolete) ARC-specific: this class has a .release_ivars method
6369 CLS_HAS_IVAR_RELEASER = 0x40,
6370 /// class was compiled with -fobjc-arr
6371 CLS_COMPILED_BY_ARC = 0x80 // (1<<7)
6372};
6373
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006374static void Write__class_ro_t_initializer(ASTContext *Context, std::string &Result,
6375 unsigned int flags,
6376 const std::string &InstanceStart,
6377 const std::string &InstanceSize,
6378 ArrayRef<ObjCMethodDecl *>baseMethods,
6379 ArrayRef<ObjCProtocolDecl *>baseProtocols,
6380 ArrayRef<ObjCIvarDecl *>ivars,
6381 ArrayRef<ObjCPropertyDecl *>Properties,
6382 StringRef VarName,
6383 StringRef ClassName) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006384 Result += "\nstatic struct _class_ro_t ";
6385 Result += VarName; Result += ClassName;
6386 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6387 Result += "\t";
6388 Result += llvm::utostr(flags); Result += ", ";
6389 Result += InstanceStart; Result += ", ";
6390 Result += InstanceSize; Result += ", \n";
6391 Result += "\t";
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00006392 const llvm::Triple &Triple(Context->getTargetInfo().getTriple());
6393 if (Triple.getArch() == llvm::Triple::x86_64)
6394 // uint32_t const reserved; // only when building for 64bit targets
6395 Result += "(unsigned int)0, \n\t";
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006396 // const uint8_t * const ivarLayout;
6397 Result += "0, \n\t";
6398 Result += "\""; Result += ClassName; Result += "\",\n\t";
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006399 bool metaclass = ((flags & CLS_META) != 0);
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006400 if (baseMethods.size() > 0) {
6401 Result += "(const struct _method_list_t *)&";
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006402 if (metaclass)
6403 Result += "_OBJC_$_CLASS_METHODS_";
6404 else
6405 Result += "_OBJC_$_INSTANCE_METHODS_";
6406 Result += ClassName;
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006407 Result += ",\n\t";
6408 }
6409 else
6410 Result += "0, \n\t";
6411
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006412 if (!metaclass && baseProtocols.size() > 0) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006413 Result += "(const struct _objc_protocol_list *)&";
6414 Result += "_OBJC_CLASS_PROTOCOLS_$_"; Result += ClassName;
6415 Result += ",\n\t";
6416 }
6417 else
6418 Result += "0, \n\t";
6419
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006420 if (!metaclass && ivars.size() > 0) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006421 Result += "(const struct _ivar_list_t *)&";
6422 Result += "_OBJC_$_INSTANCE_VARIABLES_"; Result += ClassName;
6423 Result += ",\n\t";
6424 }
6425 else
6426 Result += "0, \n\t";
6427
6428 // weakIvarLayout
6429 Result += "0, \n\t";
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006430 if (!metaclass && Properties.size() > 0) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006431 Result += "(const struct _prop_list_t *)&";
Fariborz Jahanianeeabf382012-02-16 21:57:59 +00006432 Result += "_OBJC_$_PROP_LIST_"; Result += ClassName;
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006433 Result += ",\n";
6434 }
6435 else
6436 Result += "0, \n";
6437
6438 Result += "};\n";
6439}
6440
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006441static void Write_class_t(ASTContext *Context, std::string &Result,
6442 StringRef VarName,
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006443 const ObjCInterfaceDecl *CDecl, bool metaclass) {
6444 bool rootClass = (!CDecl->getSuperClass());
6445 const ObjCInterfaceDecl *RootClass = CDecl;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006446
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006447 if (!rootClass) {
6448 // Find the Root class
6449 RootClass = CDecl->getSuperClass();
6450 while (RootClass->getSuperClass()) {
6451 RootClass = RootClass->getSuperClass();
6452 }
6453 }
6454
6455 if (metaclass && rootClass) {
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006456 // Need to handle a case of use of forward declaration.
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00006457 Result += "\n";
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006458 Result += "extern \"C\" ";
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00006459 if (CDecl->getImplementation())
6460 Result += "__declspec(dllexport) ";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006461 else
6462 Result += "__declspec(dllimport) ";
6463
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006464 Result += "struct _class_t OBJC_CLASS_$_";
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006465 Result += CDecl->getNameAsString();
6466 Result += ";\n";
6467 }
6468 // Also, for possibility of 'super' metadata class not having been defined yet.
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006469 if (!rootClass) {
Fariborz Jahanian868e9852012-03-29 19:04:10 +00006470 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00006471 Result += "\n";
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006472 Result += "extern \"C\" ";
Fariborz Jahanian868e9852012-03-29 19:04:10 +00006473 if (SuperClass->getImplementation())
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00006474 Result += "__declspec(dllexport) ";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006475 else
6476 Result += "__declspec(dllimport) ";
6477
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006478 Result += "struct _class_t ";
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00006479 Result += VarName;
Fariborz Jahanian868e9852012-03-29 19:04:10 +00006480 Result += SuperClass->getNameAsString();
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006481 Result += ";\n";
Fariborz Jahanian452eac12012-03-20 21:09:58 +00006482
Fariborz Jahanian868e9852012-03-29 19:04:10 +00006483 if (metaclass && RootClass != SuperClass) {
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006484 Result += "extern \"C\" ";
Fariborz Jahanian452eac12012-03-20 21:09:58 +00006485 if (RootClass->getImplementation())
6486 Result += "__declspec(dllexport) ";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006487 else
6488 Result += "__declspec(dllimport) ";
6489
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006490 Result += "struct _class_t ";
Fariborz Jahanian452eac12012-03-20 21:09:58 +00006491 Result += VarName;
6492 Result += RootClass->getNameAsString();
6493 Result += ";\n";
6494 }
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006495 }
6496
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006497 Result += "\nextern \"C\" __declspec(dllexport) struct _class_t ";
6498 Result += VarName; Result += CDecl->getNameAsString();
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006499 Result += " __attribute__ ((used, section (\"__DATA,__objc_data\"))) = {\n";
6500 Result += "\t";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006501 if (metaclass) {
6502 if (!rootClass) {
6503 Result += "0, // &"; Result += VarName;
6504 Result += RootClass->getNameAsString();
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006505 Result += ",\n\t";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006506 Result += "0, // &"; Result += VarName;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006507 Result += CDecl->getSuperClass()->getNameAsString();
6508 Result += ",\n\t";
6509 }
6510 else {
Fariborz Jahanian452eac12012-03-20 21:09:58 +00006511 Result += "0, // &"; Result += VarName;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006512 Result += CDecl->getNameAsString();
6513 Result += ",\n\t";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006514 Result += "0, // &OBJC_CLASS_$_"; Result += CDecl->getNameAsString();
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006515 Result += ",\n\t";
6516 }
6517 }
6518 else {
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006519 Result += "0, // &OBJC_METACLASS_$_";
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006520 Result += CDecl->getNameAsString();
6521 Result += ",\n\t";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006522 if (!rootClass) {
6523 Result += "0, // &"; Result += VarName;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006524 Result += CDecl->getSuperClass()->getNameAsString();
6525 Result += ",\n\t";
6526 }
6527 else
6528 Result += "0,\n\t";
6529 }
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006530 Result += "0, // (void *)&_objc_empty_cache,\n\t";
6531 Result += "0, // unused, was (void *)&_objc_empty_vtable,\n\t";
6532 if (metaclass)
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006533 Result += "&_OBJC_METACLASS_RO_$_";
6534 else
6535 Result += "&_OBJC_CLASS_RO_$_";
6536 Result += CDecl->getNameAsString();
6537 Result += ",\n};\n";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006538
6539 // Add static function to initialize some of the meta-data fields.
6540 // avoid doing it twice.
6541 if (metaclass)
6542 return;
6543
6544 const ObjCInterfaceDecl *SuperClass =
6545 rootClass ? CDecl : CDecl->getSuperClass();
6546
6547 Result += "static void OBJC_CLASS_SETUP_$_";
6548 Result += CDecl->getNameAsString();
6549 Result += "(void ) {\n";
6550 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
6551 Result += ".isa = "; Result += "&OBJC_METACLASS_$_";
Fariborz Jahanian452eac12012-03-20 21:09:58 +00006552 Result += RootClass->getNameAsString(); Result += ";\n";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006553
6554 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
Fariborz Jahanian452eac12012-03-20 21:09:58 +00006555 Result += ".superclass = ";
6556 if (rootClass)
6557 Result += "&OBJC_CLASS_$_";
6558 else
6559 Result += "&OBJC_METACLASS_$_";
6560
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006561 Result += SuperClass->getNameAsString(); Result += ";\n";
6562
6563 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
6564 Result += ".cache = "; Result += "&_objc_empty_cache"; Result += ";\n";
6565
6566 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6567 Result += ".isa = "; Result += "&OBJC_METACLASS_$_";
6568 Result += CDecl->getNameAsString(); Result += ";\n";
6569
6570 if (!rootClass) {
6571 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6572 Result += ".superclass = "; Result += "&OBJC_CLASS_$_";
6573 Result += SuperClass->getNameAsString(); Result += ";\n";
6574 }
6575
6576 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6577 Result += ".cache = "; Result += "&_objc_empty_cache"; Result += ";\n";
6578 Result += "}\n";
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006579}
6580
Fariborz Jahanian61186122012-02-17 18:40:41 +00006581static void Write_category_t(RewriteModernObjC &RewriteObj, ASTContext *Context,
6582 std::string &Result,
Fariborz Jahaniane0335782012-03-27 18:41:05 +00006583 ObjCCategoryDecl *CatDecl,
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006584 ObjCInterfaceDecl *ClassDecl,
Fariborz Jahanian61186122012-02-17 18:40:41 +00006585 ArrayRef<ObjCMethodDecl *> InstanceMethods,
6586 ArrayRef<ObjCMethodDecl *> ClassMethods,
6587 ArrayRef<ObjCProtocolDecl *> RefedProtocols,
6588 ArrayRef<ObjCPropertyDecl *> ClassProperties) {
Fariborz Jahaniane0335782012-03-27 18:41:05 +00006589 StringRef CatName = CatDecl->getName();
NAKAMURA Takumi20f89392012-03-21 03:21:46 +00006590 StringRef ClassName = ClassDecl->getName();
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00006591 // must declare an extern class object in case this class is not implemented
6592 // in this TU.
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006593 Result += "\n";
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006594 Result += "extern \"C\" ";
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006595 if (ClassDecl->getImplementation())
6596 Result += "__declspec(dllexport) ";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006597 else
6598 Result += "__declspec(dllimport) ";
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006599
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006600 Result += "struct _class_t ";
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00006601 Result += "OBJC_CLASS_$_"; Result += ClassName;
6602 Result += ";\n";
6603
Fariborz Jahanian61186122012-02-17 18:40:41 +00006604 Result += "\nstatic struct _category_t ";
6605 Result += "_OBJC_$_CATEGORY_";
6606 Result += ClassName; Result += "_$_"; Result += CatName;
6607 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = \n";
6608 Result += "{\n";
6609 Result += "\t\""; Result += ClassName; Result += "\",\n";
Fariborz Jahanian4b2fe6e2012-03-20 21:41:28 +00006610 Result += "\t0, // &"; Result += "OBJC_CLASS_$_"; Result += ClassName;
Fariborz Jahanian61186122012-02-17 18:40:41 +00006611 Result += ",\n";
6612 if (InstanceMethods.size() > 0) {
6613 Result += "\t(const struct _method_list_t *)&";
6614 Result += "_OBJC_$_CATEGORY_INSTANCE_METHODS_";
6615 Result += ClassName; Result += "_$_"; Result += CatName;
6616 Result += ",\n";
6617 }
6618 else
6619 Result += "\t0,\n";
6620
6621 if (ClassMethods.size() > 0) {
6622 Result += "\t(const struct _method_list_t *)&";
6623 Result += "_OBJC_$_CATEGORY_CLASS_METHODS_";
6624 Result += ClassName; Result += "_$_"; Result += CatName;
6625 Result += ",\n";
6626 }
6627 else
6628 Result += "\t0,\n";
6629
6630 if (RefedProtocols.size() > 0) {
6631 Result += "\t(const struct _protocol_list_t *)&";
6632 Result += "_OBJC_CATEGORY_PROTOCOLS_$_";
6633 Result += ClassName; Result += "_$_"; Result += CatName;
6634 Result += ",\n";
6635 }
6636 else
6637 Result += "\t0,\n";
6638
6639 if (ClassProperties.size() > 0) {
6640 Result += "\t(const struct _prop_list_t *)&"; Result += "_OBJC_$_PROP_LIST_";
6641 Result += ClassName; Result += "_$_"; Result += CatName;
6642 Result += ",\n";
6643 }
6644 else
6645 Result += "\t0,\n";
6646
6647 Result += "};\n";
Fariborz Jahanian4b2fe6e2012-03-20 21:41:28 +00006648
6649 // Add static function to initialize the class pointer in the category structure.
6650 Result += "static void OBJC_CATEGORY_SETUP_$_";
6651 Result += ClassDecl->getNameAsString();
6652 Result += "_$_";
6653 Result += CatName;
6654 Result += "(void ) {\n";
6655 Result += "\t_OBJC_$_CATEGORY_";
6656 Result += ClassDecl->getNameAsString();
6657 Result += "_$_";
6658 Result += CatName;
6659 Result += ".cls = "; Result += "&OBJC_CLASS_$_"; Result += ClassName;
6660 Result += ";\n}\n";
Fariborz Jahanian61186122012-02-17 18:40:41 +00006661}
6662
Fariborz Jahaniane0adbd82012-02-08 22:23:26 +00006663static void Write__extendedMethodTypes_initializer(RewriteModernObjC &RewriteObj,
6664 ASTContext *Context, std::string &Result,
6665 ArrayRef<ObjCMethodDecl *> Methods,
6666 StringRef VarName,
6667 StringRef ProtocolName) {
6668 if (Methods.size() == 0)
6669 return;
6670
6671 Result += "\nstatic const char *";
6672 Result += VarName; Result += ProtocolName;
6673 Result += " [] __attribute__ ((used, section (\"__DATA,__objc_const\"))) = \n";
6674 Result += "{\n";
6675 for (unsigned i = 0, e = Methods.size(); i < e; i++) {
6676 ObjCMethodDecl *MD = Methods[i];
6677 std::string MethodTypeString, QuoteMethodTypeString;
6678 Context->getObjCEncodingForMethodDecl(MD, MethodTypeString, true);
6679 RewriteObj.QuoteDoublequotes(MethodTypeString, QuoteMethodTypeString);
6680 Result += "\t\""; Result += QuoteMethodTypeString; Result += "\"";
6681 if (i == e-1)
6682 Result += "\n};\n";
6683 else {
6684 Result += ",\n";
6685 }
6686 }
6687}
6688
Fariborz Jahanianacee1c92012-04-11 21:12:36 +00006689static void Write_IvarOffsetVar(RewriteModernObjC &RewriteObj,
6690 ASTContext *Context,
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00006691 std::string &Result,
Fariborz Jahaniandb649232012-02-13 20:59:02 +00006692 ArrayRef<ObjCIvarDecl *> Ivars,
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006693 ObjCInterfaceDecl *CDecl) {
Fariborz Jahaniandb649232012-02-13 20:59:02 +00006694 // FIXME. visibilty of offset symbols may have to be set; for Darwin
6695 // this is what happens:
6696 /**
6697 if (Ivar->getAccessControl() == ObjCIvarDecl::Private ||
6698 Ivar->getAccessControl() == ObjCIvarDecl::Package ||
6699 Class->getVisibility() == HiddenVisibility)
6700 Visibility shoud be: HiddenVisibility;
6701 else
6702 Visibility shoud be: DefaultVisibility;
6703 */
6704
Fariborz Jahanian07e52882012-02-13 21:34:45 +00006705 Result += "\n";
6706 for (unsigned i =0, e = Ivars.size(); i < e; i++) {
6707 ObjCIvarDecl *IvarDecl = Ivars[i];
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00006708 if (Context->getLangOpts().MicrosoftExt)
6709 Result += "__declspec(allocate(\".objc_ivar$B\")) ";
6710
6711 if (!Context->getLangOpts().MicrosoftExt ||
6712 IvarDecl->getAccessControl() == ObjCIvarDecl::Private ||
Fariborz Jahanian117591f2012-03-10 01:34:42 +00006713 IvarDecl->getAccessControl() == ObjCIvarDecl::Package)
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006714 Result += "extern \"C\" unsigned long int ";
Fariborz Jahaniand1c84d32012-03-10 00:53:02 +00006715 else
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006716 Result += "extern \"C\" __declspec(dllexport) unsigned long int ";
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006717 WriteInternalIvarName(CDecl, IvarDecl, Result);
Fariborz Jahanian07e52882012-02-13 21:34:45 +00006718 Result += " __attribute__ ((used, section (\"__DATA,__objc_ivar\")))";
6719 Result += " = ";
Fariborz Jahanianacee1c92012-04-11 21:12:36 +00006720 RewriteObj.RewriteIvarOffsetComputation(IvarDecl, Result);
6721 Result += ";\n";
Fariborz Jahaniandb649232012-02-13 20:59:02 +00006722 }
6723}
6724
Fariborz Jahanianae932952012-02-10 20:47:10 +00006725static void Write__ivar_list_t_initializer(RewriteModernObjC &RewriteObj,
6726 ASTContext *Context, std::string &Result,
6727 ArrayRef<ObjCIvarDecl *> Ivars,
6728 StringRef VarName,
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006729 ObjCInterfaceDecl *CDecl) {
Fariborz Jahanianae932952012-02-10 20:47:10 +00006730 if (Ivars.size() > 0) {
Fariborz Jahanianacee1c92012-04-11 21:12:36 +00006731 Write_IvarOffsetVar(RewriteObj, Context, Result, Ivars, CDecl);
Fariborz Jahanian07e52882012-02-13 21:34:45 +00006732
Fariborz Jahanianae932952012-02-10 20:47:10 +00006733 Result += "\nstatic ";
6734 Write__ivar_list_t_TypeDecl(Result, Ivars.size());
6735 Result += " "; Result += VarName;
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006736 Result += CDecl->getNameAsString();
Fariborz Jahanianae932952012-02-10 20:47:10 +00006737 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6738 Result += "\t"; Result += "sizeof(_ivar_t)"; Result += ",\n";
6739 Result += "\t"; Result += utostr(Ivars.size()); Result += ",\n";
6740 for (unsigned i =0, e = Ivars.size(); i < e; i++) {
6741 ObjCIvarDecl *IvarDecl = Ivars[i];
6742 if (i == 0)
6743 Result += "\t{{";
6744 else
6745 Result += "\t {";
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006746 Result += "(unsigned long int *)&";
6747 WriteInternalIvarName(CDecl, IvarDecl, Result);
Fariborz Jahaniandb649232012-02-13 20:59:02 +00006748 Result += ", ";
Fariborz Jahanianae932952012-02-10 20:47:10 +00006749
6750 Result += "\""; Result += IvarDecl->getName(); Result += "\", ";
6751 std::string IvarTypeString, QuoteIvarTypeString;
6752 Context->getObjCEncodingForType(IvarDecl->getType(), IvarTypeString,
6753 IvarDecl);
6754 RewriteObj.QuoteDoublequotes(IvarTypeString, QuoteIvarTypeString);
6755 Result += "\""; Result += QuoteIvarTypeString; Result += "\", ";
6756
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00006757 // FIXME. this alignment represents the host alignment and need be changed to
6758 // represent the target alignment.
6759 unsigned Align = Context->getTypeAlign(IvarDecl->getType())/8;
6760 Align = llvm::Log2_32(Align);
Fariborz Jahanianae932952012-02-10 20:47:10 +00006761 Result += llvm::utostr(Align); Result += ", ";
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00006762 CharUnits Size = Context->getTypeSizeInChars(IvarDecl->getType());
6763 Result += llvm::utostr(Size.getQuantity());
Fariborz Jahanianae932952012-02-10 20:47:10 +00006764 if (i == e-1)
6765 Result += "}}\n";
6766 else
6767 Result += "},\n";
6768 }
6769 Result += "};\n";
6770 }
6771}
6772
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006773/// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006774void RewriteModernObjC::RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl,
6775 std::string &Result) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006776
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006777 // Do not synthesize the protocol more than once.
6778 if (ObjCSynthesizedProtocols.count(PDecl->getCanonicalDecl()))
6779 return;
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00006780 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006781
6782 if (ObjCProtocolDecl *Def = PDecl->getDefinition())
6783 PDecl = Def;
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006784 // Must write out all protocol definitions in current qualifier list,
6785 // and in their nested qualifiers before writing out current definition.
6786 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
6787 E = PDecl->protocol_end(); I != E; ++I)
6788 RewriteObjCProtocolMetaData(*I, Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006789
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006790 // Construct method lists.
6791 std::vector<ObjCMethodDecl *> InstanceMethods, ClassMethods;
6792 std::vector<ObjCMethodDecl *> OptInstanceMethods, OptClassMethods;
6793 for (ObjCProtocolDecl::instmeth_iterator
6794 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
6795 I != E; ++I) {
6796 ObjCMethodDecl *MD = *I;
6797 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
6798 OptInstanceMethods.push_back(MD);
6799 } else {
6800 InstanceMethods.push_back(MD);
6801 }
6802 }
6803
6804 for (ObjCProtocolDecl::classmeth_iterator
6805 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
6806 I != E; ++I) {
6807 ObjCMethodDecl *MD = *I;
6808 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
6809 OptClassMethods.push_back(MD);
6810 } else {
6811 ClassMethods.push_back(MD);
6812 }
6813 }
Fariborz Jahaniane0adbd82012-02-08 22:23:26 +00006814 std::vector<ObjCMethodDecl *> AllMethods;
6815 for (unsigned i = 0, e = InstanceMethods.size(); i < e; i++)
6816 AllMethods.push_back(InstanceMethods[i]);
6817 for (unsigned i = 0, e = ClassMethods.size(); i < e; i++)
6818 AllMethods.push_back(ClassMethods[i]);
6819 for (unsigned i = 0, e = OptInstanceMethods.size(); i < e; i++)
6820 AllMethods.push_back(OptInstanceMethods[i]);
6821 for (unsigned i = 0, e = OptClassMethods.size(); i < e; i++)
6822 AllMethods.push_back(OptClassMethods[i]);
6823
6824 Write__extendedMethodTypes_initializer(*this, Context, Result,
6825 AllMethods,
6826 "_OBJC_PROTOCOL_METHOD_TYPES_",
6827 PDecl->getNameAsString());
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006828 // Protocol's super protocol list
6829 std::vector<ObjCProtocolDecl *> SuperProtocols;
6830 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
6831 E = PDecl->protocol_end(); I != E; ++I)
6832 SuperProtocols.push_back(*I);
6833
6834 Write_protocol_list_initializer(Context, Result, SuperProtocols,
6835 "_OBJC_PROTOCOL_REFS_",
6836 PDecl->getNameAsString());
6837
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006838 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006839 "_OBJC_PROTOCOL_INSTANCE_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006840 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006841
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006842 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006843 "_OBJC_PROTOCOL_CLASS_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006844 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006845
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006846 Write_method_list_t_initializer(*this, Context, Result, OptInstanceMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006847 "_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006848 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006849
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006850 Write_method_list_t_initializer(*this, Context, Result, OptClassMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006851 "_OBJC_PROTOCOL_OPT_CLASS_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006852 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006853
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006854 // Protocol's property metadata.
6855 std::vector<ObjCPropertyDecl *> ProtocolProperties;
6856 for (ObjCContainerDecl::prop_iterator I = PDecl->prop_begin(),
6857 E = PDecl->prop_end(); I != E; ++I)
David Blaikie581deb32012-06-06 20:45:41 +00006858 ProtocolProperties.push_back(*I);
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006859
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006860 Write_prop_list_t_initializer(*this, Context, Result, ProtocolProperties,
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006861 /* Container */0,
6862 "_OBJC_PROTOCOL_PROPERTIES_",
6863 PDecl->getNameAsString());
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006864
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006865 // Writer out root metadata for current protocol: struct _protocol_t
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00006866 Result += "\n";
6867 if (LangOpts.MicrosoftExt)
Fariborz Jahanian8590d862012-04-14 17:13:08 +00006868 Result += "static ";
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00006869 Result += "struct _protocol_t _OBJC_PROTOCOL_";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006870 Result += PDecl->getNameAsString();
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006871 Result += " __attribute__ ((used, section (\"__DATA,__datacoal_nt,coalesced\"))) = {\n";
6872 Result += "\t0,\n"; // id is; is null
6873 Result += "\t\""; Result += PDecl->getNameAsString(); Result += "\",\n";
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006874 if (SuperProtocols.size() > 0) {
6875 Result += "\t(const struct _protocol_list_t *)&"; Result += "_OBJC_PROTOCOL_REFS_";
6876 Result += PDecl->getNameAsString(); Result += ",\n";
6877 }
6878 else
6879 Result += "\t0,\n";
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006880 if (InstanceMethods.size() > 0) {
6881 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
6882 Result += PDecl->getNameAsString(); Result += ",\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006883 }
6884 else
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006885 Result += "\t0,\n";
6886
6887 if (ClassMethods.size() > 0) {
6888 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_CLASS_METHODS_";
6889 Result += PDecl->getNameAsString(); Result += ",\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006890 }
6891 else
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006892 Result += "\t0,\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006893
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006894 if (OptInstanceMethods.size() > 0) {
6895 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_";
6896 Result += PDecl->getNameAsString(); Result += ",\n";
6897 }
6898 else
6899 Result += "\t0,\n";
6900
6901 if (OptClassMethods.size() > 0) {
6902 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_CLASS_METHODS_";
6903 Result += PDecl->getNameAsString(); Result += ",\n";
6904 }
6905 else
6906 Result += "\t0,\n";
6907
6908 if (ProtocolProperties.size() > 0) {
6909 Result += "\t(const struct _prop_list_t *)&_OBJC_PROTOCOL_PROPERTIES_";
6910 Result += PDecl->getNameAsString(); Result += ",\n";
6911 }
6912 else
6913 Result += "\t0,\n";
6914
6915 Result += "\t"; Result += "sizeof(_protocol_t)"; Result += ",\n";
6916 Result += "\t0,\n";
6917
Fariborz Jahaniane0adbd82012-02-08 22:23:26 +00006918 if (AllMethods.size() > 0) {
6919 Result += "\t(const char **)&"; Result += "_OBJC_PROTOCOL_METHOD_TYPES_";
6920 Result += PDecl->getNameAsString();
6921 Result += "\n};\n";
6922 }
6923 else
6924 Result += "\t0\n};\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00006925
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00006926 if (LangOpts.MicrosoftExt)
Fariborz Jahanian8590d862012-04-14 17:13:08 +00006927 Result += "static ";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00006928 Result += "struct _protocol_t *";
6929 Result += "_OBJC_LABEL_PROTOCOL_$_"; Result += PDecl->getNameAsString();
6930 Result += " = &_OBJC_PROTOCOL_"; Result += PDecl->getNameAsString();
6931 Result += ";\n";
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006932
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006933 // Mark this protocol as having been generated.
6934 if (!ObjCSynthesizedProtocols.insert(PDecl->getCanonicalDecl()))
6935 llvm_unreachable("protocol already synthesized");
6936
6937}
6938
6939void RewriteModernObjC::RewriteObjCProtocolListMetaData(
6940 const ObjCList<ObjCProtocolDecl> &Protocols,
6941 StringRef prefix, StringRef ClassName,
6942 std::string &Result) {
6943 if (Protocols.empty()) return;
6944
6945 for (unsigned i = 0; i != Protocols.size(); i++)
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006946 RewriteObjCProtocolMetaData(Protocols[i], Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006947
6948 // Output the top lovel protocol meta-data for the class.
6949 /* struct _objc_protocol_list {
6950 struct _objc_protocol_list *next;
6951 int protocol_count;
6952 struct _objc_protocol *class_protocols[];
6953 }
6954 */
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00006955 Result += "\n";
6956 if (LangOpts.MicrosoftExt)
6957 Result += "__declspec(allocate(\".cat_cls_meth$B\")) ";
6958 Result += "static struct {\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006959 Result += "\tstruct _objc_protocol_list *next;\n";
6960 Result += "\tint protocol_count;\n";
6961 Result += "\tstruct _objc_protocol *class_protocols[";
6962 Result += utostr(Protocols.size());
6963 Result += "];\n} _OBJC_";
6964 Result += prefix;
6965 Result += "_PROTOCOLS_";
6966 Result += ClassName;
6967 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
6968 "{\n\t0, ";
6969 Result += utostr(Protocols.size());
6970 Result += "\n";
6971
6972 Result += "\t,{&_OBJC_PROTOCOL_";
6973 Result += Protocols[0]->getNameAsString();
6974 Result += " \n";
6975
6976 for (unsigned i = 1; i != Protocols.size(); i++) {
6977 Result += "\t ,&_OBJC_PROTOCOL_";
6978 Result += Protocols[i]->getNameAsString();
6979 Result += "\n";
6980 }
6981 Result += "\t }\n};\n";
6982}
6983
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006984/// hasObjCExceptionAttribute - Return true if this class or any super
6985/// class has the __objc_exception__ attribute.
6986/// FIXME. Move this to ASTContext.cpp as it is also used for IRGen.
6987static bool hasObjCExceptionAttribute(ASTContext &Context,
6988 const ObjCInterfaceDecl *OID) {
6989 if (OID->hasAttr<ObjCExceptionAttr>())
6990 return true;
6991 if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
6992 return hasObjCExceptionAttribute(Context, Super);
6993 return false;
6994}
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006995
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006996void RewriteModernObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
6997 std::string &Result) {
6998 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
6999
7000 // Explicitly declared @interface's are already synthesized.
Fariborz Jahanianae932952012-02-10 20:47:10 +00007001 if (CDecl->isImplicitInterfaceDecl())
7002 assert(false &&
7003 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00007004
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00007005 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanianae932952012-02-10 20:47:10 +00007006 SmallVector<ObjCIvarDecl *, 8> IVars;
7007
7008 for (ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
7009 IVD; IVD = IVD->getNextIvar()) {
7010 // Ignore unnamed bit-fields.
7011 if (!IVD->getDeclName())
7012 continue;
7013 IVars.push_back(IVD);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007014 }
7015
Fariborz Jahanianae932952012-02-10 20:47:10 +00007016 Write__ivar_list_t_initializer(*this, Context, Result, IVars,
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00007017 "_OBJC_$_INSTANCE_VARIABLES_",
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00007018 CDecl);
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00007019
7020 // Build _objc_method_list for class's instance methods if needed
7021 SmallVector<ObjCMethodDecl *, 32>
7022 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
7023
7024 // If any of our property implementations have associated getters or
7025 // setters, produce metadata for them as well.
7026 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
7027 PropEnd = IDecl->propimpl_end();
7028 Prop != PropEnd; ++Prop) {
David Blaikie262bc182012-04-30 02:36:29 +00007029 if (Prop->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00007030 continue;
David Blaikie262bc182012-04-30 02:36:29 +00007031 if (!Prop->getPropertyIvarDecl())
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00007032 continue;
David Blaikie262bc182012-04-30 02:36:29 +00007033 ObjCPropertyDecl *PD = Prop->getPropertyDecl();
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00007034 if (!PD)
7035 continue;
7036 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
Fariborz Jahanian301e2e42012-05-03 22:52:13 +00007037 if (mustSynthesizeSetterGetterMethod(IDecl, PD, true /*getter*/))
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00007038 InstanceMethods.push_back(Getter);
7039 if (PD->isReadOnly())
7040 continue;
7041 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
Fariborz Jahanian301e2e42012-05-03 22:52:13 +00007042 if (mustSynthesizeSetterGetterMethod(IDecl, PD, false /*setter*/))
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00007043 InstanceMethods.push_back(Setter);
7044 }
7045
7046 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
7047 "_OBJC_$_INSTANCE_METHODS_",
7048 IDecl->getNameAsString(), true);
7049
7050 SmallVector<ObjCMethodDecl *, 32>
7051 ClassMethods(IDecl->classmeth_begin(), IDecl->classmeth_end());
7052
7053 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
7054 "_OBJC_$_CLASS_METHODS_",
7055 IDecl->getNameAsString(), true);
Fariborz Jahanian0a525342012-02-14 19:31:35 +00007056
7057 // Protocols referenced in class declaration?
7058 // Protocol's super protocol list
7059 std::vector<ObjCProtocolDecl *> RefedProtocols;
7060 const ObjCList<ObjCProtocolDecl> &Protocols = CDecl->getReferencedProtocols();
7061 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
7062 E = Protocols.end();
7063 I != E; ++I) {
7064 RefedProtocols.push_back(*I);
7065 // Must write out all protocol definitions in current qualifier list,
7066 // and in their nested qualifiers before writing out current definition.
7067 RewriteObjCProtocolMetaData(*I, Result);
7068 }
7069
7070 Write_protocol_list_initializer(Context, Result,
7071 RefedProtocols,
7072 "_OBJC_CLASS_PROTOCOLS_$_",
7073 IDecl->getNameAsString());
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00007074
7075 // Protocol's property metadata.
7076 std::vector<ObjCPropertyDecl *> ClassProperties;
7077 for (ObjCContainerDecl::prop_iterator I = CDecl->prop_begin(),
7078 E = CDecl->prop_end(); I != E; ++I)
David Blaikie581deb32012-06-06 20:45:41 +00007079 ClassProperties.push_back(*I);
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00007080
7081 Write_prop_list_t_initializer(*this, Context, Result, ClassProperties,
Fariborz Jahanian2df089d2012-03-22 17:39:35 +00007082 /* Container */IDecl,
Fariborz Jahanianeeabf382012-02-16 21:57:59 +00007083 "_OBJC_$_PROP_LIST_",
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00007084 CDecl->getNameAsString());
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00007085
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00007086
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00007087 // Data for initializing _class_ro_t metaclass meta-data
7088 uint32_t flags = CLS_META;
7089 std::string InstanceSize;
7090 std::string InstanceStart;
7091
7092
7093 bool classIsHidden = CDecl->getVisibility() == HiddenVisibility;
7094 if (classIsHidden)
7095 flags |= OBJC2_CLS_HIDDEN;
7096
7097 if (!CDecl->getSuperClass())
7098 // class is root
7099 flags |= CLS_ROOT;
7100 InstanceSize = "sizeof(struct _class_t)";
7101 InstanceStart = InstanceSize;
7102 Write__class_ro_t_initializer(Context, Result, flags,
7103 InstanceStart, InstanceSize,
7104 ClassMethods,
7105 0,
7106 0,
7107 0,
7108 "_OBJC_METACLASS_RO_$_",
7109 CDecl->getNameAsString());
7110
7111
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00007112 // Data for initializing _class_ro_t meta-data
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00007113 flags = CLS;
7114 if (classIsHidden)
7115 flags |= OBJC2_CLS_HIDDEN;
7116
7117 if (hasObjCExceptionAttribute(*Context, CDecl))
7118 flags |= CLS_EXCEPTION;
7119
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00007120 if (!CDecl->getSuperClass())
7121 // class is root
7122 flags |= CLS_ROOT;
7123
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00007124 InstanceSize.clear();
7125 InstanceStart.clear();
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00007126 if (!ObjCSynthesizedStructs.count(CDecl)) {
7127 InstanceSize = "0";
7128 InstanceStart = "0";
7129 }
7130 else {
7131 InstanceSize = "sizeof(struct ";
7132 InstanceSize += CDecl->getNameAsString();
7133 InstanceSize += "_IMPL)";
7134
7135 ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
7136 if (IVD) {
Fariborz Jahanianacee1c92012-04-11 21:12:36 +00007137 RewriteIvarOffsetComputation(IVD, InstanceStart);
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00007138 }
7139 else
7140 InstanceStart = InstanceSize;
7141 }
7142 Write__class_ro_t_initializer(Context, Result, flags,
7143 InstanceStart, InstanceSize,
7144 InstanceMethods,
7145 RefedProtocols,
7146 IVars,
7147 ClassProperties,
7148 "_OBJC_CLASS_RO_$_",
7149 CDecl->getNameAsString());
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00007150
7151 Write_class_t(Context, Result,
7152 "OBJC_METACLASS_$_",
7153 CDecl, /*metaclass*/true);
7154
7155 Write_class_t(Context, Result,
7156 "OBJC_CLASS_$_",
7157 CDecl, /*metaclass*/false);
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00007158
7159 if (ImplementationIsNonLazy(IDecl))
7160 DefinedNonLazyClasses.push_back(CDecl);
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00007161
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007162}
7163
Fariborz Jahaniane0335782012-03-27 18:41:05 +00007164void RewriteModernObjC::RewriteClassSetupInitHook(std::string &Result) {
7165 int ClsDefCount = ClassImplementation.size();
7166 if (!ClsDefCount)
7167 return;
7168 Result += "#pragma section(\".objc_inithooks$B\", long, read, write)\n";
7169 Result += "__declspec(allocate(\".objc_inithooks$B\")) ";
7170 Result += "static void *OBJC_CLASS_SETUP[] = {\n";
7171 for (int i = 0; i < ClsDefCount; i++) {
7172 ObjCImplementationDecl *IDecl = ClassImplementation[i];
7173 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
7174 Result += "\t(void *)&OBJC_CLASS_SETUP_$_";
7175 Result += CDecl->getName(); Result += ",\n";
7176 }
7177 Result += "};\n";
7178}
7179
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007180void RewriteModernObjC::RewriteMetaDataIntoBuffer(std::string &Result) {
7181 int ClsDefCount = ClassImplementation.size();
7182 int CatDefCount = CategoryImplementation.size();
7183
7184 // For each implemented class, write out all its meta data.
7185 for (int i = 0; i < ClsDefCount; i++)
7186 RewriteObjCClassMetaData(ClassImplementation[i], Result);
7187
Fariborz Jahaniane0335782012-03-27 18:41:05 +00007188 RewriteClassSetupInitHook(Result);
7189
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007190 // For each implemented category, write out all its meta data.
7191 for (int i = 0; i < CatDefCount; i++)
7192 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
7193
Fariborz Jahaniane0335782012-03-27 18:41:05 +00007194 RewriteCategorySetupInitHook(Result);
7195
Fariborz Jahaniandf795672012-02-17 00:06:14 +00007196 if (ClsDefCount > 0) {
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00007197 if (LangOpts.MicrosoftExt)
7198 Result += "__declspec(allocate(\".objc_classlist$B\")) ";
Fariborz Jahaniandf795672012-02-17 00:06:14 +00007199 Result += "static struct _class_t *L_OBJC_LABEL_CLASS_$ [";
7200 Result += llvm::utostr(ClsDefCount); Result += "]";
7201 Result +=
7202 " __attribute__((used, section (\"__DATA, __objc_classlist,"
7203 "regular,no_dead_strip\")))= {\n";
7204 for (int i = 0; i < ClsDefCount; i++) {
7205 Result += "\t&OBJC_CLASS_$_";
7206 Result += ClassImplementation[i]->getNameAsString();
7207 Result += ",\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007208 }
Fariborz Jahaniandf795672012-02-17 00:06:14 +00007209 Result += "};\n";
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00007210
7211 if (!DefinedNonLazyClasses.empty()) {
7212 if (LangOpts.MicrosoftExt)
7213 Result += "__declspec(allocate(\".objc_nlclslist$B\")) \n";
7214 Result += "static struct _class_t *_OBJC_LABEL_NONLAZY_CLASS_$[] = {\n\t";
7215 for (unsigned i = 0, e = DefinedNonLazyClasses.size(); i < e; i++) {
7216 Result += "\t&OBJC_CLASS_$_"; Result += DefinedNonLazyClasses[i]->getNameAsString();
7217 Result += ",\n";
7218 }
7219 Result += "};\n";
7220 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007221 }
Fariborz Jahanian61186122012-02-17 18:40:41 +00007222
7223 if (CatDefCount > 0) {
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00007224 if (LangOpts.MicrosoftExt)
7225 Result += "__declspec(allocate(\".objc_catlist$B\")) ";
Fariborz Jahanian61186122012-02-17 18:40:41 +00007226 Result += "static struct _category_t *L_OBJC_LABEL_CATEGORY_$ [";
7227 Result += llvm::utostr(CatDefCount); Result += "]";
7228 Result +=
7229 " __attribute__((used, section (\"__DATA, __objc_catlist,"
7230 "regular,no_dead_strip\")))= {\n";
7231 for (int i = 0; i < CatDefCount; i++) {
7232 Result += "\t&_OBJC_$_CATEGORY_";
7233 Result +=
7234 CategoryImplementation[i]->getClassInterface()->getNameAsString();
7235 Result += "_$_";
7236 Result += CategoryImplementation[i]->getNameAsString();
7237 Result += ",\n";
7238 }
7239 Result += "};\n";
7240 }
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00007241
7242 if (!DefinedNonLazyCategories.empty()) {
7243 if (LangOpts.MicrosoftExt)
7244 Result += "__declspec(allocate(\".objc_nlcatlist$B\")) \n";
7245 Result += "static struct _category_t *_OBJC_LABEL_NONLAZY_CATEGORY_$[] = {\n\t";
7246 for (unsigned i = 0, e = DefinedNonLazyCategories.size(); i < e; i++) {
7247 Result += "\t&_OBJC_$_CATEGORY_";
7248 Result +=
7249 DefinedNonLazyCategories[i]->getClassInterface()->getNameAsString();
7250 Result += "_$_";
7251 Result += DefinedNonLazyCategories[i]->getNameAsString();
7252 Result += ",\n";
7253 }
7254 Result += "};\n";
7255 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007256}
7257
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00007258void RewriteModernObjC::WriteImageInfo(std::string &Result) {
7259 if (LangOpts.MicrosoftExt)
7260 Result += "__declspec(allocate(\".objc_imageinfo$B\")) \n";
7261
7262 Result += "static struct IMAGE_INFO { unsigned version; unsigned flag; } ";
7263 // version 0, ObjCABI is 2
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00007264 Result += "_OBJC_IMAGE_INFO = { 0, 2 };\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00007265}
7266
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007267/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
7268/// implementation.
7269void RewriteModernObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
7270 std::string &Result) {
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00007271 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007272 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
7273 // Find category declaration for this implementation.
Fariborz Jahanian61186122012-02-17 18:40:41 +00007274 ObjCCategoryDecl *CDecl=0;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007275 for (CDecl = ClassDecl->getCategoryList(); CDecl;
7276 CDecl = CDecl->getNextClassCategory())
7277 if (CDecl->getIdentifier() == IDecl->getIdentifier())
7278 break;
7279
7280 std::string FullCategoryName = ClassDecl->getNameAsString();
Fariborz Jahanian61186122012-02-17 18:40:41 +00007281 FullCategoryName += "_$_";
7282 FullCategoryName += CDecl->getNameAsString();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007283
7284 // Build _objc_method_list for class's instance methods if needed
7285 SmallVector<ObjCMethodDecl *, 32>
7286 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
7287
7288 // If any of our property implementations have associated getters or
7289 // setters, produce metadata for them as well.
7290 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
7291 PropEnd = IDecl->propimpl_end();
7292 Prop != PropEnd; ++Prop) {
David Blaikie262bc182012-04-30 02:36:29 +00007293 if (Prop->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007294 continue;
David Blaikie262bc182012-04-30 02:36:29 +00007295 if (!Prop->getPropertyIvarDecl())
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007296 continue;
David Blaikie262bc182012-04-30 02:36:29 +00007297 ObjCPropertyDecl *PD = Prop->getPropertyDecl();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007298 if (!PD)
7299 continue;
7300 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
7301 InstanceMethods.push_back(Getter);
7302 if (PD->isReadOnly())
7303 continue;
7304 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
7305 InstanceMethods.push_back(Setter);
7306 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007307
Fariborz Jahanian61186122012-02-17 18:40:41 +00007308 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
7309 "_OBJC_$_CATEGORY_INSTANCE_METHODS_",
7310 FullCategoryName, true);
7311
7312 SmallVector<ObjCMethodDecl *, 32>
7313 ClassMethods(IDecl->classmeth_begin(), IDecl->classmeth_end());
7314
7315 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
7316 "_OBJC_$_CATEGORY_CLASS_METHODS_",
7317 FullCategoryName, true);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007318
7319 // Protocols referenced in class declaration?
Fariborz Jahanian61186122012-02-17 18:40:41 +00007320 // Protocol's super protocol list
7321 std::vector<ObjCProtocolDecl *> RefedProtocols;
Argyrios Kyrtzidisa5f44412012-03-13 01:09:41 +00007322 for (ObjCInterfaceDecl::protocol_iterator I = CDecl->protocol_begin(),
7323 E = CDecl->protocol_end();
7324
7325 I != E; ++I) {
Fariborz Jahanian61186122012-02-17 18:40:41 +00007326 RefedProtocols.push_back(*I);
7327 // Must write out all protocol definitions in current qualifier list,
7328 // and in their nested qualifiers before writing out current definition.
7329 RewriteObjCProtocolMetaData(*I, Result);
7330 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007331
Fariborz Jahanian61186122012-02-17 18:40:41 +00007332 Write_protocol_list_initializer(Context, Result,
7333 RefedProtocols,
7334 "_OBJC_CATEGORY_PROTOCOLS_$_",
7335 FullCategoryName);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007336
Fariborz Jahanian61186122012-02-17 18:40:41 +00007337 // Protocol's property metadata.
7338 std::vector<ObjCPropertyDecl *> ClassProperties;
7339 for (ObjCContainerDecl::prop_iterator I = CDecl->prop_begin(),
7340 E = CDecl->prop_end(); I != E; ++I)
David Blaikie581deb32012-06-06 20:45:41 +00007341 ClassProperties.push_back(*I);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007342
Fariborz Jahanian61186122012-02-17 18:40:41 +00007343 Write_prop_list_t_initializer(*this, Context, Result, ClassProperties,
Fariborz Jahanianebfa2722012-05-03 23:19:33 +00007344 /* Container */IDecl,
Fariborz Jahanian61186122012-02-17 18:40:41 +00007345 "_OBJC_$_PROP_LIST_",
7346 FullCategoryName);
7347
7348 Write_category_t(*this, Context, Result,
Fariborz Jahaniane0335782012-03-27 18:41:05 +00007349 CDecl,
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00007350 ClassDecl,
Fariborz Jahanian61186122012-02-17 18:40:41 +00007351 InstanceMethods,
7352 ClassMethods,
7353 RefedProtocols,
7354 ClassProperties);
7355
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00007356 // Determine if this category is also "non-lazy".
7357 if (ImplementationIsNonLazy(IDecl))
7358 DefinedNonLazyCategories.push_back(CDecl);
Fariborz Jahaniane0335782012-03-27 18:41:05 +00007359
7360}
7361
7362void RewriteModernObjC::RewriteCategorySetupInitHook(std::string &Result) {
7363 int CatDefCount = CategoryImplementation.size();
7364 if (!CatDefCount)
7365 return;
7366 Result += "#pragma section(\".objc_inithooks$B\", long, read, write)\n";
7367 Result += "__declspec(allocate(\".objc_inithooks$B\")) ";
7368 Result += "static void *OBJC_CATEGORY_SETUP[] = {\n";
7369 for (int i = 0; i < CatDefCount; i++) {
7370 ObjCCategoryImplDecl *IDecl = CategoryImplementation[i];
7371 ObjCCategoryDecl *CatDecl= IDecl->getCategoryDecl();
7372 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
7373 Result += "\t(void *)&OBJC_CATEGORY_SETUP_$_";
7374 Result += ClassDecl->getName();
7375 Result += "_$_";
7376 Result += CatDecl->getName();
7377 Result += ",\n";
7378 }
7379 Result += "};\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007380}
7381
7382// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
7383/// class methods.
7384template<typename MethodIterator>
7385void RewriteModernObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
7386 MethodIterator MethodEnd,
7387 bool IsInstanceMethod,
7388 StringRef prefix,
7389 StringRef ClassName,
7390 std::string &Result) {
7391 if (MethodBegin == MethodEnd) return;
7392
7393 if (!objc_impl_method) {
7394 /* struct _objc_method {
7395 SEL _cmd;
7396 char *method_types;
7397 void *_imp;
7398 }
7399 */
7400 Result += "\nstruct _objc_method {\n";
7401 Result += "\tSEL _cmd;\n";
7402 Result += "\tchar *method_types;\n";
7403 Result += "\tvoid *_imp;\n";
7404 Result += "};\n";
7405
7406 objc_impl_method = true;
7407 }
7408
7409 // Build _objc_method_list for class's methods if needed
7410
7411 /* struct {
7412 struct _objc_method_list *next_method;
7413 int method_count;
7414 struct _objc_method method_list[];
7415 }
7416 */
7417 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00007418 Result += "\n";
7419 if (LangOpts.MicrosoftExt) {
7420 if (IsInstanceMethod)
7421 Result += "__declspec(allocate(\".inst_meth$B\")) ";
7422 else
7423 Result += "__declspec(allocate(\".cls_meth$B\")) ";
7424 }
7425 Result += "static struct {\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007426 Result += "\tstruct _objc_method_list *next_method;\n";
7427 Result += "\tint method_count;\n";
7428 Result += "\tstruct _objc_method method_list[";
7429 Result += utostr(NumMethods);
7430 Result += "];\n} _OBJC_";
7431 Result += prefix;
7432 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
7433 Result += "_METHODS_";
7434 Result += ClassName;
7435 Result += " __attribute__ ((used, section (\"__OBJC, __";
7436 Result += IsInstanceMethod ? "inst" : "cls";
7437 Result += "_meth\")))= ";
7438 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
7439
7440 Result += "\t,{{(SEL)\"";
7441 Result += (*MethodBegin)->getSelector().getAsString().c_str();
7442 std::string MethodTypeString;
7443 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
7444 Result += "\", \"";
7445 Result += MethodTypeString;
7446 Result += "\", (void *)";
7447 Result += MethodInternalNames[*MethodBegin];
7448 Result += "}\n";
7449 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
7450 Result += "\t ,{(SEL)\"";
7451 Result += (*MethodBegin)->getSelector().getAsString().c_str();
7452 std::string MethodTypeString;
7453 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
7454 Result += "\", \"";
7455 Result += MethodTypeString;
7456 Result += "\", (void *)";
7457 Result += MethodInternalNames[*MethodBegin];
7458 Result += "}\n";
7459 }
7460 Result += "\t }\n};\n";
7461}
7462
7463Stmt *RewriteModernObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) {
7464 SourceRange OldRange = IV->getSourceRange();
7465 Expr *BaseExpr = IV->getBase();
7466
7467 // Rewrite the base, but without actually doing replaces.
7468 {
7469 DisableReplaceStmtScope S(*this);
7470 BaseExpr = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(BaseExpr));
7471 IV->setBase(BaseExpr);
7472 }
7473
7474 ObjCIvarDecl *D = IV->getDecl();
7475
7476 Expr *Replacement = IV;
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007477
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007478 if (BaseExpr->getType()->isObjCObjectPointerType()) {
7479 const ObjCInterfaceType *iFaceDecl =
Fariborz Jahanian163d3ce2012-05-08 23:54:35 +00007480 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007481 assert(iFaceDecl && "RewriteObjCIvarRefExpr - iFaceDecl is null");
7482 // lookup which class implements the instance variable.
7483 ObjCInterfaceDecl *clsDeclared = 0;
7484 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
7485 clsDeclared);
7486 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
7487
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007488 // Build name of symbol holding ivar offset.
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00007489 std::string IvarOffsetName;
7490 WriteInternalIvarName(clsDeclared, D, IvarOffsetName);
7491
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00007492 ReferencedIvars[clsDeclared].insert(D);
7493
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007494 // cast offset to "char *".
7495 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context,
7496 Context->getPointerType(Context->CharTy),
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007497 CK_BitCast,
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007498 BaseExpr);
7499 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
7500 SourceLocation(), &Context->Idents.get(IvarOffsetName),
7501 Context->UnsignedLongTy, 0, SC_Extern, SC_None);
John McCallf4b88a42012-03-10 09:33:50 +00007502 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, false,
7503 Context->UnsignedLongTy, VK_LValue,
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007504 SourceLocation());
7505 BinaryOperator *addExpr =
7506 new (Context) BinaryOperator(castExpr, DRE, BO_Add,
7507 Context->getPointerType(Context->CharTy),
Lang Hamesbe9af122012-10-02 04:45:10 +00007508 VK_RValue, OK_Ordinary, SourceLocation(), false);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007509 // Don't forget the parens to enforce the proper binding.
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007510 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(),
7511 SourceLocation(),
7512 addExpr);
Fariborz Jahanian0d6e22a2012-02-24 17:35:35 +00007513 QualType IvarT = D->getType();
Fariborz Jahanian27fc81b2012-04-27 22:48:54 +00007514
Fariborz Jahanianf5eac482012-05-02 17:34:59 +00007515 if (!isa<TypedefType>(IvarT) && IvarT->isRecordType()) {
Fariborz Jahanian27fc81b2012-04-27 22:48:54 +00007516 RecordDecl *RD = IvarT->getAs<RecordType>()->getDecl();
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00007517 RD = RD->getDefinition();
7518 if (RD && !RD->getDeclName().getAsIdentifierInfo()) {
Fariborz Jahanian27fc81b2012-04-27 22:48:54 +00007519 // decltype(((Foo_IMPL*)0)->bar) *
Fariborz Jahanianf5eac482012-05-02 17:34:59 +00007520 ObjCContainerDecl *CDecl =
7521 dyn_cast<ObjCContainerDecl>(D->getDeclContext());
7522 // ivar in class extensions requires special treatment.
7523 if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(CDecl))
7524 CDecl = CatDecl->getClassInterface();
7525 std::string RecName = CDecl->getName();
Fariborz Jahanian27fc81b2012-04-27 22:48:54 +00007526 RecName += "_IMPL";
7527 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
7528 SourceLocation(), SourceLocation(),
7529 &Context->Idents.get(RecName.c_str()));
7530 QualType PtrStructIMPL = Context->getPointerType(Context->getTagDeclType(RD));
7531 unsigned UnsignedIntSize =
7532 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
7533 Expr *Zero = IntegerLiteral::Create(*Context,
7534 llvm::APInt(UnsignedIntSize, 0),
7535 Context->UnsignedIntTy, SourceLocation());
7536 Zero = NoTypeInfoCStyleCastExpr(Context, PtrStructIMPL, CK_BitCast, Zero);
7537 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
7538 Zero);
7539 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
7540 SourceLocation(),
7541 &Context->Idents.get(D->getNameAsString()),
7542 IvarT, 0,
7543 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smithca523302012-06-10 03:12:00 +00007544 ICIS_NoInit);
Fariborz Jahanian27fc81b2012-04-27 22:48:54 +00007545 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
7546 FD->getType(), VK_LValue,
7547 OK_Ordinary);
7548 IvarT = Context->getDecltypeType(ME, ME->getType());
7549 }
7550 }
Fariborz Jahanian8e0913d2012-02-29 00:26:20 +00007551 convertObjCTypeToCStyleType(IvarT);
Fariborz Jahanian0d6e22a2012-02-24 17:35:35 +00007552 QualType castT = Context->getPointerType(IvarT);
Fariborz Jahanian27fc81b2012-04-27 22:48:54 +00007553
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007554 castExpr = NoTypeInfoCStyleCastExpr(Context,
7555 castT,
7556 CK_BitCast,
7557 PE);
Fariborz Jahanian27fc81b2012-04-27 22:48:54 +00007558
7559
Fariborz Jahanian8e0913d2012-02-29 00:26:20 +00007560 Expr *Exp = new (Context) UnaryOperator(castExpr, UO_Deref, IvarT,
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007561 VK_LValue, OK_Ordinary,
7562 SourceLocation());
7563 PE = new (Context) ParenExpr(OldRange.getBegin(),
7564 OldRange.getEnd(),
7565 Exp);
7566
7567 Replacement = PE;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007568 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007569
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007570 ReplaceStmtWithRange(IV, Replacement, OldRange);
7571 return Replacement;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007572}