blob: 9c98a7ff2ba948b4a71a7e74fa5bf780d4f3e132 [file] [log] [blame]
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001//===--- RewriteObjC.cpp - Playground for the code rewriter ---------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// Hacks and fun related to the code rewriter.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/Rewrite/ASTConsumers.h"
15#include "clang/Rewrite/Rewriter.h"
16#include "clang/AST/AST.h"
17#include "clang/AST/ASTConsumer.h"
18#include "clang/AST/ParentMap.h"
19#include "clang/Basic/SourceManager.h"
20#include "clang/Basic/IdentifierTable.h"
21#include "clang/Basic/Diagnostic.h"
22#include "clang/Lex/Lexer.h"
23#include "llvm/Support/MemoryBuffer.h"
24#include "llvm/Support/raw_ostream.h"
25#include "llvm/ADT/StringExtras.h"
26#include "llvm/ADT/SmallPtrSet.h"
27#include "llvm/ADT/OwningPtr.h"
28#include "llvm/ADT/DenseSet.h"
29
30using namespace clang;
31using llvm::utostr;
32
33namespace {
34 class RewriteModernObjC : public ASTConsumer {
35 protected:
36
37 enum {
38 BLOCK_FIELD_IS_OBJECT = 3, /* id, NSObject, __attribute__((NSObject)),
39 block, ... */
40 BLOCK_FIELD_IS_BLOCK = 7, /* a block variable */
41 BLOCK_FIELD_IS_BYREF = 8, /* the on stack structure holding the
42 __block variable */
43 BLOCK_FIELD_IS_WEAK = 16, /* declared __weak, only used in byref copy
44 helpers */
45 BLOCK_BYREF_CALLER = 128, /* called from __block (byref) copy/dispose
46 support routines */
47 BLOCK_BYREF_CURRENT_MAX = 256
48 };
49
50 enum {
51 BLOCK_NEEDS_FREE = (1 << 24),
52 BLOCK_HAS_COPY_DISPOSE = (1 << 25),
53 BLOCK_HAS_CXX_OBJ = (1 << 26),
54 BLOCK_IS_GC = (1 << 27),
55 BLOCK_IS_GLOBAL = (1 << 28),
56 BLOCK_HAS_DESCRIPTOR = (1 << 29)
57 };
58 static const int OBJC_ABI_VERSION = 7;
59
60 Rewriter Rewrite;
61 DiagnosticsEngine &Diags;
62 const LangOptions &LangOpts;
63 ASTContext *Context;
64 SourceManager *SM;
65 TranslationUnitDecl *TUDecl;
66 FileID MainFileID;
67 const char *MainFileStart, *MainFileEnd;
68 Stmt *CurrentBody;
69 ParentMap *PropParentMap; // created lazily.
70 std::string InFileName;
71 raw_ostream* OutFile;
72 std::string Preamble;
73
74 TypeDecl *ProtocolTypeDecl;
75 VarDecl *GlobalVarDecl;
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +000076 Expr *GlobalConstructionExp;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +000077 unsigned RewriteFailedDiag;
Fariborz Jahaniand13c2c22012-03-22 19:54:39 +000078 unsigned GlobalBlockRewriteFailedDiag;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +000079 // ObjC string constant support.
80 unsigned NumObjCStringLiterals;
81 VarDecl *ConstantStringClassReference;
82 RecordDecl *NSStringRecord;
83
84 // ObjC foreach break/continue generation support.
85 int BcLabelCount;
86
87 unsigned TryFinallyContainsReturnDiag;
88 // Needed for super.
89 ObjCMethodDecl *CurMethodDef;
90 RecordDecl *SuperStructDecl;
91 RecordDecl *ConstantStringDecl;
92
93 FunctionDecl *MsgSendFunctionDecl;
94 FunctionDecl *MsgSendSuperFunctionDecl;
95 FunctionDecl *MsgSendStretFunctionDecl;
96 FunctionDecl *MsgSendSuperStretFunctionDecl;
97 FunctionDecl *MsgSendFpretFunctionDecl;
98 FunctionDecl *GetClassFunctionDecl;
99 FunctionDecl *GetMetaClassFunctionDecl;
100 FunctionDecl *GetSuperClassFunctionDecl;
101 FunctionDecl *SelGetUidFunctionDecl;
102 FunctionDecl *CFStringFunctionDecl;
103 FunctionDecl *SuperContructorFunctionDecl;
104 FunctionDecl *CurFunctionDef;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000105
106 /* Misc. containers needed for meta-data rewrite. */
107 SmallVector<ObjCImplementationDecl *, 8> ClassImplementation;
108 SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation;
109 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCSynthesizedStructs;
110 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> ObjCSynthesizedProtocols;
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +0000111 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCWrittenInterfaces;
Fariborz Jahanian8fba8942012-04-30 23:20:30 +0000112 llvm::SmallPtrSet<TagDecl*, 32> GlobalDefinedTags;
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +0000113 SmallVector<ObjCInterfaceDecl*, 32> ObjCInterfacesSeen;
Fariborz Jahanian88f7f752012-03-14 23:18:19 +0000114 /// DefinedNonLazyClasses - List of defined "non-lazy" classes.
115 SmallVector<ObjCInterfaceDecl*, 8> DefinedNonLazyClasses;
116
117 /// DefinedNonLazyCategories - List of defined "non-lazy" categories.
118 llvm::SmallVector<ObjCCategoryDecl*, 8> DefinedNonLazyCategories;
119
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000120 SmallVector<Stmt *, 32> Stmts;
121 SmallVector<int, 8> ObjCBcLabelNo;
122 // Remember all the @protocol(<expr>) expressions.
123 llvm::SmallPtrSet<ObjCProtocolDecl *, 32> ProtocolExprDecls;
124
125 llvm::DenseSet<uint64_t> CopyDestroyCache;
126
127 // Block expressions.
128 SmallVector<BlockExpr *, 32> Blocks;
129 SmallVector<int, 32> InnerDeclRefsCount;
John McCallf4b88a42012-03-10 09:33:50 +0000130 SmallVector<DeclRefExpr *, 32> InnerDeclRefs;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000131
John McCallf4b88a42012-03-10 09:33:50 +0000132 SmallVector<DeclRefExpr *, 32> BlockDeclRefs;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000133
134 // Block related declarations.
135 SmallVector<ValueDecl *, 8> BlockByCopyDecls;
136 llvm::SmallPtrSet<ValueDecl *, 8> BlockByCopyDeclsPtrSet;
137 SmallVector<ValueDecl *, 8> BlockByRefDecls;
138 llvm::SmallPtrSet<ValueDecl *, 8> BlockByRefDeclsPtrSet;
139 llvm::DenseMap<ValueDecl *, unsigned> BlockByRefDeclNo;
140 llvm::SmallPtrSet<ValueDecl *, 8> ImportedBlockDecls;
141 llvm::SmallPtrSet<VarDecl *, 8> ImportedLocalExternalDecls;
142
143 llvm::DenseMap<BlockExpr *, std::string> RewrittenBlockExprs;
Fariborz Jahanian72c88f12012-02-22 18:13:25 +0000144 llvm::DenseMap<ObjCInterfaceDecl *,
145 llvm::SmallPtrSet<ObjCIvarDecl *, 8> > ReferencedIvars;
146
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000147 // This maps an original source AST to it's rewritten form. This allows
148 // us to avoid rewriting the same node twice (which is very uncommon).
149 // This is needed to support some of the exotic property rewriting.
150 llvm::DenseMap<Stmt *, Stmt *> ReplacedNodes;
151
152 // Needed for header files being rewritten
153 bool IsHeader;
154 bool SilenceRewriteMacroWarning;
155 bool objc_impl_method;
156
157 bool DisableReplaceStmt;
158 class DisableReplaceStmtScope {
159 RewriteModernObjC &R;
160 bool SavedValue;
161
162 public:
163 DisableReplaceStmtScope(RewriteModernObjC &R)
164 : R(R), SavedValue(R.DisableReplaceStmt) {
165 R.DisableReplaceStmt = true;
166 }
167 ~DisableReplaceStmtScope() {
168 R.DisableReplaceStmt = SavedValue;
169 }
170 };
171 void InitializeCommon(ASTContext &context);
172
173 public:
Fariborz Jahanian90af4e22012-02-14 17:19:02 +0000174 llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000175 // Top Level Driver code.
176 virtual bool HandleTopLevelDecl(DeclGroupRef D) {
177 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
178 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(*I)) {
179 if (!Class->isThisDeclarationADefinition()) {
180 RewriteForwardClassDecl(D);
181 break;
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +0000182 } else {
183 // Keep track of all interface declarations seen.
Fariborz Jahanianf3295272012-02-24 21:42:38 +0000184 ObjCInterfacesSeen.push_back(Class);
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +0000185 break;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000186 }
187 }
188
189 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>(*I)) {
190 if (!Proto->isThisDeclarationADefinition()) {
191 RewriteForwardProtocolDecl(D);
192 break;
193 }
194 }
195
196 HandleTopLevelSingleDecl(*I);
197 }
198 return true;
199 }
200 void HandleTopLevelSingleDecl(Decl *D);
201 void HandleDeclInMainFile(Decl *D);
202 RewriteModernObjC(std::string inFile, raw_ostream *OS,
203 DiagnosticsEngine &D, const LangOptions &LOpts,
204 bool silenceMacroWarn);
205
206 ~RewriteModernObjC() {}
207
208 virtual void HandleTranslationUnit(ASTContext &C);
209
210 void ReplaceStmt(Stmt *Old, Stmt *New) {
211 Stmt *ReplacingStmt = ReplacedNodes[Old];
212
213 if (ReplacingStmt)
214 return; // We can't rewrite the same node twice.
215
216 if (DisableReplaceStmt)
217 return;
218
219 // If replacement succeeded or warning disabled return with no warning.
220 if (!Rewrite.ReplaceStmt(Old, New)) {
221 ReplacedNodes[Old] = New;
222 return;
223 }
224 if (SilenceRewriteMacroWarning)
225 return;
226 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
227 << Old->getSourceRange();
228 }
229
230 void ReplaceStmtWithRange(Stmt *Old, Stmt *New, SourceRange SrcRange) {
231 if (DisableReplaceStmt)
232 return;
233
234 // Measure the old text.
235 int Size = Rewrite.getRangeSize(SrcRange);
236 if (Size == -1) {
237 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
238 << Old->getSourceRange();
239 return;
240 }
241 // Get the new text.
242 std::string SStr;
243 llvm::raw_string_ostream S(SStr);
Richard Smithd1420c62012-08-16 03:56:14 +0000244 New->printPretty(S, 0, PrintingPolicy(LangOpts));
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000245 const std::string &Str = S.str();
246
247 // If replacement succeeded or warning disabled return with no warning.
248 if (!Rewrite.ReplaceText(SrcRange.getBegin(), Size, Str)) {
249 ReplacedNodes[Old] = New;
250 return;
251 }
252 if (SilenceRewriteMacroWarning)
253 return;
254 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
255 << Old->getSourceRange();
256 }
257
258 void InsertText(SourceLocation Loc, StringRef Str,
259 bool InsertAfter = true) {
260 // If insertion succeeded or warning disabled return with no warning.
261 if (!Rewrite.InsertText(Loc, Str, InsertAfter) ||
262 SilenceRewriteMacroWarning)
263 return;
264
265 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
266 }
267
268 void ReplaceText(SourceLocation Start, unsigned OrigLength,
269 StringRef Str) {
270 // If removal succeeded or warning disabled return with no warning.
271 if (!Rewrite.ReplaceText(Start, OrigLength, Str) ||
272 SilenceRewriteMacroWarning)
273 return;
274
275 Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
276 }
277
278 // Syntactic Rewriting.
279 void RewriteRecordBody(RecordDecl *RD);
280 void RewriteInclude();
281 void RewriteForwardClassDecl(DeclGroupRef D);
282 void RewriteForwardClassDecl(const llvm::SmallVector<Decl*, 8> &DG);
283 void RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
284 const std::string &typedefString);
285 void RewriteImplementations();
286 void RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
287 ObjCImplementationDecl *IMD,
288 ObjCCategoryImplDecl *CID);
289 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
290 void RewriteImplementationDecl(Decl *Dcl);
291 void RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
292 ObjCMethodDecl *MDecl, std::string &ResultStr);
293 void RewriteTypeIntoString(QualType T, std::string &ResultStr,
294 const FunctionType *&FPRetType);
295 void RewriteByRefString(std::string &ResultStr, const std::string &Name,
296 ValueDecl *VD, bool def=false);
297 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
298 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
299 void RewriteForwardProtocolDecl(DeclGroupRef D);
300 void RewriteForwardProtocolDecl(const llvm::SmallVector<Decl*, 8> &DG);
301 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
302 void RewriteProperty(ObjCPropertyDecl *prop);
303 void RewriteFunctionDecl(FunctionDecl *FD);
304 void RewriteBlockPointerType(std::string& Str, QualType Type);
305 void RewriteBlockPointerTypeVariable(std::string& Str, ValueDecl *VD);
Fariborz Jahanianb75f8de2012-04-19 00:50:01 +0000306 void RewriteBlockLiteralFunctionDecl(FunctionDecl *FD);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000307 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
308 void RewriteTypeOfDecl(VarDecl *VD);
309 void RewriteObjCQualifiedInterfaceTypes(Expr *E);
Fariborz Jahanian163d3ce2012-05-08 23:54:35 +0000310
311 std::string getIvarAccessString(ObjCIvarDecl *D);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000312
313 // Expression Rewriting.
314 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
315 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
316 Stmt *RewritePropertyOrImplicitGetter(PseudoObjectExpr *Pseudo);
317 Stmt *RewritePropertyOrImplicitSetter(PseudoObjectExpr *Pseudo);
318 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
319 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
320 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian55947042012-03-27 20:17:30 +0000321 Stmt *RewriteObjCBoolLiteralExpr(ObjCBoolLiteralExpr *Exp);
Patrick Beardeb382ec2012-04-19 00:25:12 +0000322 Stmt *RewriteObjCBoxedExpr(ObjCBoxedExpr *Exp);
Fariborz Jahanian86cff602012-03-30 23:35:47 +0000323 Stmt *RewriteObjCArrayLiteralExpr(ObjCArrayLiteral *Exp);
Fariborz Jahaniane35abe12012-04-06 22:29:36 +0000324 Stmt *RewriteObjCDictionaryLiteralExpr(ObjCDictionaryLiteral *Exp);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000325 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000326 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
Fariborz Jahanian042b91d2012-05-23 23:47:20 +0000327 Stmt *RewriteObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000328 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
329 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
330 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
331 SourceLocation OrigEnd);
332 Stmt *RewriteBreakStmt(BreakStmt *S);
333 Stmt *RewriteContinueStmt(ContinueStmt *S);
334 void RewriteCastExpr(CStyleCastExpr *CE);
Fariborz Jahanianf1ee6872012-04-10 00:08:18 +0000335 void RewriteImplicitCastObjCExpr(CastExpr *IE);
Fariborz Jahanianb3f904f2012-04-03 17:35:38 +0000336 void RewriteLinkageSpec(LinkageSpecDecl *LSD);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000337
338 // Block rewriting.
339 void RewriteBlocksInFunctionProtoType(QualType funcType, NamedDecl *D);
340
341 // Block specific rewrite rules.
342 void RewriteBlockPointerDecl(NamedDecl *VD);
Fariborz Jahanian4fe261c2012-04-24 19:38:45 +0000343 void RewriteByRefVar(VarDecl *VD, bool firstDecl, bool lastDecl);
John McCallf4b88a42012-03-10 09:33:50 +0000344 Stmt *RewriteBlockDeclRefExpr(DeclRefExpr *VD);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000345 Stmt *RewriteLocalVariableExternalStorage(DeclRefExpr *DRE);
346 void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
347
348 void RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
349 std::string &Result);
350
Fariborz Jahanian15f87772012-02-28 22:45:07 +0000351 void RewriteObjCFieldDecl(FieldDecl *fieldDecl, std::string &Result);
Fariborz Jahanianb68258f2012-05-01 17:46:45 +0000352 bool IsTagDefinedInsideClass(ObjCContainerDecl *IDecl, TagDecl *Tag,
Fariborz Jahanian8fba8942012-04-30 23:20:30 +0000353 bool &IsNamedDefinition);
354 void RewriteLocallyDefinedNamedAggregates(FieldDecl *fieldDecl,
355 std::string &Result);
Fariborz Jahanian15f87772012-02-28 22:45:07 +0000356
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +0000357 bool RewriteObjCFieldDeclType(QualType &Type, std::string &Result);
358
Fariborz Jahanian72c88f12012-02-22 18:13:25 +0000359 void RewriteIvarOffsetSymbols(ObjCInterfaceDecl *CDecl,
360 std::string &Result);
361
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000362 virtual void Initialize(ASTContext &context);
363
Benjamin Kramer48d798c2012-06-02 10:20:41 +0000364 // Misc. AST transformation routines. Sometimes they end up calling
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000365 // rewriting routines on the new ASTs.
366 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
367 Expr **args, unsigned nargs,
368 SourceLocation StartLoc=SourceLocation(),
369 SourceLocation EndLoc=SourceLocation());
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +0000370
371 Expr *SynthMsgSendStretCallExpr(FunctionDecl *MsgSendStretFlavor,
372 QualType msgSendType,
373 QualType returnType,
374 SmallVectorImpl<QualType> &ArgTypes,
375 SmallVectorImpl<Expr*> &MsgExprs,
376 ObjCMethodDecl *Method);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000377
378 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp,
379 SourceLocation StartLoc=SourceLocation(),
380 SourceLocation EndLoc=SourceLocation());
381
382 void SynthCountByEnumWithState(std::string &buf);
383 void SynthMsgSendFunctionDecl();
384 void SynthMsgSendSuperFunctionDecl();
385 void SynthMsgSendStretFunctionDecl();
386 void SynthMsgSendFpretFunctionDecl();
387 void SynthMsgSendSuperStretFunctionDecl();
388 void SynthGetClassFunctionDecl();
389 void SynthGetMetaClassFunctionDecl();
390 void SynthGetSuperClassFunctionDecl();
391 void SynthSelGetUidFunctionDecl();
392 void SynthSuperContructorFunctionDecl();
393
394 // Rewriting metadata
395 template<typename MethodIterator>
396 void RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
397 MethodIterator MethodEnd,
398 bool IsInstanceMethod,
399 StringRef prefix,
400 StringRef ClassName,
401 std::string &Result);
Fariborz Jahanianda9624a2012-02-08 19:53:58 +0000402 void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
403 std::string &Result);
Fariborz Jahanianb4ee8802012-04-30 16:57:52 +0000404 void RewriteObjCProtocolListMetaData(
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000405 const ObjCList<ObjCProtocolDecl> &Prots,
406 StringRef prefix, StringRef ClassName, std::string &Result);
Fariborz Jahanianb4ee8802012-04-30 16:57:52 +0000407 void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000408 std::string &Result);
Fariborz Jahanianb4ee8802012-04-30 16:57:52 +0000409 void RewriteClassSetupInitHook(std::string &Result);
Fariborz Jahaniane0335782012-03-27 18:41:05 +0000410
Fariborz Jahanianb4ee8802012-04-30 16:57:52 +0000411 void RewriteMetaDataIntoBuffer(std::string &Result);
412 void WriteImageInfo(std::string &Result);
413 void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000414 std::string &Result);
Fariborz Jahanianb4ee8802012-04-30 16:57:52 +0000415 void RewriteCategorySetupInitHook(std::string &Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000416
417 // Rewriting ivar
Fariborz Jahanianb4ee8802012-04-30 16:57:52 +0000418 void RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000419 std::string &Result);
Fariborz Jahanianb4ee8802012-04-30 16:57:52 +0000420 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000421
422
423 std::string SynthesizeByrefCopyDestroyHelper(VarDecl *VD, int flag);
424 std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
425 StringRef funcName, std::string Tag);
426 std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
427 StringRef funcName, std::string Tag);
428 std::string SynthesizeBlockImpl(BlockExpr *CE,
429 std::string Tag, std::string Desc);
430 std::string SynthesizeBlockDescriptor(std::string DescTag,
431 std::string ImplTag,
432 int i, StringRef funcName,
433 unsigned hasCopy);
434 Stmt *SynthesizeBlockCall(CallExpr *Exp, const Expr* BlockExp);
435 void SynthesizeBlockLiterals(SourceLocation FunLocStart,
436 StringRef FunName);
437 FunctionDecl *SynthBlockInitFunctionDecl(StringRef name);
438 Stmt *SynthBlockInitExpr(BlockExpr *Exp,
John McCallf4b88a42012-03-10 09:33:50 +0000439 const SmallVector<DeclRefExpr *, 8> &InnerBlockDeclRefs);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000440
441 // Misc. helper routines.
442 QualType getProtocolType();
443 void WarnAboutReturnGotoStmts(Stmt *S);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000444 void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
445 void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
446 void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
447
448 bool IsDeclStmtInForeachHeader(DeclStmt *DS);
449 void CollectBlockDeclRefInfo(BlockExpr *Exp);
450 void GetBlockDeclRefExprs(Stmt *S);
451 void GetInnerBlockDeclRefExprs(Stmt *S,
John McCallf4b88a42012-03-10 09:33:50 +0000452 SmallVector<DeclRefExpr *, 8> &InnerBlockDeclRefs,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000453 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts);
454
455 // We avoid calling Type::isBlockPointerType(), since it operates on the
456 // canonical type. We only care if the top-level type is a closure pointer.
457 bool isTopLevelBlockPointerType(QualType T) {
458 return isa<BlockPointerType>(T);
459 }
460
461 /// convertBlockPointerToFunctionPointer - Converts a block-pointer type
462 /// to a function pointer type and upon success, returns true; false
463 /// otherwise.
464 bool convertBlockPointerToFunctionPointer(QualType &T) {
465 if (isTopLevelBlockPointerType(T)) {
466 const BlockPointerType *BPT = T->getAs<BlockPointerType>();
467 T = Context->getPointerType(BPT->getPointeeType());
468 return true;
469 }
470 return false;
471 }
472
Fariborz Jahanian164d6f82012-02-13 18:57:49 +0000473 bool convertObjCTypeToCStyleType(QualType &T);
474
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000475 bool needToScanForQualifiers(QualType T);
476 QualType getSuperStructType();
477 QualType getConstantStringStructType();
478 QualType convertFunctionTypeOfBlocks(const FunctionType *FT);
479 bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf);
480
481 void convertToUnqualifiedObjCType(QualType &T) {
Fariborz Jahaniane35abe12012-04-06 22:29:36 +0000482 if (T->isObjCQualifiedIdType()) {
483 bool isConst = T.isConstQualified();
484 T = isConst ? Context->getObjCIdType().withConst()
485 : Context->getObjCIdType();
486 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000487 else if (T->isObjCQualifiedClassType())
488 T = Context->getObjCClassType();
489 else if (T->isObjCObjectPointerType() &&
490 T->getPointeeType()->isObjCQualifiedInterfaceType()) {
491 if (const ObjCObjectPointerType * OBJPT =
492 T->getAsObjCInterfacePointerType()) {
493 const ObjCInterfaceType *IFaceT = OBJPT->getInterfaceType();
494 T = QualType(IFaceT, 0);
495 T = Context->getPointerType(T);
496 }
497 }
498 }
499
500 // FIXME: This predicate seems like it would be useful to add to ASTContext.
501 bool isObjCType(QualType T) {
502 if (!LangOpts.ObjC1 && !LangOpts.ObjC2)
503 return false;
504
505 QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
506
507 if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
508 OCT == Context->getCanonicalType(Context->getObjCClassType()))
509 return true;
510
511 if (const PointerType *PT = OCT->getAs<PointerType>()) {
512 if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
513 PT->getPointeeType()->isObjCQualifiedIdType())
514 return true;
515 }
516 return false;
517 }
518 bool PointerTypeTakesAnyBlockArguments(QualType QT);
519 bool PointerTypeTakesAnyObjCQualifiedType(QualType QT);
520 void GetExtentOfArgList(const char *Name, const char *&LParen,
521 const char *&RParen);
522
523 void QuoteDoublequotes(std::string &From, std::string &To) {
524 for (unsigned i = 0; i < From.length(); i++) {
525 if (From[i] == '"')
526 To += "\\\"";
527 else
528 To += From[i];
529 }
530 }
531
532 QualType getSimpleFunctionType(QualType result,
533 const QualType *args,
534 unsigned numArgs,
535 bool variadic = false) {
536 if (result == Context->getObjCInstanceType())
537 result = Context->getObjCIdType();
538 FunctionProtoType::ExtProtoInfo fpi;
539 fpi.Variadic = variadic;
540 return Context->getFunctionType(result, args, numArgs, fpi);
541 }
542
543 // Helper function: create a CStyleCastExpr with trivial type source info.
544 CStyleCastExpr* NoTypeInfoCStyleCastExpr(ASTContext *Ctx, QualType Ty,
545 CastKind Kind, Expr *E) {
546 TypeSourceInfo *TInfo = Ctx->getTrivialTypeSourceInfo(Ty, SourceLocation());
547 return CStyleCastExpr::Create(*Ctx, Ty, VK_RValue, Kind, E, 0, TInfo,
548 SourceLocation(), SourceLocation());
549 }
Fariborz Jahanian88f7f752012-03-14 23:18:19 +0000550
551 bool ImplementationIsNonLazy(const ObjCImplDecl *OD) const {
552 IdentifierInfo* II = &Context->Idents.get("load");
553 Selector LoadSel = Context->Selectors.getSelector(0, &II);
554 return OD->getClassMethod(LoadSel) != 0;
555 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000556 };
557
558}
559
560void RewriteModernObjC::RewriteBlocksInFunctionProtoType(QualType funcType,
561 NamedDecl *D) {
562 if (const FunctionProtoType *fproto
563 = dyn_cast<FunctionProtoType>(funcType.IgnoreParens())) {
564 for (FunctionProtoType::arg_type_iterator I = fproto->arg_type_begin(),
565 E = fproto->arg_type_end(); I && (I != E); ++I)
566 if (isTopLevelBlockPointerType(*I)) {
567 // All the args are checked/rewritten. Don't call twice!
568 RewriteBlockPointerDecl(D);
569 break;
570 }
571 }
572}
573
574void RewriteModernObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
575 const PointerType *PT = funcType->getAs<PointerType>();
576 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
577 RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND);
578}
579
580static bool IsHeaderFile(const std::string &Filename) {
581 std::string::size_type DotPos = Filename.rfind('.');
582
583 if (DotPos == std::string::npos) {
584 // no file extension
585 return false;
586 }
587
588 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
589 // C header: .h
590 // C++ header: .hh or .H;
591 return Ext == "h" || Ext == "hh" || Ext == "H";
592}
593
594RewriteModernObjC::RewriteModernObjC(std::string inFile, raw_ostream* OS,
595 DiagnosticsEngine &D, const LangOptions &LOpts,
596 bool silenceMacroWarn)
597 : Diags(D), LangOpts(LOpts), InFileName(inFile), OutFile(OS),
598 SilenceRewriteMacroWarning(silenceMacroWarn) {
599 IsHeader = IsHeaderFile(inFile);
600 RewriteFailedDiag = Diags.getCustomDiagID(DiagnosticsEngine::Warning,
601 "rewriting sub-expression within a macro (may not be correct)");
Fariborz Jahaniand13c2c22012-03-22 19:54:39 +0000602 // FIXME. This should be an error. But if block is not called, it is OK. And it
603 // may break including some headers.
604 GlobalBlockRewriteFailedDiag = Diags.getCustomDiagID(DiagnosticsEngine::Warning,
605 "rewriting block literal declared in global scope is not implemented");
606
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000607 TryFinallyContainsReturnDiag = Diags.getCustomDiagID(
608 DiagnosticsEngine::Warning,
609 "rewriter doesn't support user-specified control flow semantics "
610 "for @try/@finally (code may not execute properly)");
611}
612
613ASTConsumer *clang::CreateModernObjCRewriter(const std::string& InFile,
614 raw_ostream* OS,
615 DiagnosticsEngine &Diags,
616 const LangOptions &LOpts,
617 bool SilenceRewriteMacroWarning) {
618 return new RewriteModernObjC(InFile, OS, Diags, LOpts, SilenceRewriteMacroWarning);
619}
620
621void RewriteModernObjC::InitializeCommon(ASTContext &context) {
622 Context = &context;
623 SM = &Context->getSourceManager();
624 TUDecl = Context->getTranslationUnitDecl();
625 MsgSendFunctionDecl = 0;
626 MsgSendSuperFunctionDecl = 0;
627 MsgSendStretFunctionDecl = 0;
628 MsgSendSuperStretFunctionDecl = 0;
629 MsgSendFpretFunctionDecl = 0;
630 GetClassFunctionDecl = 0;
631 GetMetaClassFunctionDecl = 0;
632 GetSuperClassFunctionDecl = 0;
633 SelGetUidFunctionDecl = 0;
634 CFStringFunctionDecl = 0;
635 ConstantStringClassReference = 0;
636 NSStringRecord = 0;
637 CurMethodDef = 0;
638 CurFunctionDef = 0;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000639 GlobalVarDecl = 0;
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +0000640 GlobalConstructionExp = 0;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000641 SuperStructDecl = 0;
642 ProtocolTypeDecl = 0;
643 ConstantStringDecl = 0;
644 BcLabelCount = 0;
645 SuperContructorFunctionDecl = 0;
646 NumObjCStringLiterals = 0;
647 PropParentMap = 0;
648 CurrentBody = 0;
649 DisableReplaceStmt = false;
650 objc_impl_method = false;
651
652 // Get the ID and start/end of the main file.
653 MainFileID = SM->getMainFileID();
654 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
655 MainFileStart = MainBuf->getBufferStart();
656 MainFileEnd = MainBuf->getBufferEnd();
657
David Blaikie4e4d0842012-03-11 07:00:24 +0000658 Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOpts());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000659}
660
661//===----------------------------------------------------------------------===//
662// Top Level Driver Code
663//===----------------------------------------------------------------------===//
664
665void RewriteModernObjC::HandleTopLevelSingleDecl(Decl *D) {
666 if (Diags.hasErrorOccurred())
667 return;
668
669 // Two cases: either the decl could be in the main file, or it could be in a
670 // #included file. If the former, rewrite it now. If the later, check to see
671 // if we rewrote the #include/#import.
672 SourceLocation Loc = D->getLocation();
673 Loc = SM->getExpansionLoc(Loc);
674
675 // If this is for a builtin, ignore it.
676 if (Loc.isInvalid()) return;
677
678 // Look for built-in declarations that we need to refer during the rewrite.
679 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
680 RewriteFunctionDecl(FD);
681 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
682 // declared in <Foundation/NSString.h>
683 if (FVD->getName() == "_NSConstantStringClassReference") {
684 ConstantStringClassReference = FVD;
685 return;
686 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000687 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
688 RewriteCategoryDecl(CD);
689 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
690 if (PD->isThisDeclarationADefinition())
691 RewriteProtocolDecl(PD);
692 } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) {
Fariborz Jahanian8e86b2d2012-04-04 17:16:15 +0000693 // FIXME. This will not work in all situations and leaving it out
694 // is harmless.
695 // RewriteLinkageSpec(LSD);
696
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000697 // Recurse into linkage specifications
698 for (DeclContext::decl_iterator DI = LSD->decls_begin(),
699 DIEnd = LSD->decls_end();
700 DI != DIEnd; ) {
701 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>((*DI))) {
702 if (!IFace->isThisDeclarationADefinition()) {
703 SmallVector<Decl *, 8> DG;
704 SourceLocation StartLoc = IFace->getLocStart();
705 do {
706 if (isa<ObjCInterfaceDecl>(*DI) &&
707 !cast<ObjCInterfaceDecl>(*DI)->isThisDeclarationADefinition() &&
708 StartLoc == (*DI)->getLocStart())
709 DG.push_back(*DI);
710 else
711 break;
712
713 ++DI;
714 } while (DI != DIEnd);
715 RewriteForwardClassDecl(DG);
716 continue;
717 }
Fariborz Jahanianb3f904f2012-04-03 17:35:38 +0000718 else {
719 // Keep track of all interface declarations seen.
720 ObjCInterfacesSeen.push_back(IFace);
721 ++DI;
722 continue;
723 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000724 }
725
726 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>((*DI))) {
727 if (!Proto->isThisDeclarationADefinition()) {
728 SmallVector<Decl *, 8> DG;
729 SourceLocation StartLoc = Proto->getLocStart();
730 do {
731 if (isa<ObjCProtocolDecl>(*DI) &&
732 !cast<ObjCProtocolDecl>(*DI)->isThisDeclarationADefinition() &&
733 StartLoc == (*DI)->getLocStart())
734 DG.push_back(*DI);
735 else
736 break;
737
738 ++DI;
739 } while (DI != DIEnd);
740 RewriteForwardProtocolDecl(DG);
741 continue;
742 }
743 }
744
745 HandleTopLevelSingleDecl(*DI);
746 ++DI;
747 }
748 }
749 // If we have a decl in the main file, see if we should rewrite it.
750 if (SM->isFromMainFile(Loc))
751 return HandleDeclInMainFile(D);
752}
753
754//===----------------------------------------------------------------------===//
755// Syntactic (non-AST) Rewriting Code
756//===----------------------------------------------------------------------===//
757
758void RewriteModernObjC::RewriteInclude() {
759 SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID);
760 StringRef MainBuf = SM->getBufferData(MainFileID);
761 const char *MainBufStart = MainBuf.begin();
762 const char *MainBufEnd = MainBuf.end();
763 size_t ImportLen = strlen("import");
764
765 // Loop over the whole file, looking for includes.
766 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
767 if (*BufPtr == '#') {
768 if (++BufPtr == MainBufEnd)
769 return;
770 while (*BufPtr == ' ' || *BufPtr == '\t')
771 if (++BufPtr == MainBufEnd)
772 return;
773 if (!strncmp(BufPtr, "import", ImportLen)) {
774 // replace import with include
775 SourceLocation ImportLoc =
776 LocStart.getLocWithOffset(BufPtr-MainBufStart);
777 ReplaceText(ImportLoc, ImportLen, "include");
778 BufPtr += ImportLen;
779 }
780 }
781 }
782}
783
Fariborz Jahanian163d3ce2012-05-08 23:54:35 +0000784static void WriteInternalIvarName(const ObjCInterfaceDecl *IDecl,
785 ObjCIvarDecl *IvarDecl, std::string &Result) {
786 Result += "OBJC_IVAR_$_";
787 Result += IDecl->getName();
788 Result += "$";
789 Result += IvarDecl->getName();
790}
791
792std::string
793RewriteModernObjC::getIvarAccessString(ObjCIvarDecl *D) {
794 const ObjCInterfaceDecl *ClassDecl = D->getContainingInterface();
795
796 // Build name of symbol holding ivar offset.
797 std::string IvarOffsetName;
798 WriteInternalIvarName(ClassDecl, D, IvarOffsetName);
799
800
801 std::string S = "(*(";
802 QualType IvarT = D->getType();
803
804 if (!isa<TypedefType>(IvarT) && IvarT->isRecordType()) {
805 RecordDecl *RD = IvarT->getAs<RecordType>()->getDecl();
806 RD = RD->getDefinition();
807 if (RD && !RD->getDeclName().getAsIdentifierInfo()) {
808 // decltype(((Foo_IMPL*)0)->bar) *
809 ObjCContainerDecl *CDecl =
810 dyn_cast<ObjCContainerDecl>(D->getDeclContext());
811 // ivar in class extensions requires special treatment.
812 if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(CDecl))
813 CDecl = CatDecl->getClassInterface();
814 std::string RecName = CDecl->getName();
815 RecName += "_IMPL";
816 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
817 SourceLocation(), SourceLocation(),
818 &Context->Idents.get(RecName.c_str()));
819 QualType PtrStructIMPL = Context->getPointerType(Context->getTagDeclType(RD));
820 unsigned UnsignedIntSize =
821 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
822 Expr *Zero = IntegerLiteral::Create(*Context,
823 llvm::APInt(UnsignedIntSize, 0),
824 Context->UnsignedIntTy, SourceLocation());
825 Zero = NoTypeInfoCStyleCastExpr(Context, PtrStructIMPL, CK_BitCast, Zero);
826 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
827 Zero);
828 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
829 SourceLocation(),
830 &Context->Idents.get(D->getNameAsString()),
831 IvarT, 0,
832 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smithca523302012-06-10 03:12:00 +0000833 ICIS_NoInit);
Fariborz Jahanian163d3ce2012-05-08 23:54:35 +0000834 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
835 FD->getType(), VK_LValue,
836 OK_Ordinary);
837 IvarT = Context->getDecltypeType(ME, ME->getType());
838 }
839 }
840 convertObjCTypeToCStyleType(IvarT);
841 QualType castT = Context->getPointerType(IvarT);
842 std::string TypeString(castT.getAsString(Context->getPrintingPolicy()));
843 S += TypeString;
844 S += ")";
845
846 // ((char *)self + IVAR_OFFSET_SYMBOL_NAME)
847 S += "((char *)self + ";
848 S += IvarOffsetName;
849 S += "))";
850 ReferencedIvars[const_cast<ObjCInterfaceDecl *>(ClassDecl)].insert(D);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000851 return S;
852}
853
Fariborz Jahanian301e2e42012-05-03 22:52:13 +0000854/// mustSynthesizeSetterGetterMethod - returns true if setter or getter has not
855/// been found in the class implementation. In this case, it must be synthesized.
856static bool mustSynthesizeSetterGetterMethod(ObjCImplementationDecl *IMP,
857 ObjCPropertyDecl *PD,
858 bool getter) {
859 return getter ? !IMP->getInstanceMethod(PD->getGetterName())
860 : !IMP->getInstanceMethod(PD->getSetterName());
861
862}
863
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000864void RewriteModernObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
865 ObjCImplementationDecl *IMD,
866 ObjCCategoryImplDecl *CID) {
867 static bool objcGetPropertyDefined = false;
868 static bool objcSetPropertyDefined = false;
Fariborz Jahanian301e2e42012-05-03 22:52:13 +0000869 SourceLocation startGetterSetterLoc;
870
871 if (PID->getLocStart().isValid()) {
872 SourceLocation startLoc = PID->getLocStart();
873 InsertText(startLoc, "// ");
874 const char *startBuf = SM->getCharacterData(startLoc);
875 assert((*startBuf == '@') && "bogus @synthesize location");
876 const char *semiBuf = strchr(startBuf, ';');
877 assert((*semiBuf == ';') && "@synthesize: can't find ';'");
878 startGetterSetterLoc = startLoc.getLocWithOffset(semiBuf-startBuf+1);
879 }
880 else
881 startGetterSetterLoc = IMD ? IMD->getLocEnd() : CID->getLocEnd();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000882
883 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
884 return; // FIXME: is this correct?
885
886 // Generate the 'getter' function.
887 ObjCPropertyDecl *PD = PID->getPropertyDecl();
888 ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
889
890 if (!OID)
891 return;
892 unsigned Attributes = PD->getPropertyAttributes();
Fariborz Jahanian301e2e42012-05-03 22:52:13 +0000893 if (mustSynthesizeSetterGetterMethod(IMD, PD, true /*getter*/)) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000894 bool GenGetProperty = !(Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic) &&
895 (Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
896 ObjCPropertyDecl::OBJC_PR_copy));
897 std::string Getr;
898 if (GenGetProperty && !objcGetPropertyDefined) {
899 objcGetPropertyDefined = true;
900 // FIXME. Is this attribute correct in all cases?
901 Getr = "\nextern \"C\" __declspec(dllimport) "
902 "id objc_getProperty(id, SEL, long, bool);\n";
903 }
904 RewriteObjCMethodDecl(OID->getContainingInterface(),
905 PD->getGetterMethodDecl(), Getr);
906 Getr += "{ ";
907 // Synthesize an explicit cast to gain access to the ivar.
908 // See objc-act.c:objc_synthesize_new_getter() for details.
909 if (GenGetProperty) {
910 // return objc_getProperty(self, _cmd, offsetof(ClassDecl, OID), 1)
911 Getr += "typedef ";
912 const FunctionType *FPRetType = 0;
913 RewriteTypeIntoString(PD->getGetterMethodDecl()->getResultType(), Getr,
914 FPRetType);
915 Getr += " _TYPE";
916 if (FPRetType) {
917 Getr += ")"; // close the precedence "scope" for "*".
918
919 // Now, emit the argument types (if any).
920 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)){
921 Getr += "(";
922 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
923 if (i) Getr += ", ";
924 std::string ParamStr = FT->getArgType(i).getAsString(
925 Context->getPrintingPolicy());
926 Getr += ParamStr;
927 }
928 if (FT->isVariadic()) {
929 if (FT->getNumArgs()) Getr += ", ";
930 Getr += "...";
931 }
932 Getr += ")";
933 } else
934 Getr += "()";
935 }
936 Getr += ";\n";
937 Getr += "return (_TYPE)";
938 Getr += "objc_getProperty(self, _cmd, ";
939 RewriteIvarOffsetComputation(OID, Getr);
940 Getr += ", 1)";
941 }
942 else
943 Getr += "return " + getIvarAccessString(OID);
944 Getr += "; }";
Fariborz Jahanian301e2e42012-05-03 22:52:13 +0000945 InsertText(startGetterSetterLoc, Getr);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000946 }
947
Fariborz Jahanian301e2e42012-05-03 22:52:13 +0000948 if (PD->isReadOnly() ||
949 !mustSynthesizeSetterGetterMethod(IMD, PD, false /*setter*/))
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000950 return;
951
952 // Generate the 'setter' function.
953 std::string Setr;
954 bool GenSetProperty = Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
955 ObjCPropertyDecl::OBJC_PR_copy);
956 if (GenSetProperty && !objcSetPropertyDefined) {
957 objcSetPropertyDefined = true;
958 // FIXME. Is this attribute correct in all cases?
959 Setr = "\nextern \"C\" __declspec(dllimport) "
960 "void objc_setProperty (id, SEL, long, id, bool, bool);\n";
961 }
962
963 RewriteObjCMethodDecl(OID->getContainingInterface(),
964 PD->getSetterMethodDecl(), Setr);
965 Setr += "{ ";
966 // Synthesize an explicit cast to initialize the ivar.
967 // See objc-act.c:objc_synthesize_new_setter() for details.
968 if (GenSetProperty) {
969 Setr += "objc_setProperty (self, _cmd, ";
970 RewriteIvarOffsetComputation(OID, Setr);
971 Setr += ", (id)";
972 Setr += PD->getName();
973 Setr += ", ";
974 if (Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic)
975 Setr += "0, ";
976 else
977 Setr += "1, ";
978 if (Attributes & ObjCPropertyDecl::OBJC_PR_copy)
979 Setr += "1)";
980 else
981 Setr += "0)";
982 }
983 else {
984 Setr += getIvarAccessString(OID) + " = ";
985 Setr += PD->getName();
986 }
Fariborz Jahanian301e2e42012-05-03 22:52:13 +0000987 Setr += "; }\n";
988 InsertText(startGetterSetterLoc, Setr);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000989}
990
991static void RewriteOneForwardClassDecl(ObjCInterfaceDecl *ForwardDecl,
992 std::string &typedefString) {
993 typedefString += "#ifndef _REWRITER_typedef_";
994 typedefString += ForwardDecl->getNameAsString();
995 typedefString += "\n";
996 typedefString += "#define _REWRITER_typedef_";
997 typedefString += ForwardDecl->getNameAsString();
998 typedefString += "\n";
999 typedefString += "typedef struct objc_object ";
1000 typedefString += ForwardDecl->getNameAsString();
Fariborz Jahanianc38503b2012-03-12 23:58:28 +00001001 // typedef struct { } _objc_exc_Classname;
1002 typedefString += ";\ntypedef struct {} _objc_exc_";
1003 typedefString += ForwardDecl->getNameAsString();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001004 typedefString += ";\n#endif\n";
1005}
1006
1007void RewriteModernObjC::RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
1008 const std::string &typedefString) {
1009 SourceLocation startLoc = ClassDecl->getLocStart();
1010 const char *startBuf = SM->getCharacterData(startLoc);
1011 const char *semiPtr = strchr(startBuf, ';');
1012 // Replace the @class with typedefs corresponding to the classes.
1013 ReplaceText(startLoc, semiPtr-startBuf+1, typedefString);
1014}
1015
1016void RewriteModernObjC::RewriteForwardClassDecl(DeclGroupRef D) {
1017 std::string typedefString;
1018 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
1019 ObjCInterfaceDecl *ForwardDecl = cast<ObjCInterfaceDecl>(*I);
1020 if (I == D.begin()) {
1021 // Translate to typedef's that forward reference structs with the same name
1022 // as the class. As a convenience, we include the original declaration
1023 // as a comment.
1024 typedefString += "// @class ";
1025 typedefString += ForwardDecl->getNameAsString();
1026 typedefString += ";\n";
1027 }
1028 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
1029 }
1030 DeclGroupRef::iterator I = D.begin();
1031 RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(*I), typedefString);
1032}
1033
1034void RewriteModernObjC::RewriteForwardClassDecl(
1035 const llvm::SmallVector<Decl*, 8> &D) {
1036 std::string typedefString;
1037 for (unsigned i = 0; i < D.size(); i++) {
1038 ObjCInterfaceDecl *ForwardDecl = cast<ObjCInterfaceDecl>(D[i]);
1039 if (i == 0) {
1040 typedefString += "// @class ";
1041 typedefString += ForwardDecl->getNameAsString();
1042 typedefString += ";\n";
1043 }
1044 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
1045 }
1046 RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(D[0]), typedefString);
1047}
1048
1049void RewriteModernObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
1050 // When method is a synthesized one, such as a getter/setter there is
1051 // nothing to rewrite.
1052 if (Method->isImplicit())
1053 return;
1054 SourceLocation LocStart = Method->getLocStart();
1055 SourceLocation LocEnd = Method->getLocEnd();
1056
1057 if (SM->getExpansionLineNumber(LocEnd) >
1058 SM->getExpansionLineNumber(LocStart)) {
1059 InsertText(LocStart, "#if 0\n");
1060 ReplaceText(LocEnd, 1, ";\n#endif\n");
1061 } else {
1062 InsertText(LocStart, "// ");
1063 }
1064}
1065
1066void RewriteModernObjC::RewriteProperty(ObjCPropertyDecl *prop) {
1067 SourceLocation Loc = prop->getAtLoc();
1068
1069 ReplaceText(Loc, 0, "// ");
1070 // FIXME: handle properties that are declared across multiple lines.
1071}
1072
1073void RewriteModernObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
1074 SourceLocation LocStart = CatDecl->getLocStart();
1075
1076 // FIXME: handle category headers that are declared across multiple lines.
Fariborz Jahanianb68258f2012-05-01 17:46:45 +00001077 if (CatDecl->getIvarRBraceLoc().isValid()) {
1078 ReplaceText(LocStart, 1, "/** ");
1079 ReplaceText(CatDecl->getIvarRBraceLoc(), 1, "**/ ");
1080 }
1081 else {
Fariborz Jahaniand2aea122012-02-19 19:00:05 +00001082 ReplaceText(LocStart, 0, "// ");
Fariborz Jahanianb68258f2012-05-01 17:46:45 +00001083 }
Fariborz Jahanianaf300292012-02-20 20:09:20 +00001084
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001085 for (ObjCCategoryDecl::prop_iterator I = CatDecl->prop_begin(),
1086 E = CatDecl->prop_end(); I != E; ++I)
David Blaikie581deb32012-06-06 20:45:41 +00001087 RewriteProperty(*I);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001088
1089 for (ObjCCategoryDecl::instmeth_iterator
1090 I = CatDecl->instmeth_begin(), E = CatDecl->instmeth_end();
1091 I != E; ++I)
1092 RewriteMethodDeclaration(*I);
1093 for (ObjCCategoryDecl::classmeth_iterator
1094 I = CatDecl->classmeth_begin(), E = CatDecl->classmeth_end();
1095 I != E; ++I)
1096 RewriteMethodDeclaration(*I);
1097
1098 // Lastly, comment out the @end.
1099 ReplaceText(CatDecl->getAtEndRange().getBegin(),
1100 strlen("@end"), "/* @end */");
1101}
1102
1103void RewriteModernObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
1104 SourceLocation LocStart = PDecl->getLocStart();
1105 assert(PDecl->isThisDeclarationADefinition());
1106
1107 // FIXME: handle protocol headers that are declared across multiple lines.
1108 ReplaceText(LocStart, 0, "// ");
1109
1110 for (ObjCProtocolDecl::instmeth_iterator
1111 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
1112 I != E; ++I)
1113 RewriteMethodDeclaration(*I);
1114 for (ObjCProtocolDecl::classmeth_iterator
1115 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
1116 I != E; ++I)
1117 RewriteMethodDeclaration(*I);
1118
1119 for (ObjCInterfaceDecl::prop_iterator I = PDecl->prop_begin(),
1120 E = PDecl->prop_end(); I != E; ++I)
David Blaikie581deb32012-06-06 20:45:41 +00001121 RewriteProperty(*I);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001122
1123 // Lastly, comment out the @end.
1124 SourceLocation LocEnd = PDecl->getAtEndRange().getBegin();
1125 ReplaceText(LocEnd, strlen("@end"), "/* @end */");
1126
1127 // Must comment out @optional/@required
1128 const char *startBuf = SM->getCharacterData(LocStart);
1129 const char *endBuf = SM->getCharacterData(LocEnd);
1130 for (const char *p = startBuf; p < endBuf; p++) {
1131 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
1132 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
1133 ReplaceText(OptionalLoc, strlen("@optional"), "/* @optional */");
1134
1135 }
1136 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
1137 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
1138 ReplaceText(OptionalLoc, strlen("@required"), "/* @required */");
1139
1140 }
1141 }
1142}
1143
1144void RewriteModernObjC::RewriteForwardProtocolDecl(DeclGroupRef D) {
1145 SourceLocation LocStart = (*D.begin())->getLocStart();
1146 if (LocStart.isInvalid())
1147 llvm_unreachable("Invalid SourceLocation");
1148 // FIXME: handle forward protocol that are declared across multiple lines.
1149 ReplaceText(LocStart, 0, "// ");
1150}
1151
1152void
1153RewriteModernObjC::RewriteForwardProtocolDecl(const llvm::SmallVector<Decl*, 8> &DG) {
1154 SourceLocation LocStart = DG[0]->getLocStart();
1155 if (LocStart.isInvalid())
1156 llvm_unreachable("Invalid SourceLocation");
1157 // FIXME: handle forward protocol that are declared across multiple lines.
1158 ReplaceText(LocStart, 0, "// ");
1159}
1160
Fariborz Jahanianb3f904f2012-04-03 17:35:38 +00001161void
1162RewriteModernObjC::RewriteLinkageSpec(LinkageSpecDecl *LSD) {
1163 SourceLocation LocStart = LSD->getExternLoc();
1164 if (LocStart.isInvalid())
1165 llvm_unreachable("Invalid extern SourceLocation");
1166
1167 ReplaceText(LocStart, 0, "// ");
1168 if (!LSD->hasBraces())
1169 return;
1170 // FIXME. We don't rewrite well if '{' is not on same line as 'extern'.
1171 SourceLocation LocRBrace = LSD->getRBraceLoc();
1172 if (LocRBrace.isInvalid())
1173 llvm_unreachable("Invalid rbrace SourceLocation");
1174 ReplaceText(LocRBrace, 0, "// ");
1175}
1176
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001177void RewriteModernObjC::RewriteTypeIntoString(QualType T, std::string &ResultStr,
1178 const FunctionType *&FPRetType) {
1179 if (T->isObjCQualifiedIdType())
1180 ResultStr += "id";
1181 else if (T->isFunctionPointerType() ||
1182 T->isBlockPointerType()) {
1183 // needs special handling, since pointer-to-functions have special
1184 // syntax (where a decaration models use).
1185 QualType retType = T;
1186 QualType PointeeTy;
1187 if (const PointerType* PT = retType->getAs<PointerType>())
1188 PointeeTy = PT->getPointeeType();
1189 else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>())
1190 PointeeTy = BPT->getPointeeType();
1191 if ((FPRetType = PointeeTy->getAs<FunctionType>())) {
1192 ResultStr += FPRetType->getResultType().getAsString(
1193 Context->getPrintingPolicy());
1194 ResultStr += "(*";
1195 }
1196 } else
1197 ResultStr += T.getAsString(Context->getPrintingPolicy());
1198}
1199
1200void RewriteModernObjC::RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
1201 ObjCMethodDecl *OMD,
1202 std::string &ResultStr) {
1203 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
1204 const FunctionType *FPRetType = 0;
1205 ResultStr += "\nstatic ";
1206 RewriteTypeIntoString(OMD->getResultType(), ResultStr, FPRetType);
1207 ResultStr += " ";
1208
1209 // Unique method name
1210 std::string NameStr;
1211
1212 if (OMD->isInstanceMethod())
1213 NameStr += "_I_";
1214 else
1215 NameStr += "_C_";
1216
1217 NameStr += IDecl->getNameAsString();
1218 NameStr += "_";
1219
1220 if (ObjCCategoryImplDecl *CID =
1221 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
1222 NameStr += CID->getNameAsString();
1223 NameStr += "_";
1224 }
1225 // Append selector names, replacing ':' with '_'
1226 {
1227 std::string selString = OMD->getSelector().getAsString();
1228 int len = selString.size();
1229 for (int i = 0; i < len; i++)
1230 if (selString[i] == ':')
1231 selString[i] = '_';
1232 NameStr += selString;
1233 }
1234 // Remember this name for metadata emission
1235 MethodInternalNames[OMD] = NameStr;
1236 ResultStr += NameStr;
1237
1238 // Rewrite arguments
1239 ResultStr += "(";
1240
1241 // invisible arguments
1242 if (OMD->isInstanceMethod()) {
1243 QualType selfTy = Context->getObjCInterfaceType(IDecl);
1244 selfTy = Context->getPointerType(selfTy);
1245 if (!LangOpts.MicrosoftExt) {
1246 if (ObjCSynthesizedStructs.count(const_cast<ObjCInterfaceDecl*>(IDecl)))
1247 ResultStr += "struct ";
1248 }
1249 // When rewriting for Microsoft, explicitly omit the structure name.
1250 ResultStr += IDecl->getNameAsString();
1251 ResultStr += " *";
1252 }
1253 else
1254 ResultStr += Context->getObjCClassType().getAsString(
1255 Context->getPrintingPolicy());
1256
1257 ResultStr += " self, ";
1258 ResultStr += Context->getObjCSelType().getAsString(Context->getPrintingPolicy());
1259 ResultStr += " _cmd";
1260
1261 // Method arguments.
1262 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
1263 E = OMD->param_end(); PI != E; ++PI) {
1264 ParmVarDecl *PDecl = *PI;
1265 ResultStr += ", ";
1266 if (PDecl->getType()->isObjCQualifiedIdType()) {
1267 ResultStr += "id ";
1268 ResultStr += PDecl->getNameAsString();
1269 } else {
1270 std::string Name = PDecl->getNameAsString();
1271 QualType QT = PDecl->getType();
1272 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian2610f902012-03-27 16:42:20 +00001273 (void)convertBlockPointerToFunctionPointer(QT);
1274 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001275 ResultStr += Name;
1276 }
1277 }
1278 if (OMD->isVariadic())
1279 ResultStr += ", ...";
1280 ResultStr += ") ";
1281
1282 if (FPRetType) {
1283 ResultStr += ")"; // close the precedence "scope" for "*".
1284
1285 // Now, emit the argument types (if any).
1286 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
1287 ResultStr += "(";
1288 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
1289 if (i) ResultStr += ", ";
1290 std::string ParamStr = FT->getArgType(i).getAsString(
1291 Context->getPrintingPolicy());
1292 ResultStr += ParamStr;
1293 }
1294 if (FT->isVariadic()) {
1295 if (FT->getNumArgs()) ResultStr += ", ";
1296 ResultStr += "...";
1297 }
1298 ResultStr += ")";
1299 } else {
1300 ResultStr += "()";
1301 }
1302 }
1303}
1304void RewriteModernObjC::RewriteImplementationDecl(Decl *OID) {
1305 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
1306 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
1307
Fariborz Jahaniand2aea122012-02-19 19:00:05 +00001308 if (IMD) {
Fariborz Jahanianb68258f2012-05-01 17:46:45 +00001309 if (IMD->getIvarRBraceLoc().isValid()) {
1310 ReplaceText(IMD->getLocStart(), 1, "/** ");
1311 ReplaceText(IMD->getIvarRBraceLoc(), 1, "**/ ");
Fariborz Jahaniand2aea122012-02-19 19:00:05 +00001312 }
Fariborz Jahanianb68258f2012-05-01 17:46:45 +00001313 else {
1314 InsertText(IMD->getLocStart(), "// ");
1315 }
Fariborz Jahaniand2aea122012-02-19 19:00:05 +00001316 }
1317 else
1318 InsertText(CID->getLocStart(), "// ");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001319
1320 for (ObjCCategoryImplDecl::instmeth_iterator
1321 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
1322 E = IMD ? IMD->instmeth_end() : CID->instmeth_end();
1323 I != E; ++I) {
1324 std::string ResultStr;
1325 ObjCMethodDecl *OMD = *I;
1326 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
1327 SourceLocation LocStart = OMD->getLocStart();
1328 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
1329
1330 const char *startBuf = SM->getCharacterData(LocStart);
1331 const char *endBuf = SM->getCharacterData(LocEnd);
1332 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
1333 }
1334
1335 for (ObjCCategoryImplDecl::classmeth_iterator
1336 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
1337 E = IMD ? IMD->classmeth_end() : CID->classmeth_end();
1338 I != E; ++I) {
1339 std::string ResultStr;
1340 ObjCMethodDecl *OMD = *I;
1341 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
1342 SourceLocation LocStart = OMD->getLocStart();
1343 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
1344
1345 const char *startBuf = SM->getCharacterData(LocStart);
1346 const char *endBuf = SM->getCharacterData(LocEnd);
1347 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
1348 }
1349 for (ObjCCategoryImplDecl::propimpl_iterator
1350 I = IMD ? IMD->propimpl_begin() : CID->propimpl_begin(),
1351 E = IMD ? IMD->propimpl_end() : CID->propimpl_end();
1352 I != E; ++I) {
David Blaikie581deb32012-06-06 20:45:41 +00001353 RewritePropertyImplDecl(*I, IMD, CID);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001354 }
1355
1356 InsertText(IMD ? IMD->getLocEnd() : CID->getLocEnd(), "// ");
1357}
1358
1359void RewriteModernObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00001360 // Do not synthesize more than once.
1361 if (ObjCSynthesizedStructs.count(ClassDecl))
1362 return;
1363 // Make sure super class's are written before current class is written.
1364 ObjCInterfaceDecl *SuperClass = ClassDecl->getSuperClass();
1365 while (SuperClass) {
1366 RewriteInterfaceDecl(SuperClass);
1367 SuperClass = SuperClass->getSuperClass();
1368 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001369 std::string ResultStr;
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +00001370 if (!ObjCWrittenInterfaces.count(ClassDecl->getCanonicalDecl())) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001371 // we haven't seen a forward decl - generate a typedef.
Fariborz Jahanianc38503b2012-03-12 23:58:28 +00001372 RewriteOneForwardClassDecl(ClassDecl, ResultStr);
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00001373 RewriteIvarOffsetSymbols(ClassDecl, ResultStr);
1374
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001375 RewriteObjCInternalStruct(ClassDecl, ResultStr);
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +00001376 // Mark this typedef as having been written into its c++ equivalent.
1377 ObjCWrittenInterfaces.insert(ClassDecl->getCanonicalDecl());
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001378
1379 for (ObjCInterfaceDecl::prop_iterator I = ClassDecl->prop_begin(),
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001380 E = ClassDecl->prop_end(); I != E; ++I)
David Blaikie581deb32012-06-06 20:45:41 +00001381 RewriteProperty(*I);
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001382 for (ObjCInterfaceDecl::instmeth_iterator
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001383 I = ClassDecl->instmeth_begin(), E = ClassDecl->instmeth_end();
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001384 I != E; ++I)
1385 RewriteMethodDeclaration(*I);
1386 for (ObjCInterfaceDecl::classmeth_iterator
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001387 I = ClassDecl->classmeth_begin(), E = ClassDecl->classmeth_end();
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001388 I != E; ++I)
1389 RewriteMethodDeclaration(*I);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001390
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001391 // Lastly, comment out the @end.
1392 ReplaceText(ClassDecl->getAtEndRange().getBegin(), strlen("@end"),
1393 "/* @end */");
1394 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001395}
1396
1397Stmt *RewriteModernObjC::RewritePropertyOrImplicitSetter(PseudoObjectExpr *PseudoOp) {
1398 SourceRange OldRange = PseudoOp->getSourceRange();
1399
1400 // We just magically know some things about the structure of this
1401 // expression.
1402 ObjCMessageExpr *OldMsg =
1403 cast<ObjCMessageExpr>(PseudoOp->getSemanticExpr(
1404 PseudoOp->getNumSemanticExprs() - 1));
1405
1406 // Because the rewriter doesn't allow us to rewrite rewritten code,
1407 // we need to suppress rewriting the sub-statements.
Fariborz Jahanian88ec6102012-04-10 22:06:54 +00001408 Expr *Base;
1409 SmallVector<Expr*, 2> Args;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001410 {
1411 DisableReplaceStmtScope S(*this);
1412
1413 // Rebuild the base expression if we have one.
1414 Base = 0;
1415 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1416 Base = OldMsg->getInstanceReceiver();
1417 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1418 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1419 }
Fariborz Jahanian88ec6102012-04-10 22:06:54 +00001420
1421 unsigned numArgs = OldMsg->getNumArgs();
1422 for (unsigned i = 0; i < numArgs; i++) {
1423 Expr *Arg = OldMsg->getArg(i);
1424 if (isa<OpaqueValueExpr>(Arg))
1425 Arg = cast<OpaqueValueExpr>(Arg)->getSourceExpr();
1426 Arg = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Arg));
1427 Args.push_back(Arg);
1428 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001429 }
1430
1431 // TODO: avoid this copy.
1432 SmallVector<SourceLocation, 1> SelLocs;
1433 OldMsg->getSelectorLocs(SelLocs);
1434
1435 ObjCMessageExpr *NewMsg = 0;
1436 switch (OldMsg->getReceiverKind()) {
1437 case ObjCMessageExpr::Class:
1438 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1439 OldMsg->getValueKind(),
1440 OldMsg->getLeftLoc(),
1441 OldMsg->getClassReceiverTypeInfo(),
1442 OldMsg->getSelector(),
1443 SelLocs,
1444 OldMsg->getMethodDecl(),
Fariborz Jahanian88ec6102012-04-10 22:06:54 +00001445 Args,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001446 OldMsg->getRightLoc(),
1447 OldMsg->isImplicit());
1448 break;
1449
1450 case ObjCMessageExpr::Instance:
1451 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1452 OldMsg->getValueKind(),
1453 OldMsg->getLeftLoc(),
1454 Base,
1455 OldMsg->getSelector(),
1456 SelLocs,
1457 OldMsg->getMethodDecl(),
Fariborz Jahanian88ec6102012-04-10 22:06:54 +00001458 Args,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001459 OldMsg->getRightLoc(),
1460 OldMsg->isImplicit());
1461 break;
1462
1463 case ObjCMessageExpr::SuperClass:
1464 case ObjCMessageExpr::SuperInstance:
1465 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1466 OldMsg->getValueKind(),
1467 OldMsg->getLeftLoc(),
1468 OldMsg->getSuperLoc(),
1469 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1470 OldMsg->getSuperType(),
1471 OldMsg->getSelector(),
1472 SelLocs,
1473 OldMsg->getMethodDecl(),
Fariborz Jahanian88ec6102012-04-10 22:06:54 +00001474 Args,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001475 OldMsg->getRightLoc(),
1476 OldMsg->isImplicit());
1477 break;
1478 }
1479
1480 Stmt *Replacement = SynthMessageExpr(NewMsg);
1481 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1482 return Replacement;
1483}
1484
1485Stmt *RewriteModernObjC::RewritePropertyOrImplicitGetter(PseudoObjectExpr *PseudoOp) {
1486 SourceRange OldRange = PseudoOp->getSourceRange();
1487
1488 // We just magically know some things about the structure of this
1489 // expression.
1490 ObjCMessageExpr *OldMsg =
1491 cast<ObjCMessageExpr>(PseudoOp->getResultExpr()->IgnoreImplicit());
1492
1493 // Because the rewriter doesn't allow us to rewrite rewritten code,
1494 // we need to suppress rewriting the sub-statements.
1495 Expr *Base = 0;
Fariborz Jahanian88ec6102012-04-10 22:06:54 +00001496 SmallVector<Expr*, 1> Args;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001497 {
1498 DisableReplaceStmtScope S(*this);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001499 // Rebuild the base expression if we have one.
1500 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1501 Base = OldMsg->getInstanceReceiver();
1502 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1503 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1504 }
Fariborz Jahanian88ec6102012-04-10 22:06:54 +00001505 unsigned numArgs = OldMsg->getNumArgs();
1506 for (unsigned i = 0; i < numArgs; i++) {
1507 Expr *Arg = OldMsg->getArg(i);
1508 if (isa<OpaqueValueExpr>(Arg))
1509 Arg = cast<OpaqueValueExpr>(Arg)->getSourceExpr();
1510 Arg = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Arg));
1511 Args.push_back(Arg);
1512 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001513 }
1514
1515 // Intentionally empty.
1516 SmallVector<SourceLocation, 1> SelLocs;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001517
1518 ObjCMessageExpr *NewMsg = 0;
1519 switch (OldMsg->getReceiverKind()) {
1520 case ObjCMessageExpr::Class:
1521 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1522 OldMsg->getValueKind(),
1523 OldMsg->getLeftLoc(),
1524 OldMsg->getClassReceiverTypeInfo(),
1525 OldMsg->getSelector(),
1526 SelLocs,
1527 OldMsg->getMethodDecl(),
1528 Args,
1529 OldMsg->getRightLoc(),
1530 OldMsg->isImplicit());
1531 break;
1532
1533 case ObjCMessageExpr::Instance:
1534 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1535 OldMsg->getValueKind(),
1536 OldMsg->getLeftLoc(),
1537 Base,
1538 OldMsg->getSelector(),
1539 SelLocs,
1540 OldMsg->getMethodDecl(),
1541 Args,
1542 OldMsg->getRightLoc(),
1543 OldMsg->isImplicit());
1544 break;
1545
1546 case ObjCMessageExpr::SuperClass:
1547 case ObjCMessageExpr::SuperInstance:
1548 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1549 OldMsg->getValueKind(),
1550 OldMsg->getLeftLoc(),
1551 OldMsg->getSuperLoc(),
1552 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1553 OldMsg->getSuperType(),
1554 OldMsg->getSelector(),
1555 SelLocs,
1556 OldMsg->getMethodDecl(),
1557 Args,
1558 OldMsg->getRightLoc(),
1559 OldMsg->isImplicit());
1560 break;
1561 }
1562
1563 Stmt *Replacement = SynthMessageExpr(NewMsg);
1564 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1565 return Replacement;
1566}
1567
1568/// SynthCountByEnumWithState - To print:
1569/// ((unsigned int (*)
1570/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1571/// (void *)objc_msgSend)((id)l_collection,
1572/// sel_registerName(
1573/// "countByEnumeratingWithState:objects:count:"),
1574/// &enumState,
1575/// (id *)__rw_items, (unsigned int)16)
1576///
1577void RewriteModernObjC::SynthCountByEnumWithState(std::string &buf) {
1578 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1579 "id *, unsigned int))(void *)objc_msgSend)";
1580 buf += "\n\t\t";
1581 buf += "((id)l_collection,\n\t\t";
1582 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1583 buf += "\n\t\t";
1584 buf += "&enumState, "
1585 "(id *)__rw_items, (unsigned int)16)";
1586}
1587
1588/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1589/// statement to exit to its outer synthesized loop.
1590///
1591Stmt *RewriteModernObjC::RewriteBreakStmt(BreakStmt *S) {
1592 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1593 return S;
1594 // replace break with goto __break_label
1595 std::string buf;
1596
1597 SourceLocation startLoc = S->getLocStart();
1598 buf = "goto __break_label_";
1599 buf += utostr(ObjCBcLabelNo.back());
1600 ReplaceText(startLoc, strlen("break"), buf);
1601
1602 return 0;
1603}
1604
1605/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1606/// statement to continue with its inner synthesized loop.
1607///
1608Stmt *RewriteModernObjC::RewriteContinueStmt(ContinueStmt *S) {
1609 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1610 return S;
1611 // replace continue with goto __continue_label
1612 std::string buf;
1613
1614 SourceLocation startLoc = S->getLocStart();
1615 buf = "goto __continue_label_";
1616 buf += utostr(ObjCBcLabelNo.back());
1617 ReplaceText(startLoc, strlen("continue"), buf);
1618
1619 return 0;
1620}
1621
1622/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
1623/// It rewrites:
1624/// for ( type elem in collection) { stmts; }
1625
1626/// Into:
1627/// {
1628/// type elem;
1629/// struct __objcFastEnumerationState enumState = { 0 };
1630/// id __rw_items[16];
1631/// id l_collection = (id)collection;
1632/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1633/// objects:__rw_items count:16];
1634/// if (limit) {
1635/// unsigned long startMutations = *enumState.mutationsPtr;
1636/// do {
1637/// unsigned long counter = 0;
1638/// do {
1639/// if (startMutations != *enumState.mutationsPtr)
1640/// objc_enumerationMutation(l_collection);
1641/// elem = (type)enumState.itemsPtr[counter++];
1642/// stmts;
1643/// __continue_label: ;
1644/// } while (counter < limit);
1645/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1646/// objects:__rw_items count:16]);
1647/// elem = nil;
1648/// __break_label: ;
1649/// }
1650/// else
1651/// elem = nil;
1652/// }
1653///
1654Stmt *RewriteModernObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
1655 SourceLocation OrigEnd) {
1656 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
1657 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
1658 "ObjCForCollectionStmt Statement stack mismatch");
1659 assert(!ObjCBcLabelNo.empty() &&
1660 "ObjCForCollectionStmt - Label No stack empty");
1661
1662 SourceLocation startLoc = S->getLocStart();
1663 const char *startBuf = SM->getCharacterData(startLoc);
1664 StringRef elementName;
1665 std::string elementTypeAsString;
1666 std::string buf;
1667 buf = "\n{\n\t";
1668 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1669 // type elem;
1670 NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
1671 QualType ElementType = cast<ValueDecl>(D)->getType();
1672 if (ElementType->isObjCQualifiedIdType() ||
1673 ElementType->isObjCQualifiedInterfaceType())
1674 // Simply use 'id' for all qualified types.
1675 elementTypeAsString = "id";
1676 else
1677 elementTypeAsString = ElementType.getAsString(Context->getPrintingPolicy());
1678 buf += elementTypeAsString;
1679 buf += " ";
1680 elementName = D->getName();
1681 buf += elementName;
1682 buf += ";\n\t";
1683 }
1684 else {
1685 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
1686 elementName = DR->getDecl()->getName();
1687 ValueDecl *VD = cast<ValueDecl>(DR->getDecl());
1688 if (VD->getType()->isObjCQualifiedIdType() ||
1689 VD->getType()->isObjCQualifiedInterfaceType())
1690 // Simply use 'id' for all qualified types.
1691 elementTypeAsString = "id";
1692 else
1693 elementTypeAsString = VD->getType().getAsString(Context->getPrintingPolicy());
1694 }
1695
1696 // struct __objcFastEnumerationState enumState = { 0 };
1697 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1698 // id __rw_items[16];
1699 buf += "id __rw_items[16];\n\t";
1700 // id l_collection = (id)
1701 buf += "id l_collection = (id)";
1702 // Find start location of 'collection' the hard way!
1703 const char *startCollectionBuf = startBuf;
1704 startCollectionBuf += 3; // skip 'for'
1705 startCollectionBuf = strchr(startCollectionBuf, '(');
1706 startCollectionBuf++; // skip '('
1707 // find 'in' and skip it.
1708 while (*startCollectionBuf != ' ' ||
1709 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1710 (*(startCollectionBuf+3) != ' ' &&
1711 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1712 startCollectionBuf++;
1713 startCollectionBuf += 3;
1714
1715 // Replace: "for (type element in" with string constructed thus far.
1716 ReplaceText(startLoc, startCollectionBuf - startBuf, buf);
1717 // Replace ')' in for '(' type elem in collection ')' with ';'
1718 SourceLocation rightParenLoc = S->getRParenLoc();
1719 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1720 SourceLocation lparenLoc = startLoc.getLocWithOffset(rparenBuf-startBuf);
1721 buf = ";\n\t";
1722
1723 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1724 // objects:__rw_items count:16];
1725 // which is synthesized into:
1726 // unsigned int limit =
1727 // ((unsigned int (*)
1728 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1729 // (void *)objc_msgSend)((id)l_collection,
1730 // sel_registerName(
1731 // "countByEnumeratingWithState:objects:count:"),
1732 // (struct __objcFastEnumerationState *)&state,
1733 // (id *)__rw_items, (unsigned int)16);
1734 buf += "unsigned long limit =\n\t\t";
1735 SynthCountByEnumWithState(buf);
1736 buf += ";\n\t";
1737 /// if (limit) {
1738 /// unsigned long startMutations = *enumState.mutationsPtr;
1739 /// do {
1740 /// unsigned long counter = 0;
1741 /// do {
1742 /// if (startMutations != *enumState.mutationsPtr)
1743 /// objc_enumerationMutation(l_collection);
1744 /// elem = (type)enumState.itemsPtr[counter++];
1745 buf += "if (limit) {\n\t";
1746 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1747 buf += "do {\n\t\t";
1748 buf += "unsigned long counter = 0;\n\t\t";
1749 buf += "do {\n\t\t\t";
1750 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1751 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1752 buf += elementName;
1753 buf += " = (";
1754 buf += elementTypeAsString;
1755 buf += ")enumState.itemsPtr[counter++];";
1756 // Replace ')' in for '(' type elem in collection ')' with all of these.
1757 ReplaceText(lparenLoc, 1, buf);
1758
1759 /// __continue_label: ;
1760 /// } while (counter < limit);
1761 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1762 /// objects:__rw_items count:16]);
1763 /// elem = nil;
1764 /// __break_label: ;
1765 /// }
1766 /// else
1767 /// elem = nil;
1768 /// }
1769 ///
1770 buf = ";\n\t";
1771 buf += "__continue_label_";
1772 buf += utostr(ObjCBcLabelNo.back());
1773 buf += ": ;";
1774 buf += "\n\t\t";
1775 buf += "} while (counter < limit);\n\t";
1776 buf += "} while (limit = ";
1777 SynthCountByEnumWithState(buf);
1778 buf += ");\n\t";
1779 buf += elementName;
1780 buf += " = ((";
1781 buf += elementTypeAsString;
1782 buf += ")0);\n\t";
1783 buf += "__break_label_";
1784 buf += utostr(ObjCBcLabelNo.back());
1785 buf += ": ;\n\t";
1786 buf += "}\n\t";
1787 buf += "else\n\t\t";
1788 buf += elementName;
1789 buf += " = ((";
1790 buf += elementTypeAsString;
1791 buf += ")0);\n\t";
1792 buf += "}\n";
1793
1794 // Insert all these *after* the statement body.
1795 // FIXME: If this should support Obj-C++, support CXXTryStmt
1796 if (isa<CompoundStmt>(S->getBody())) {
1797 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(1);
1798 InsertText(endBodyLoc, buf);
1799 } else {
1800 /* Need to treat single statements specially. For example:
1801 *
1802 * for (A *a in b) if (stuff()) break;
1803 * for (A *a in b) xxxyy;
1804 *
1805 * The following code simply scans ahead to the semi to find the actual end.
1806 */
1807 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1808 const char *semiBuf = strchr(stmtBuf, ';');
1809 assert(semiBuf && "Can't find ';'");
1810 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(semiBuf-stmtBuf+1);
1811 InsertText(endBodyLoc, buf);
1812 }
1813 Stmts.pop_back();
1814 ObjCBcLabelNo.pop_back();
1815 return 0;
1816}
1817
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001818static void Write_RethrowObject(std::string &buf) {
1819 buf += "{ struct _FIN { _FIN(id reth) : rethrow(reth) {}\n";
1820 buf += "\t~_FIN() { if (rethrow) objc_exception_throw(rethrow); }\n";
1821 buf += "\tid rethrow;\n";
1822 buf += "\t} _fin_force_rethow(_rethrow);";
1823}
1824
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001825/// RewriteObjCSynchronizedStmt -
1826/// This routine rewrites @synchronized(expr) stmt;
1827/// into:
1828/// objc_sync_enter(expr);
1829/// @try stmt @finally { objc_sync_exit(expr); }
1830///
1831Stmt *RewriteModernObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
1832 // Get the start location and compute the semi location.
1833 SourceLocation startLoc = S->getLocStart();
1834 const char *startBuf = SM->getCharacterData(startLoc);
1835
1836 assert((*startBuf == '@') && "bogus @synchronized location");
1837
1838 std::string buf;
Fariborz Jahanian22e2f852012-03-17 17:46:02 +00001839 buf = "{ id _rethrow = 0; id _sync_obj = ";
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001840
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001841 const char *lparenBuf = startBuf;
1842 while (*lparenBuf != '(') lparenBuf++;
1843 ReplaceText(startLoc, lparenBuf-startBuf+1, buf);
Fariborz Jahanian22e2f852012-03-17 17:46:02 +00001844
1845 buf = "; objc_sync_enter(_sync_obj);\n";
1846 buf += "try {\n\tstruct _SYNC_EXIT { _SYNC_EXIT(id arg) : sync_exit(arg) {}";
1847 buf += "\n\t~_SYNC_EXIT() {objc_sync_exit(sync_exit);}";
1848 buf += "\n\tid sync_exit;";
1849 buf += "\n\t} _sync_exit(_sync_obj);\n";
1850
1851 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1852 // the sync expression is typically a message expression that's already
1853 // been rewritten! (which implies the SourceLocation's are invalid).
1854 SourceLocation RParenExprLoc = S->getSynchBody()->getLocStart();
1855 const char *RParenExprLocBuf = SM->getCharacterData(RParenExprLoc);
1856 while (*RParenExprLocBuf != ')') RParenExprLocBuf--;
1857 RParenExprLoc = startLoc.getLocWithOffset(RParenExprLocBuf-startBuf);
1858
1859 SourceLocation LBranceLoc = S->getSynchBody()->getLocStart();
1860 const char *LBraceLocBuf = SM->getCharacterData(LBranceLoc);
1861 assert (*LBraceLocBuf == '{');
1862 ReplaceText(RParenExprLoc, (LBraceLocBuf - SM->getCharacterData(RParenExprLoc) + 1), buf);
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001863
Fariborz Jahanianb655bf02012-03-16 21:43:45 +00001864 SourceLocation startRBraceLoc = S->getSynchBody()->getLocEnd();
Matt Beaumont-Gay9ab511c2012-03-16 22:20:39 +00001865 assert((*SM->getCharacterData(startRBraceLoc) == '}') &&
1866 "bogus @synchronized block");
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001867
1868 buf = "} catch (id e) {_rethrow = e;}\n";
1869 Write_RethrowObject(buf);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001870 buf += "}\n";
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001871 buf += "}\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001872
Fariborz Jahanianb655bf02012-03-16 21:43:45 +00001873 ReplaceText(startRBraceLoc, 1, buf);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001874
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001875 return 0;
1876}
1877
1878void RewriteModernObjC::WarnAboutReturnGotoStmts(Stmt *S)
1879{
1880 // Perform a bottom up traversal of all children.
1881 for (Stmt::child_range CI = S->children(); CI; ++CI)
1882 if (*CI)
1883 WarnAboutReturnGotoStmts(*CI);
1884
1885 if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
1886 Diags.Report(Context->getFullLoc(S->getLocStart()),
1887 TryFinallyContainsReturnDiag);
1888 }
1889 return;
1890}
1891
Fariborz Jahanian042b91d2012-05-23 23:47:20 +00001892Stmt *RewriteModernObjC::RewriteObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S) {
1893 SourceLocation startLoc = S->getAtLoc();
1894 ReplaceText(startLoc, strlen("@autoreleasepool"), "/* @autoreleasepool */");
Fariborz Jahanianc9b72b62012-05-24 22:59:56 +00001895 ReplaceText(S->getSubStmt()->getLocStart(), 1,
1896 "{ __AtAutoreleasePool __autoreleasepool; ");
Fariborz Jahanian042b91d2012-05-23 23:47:20 +00001897
1898 return 0;
1899}
1900
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001901Stmt *RewriteModernObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Fariborz Jahanianb1228182012-03-15 22:42:15 +00001902 ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt();
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001903 bool noCatch = S->getNumCatchStmts() == 0;
Fariborz Jahanianb1228182012-03-15 22:42:15 +00001904 std::string buf;
1905
1906 if (finalStmt) {
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001907 if (noCatch)
1908 buf = "{ id volatile _rethrow = 0;\n";
1909 else {
1910 buf = "{ id volatile _rethrow = 0;\ntry {\n";
1911 }
Fariborz Jahanianb1228182012-03-15 22:42:15 +00001912 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001913 // Get the start location and compute the semi location.
1914 SourceLocation startLoc = S->getLocStart();
1915 const char *startBuf = SM->getCharacterData(startLoc);
1916
1917 assert((*startBuf == '@') && "bogus @try location");
Fariborz Jahanianb1228182012-03-15 22:42:15 +00001918 if (finalStmt)
1919 ReplaceText(startLoc, 1, buf);
1920 else
1921 // @try -> try
1922 ReplaceText(startLoc, 1, "");
1923
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001924 for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I) {
1925 ObjCAtCatchStmt *Catch = S->getCatchStmt(I);
Fariborz Jahanian4c148812012-03-15 20:11:10 +00001926 VarDecl *catchDecl = Catch->getCatchParamDecl();
Fariborz Jahanianc38503b2012-03-12 23:58:28 +00001927
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001928 startLoc = Catch->getLocStart();
Fariborz Jahanian4c148812012-03-15 20:11:10 +00001929 bool AtRemoved = false;
1930 if (catchDecl) {
1931 QualType t = catchDecl->getType();
1932 if (const ObjCObjectPointerType *Ptr = t->getAs<ObjCObjectPointerType>()) {
1933 // Should be a pointer to a class.
1934 ObjCInterfaceDecl *IDecl = Ptr->getObjectType()->getInterface();
1935 if (IDecl) {
1936 std::string Result;
1937 startBuf = SM->getCharacterData(startLoc);
1938 assert((*startBuf == '@') && "bogus @catch location");
1939 SourceLocation rParenLoc = Catch->getRParenLoc();
1940 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1941
1942 // _objc_exc_Foo *_e as argument to catch.
1943 Result = "catch (_objc_exc_"; Result += IDecl->getNameAsString();
1944 Result += " *_"; Result += catchDecl->getNameAsString();
1945 Result += ")";
1946 ReplaceText(startLoc, rParenBuf-startBuf+1, Result);
1947 // Foo *e = (Foo *)_e;
1948 Result.clear();
1949 Result = "{ ";
1950 Result += IDecl->getNameAsString();
1951 Result += " *"; Result += catchDecl->getNameAsString();
1952 Result += " = ("; Result += IDecl->getNameAsString(); Result += "*)";
1953 Result += "_"; Result += catchDecl->getNameAsString();
1954
1955 Result += "; ";
1956 SourceLocation lBraceLoc = Catch->getCatchBody()->getLocStart();
1957 ReplaceText(lBraceLoc, 1, Result);
1958 AtRemoved = true;
1959 }
1960 }
1961 }
1962 if (!AtRemoved)
1963 // @catch -> catch
1964 ReplaceText(startLoc, 1, "");
Fariborz Jahanianc38503b2012-03-12 23:58:28 +00001965
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001966 }
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001967 if (finalStmt) {
1968 buf.clear();
1969 if (noCatch)
1970 buf = "catch (id e) {_rethrow = e;}\n";
1971 else
1972 buf = "}\ncatch (id e) {_rethrow = e;}\n";
1973
1974 SourceLocation startFinalLoc = finalStmt->getLocStart();
1975 ReplaceText(startFinalLoc, 8, buf);
1976 Stmt *body = finalStmt->getFinallyBody();
1977 SourceLocation startFinalBodyLoc = body->getLocStart();
1978 buf.clear();
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001979 Write_RethrowObject(buf);
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001980 ReplaceText(startFinalBodyLoc, 1, buf);
1981
1982 SourceLocation endFinalBodyLoc = body->getLocEnd();
1983 ReplaceText(endFinalBodyLoc, 1, "}\n}");
Fariborz Jahanian22e2f852012-03-17 17:46:02 +00001984 // Now check for any return/continue/go statements within the @try.
1985 WarnAboutReturnGotoStmts(S->getTryBody());
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001986 }
1987
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001988 return 0;
1989}
1990
1991// This can't be done with ReplaceStmt(S, ThrowExpr), since
1992// the throw expression is typically a message expression that's already
1993// been rewritten! (which implies the SourceLocation's are invalid).
1994Stmt *RewriteModernObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
1995 // Get the start location and compute the semi location.
1996 SourceLocation startLoc = S->getLocStart();
1997 const char *startBuf = SM->getCharacterData(startLoc);
1998
1999 assert((*startBuf == '@') && "bogus @throw location");
2000
2001 std::string buf;
2002 /* void objc_exception_throw(id) __attribute__((noreturn)); */
2003 if (S->getThrowExpr())
2004 buf = "objc_exception_throw(";
Fariborz Jahanian40539462012-03-16 16:52:06 +00002005 else
2006 buf = "throw";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002007
2008 // handle "@ throw" correctly.
2009 const char *wBuf = strchr(startBuf, 'w');
2010 assert((*wBuf == 'w') && "@throw: can't find 'w'");
2011 ReplaceText(startLoc, wBuf-startBuf+1, buf);
2012
2013 const char *semiBuf = strchr(startBuf, ';');
2014 assert((*semiBuf == ';') && "@throw: can't find ';'");
2015 SourceLocation semiLoc = startLoc.getLocWithOffset(semiBuf-startBuf);
Fariborz Jahanian40539462012-03-16 16:52:06 +00002016 if (S->getThrowExpr())
2017 ReplaceText(semiLoc, 1, ");");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002018 return 0;
2019}
2020
2021Stmt *RewriteModernObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
2022 // Create a new string expression.
2023 QualType StrType = Context->getPointerType(Context->CharTy);
2024 std::string StrEncoding;
2025 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
2026 Expr *Replacement = StringLiteral::Create(*Context, StrEncoding,
2027 StringLiteral::Ascii, false,
2028 StrType, SourceLocation());
2029 ReplaceStmt(Exp, Replacement);
2030
2031 // Replace this subexpr in the parent.
2032 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2033 return Replacement;
2034}
2035
2036Stmt *RewriteModernObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
2037 if (!SelGetUidFunctionDecl)
2038 SynthSelGetUidFunctionDecl();
2039 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
2040 // Create a call to sel_registerName("selName").
2041 SmallVector<Expr*, 8> SelExprs;
2042 QualType argType = Context->getPointerType(Context->CharTy);
2043 SelExprs.push_back(StringLiteral::Create(*Context,
2044 Exp->getSelector().getAsString(),
2045 StringLiteral::Ascii, false,
2046 argType, SourceLocation()));
2047 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2048 &SelExprs[0], SelExprs.size());
2049 ReplaceStmt(Exp, SelExp);
2050 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2051 return SelExp;
2052}
2053
2054CallExpr *RewriteModernObjC::SynthesizeCallToFunctionDecl(
2055 FunctionDecl *FD, Expr **args, unsigned nargs, SourceLocation StartLoc,
2056 SourceLocation EndLoc) {
2057 // Get the type, we will need to reference it in a couple spots.
2058 QualType msgSendType = FD->getType();
2059
2060 // Create a reference to the objc_msgSend() declaration.
2061 DeclRefExpr *DRE =
John McCallf4b88a42012-03-10 09:33:50 +00002062 new (Context) DeclRefExpr(FD, false, msgSendType, VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002063
2064 // Now, we cast the reference to a pointer to the objc_msgSend type.
2065 QualType pToFunc = Context->getPointerType(msgSendType);
2066 ImplicitCastExpr *ICE =
2067 ImplicitCastExpr::Create(*Context, pToFunc, CK_FunctionToPointerDecay,
2068 DRE, 0, VK_RValue);
2069
2070 const FunctionType *FT = msgSendType->getAs<FunctionType>();
2071
2072 CallExpr *Exp =
2073 new (Context) CallExpr(*Context, ICE, args, nargs,
2074 FT->getCallResultType(*Context),
2075 VK_RValue, EndLoc);
2076 return Exp;
2077}
2078
2079static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
2080 const char *&startRef, const char *&endRef) {
2081 while (startBuf < endBuf) {
2082 if (*startBuf == '<')
2083 startRef = startBuf; // mark the start.
2084 if (*startBuf == '>') {
2085 if (startRef && *startRef == '<') {
2086 endRef = startBuf; // mark the end.
2087 return true;
2088 }
2089 return false;
2090 }
2091 startBuf++;
2092 }
2093 return false;
2094}
2095
2096static void scanToNextArgument(const char *&argRef) {
2097 int angle = 0;
2098 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
2099 if (*argRef == '<')
2100 angle++;
2101 else if (*argRef == '>')
2102 angle--;
2103 argRef++;
2104 }
2105 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
2106}
2107
2108bool RewriteModernObjC::needToScanForQualifiers(QualType T) {
2109 if (T->isObjCQualifiedIdType())
2110 return true;
2111 if (const PointerType *PT = T->getAs<PointerType>()) {
2112 if (PT->getPointeeType()->isObjCQualifiedIdType())
2113 return true;
2114 }
2115 if (T->isObjCObjectPointerType()) {
2116 T = T->getPointeeType();
2117 return T->isObjCQualifiedInterfaceType();
2118 }
2119 if (T->isArrayType()) {
2120 QualType ElemTy = Context->getBaseElementType(T);
2121 return needToScanForQualifiers(ElemTy);
2122 }
2123 return false;
2124}
2125
2126void RewriteModernObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
2127 QualType Type = E->getType();
2128 if (needToScanForQualifiers(Type)) {
2129 SourceLocation Loc, EndLoc;
2130
2131 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
2132 Loc = ECE->getLParenLoc();
2133 EndLoc = ECE->getRParenLoc();
2134 } else {
2135 Loc = E->getLocStart();
2136 EndLoc = E->getLocEnd();
2137 }
2138 // This will defend against trying to rewrite synthesized expressions.
2139 if (Loc.isInvalid() || EndLoc.isInvalid())
2140 return;
2141
2142 const char *startBuf = SM->getCharacterData(Loc);
2143 const char *endBuf = SM->getCharacterData(EndLoc);
2144 const char *startRef = 0, *endRef = 0;
2145 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2146 // Get the locations of the startRef, endRef.
2147 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-startBuf);
2148 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-startBuf+1);
2149 // Comment out the protocol references.
2150 InsertText(LessLoc, "/*");
2151 InsertText(GreaterLoc, "*/");
2152 }
2153 }
2154}
2155
2156void RewriteModernObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
2157 SourceLocation Loc;
2158 QualType Type;
2159 const FunctionProtoType *proto = 0;
2160 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
2161 Loc = VD->getLocation();
2162 Type = VD->getType();
2163 }
2164 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
2165 Loc = FD->getLocation();
2166 // Check for ObjC 'id' and class types that have been adorned with protocol
2167 // information (id<p>, C<p>*). The protocol references need to be rewritten!
2168 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2169 assert(funcType && "missing function type");
2170 proto = dyn_cast<FunctionProtoType>(funcType);
2171 if (!proto)
2172 return;
2173 Type = proto->getResultType();
2174 }
2175 else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
2176 Loc = FD->getLocation();
2177 Type = FD->getType();
2178 }
2179 else
2180 return;
2181
2182 if (needToScanForQualifiers(Type)) {
2183 // Since types are unique, we need to scan the buffer.
2184
2185 const char *endBuf = SM->getCharacterData(Loc);
2186 const char *startBuf = endBuf;
2187 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
2188 startBuf--; // scan backward (from the decl location) for return type.
2189 const char *startRef = 0, *endRef = 0;
2190 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2191 // Get the locations of the startRef, endRef.
2192 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-endBuf);
2193 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-endBuf+1);
2194 // Comment out the protocol references.
2195 InsertText(LessLoc, "/*");
2196 InsertText(GreaterLoc, "*/");
2197 }
2198 }
2199 if (!proto)
2200 return; // most likely, was a variable
2201 // Now check arguments.
2202 const char *startBuf = SM->getCharacterData(Loc);
2203 const char *startFuncBuf = startBuf;
2204 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
2205 if (needToScanForQualifiers(proto->getArgType(i))) {
2206 // Since types are unique, we need to scan the buffer.
2207
2208 const char *endBuf = startBuf;
2209 // scan forward (from the decl location) for argument types.
2210 scanToNextArgument(endBuf);
2211 const char *startRef = 0, *endRef = 0;
2212 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2213 // Get the locations of the startRef, endRef.
2214 SourceLocation LessLoc =
2215 Loc.getLocWithOffset(startRef-startFuncBuf);
2216 SourceLocation GreaterLoc =
2217 Loc.getLocWithOffset(endRef-startFuncBuf+1);
2218 // Comment out the protocol references.
2219 InsertText(LessLoc, "/*");
2220 InsertText(GreaterLoc, "*/");
2221 }
2222 startBuf = ++endBuf;
2223 }
2224 else {
2225 // If the function name is derived from a macro expansion, then the
2226 // argument buffer will not follow the name. Need to speak with Chris.
2227 while (*startBuf && *startBuf != ')' && *startBuf != ',')
2228 startBuf++; // scan forward (from the decl location) for argument types.
2229 startBuf++;
2230 }
2231 }
2232}
2233
2234void RewriteModernObjC::RewriteTypeOfDecl(VarDecl *ND) {
2235 QualType QT = ND->getType();
2236 const Type* TypePtr = QT->getAs<Type>();
2237 if (!isa<TypeOfExprType>(TypePtr))
2238 return;
2239 while (isa<TypeOfExprType>(TypePtr)) {
2240 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
2241 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
2242 TypePtr = QT->getAs<Type>();
2243 }
2244 // FIXME. This will not work for multiple declarators; as in:
2245 // __typeof__(a) b,c,d;
2246 std::string TypeAsString(QT.getAsString(Context->getPrintingPolicy()));
2247 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
2248 const char *startBuf = SM->getCharacterData(DeclLoc);
2249 if (ND->getInit()) {
2250 std::string Name(ND->getNameAsString());
2251 TypeAsString += " " + Name + " = ";
2252 Expr *E = ND->getInit();
2253 SourceLocation startLoc;
2254 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
2255 startLoc = ECE->getLParenLoc();
2256 else
2257 startLoc = E->getLocStart();
2258 startLoc = SM->getExpansionLoc(startLoc);
2259 const char *endBuf = SM->getCharacterData(startLoc);
2260 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
2261 }
2262 else {
2263 SourceLocation X = ND->getLocEnd();
2264 X = SM->getExpansionLoc(X);
2265 const char *endBuf = SM->getCharacterData(X);
2266 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
2267 }
2268}
2269
2270// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
2271void RewriteModernObjC::SynthSelGetUidFunctionDecl() {
2272 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
2273 SmallVector<QualType, 16> ArgTys;
2274 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2275 QualType getFuncType =
2276 getSimpleFunctionType(Context->getObjCSelType(), &ArgTys[0], ArgTys.size());
2277 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2278 SourceLocation(),
2279 SourceLocation(),
2280 SelGetUidIdent, getFuncType, 0,
2281 SC_Extern,
2282 SC_None, false);
2283}
2284
2285void RewriteModernObjC::RewriteFunctionDecl(FunctionDecl *FD) {
2286 // declared in <objc/objc.h>
2287 if (FD->getIdentifier() &&
2288 FD->getName() == "sel_registerName") {
2289 SelGetUidFunctionDecl = FD;
2290 return;
2291 }
2292 RewriteObjCQualifiedInterfaceTypes(FD);
2293}
2294
2295void RewriteModernObjC::RewriteBlockPointerType(std::string& Str, QualType Type) {
2296 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
2297 const char *argPtr = TypeString.c_str();
2298 if (!strchr(argPtr, '^')) {
2299 Str += TypeString;
2300 return;
2301 }
2302 while (*argPtr) {
2303 Str += (*argPtr == '^' ? '*' : *argPtr);
2304 argPtr++;
2305 }
2306}
2307
2308// FIXME. Consolidate this routine with RewriteBlockPointerType.
2309void RewriteModernObjC::RewriteBlockPointerTypeVariable(std::string& Str,
2310 ValueDecl *VD) {
2311 QualType Type = VD->getType();
2312 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
2313 const char *argPtr = TypeString.c_str();
2314 int paren = 0;
2315 while (*argPtr) {
2316 switch (*argPtr) {
2317 case '(':
2318 Str += *argPtr;
2319 paren++;
2320 break;
2321 case ')':
2322 Str += *argPtr;
2323 paren--;
2324 break;
2325 case '^':
2326 Str += '*';
2327 if (paren == 1)
2328 Str += VD->getNameAsString();
2329 break;
2330 default:
2331 Str += *argPtr;
2332 break;
2333 }
2334 argPtr++;
2335 }
2336}
2337
Fariborz Jahanianb75f8de2012-04-19 00:50:01 +00002338void RewriteModernObjC::RewriteBlockLiteralFunctionDecl(FunctionDecl *FD) {
2339 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
2340 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2341 const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(funcType);
2342 if (!proto)
2343 return;
2344 QualType Type = proto->getResultType();
2345 std::string FdStr = Type.getAsString(Context->getPrintingPolicy());
2346 FdStr += " ";
2347 FdStr += FD->getName();
2348 FdStr += "(";
2349 unsigned numArgs = proto->getNumArgs();
2350 for (unsigned i = 0; i < numArgs; i++) {
2351 QualType ArgType = proto->getArgType(i);
2352 RewriteBlockPointerType(FdStr, ArgType);
2353 if (i+1 < numArgs)
2354 FdStr += ", ";
2355 }
Fariborz Jahanianb5863da2012-04-19 16:30:28 +00002356 if (FD->isVariadic()) {
2357 FdStr += (numArgs > 0) ? ", ...);\n" : "...);\n";
2358 }
2359 else
2360 FdStr += ");\n";
Fariborz Jahanianb75f8de2012-04-19 00:50:01 +00002361 InsertText(FunLocStart, FdStr);
2362}
2363
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002364// SynthSuperContructorFunctionDecl - id __rw_objc_super(id obj, id super);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002365void RewriteModernObjC::SynthSuperContructorFunctionDecl() {
2366 if (SuperContructorFunctionDecl)
2367 return;
2368 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
2369 SmallVector<QualType, 16> ArgTys;
2370 QualType argT = Context->getObjCIdType();
2371 assert(!argT.isNull() && "Can't find 'id' type");
2372 ArgTys.push_back(argT);
2373 ArgTys.push_back(argT);
2374 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2375 &ArgTys[0], ArgTys.size());
2376 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2377 SourceLocation(),
2378 SourceLocation(),
2379 msgSendIdent, msgSendType, 0,
2380 SC_Extern,
2381 SC_None, false);
2382}
2383
2384// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
2385void RewriteModernObjC::SynthMsgSendFunctionDecl() {
2386 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
2387 SmallVector<QualType, 16> ArgTys;
2388 QualType argT = Context->getObjCIdType();
2389 assert(!argT.isNull() && "Can't find 'id' type");
2390 ArgTys.push_back(argT);
2391 argT = Context->getObjCSelType();
2392 assert(!argT.isNull() && "Can't find 'SEL' type");
2393 ArgTys.push_back(argT);
2394 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2395 &ArgTys[0], ArgTys.size(),
2396 true /*isVariadic*/);
2397 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2398 SourceLocation(),
2399 SourceLocation(),
2400 msgSendIdent, msgSendType, 0,
2401 SC_Extern,
2402 SC_None, false);
2403}
2404
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002405// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(void);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002406void RewriteModernObjC::SynthMsgSendSuperFunctionDecl() {
2407 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002408 SmallVector<QualType, 2> ArgTys;
2409 ArgTys.push_back(Context->VoidTy);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002410 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002411 &ArgTys[0], 1,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002412 true /*isVariadic*/);
2413 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2414 SourceLocation(),
2415 SourceLocation(),
2416 msgSendIdent, msgSendType, 0,
2417 SC_Extern,
2418 SC_None, false);
2419}
2420
2421// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
2422void RewriteModernObjC::SynthMsgSendStretFunctionDecl() {
2423 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
2424 SmallVector<QualType, 16> ArgTys;
2425 QualType argT = Context->getObjCIdType();
2426 assert(!argT.isNull() && "Can't find 'id' type");
2427 ArgTys.push_back(argT);
2428 argT = Context->getObjCSelType();
2429 assert(!argT.isNull() && "Can't find 'SEL' type");
2430 ArgTys.push_back(argT);
2431 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2432 &ArgTys[0], ArgTys.size(),
2433 true /*isVariadic*/);
2434 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2435 SourceLocation(),
2436 SourceLocation(),
2437 msgSendIdent, msgSendType, 0,
2438 SC_Extern,
2439 SC_None, false);
2440}
2441
2442// SynthMsgSendSuperStretFunctionDecl -
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002443// id objc_msgSendSuper_stret(void);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002444void RewriteModernObjC::SynthMsgSendSuperStretFunctionDecl() {
2445 IdentifierInfo *msgSendIdent =
2446 &Context->Idents.get("objc_msgSendSuper_stret");
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002447 SmallVector<QualType, 2> ArgTys;
2448 ArgTys.push_back(Context->VoidTy);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002449 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002450 &ArgTys[0], 1,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002451 true /*isVariadic*/);
2452 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2453 SourceLocation(),
2454 SourceLocation(),
2455 msgSendIdent, msgSendType, 0,
2456 SC_Extern,
2457 SC_None, false);
2458}
2459
2460// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
2461void RewriteModernObjC::SynthMsgSendFpretFunctionDecl() {
2462 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
2463 SmallVector<QualType, 16> ArgTys;
2464 QualType argT = Context->getObjCIdType();
2465 assert(!argT.isNull() && "Can't find 'id' type");
2466 ArgTys.push_back(argT);
2467 argT = Context->getObjCSelType();
2468 assert(!argT.isNull() && "Can't find 'SEL' type");
2469 ArgTys.push_back(argT);
2470 QualType msgSendType = getSimpleFunctionType(Context->DoubleTy,
2471 &ArgTys[0], ArgTys.size(),
2472 true /*isVariadic*/);
2473 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2474 SourceLocation(),
2475 SourceLocation(),
2476 msgSendIdent, msgSendType, 0,
2477 SC_Extern,
2478 SC_None, false);
2479}
2480
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00002481// SynthGetClassFunctionDecl - Class objc_getClass(const char *name);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002482void RewriteModernObjC::SynthGetClassFunctionDecl() {
2483 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
2484 SmallVector<QualType, 16> ArgTys;
2485 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00002486 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002487 &ArgTys[0], ArgTys.size());
2488 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2489 SourceLocation(),
2490 SourceLocation(),
2491 getClassIdent, getClassType, 0,
2492 SC_Extern,
2493 SC_None, false);
2494}
2495
2496// SynthGetSuperClassFunctionDecl - Class class_getSuperclass(Class cls);
2497void RewriteModernObjC::SynthGetSuperClassFunctionDecl() {
2498 IdentifierInfo *getSuperClassIdent =
2499 &Context->Idents.get("class_getSuperclass");
2500 SmallVector<QualType, 16> ArgTys;
2501 ArgTys.push_back(Context->getObjCClassType());
2502 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
2503 &ArgTys[0], ArgTys.size());
2504 GetSuperClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2505 SourceLocation(),
2506 SourceLocation(),
2507 getSuperClassIdent,
2508 getClassType, 0,
2509 SC_Extern,
2510 SC_None,
2511 false);
2512}
2513
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00002514// SynthGetMetaClassFunctionDecl - Class objc_getMetaClass(const char *name);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002515void RewriteModernObjC::SynthGetMetaClassFunctionDecl() {
2516 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
2517 SmallVector<QualType, 16> ArgTys;
2518 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00002519 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002520 &ArgTys[0], ArgTys.size());
2521 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2522 SourceLocation(),
2523 SourceLocation(),
2524 getClassIdent, getClassType, 0,
2525 SC_Extern,
2526 SC_None, false);
2527}
2528
2529Stmt *RewriteModernObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
2530 QualType strType = getConstantStringStructType();
2531
2532 std::string S = "__NSConstantStringImpl_";
2533
2534 std::string tmpName = InFileName;
2535 unsigned i;
2536 for (i=0; i < tmpName.length(); i++) {
2537 char c = tmpName.at(i);
2538 // replace any non alphanumeric characters with '_'.
2539 if (!isalpha(c) && (c < '0' || c > '9'))
2540 tmpName[i] = '_';
2541 }
2542 S += tmpName;
2543 S += "_";
2544 S += utostr(NumObjCStringLiterals++);
2545
2546 Preamble += "static __NSConstantStringImpl " + S;
2547 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2548 Preamble += "0x000007c8,"; // utf8_str
2549 // The pretty printer for StringLiteral handles escape characters properly.
2550 std::string prettyBufS;
2551 llvm::raw_string_ostream prettyBuf(prettyBufS);
Richard Smithd1420c62012-08-16 03:56:14 +00002552 Exp->getString()->printPretty(prettyBuf, 0, PrintingPolicy(LangOpts));
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002553 Preamble += prettyBuf.str();
2554 Preamble += ",";
2555 Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
2556
2557 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
2558 SourceLocation(), &Context->Idents.get(S),
2559 strType, 0, SC_Static, SC_None);
John McCallf4b88a42012-03-10 09:33:50 +00002560 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, false, strType, VK_LValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002561 SourceLocation());
2562 Expr *Unop = new (Context) UnaryOperator(DRE, UO_AddrOf,
2563 Context->getPointerType(DRE->getType()),
2564 VK_RValue, OK_Ordinary,
2565 SourceLocation());
2566 // cast to NSConstantString *
2567 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Exp->getType(),
2568 CK_CPointerToObjCPointerCast, Unop);
2569 ReplaceStmt(Exp, cast);
2570 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2571 return cast;
2572}
2573
Fariborz Jahanian55947042012-03-27 20:17:30 +00002574Stmt *RewriteModernObjC::RewriteObjCBoolLiteralExpr(ObjCBoolLiteralExpr *Exp) {
2575 unsigned IntSize =
2576 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
2577
2578 Expr *FlagExp = IntegerLiteral::Create(*Context,
2579 llvm::APInt(IntSize, Exp->getValue()),
2580 Context->IntTy, Exp->getLocation());
2581 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Context->ObjCBuiltinBoolTy,
2582 CK_BitCast, FlagExp);
2583 ParenExpr *PE = new (Context) ParenExpr(Exp->getLocation(), Exp->getExprLoc(),
2584 cast);
2585 ReplaceStmt(Exp, PE);
2586 return PE;
2587}
2588
Patrick Beardeb382ec2012-04-19 00:25:12 +00002589Stmt *RewriteModernObjC::RewriteObjCBoxedExpr(ObjCBoxedExpr *Exp) {
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002590 // synthesize declaration of helper functions needed in this routine.
2591 if (!SelGetUidFunctionDecl)
2592 SynthSelGetUidFunctionDecl();
2593 // use objc_msgSend() for all.
2594 if (!MsgSendFunctionDecl)
2595 SynthMsgSendFunctionDecl();
2596 if (!GetClassFunctionDecl)
2597 SynthGetClassFunctionDecl();
2598
2599 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2600 SourceLocation StartLoc = Exp->getLocStart();
2601 SourceLocation EndLoc = Exp->getLocEnd();
2602
2603 // Synthesize a call to objc_msgSend().
2604 SmallVector<Expr*, 4> MsgExprs;
2605 SmallVector<Expr*, 4> ClsExprs;
2606 QualType argType = Context->getPointerType(Context->CharTy);
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002607
Patrick Beardeb382ec2012-04-19 00:25:12 +00002608 // Create a call to objc_getClass("<BoxingClass>"). It will be the 1st argument.
2609 ObjCMethodDecl *BoxingMethod = Exp->getBoxingMethod();
2610 ObjCInterfaceDecl *BoxingClass = BoxingMethod->getClassInterface();
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002611
Patrick Beardeb382ec2012-04-19 00:25:12 +00002612 IdentifierInfo *clsName = BoxingClass->getIdentifier();
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002613 ClsExprs.push_back(StringLiteral::Create(*Context,
2614 clsName->getName(),
2615 StringLiteral::Ascii, false,
2616 argType, SourceLocation()));
2617 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2618 &ClsExprs[0],
2619 ClsExprs.size(),
2620 StartLoc, EndLoc);
2621 MsgExprs.push_back(Cls);
2622
Patrick Beardeb382ec2012-04-19 00:25:12 +00002623 // Create a call to sel_registerName("<BoxingMethod>:"), etc.
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002624 // it will be the 2nd argument.
2625 SmallVector<Expr*, 4> SelExprs;
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002626 SelExprs.push_back(StringLiteral::Create(*Context,
Patrick Beardeb382ec2012-04-19 00:25:12 +00002627 BoxingMethod->getSelector().getAsString(),
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002628 StringLiteral::Ascii, false,
2629 argType, SourceLocation()));
2630 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2631 &SelExprs[0], SelExprs.size(),
2632 StartLoc, EndLoc);
2633 MsgExprs.push_back(SelExp);
2634
Patrick Beardeb382ec2012-04-19 00:25:12 +00002635 // User provided sub-expression is the 3rd, and last, argument.
2636 Expr *subExpr = Exp->getSubExpr();
2637 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(subExpr)) {
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002638 QualType type = ICE->getType();
2639 const Expr *SubExpr = ICE->IgnoreParenImpCasts();
2640 CastKind CK = CK_BitCast;
2641 if (SubExpr->getType()->isIntegralType(*Context) && type->isBooleanType())
2642 CK = CK_IntegralToBoolean;
Patrick Beardeb382ec2012-04-19 00:25:12 +00002643 subExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, subExpr);
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002644 }
Patrick Beardeb382ec2012-04-19 00:25:12 +00002645 MsgExprs.push_back(subExpr);
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002646
2647 SmallVector<QualType, 4> ArgTypes;
2648 ArgTypes.push_back(Context->getObjCIdType());
2649 ArgTypes.push_back(Context->getObjCSelType());
Patrick Beardeb382ec2012-04-19 00:25:12 +00002650 for (ObjCMethodDecl::param_iterator PI = BoxingMethod->param_begin(),
2651 E = BoxingMethod->param_end(); PI != E; ++PI)
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002652 ArgTypes.push_back((*PI)->getType());
Patrick Beardeb382ec2012-04-19 00:25:12 +00002653
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002654 QualType returnType = Exp->getType();
2655 // Get the type, we will need to reference it in a couple spots.
2656 QualType msgSendType = MsgSendFlavor->getType();
2657
2658 // Create a reference to the objc_msgSend() declaration.
2659 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
2660 VK_LValue, SourceLocation());
2661
2662 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
Patrick Beardeb382ec2012-04-19 00:25:12 +00002663 Context->getPointerType(Context->VoidTy),
2664 CK_BitCast, DRE);
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002665
2666 // Now do the "normal" pointer to function cast.
2667 QualType castType =
Patrick Beardeb382ec2012-04-19 00:25:12 +00002668 getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
2669 BoxingMethod->isVariadic());
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002670 castType = Context->getPointerType(castType);
2671 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2672 cast);
2673
2674 // Don't forget the parens to enforce the proper binding.
2675 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
2676
2677 const FunctionType *FT = msgSendType->getAs<FunctionType>();
2678 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
2679 MsgExprs.size(),
2680 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 =
2721 new (Context) CallExpr(*Context, NSArrayDRE, &InitExprs[0], InitExprs.size(),
2722 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>();
2817 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
2818 MsgExprs.size(),
2819 FT->getResultType(), VK_RValue,
2820 EndLoc);
2821 ReplaceStmt(Exp, CE);
2822 return CE;
2823}
2824
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00002825Stmt *RewriteModernObjC::RewriteObjCDictionaryLiteralExpr(ObjCDictionaryLiteral *Exp) {
2826 // synthesize declaration of helper functions needed in this routine.
2827 if (!SelGetUidFunctionDecl)
2828 SynthSelGetUidFunctionDecl();
2829 // use objc_msgSend() for all.
2830 if (!MsgSendFunctionDecl)
2831 SynthMsgSendFunctionDecl();
2832 if (!GetClassFunctionDecl)
2833 SynthGetClassFunctionDecl();
2834
2835 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2836 SourceLocation StartLoc = Exp->getLocStart();
2837 SourceLocation EndLoc = Exp->getLocEnd();
2838
2839 // Build the expression: __NSContainer_literal(int, ...).arr
2840 QualType IntQT = Context->IntTy;
2841 QualType NSDictFType =
2842 getSimpleFunctionType(Context->VoidTy, &IntQT, 1, true);
2843 std::string NSDictFName("__NSContainer_literal");
2844 FunctionDecl *NSDictFD = SynthBlockInitFunctionDecl(NSDictFName);
2845 DeclRefExpr *NSDictDRE =
2846 new (Context) DeclRefExpr(NSDictFD, false, NSDictFType, VK_RValue,
2847 SourceLocation());
2848
2849 SmallVector<Expr*, 16> KeyExprs;
2850 SmallVector<Expr*, 16> ValueExprs;
2851
2852 unsigned NumElements = Exp->getNumElements();
2853 unsigned UnsignedIntSize =
2854 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
2855 Expr *count = IntegerLiteral::Create(*Context,
2856 llvm::APInt(UnsignedIntSize, NumElements),
2857 Context->UnsignedIntTy, SourceLocation());
2858 KeyExprs.push_back(count);
2859 ValueExprs.push_back(count);
2860 for (unsigned i = 0; i < NumElements; i++) {
2861 ObjCDictionaryElement Element = Exp->getKeyValueElement(i);
2862 KeyExprs.push_back(Element.Key);
2863 ValueExprs.push_back(Element.Value);
2864 }
2865
2866 // (const id [])objects
2867 Expr *NSValueCallExpr =
2868 new (Context) CallExpr(*Context, NSDictDRE, &ValueExprs[0], ValueExprs.size(),
2869 NSDictFType, VK_LValue, SourceLocation());
2870
2871 FieldDecl *ARRFD = FieldDecl::Create(*Context, 0, SourceLocation(),
2872 SourceLocation(),
2873 &Context->Idents.get("arr"),
2874 Context->getPointerType(Context->VoidPtrTy), 0,
2875 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smithca523302012-06-10 03:12:00 +00002876 ICIS_NoInit);
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00002877 MemberExpr *DictLiteralValueME =
2878 new (Context) MemberExpr(NSValueCallExpr, false, ARRFD,
2879 SourceLocation(),
2880 ARRFD->getType(), VK_LValue,
2881 OK_Ordinary);
2882 QualType ConstIdT = Context->getObjCIdType().withConst();
2883 CStyleCastExpr * DictValueObjects =
2884 NoTypeInfoCStyleCastExpr(Context,
2885 Context->getPointerType(ConstIdT),
2886 CK_BitCast,
2887 DictLiteralValueME);
2888 // (const id <NSCopying> [])keys
2889 Expr *NSKeyCallExpr =
2890 new (Context) CallExpr(*Context, NSDictDRE, &KeyExprs[0], KeyExprs.size(),
2891 NSDictFType, VK_LValue, SourceLocation());
2892
2893 MemberExpr *DictLiteralKeyME =
2894 new (Context) MemberExpr(NSKeyCallExpr, false, ARRFD,
2895 SourceLocation(),
2896 ARRFD->getType(), VK_LValue,
2897 OK_Ordinary);
2898
2899 CStyleCastExpr * DictKeyObjects =
2900 NoTypeInfoCStyleCastExpr(Context,
2901 Context->getPointerType(ConstIdT),
2902 CK_BitCast,
2903 DictLiteralKeyME);
2904
2905
2906
2907 // Synthesize a call to objc_msgSend().
2908 SmallVector<Expr*, 32> MsgExprs;
2909 SmallVector<Expr*, 4> ClsExprs;
2910 QualType argType = Context->getPointerType(Context->CharTy);
2911 QualType expType = Exp->getType();
2912
2913 // Create a call to objc_getClass("NSArray"). It will be th 1st argument.
2914 ObjCInterfaceDecl *Class =
2915 expType->getPointeeType()->getAs<ObjCObjectType>()->getInterface();
2916
2917 IdentifierInfo *clsName = Class->getIdentifier();
2918 ClsExprs.push_back(StringLiteral::Create(*Context,
2919 clsName->getName(),
2920 StringLiteral::Ascii, false,
2921 argType, SourceLocation()));
2922 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2923 &ClsExprs[0],
2924 ClsExprs.size(),
2925 StartLoc, EndLoc);
2926 MsgExprs.push_back(Cls);
2927
2928 // Create a call to sel_registerName("arrayWithObjects:count:").
2929 // it will be the 2nd argument.
2930 SmallVector<Expr*, 4> SelExprs;
2931 ObjCMethodDecl *DictMethod = Exp->getDictWithObjectsMethod();
2932 SelExprs.push_back(StringLiteral::Create(*Context,
2933 DictMethod->getSelector().getAsString(),
2934 StringLiteral::Ascii, false,
2935 argType, SourceLocation()));
2936 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2937 &SelExprs[0], SelExprs.size(),
2938 StartLoc, EndLoc);
2939 MsgExprs.push_back(SelExp);
2940
2941 // (const id [])objects
2942 MsgExprs.push_back(DictValueObjects);
2943
2944 // (const id <NSCopying> [])keys
2945 MsgExprs.push_back(DictKeyObjects);
2946
2947 // (NSUInteger)cnt
2948 Expr *cnt = IntegerLiteral::Create(*Context,
2949 llvm::APInt(UnsignedIntSize, NumElements),
2950 Context->UnsignedIntTy, SourceLocation());
2951 MsgExprs.push_back(cnt);
2952
2953
2954 SmallVector<QualType, 8> ArgTypes;
2955 ArgTypes.push_back(Context->getObjCIdType());
2956 ArgTypes.push_back(Context->getObjCSelType());
2957 for (ObjCMethodDecl::param_iterator PI = DictMethod->param_begin(),
2958 E = DictMethod->param_end(); PI != E; ++PI) {
2959 QualType T = (*PI)->getType();
2960 if (const PointerType* PT = T->getAs<PointerType>()) {
2961 QualType PointeeTy = PT->getPointeeType();
2962 convertToUnqualifiedObjCType(PointeeTy);
2963 T = Context->getPointerType(PointeeTy);
2964 }
2965 ArgTypes.push_back(T);
2966 }
2967
2968 QualType returnType = Exp->getType();
2969 // Get the type, we will need to reference it in a couple spots.
2970 QualType msgSendType = MsgSendFlavor->getType();
2971
2972 // Create a reference to the objc_msgSend() declaration.
2973 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
2974 VK_LValue, SourceLocation());
2975
2976 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
2977 Context->getPointerType(Context->VoidTy),
2978 CK_BitCast, DRE);
2979
2980 // Now do the "normal" pointer to function cast.
2981 QualType castType =
2982 getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
2983 DictMethod->isVariadic());
2984 castType = Context->getPointerType(castType);
2985 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2986 cast);
2987
2988 // Don't forget the parens to enforce the proper binding.
2989 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
2990
2991 const FunctionType *FT = msgSendType->getAs<FunctionType>();
2992 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
2993 MsgExprs.size(),
2994 FT->getResultType(), VK_RValue,
2995 EndLoc);
2996 ReplaceStmt(Exp, CE);
2997 return CE;
2998}
2999
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003000// struct __rw_objc_super {
3001// struct objc_object *object; struct objc_object *superClass;
3002// };
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003003QualType RewriteModernObjC::getSuperStructType() {
3004 if (!SuperStructDecl) {
3005 SuperStructDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
3006 SourceLocation(), SourceLocation(),
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003007 &Context->Idents.get("__rw_objc_super"));
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003008 QualType FieldTypes[2];
3009
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003010 // struct objc_object *object;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003011 FieldTypes[0] = Context->getObjCIdType();
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003012 // struct objc_object *superClass;
3013 FieldTypes[1] = Context->getObjCIdType();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003014
3015 // Create fields
3016 for (unsigned i = 0; i < 2; ++i) {
3017 SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
3018 SourceLocation(),
3019 SourceLocation(), 0,
3020 FieldTypes[i], 0,
3021 /*BitWidth=*/0,
3022 /*Mutable=*/false,
Richard Smithca523302012-06-10 03:12:00 +00003023 ICIS_NoInit));
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003024 }
3025
3026 SuperStructDecl->completeDefinition();
3027 }
3028 return Context->getTagDeclType(SuperStructDecl);
3029}
3030
3031QualType RewriteModernObjC::getConstantStringStructType() {
3032 if (!ConstantStringDecl) {
3033 ConstantStringDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
3034 SourceLocation(), SourceLocation(),
3035 &Context->Idents.get("__NSConstantStringImpl"));
3036 QualType FieldTypes[4];
3037
3038 // struct objc_object *receiver;
3039 FieldTypes[0] = Context->getObjCIdType();
3040 // int flags;
3041 FieldTypes[1] = Context->IntTy;
3042 // char *str;
3043 FieldTypes[2] = Context->getPointerType(Context->CharTy);
3044 // long length;
3045 FieldTypes[3] = Context->LongTy;
3046
3047 // Create fields
3048 for (unsigned i = 0; i < 4; ++i) {
3049 ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
3050 ConstantStringDecl,
3051 SourceLocation(),
3052 SourceLocation(), 0,
3053 FieldTypes[i], 0,
3054 /*BitWidth=*/0,
3055 /*Mutable=*/true,
Richard Smithca523302012-06-10 03:12:00 +00003056 ICIS_NoInit));
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003057 }
3058
3059 ConstantStringDecl->completeDefinition();
3060 }
3061 return Context->getTagDeclType(ConstantStringDecl);
3062}
3063
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +00003064/// getFunctionSourceLocation - returns start location of a function
3065/// definition. Complication arises when function has declared as
3066/// extern "C" or extern "C" {...}
3067static SourceLocation getFunctionSourceLocation (RewriteModernObjC &R,
3068 FunctionDecl *FD) {
3069 if (FD->isExternC() && !FD->isMain()) {
3070 const DeclContext *DC = FD->getDeclContext();
3071 if (const LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(DC))
3072 // if it is extern "C" {...}, return function decl's own location.
3073 if (!LSD->getRBraceLoc().isValid())
3074 return LSD->getExternLoc();
3075 }
3076 if (FD->getStorageClassAsWritten() != SC_None)
3077 R.RewriteBlockLiteralFunctionDecl(FD);
3078 return FD->getTypeSpecStartLoc();
3079}
3080
3081/// SynthMsgSendStretCallExpr - This routine translates message expression
3082/// into a call to objc_msgSend_stret() entry point. Tricky part is that
3083/// nil check on receiver must be performed before calling objc_msgSend_stret.
3084/// MsgSendStretFlavor - function declaration objc_msgSend_stret(...)
3085/// msgSendType - function type of objc_msgSend_stret(...)
3086/// returnType - Result type of the method being synthesized.
3087/// ArgTypes - type of the arguments passed to objc_msgSend_stret, starting with receiver type.
3088/// MsgExprs - list of argument expressions being passed to objc_msgSend_stret,
3089/// starting with receiver.
3090/// Method - Method being rewritten.
3091Expr *RewriteModernObjC::SynthMsgSendStretCallExpr(FunctionDecl *MsgSendStretFlavor,
3092 QualType msgSendType,
3093 QualType returnType,
3094 SmallVectorImpl<QualType> &ArgTypes,
3095 SmallVectorImpl<Expr*> &MsgExprs,
3096 ObjCMethodDecl *Method) {
3097 // Now do the "normal" pointer to function cast.
3098 QualType castType = getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
3099 Method ? Method->isVariadic() : false);
3100 castType = Context->getPointerType(castType);
3101
3102 // build type for containing the objc_msgSend_stret object.
3103 static unsigned stretCount=0;
3104 std::string name = "__Stret"; name += utostr(stretCount);
Fariborz Jahanian2ca5af22012-07-25 21:48:36 +00003105 std::string str =
3106 "extern \"C\" void * __cdecl memset(void *_Dst, int _Val, size_t _Size);\n";
3107 str += "struct "; str += name;
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +00003108 str += " {\n\t";
3109 str += name;
3110 str += "(id receiver, SEL sel";
3111 for (unsigned i = 2; i < ArgTypes.size(); i++) {
Fariborz Jahanian6734ec42012-06-29 19:55:46 +00003112 std::string ArgName = "arg"; ArgName += utostr(i);
3113 ArgTypes[i].getAsStringInternal(ArgName, Context->getPrintingPolicy());
3114 str += ", "; str += ArgName;
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +00003115 }
3116 // could be vararg.
3117 for (unsigned i = ArgTypes.size(); i < MsgExprs.size(); i++) {
Fariborz Jahanian6734ec42012-06-29 19:55:46 +00003118 std::string ArgName = "arg"; ArgName += utostr(i);
3119 MsgExprs[i]->getType().getAsStringInternal(ArgName,
3120 Context->getPrintingPolicy());
3121 str += ", "; str += ArgName;
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +00003122 }
3123
3124 str += ") {\n";
3125 str += "\t if (receiver == 0)\n";
3126 str += "\t memset((void*)&s, 0, sizeof(s));\n";
3127 str += "\t else\n";
3128 str += "\t s = (("; str += castType.getAsString(Context->getPrintingPolicy());
3129 str += ")(void *)objc_msgSend_stret)(receiver, sel";
3130 for (unsigned i = 2; i < ArgTypes.size(); i++) {
3131 str += ", arg"; str += utostr(i);
3132 }
3133 // could be vararg.
3134 for (unsigned i = ArgTypes.size(); i < MsgExprs.size(); i++) {
3135 str += ", arg"; str += utostr(i);
3136 }
3137
3138 str += ");\n";
3139 str += "\t}\n";
3140 str += "\t"; str += returnType.getAsString(Context->getPrintingPolicy());
3141 str += " s;\n";
3142 str += "};\n\n";
Fariborz Jahaniana6e5a6e2012-08-21 18:56:50 +00003143 SourceLocation FunLocStart;
3144 if (CurFunctionDef)
3145 FunLocStart = getFunctionSourceLocation(*this, CurFunctionDef);
3146 else {
3147 assert(CurMethodDef && "SynthMsgSendStretCallExpr - CurMethodDef is null");
3148 FunLocStart = CurMethodDef->getLocStart();
3149 }
3150
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +00003151 InsertText(FunLocStart, str);
3152 ++stretCount;
3153
3154 // AST for __Stretn(receiver, args).s;
3155 IdentifierInfo *ID = &Context->Idents.get(name);
3156 FunctionDecl *FD = FunctionDecl::Create(*Context, TUDecl, SourceLocation(),
3157 SourceLocation(), ID, castType, 0, SC_Extern,
3158 SC_None, false, false);
3159 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, false, castType, VK_RValue,
3160 SourceLocation());
3161 CallExpr *STCE = new (Context) CallExpr(*Context, DRE, &MsgExprs[0], MsgExprs.size(),
3162 castType, VK_LValue, SourceLocation());
3163
3164 FieldDecl *FieldD = FieldDecl::Create(*Context, 0, SourceLocation(),
3165 SourceLocation(),
3166 &Context->Idents.get("s"),
3167 returnType, 0,
3168 /*BitWidth=*/0, /*Mutable=*/true,
3169 ICIS_NoInit);
3170 MemberExpr *ME = new (Context) MemberExpr(STCE, false, FieldD, SourceLocation(),
3171 FieldD->getType(), VK_LValue,
3172 OK_Ordinary);
3173
3174 return ME;
3175}
3176
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003177Stmt *RewriteModernObjC::SynthMessageExpr(ObjCMessageExpr *Exp,
3178 SourceLocation StartLoc,
3179 SourceLocation EndLoc) {
3180 if (!SelGetUidFunctionDecl)
3181 SynthSelGetUidFunctionDecl();
3182 if (!MsgSendFunctionDecl)
3183 SynthMsgSendFunctionDecl();
3184 if (!MsgSendSuperFunctionDecl)
3185 SynthMsgSendSuperFunctionDecl();
3186 if (!MsgSendStretFunctionDecl)
3187 SynthMsgSendStretFunctionDecl();
3188 if (!MsgSendSuperStretFunctionDecl)
3189 SynthMsgSendSuperStretFunctionDecl();
3190 if (!MsgSendFpretFunctionDecl)
3191 SynthMsgSendFpretFunctionDecl();
3192 if (!GetClassFunctionDecl)
3193 SynthGetClassFunctionDecl();
3194 if (!GetSuperClassFunctionDecl)
3195 SynthGetSuperClassFunctionDecl();
3196 if (!GetMetaClassFunctionDecl)
3197 SynthGetMetaClassFunctionDecl();
3198
3199 // default to objc_msgSend().
3200 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
3201 // May need to use objc_msgSend_stret() as well.
3202 FunctionDecl *MsgSendStretFlavor = 0;
3203 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
3204 QualType resultType = mDecl->getResultType();
3205 if (resultType->isRecordType())
3206 MsgSendStretFlavor = MsgSendStretFunctionDecl;
3207 else if (resultType->isRealFloatingType())
3208 MsgSendFlavor = MsgSendFpretFunctionDecl;
3209 }
3210
3211 // Synthesize a call to objc_msgSend().
3212 SmallVector<Expr*, 8> MsgExprs;
3213 switch (Exp->getReceiverKind()) {
3214 case ObjCMessageExpr::SuperClass: {
3215 MsgSendFlavor = MsgSendSuperFunctionDecl;
3216 if (MsgSendStretFlavor)
3217 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
3218 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
3219
3220 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
3221
3222 SmallVector<Expr*, 4> InitExprs;
3223
3224 // set the receiver to self, the first argument to all methods.
3225 InitExprs.push_back(
3226 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3227 CK_BitCast,
3228 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCallf4b88a42012-03-10 09:33:50 +00003229 false,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003230 Context->getObjCIdType(),
3231 VK_RValue,
3232 SourceLocation()))
3233 ); // set the 'receiver'.
3234
3235 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3236 SmallVector<Expr*, 8> ClsExprs;
3237 QualType argType = Context->getPointerType(Context->CharTy);
3238 ClsExprs.push_back(StringLiteral::Create(*Context,
3239 ClassDecl->getIdentifier()->getName(),
3240 StringLiteral::Ascii, false,
3241 argType, SourceLocation()));
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00003242 // (Class)objc_getClass("CurrentClass")
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003243 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
3244 &ClsExprs[0],
3245 ClsExprs.size(),
3246 StartLoc,
3247 EndLoc);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003248 ClsExprs.clear();
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00003249 ClsExprs.push_back(Cls);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003250 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
3251 &ClsExprs[0], ClsExprs.size(),
3252 StartLoc, EndLoc);
3253
3254 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3255 // To turn off a warning, type-cast to 'id'
3256 InitExprs.push_back( // set 'super class', using class_getSuperclass().
3257 NoTypeInfoCStyleCastExpr(Context,
3258 Context->getObjCIdType(),
3259 CK_BitCast, Cls));
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003260 // struct __rw_objc_super
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003261 QualType superType = getSuperStructType();
3262 Expr *SuperRep;
3263
3264 if (LangOpts.MicrosoftExt) {
3265 SynthSuperContructorFunctionDecl();
3266 // Simulate a contructor call...
3267 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
John McCallf4b88a42012-03-10 09:33:50 +00003268 false, superType, VK_LValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003269 SourceLocation());
3270 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
3271 InitExprs.size(),
3272 superType, VK_LValue,
3273 SourceLocation());
3274 // The code for super is a little tricky to prevent collision with
3275 // the structure definition in the header. The rewriter has it's own
3276 // internal definition (__rw_objc_super) that is uses. This is why
3277 // we need the cast below. For example:
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003278 // (struct __rw_objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003279 //
3280 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
3281 Context->getPointerType(SuperRep->getType()),
3282 VK_RValue, OK_Ordinary,
3283 SourceLocation());
3284 SuperRep = NoTypeInfoCStyleCastExpr(Context,
3285 Context->getPointerType(superType),
3286 CK_BitCast, SuperRep);
3287 } else {
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003288 // (struct __rw_objc_super) { <exprs from above> }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003289 InitListExpr *ILE =
3290 new (Context) InitListExpr(*Context, SourceLocation(),
3291 &InitExprs[0], InitExprs.size(),
3292 SourceLocation());
3293 TypeSourceInfo *superTInfo
3294 = Context->getTrivialTypeSourceInfo(superType);
3295 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
3296 superType, VK_LValue,
3297 ILE, false);
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003298 // struct __rw_objc_super *
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003299 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
3300 Context->getPointerType(SuperRep->getType()),
3301 VK_RValue, OK_Ordinary,
3302 SourceLocation());
3303 }
3304 MsgExprs.push_back(SuperRep);
3305 break;
3306 }
3307
3308 case ObjCMessageExpr::Class: {
3309 SmallVector<Expr*, 8> ClsExprs;
3310 QualType argType = Context->getPointerType(Context->CharTy);
3311 ObjCInterfaceDecl *Class
3312 = Exp->getClassReceiver()->getAs<ObjCObjectType>()->getInterface();
3313 IdentifierInfo *clsName = Class->getIdentifier();
3314 ClsExprs.push_back(StringLiteral::Create(*Context,
3315 clsName->getName(),
3316 StringLiteral::Ascii, false,
3317 argType, SourceLocation()));
3318 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
3319 &ClsExprs[0],
3320 ClsExprs.size(),
3321 StartLoc, EndLoc);
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00003322 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
3323 Context->getObjCIdType(),
3324 CK_BitCast, Cls);
3325 MsgExprs.push_back(ArgExpr);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003326 break;
3327 }
3328
3329 case ObjCMessageExpr::SuperInstance:{
3330 MsgSendFlavor = MsgSendSuperFunctionDecl;
3331 if (MsgSendStretFlavor)
3332 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
3333 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
3334 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
3335 SmallVector<Expr*, 4> InitExprs;
3336
3337 InitExprs.push_back(
3338 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3339 CK_BitCast,
3340 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCallf4b88a42012-03-10 09:33:50 +00003341 false,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003342 Context->getObjCIdType(),
3343 VK_RValue, SourceLocation()))
3344 ); // set the 'receiver'.
3345
3346 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3347 SmallVector<Expr*, 8> ClsExprs;
3348 QualType argType = Context->getPointerType(Context->CharTy);
3349 ClsExprs.push_back(StringLiteral::Create(*Context,
3350 ClassDecl->getIdentifier()->getName(),
3351 StringLiteral::Ascii, false, argType,
3352 SourceLocation()));
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00003353 // (Class)objc_getClass("CurrentClass")
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003354 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
3355 &ClsExprs[0],
3356 ClsExprs.size(),
3357 StartLoc, EndLoc);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003358 ClsExprs.clear();
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00003359 ClsExprs.push_back(Cls);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003360 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
3361 &ClsExprs[0], ClsExprs.size(),
3362 StartLoc, EndLoc);
3363
3364 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3365 // To turn off a warning, type-cast to 'id'
3366 InitExprs.push_back(
3367 // set 'super class', using class_getSuperclass().
3368 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3369 CK_BitCast, Cls));
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003370 // struct __rw_objc_super
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003371 QualType superType = getSuperStructType();
3372 Expr *SuperRep;
3373
3374 if (LangOpts.MicrosoftExt) {
3375 SynthSuperContructorFunctionDecl();
3376 // Simulate a contructor call...
3377 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
John McCallf4b88a42012-03-10 09:33:50 +00003378 false, superType, VK_LValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003379 SourceLocation());
3380 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
3381 InitExprs.size(),
3382 superType, VK_LValue, SourceLocation());
3383 // The code for super is a little tricky to prevent collision with
3384 // the structure definition in the header. The rewriter has it's own
3385 // internal definition (__rw_objc_super) that is uses. This is why
3386 // we need the cast below. For example:
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003387 // (struct __rw_objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003388 //
3389 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
3390 Context->getPointerType(SuperRep->getType()),
3391 VK_RValue, OK_Ordinary,
3392 SourceLocation());
3393 SuperRep = NoTypeInfoCStyleCastExpr(Context,
3394 Context->getPointerType(superType),
3395 CK_BitCast, SuperRep);
3396 } else {
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003397 // (struct __rw_objc_super) { <exprs from above> }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003398 InitListExpr *ILE =
3399 new (Context) InitListExpr(*Context, SourceLocation(),
3400 &InitExprs[0], InitExprs.size(),
3401 SourceLocation());
3402 TypeSourceInfo *superTInfo
3403 = Context->getTrivialTypeSourceInfo(superType);
3404 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
3405 superType, VK_RValue, ILE,
3406 false);
3407 }
3408 MsgExprs.push_back(SuperRep);
3409 break;
3410 }
3411
3412 case ObjCMessageExpr::Instance: {
3413 // Remove all type-casts because it may contain objc-style types; e.g.
3414 // Foo<Proto> *.
3415 Expr *recExpr = Exp->getInstanceReceiver();
3416 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
3417 recExpr = CE->getSubExpr();
3418 CastKind CK = recExpr->getType()->isObjCObjectPointerType()
3419 ? CK_BitCast : recExpr->getType()->isBlockPointerType()
3420 ? CK_BlockPointerToObjCPointerCast
3421 : CK_CPointerToObjCPointerCast;
3422
3423 recExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3424 CK, recExpr);
3425 MsgExprs.push_back(recExpr);
3426 break;
3427 }
3428 }
3429
3430 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
3431 SmallVector<Expr*, 8> SelExprs;
3432 QualType argType = Context->getPointerType(Context->CharTy);
3433 SelExprs.push_back(StringLiteral::Create(*Context,
3434 Exp->getSelector().getAsString(),
3435 StringLiteral::Ascii, false,
3436 argType, SourceLocation()));
3437 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
3438 &SelExprs[0], SelExprs.size(),
3439 StartLoc,
3440 EndLoc);
3441 MsgExprs.push_back(SelExp);
3442
3443 // Now push any user supplied arguments.
3444 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
3445 Expr *userExpr = Exp->getArg(i);
3446 // Make all implicit casts explicit...ICE comes in handy:-)
3447 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
3448 // Reuse the ICE type, it is exactly what the doctor ordered.
3449 QualType type = ICE->getType();
3450 if (needToScanForQualifiers(type))
3451 type = Context->getObjCIdType();
3452 // Make sure we convert "type (^)(...)" to "type (*)(...)".
3453 (void)convertBlockPointerToFunctionPointer(type);
3454 const Expr *SubExpr = ICE->IgnoreParenImpCasts();
3455 CastKind CK;
3456 if (SubExpr->getType()->isIntegralType(*Context) &&
3457 type->isBooleanType()) {
3458 CK = CK_IntegralToBoolean;
3459 } else if (type->isObjCObjectPointerType()) {
3460 if (SubExpr->getType()->isBlockPointerType()) {
3461 CK = CK_BlockPointerToObjCPointerCast;
3462 } else if (SubExpr->getType()->isPointerType()) {
3463 CK = CK_CPointerToObjCPointerCast;
3464 } else {
3465 CK = CK_BitCast;
3466 }
3467 } else {
3468 CK = CK_BitCast;
3469 }
3470
3471 userExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, userExpr);
3472 }
3473 // Make id<P...> cast into an 'id' cast.
3474 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
3475 if (CE->getType()->isObjCQualifiedIdType()) {
3476 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
3477 userExpr = CE->getSubExpr();
3478 CastKind CK;
3479 if (userExpr->getType()->isIntegralType(*Context)) {
3480 CK = CK_IntegralToPointer;
3481 } else if (userExpr->getType()->isBlockPointerType()) {
3482 CK = CK_BlockPointerToObjCPointerCast;
3483 } else if (userExpr->getType()->isPointerType()) {
3484 CK = CK_CPointerToObjCPointerCast;
3485 } else {
3486 CK = CK_BitCast;
3487 }
3488 userExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3489 CK, userExpr);
3490 }
3491 }
3492 MsgExprs.push_back(userExpr);
3493 // We've transferred the ownership to MsgExprs. For now, we *don't* null
3494 // out the argument in the original expression (since we aren't deleting
3495 // the ObjCMessageExpr). See RewritePropertyOrImplicitSetter() usage for more info.
3496 //Exp->setArg(i, 0);
3497 }
3498 // Generate the funky cast.
3499 CastExpr *cast;
3500 SmallVector<QualType, 8> ArgTypes;
3501 QualType returnType;
3502
3503 // Push 'id' and 'SEL', the 2 implicit arguments.
3504 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
3505 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
3506 else
3507 ArgTypes.push_back(Context->getObjCIdType());
3508 ArgTypes.push_back(Context->getObjCSelType());
3509 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
3510 // Push any user argument types.
3511 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
3512 E = OMD->param_end(); PI != E; ++PI) {
3513 QualType t = (*PI)->getType()->isObjCQualifiedIdType()
3514 ? Context->getObjCIdType()
3515 : (*PI)->getType();
3516 // Make sure we convert "t (^)(...)" to "t (*)(...)".
3517 (void)convertBlockPointerToFunctionPointer(t);
3518 ArgTypes.push_back(t);
3519 }
3520 returnType = Exp->getType();
3521 convertToUnqualifiedObjCType(returnType);
3522 (void)convertBlockPointerToFunctionPointer(returnType);
3523 } else {
3524 returnType = Context->getObjCIdType();
3525 }
3526 // Get the type, we will need to reference it in a couple spots.
3527 QualType msgSendType = MsgSendFlavor->getType();
3528
3529 // Create a reference to the objc_msgSend() declaration.
John McCallf4b88a42012-03-10 09:33:50 +00003530 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003531 VK_LValue, SourceLocation());
3532
3533 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
3534 // If we don't do this cast, we get the following bizarre warning/note:
3535 // xx.m:13: warning: function called through a non-compatible type
3536 // xx.m:13: note: if this code is reached, the program will abort
3537 cast = NoTypeInfoCStyleCastExpr(Context,
3538 Context->getPointerType(Context->VoidTy),
3539 CK_BitCast, DRE);
3540
3541 // Now do the "normal" pointer to function cast.
3542 QualType castType =
3543 getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
3544 // If we don't have a method decl, force a variadic cast.
3545 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true);
3546 castType = Context->getPointerType(castType);
3547 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
3548 cast);
3549
3550 // Don't forget the parens to enforce the proper binding.
3551 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
3552
3553 const FunctionType *FT = msgSendType->getAs<FunctionType>();
3554 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
3555 MsgExprs.size(),
3556 FT->getResultType(), VK_RValue,
3557 EndLoc);
3558 Stmt *ReplacingStmt = CE;
3559 if (MsgSendStretFlavor) {
3560 // We have the method which returns a struct/union. Must also generate
3561 // call to objc_msgSend_stret and hang both varieties on a conditional
3562 // expression which dictate which one to envoke depending on size of
3563 // method's return type.
3564
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +00003565 Expr *STCE = SynthMsgSendStretCallExpr(MsgSendStretFlavor,
3566 msgSendType, returnType,
3567 ArgTypes, MsgExprs,
3568 Exp->getMethodDecl());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003569
3570 // Build sizeof(returnType)
3571 UnaryExprOrTypeTraitExpr *sizeofExpr =
3572 new (Context) UnaryExprOrTypeTraitExpr(UETT_SizeOf,
3573 Context->getTrivialTypeSourceInfo(returnType),
3574 Context->getSizeType(), SourceLocation(),
3575 SourceLocation());
3576 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
3577 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
3578 // For X86 it is more complicated and some kind of target specific routine
3579 // is needed to decide what to do.
3580 unsigned IntSize =
3581 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
3582 IntegerLiteral *limit = IntegerLiteral::Create(*Context,
3583 llvm::APInt(IntSize, 8),
3584 Context->IntTy,
3585 SourceLocation());
3586 BinaryOperator *lessThanExpr =
3587 new (Context) BinaryOperator(sizeofExpr, limit, BO_LE, Context->IntTy,
3588 VK_RValue, OK_Ordinary, SourceLocation());
3589 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
3590 ConditionalOperator *CondExpr =
3591 new (Context) ConditionalOperator(lessThanExpr,
3592 SourceLocation(), CE,
3593 SourceLocation(), STCE,
3594 returnType, VK_RValue, OK_Ordinary);
3595 ReplacingStmt = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3596 CondExpr);
3597 }
3598 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3599 return ReplacingStmt;
3600}
3601
3602Stmt *RewriteModernObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
3603 Stmt *ReplacingStmt = SynthMessageExpr(Exp, Exp->getLocStart(),
3604 Exp->getLocEnd());
3605
3606 // Now do the actual rewrite.
3607 ReplaceStmt(Exp, ReplacingStmt);
3608
3609 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3610 return ReplacingStmt;
3611}
3612
3613// typedef struct objc_object Protocol;
3614QualType RewriteModernObjC::getProtocolType() {
3615 if (!ProtocolTypeDecl) {
3616 TypeSourceInfo *TInfo
3617 = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
3618 ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
3619 SourceLocation(), SourceLocation(),
3620 &Context->Idents.get("Protocol"),
3621 TInfo);
3622 }
3623 return Context->getTypeDeclType(ProtocolTypeDecl);
3624}
3625
3626/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
3627/// a synthesized/forward data reference (to the protocol's metadata).
3628/// The forward references (and metadata) are generated in
3629/// RewriteModernObjC::HandleTranslationUnit().
3630Stmt *RewriteModernObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00003631 std::string Name = "_OBJC_PROTOCOL_REFERENCE_$_" +
3632 Exp->getProtocol()->getNameAsString();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003633 IdentifierInfo *ID = &Context->Idents.get(Name);
3634 VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
3635 SourceLocation(), ID, getProtocolType(), 0,
3636 SC_Extern, SC_None);
John McCallf4b88a42012-03-10 09:33:50 +00003637 DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, false, getProtocolType(),
3638 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003639 Expr *DerefExpr = new (Context) UnaryOperator(DRE, UO_AddrOf,
3640 Context->getPointerType(DRE->getType()),
3641 VK_RValue, OK_Ordinary, SourceLocation());
3642 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, DerefExpr->getType(),
3643 CK_BitCast,
3644 DerefExpr);
3645 ReplaceStmt(Exp, castExpr);
3646 ProtocolExprDecls.insert(Exp->getProtocol()->getCanonicalDecl());
3647 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3648 return castExpr;
3649
3650}
3651
3652bool RewriteModernObjC::BufferContainsPPDirectives(const char *startBuf,
3653 const char *endBuf) {
3654 while (startBuf < endBuf) {
3655 if (*startBuf == '#') {
3656 // Skip whitespace.
3657 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
3658 ;
3659 if (!strncmp(startBuf, "if", strlen("if")) ||
3660 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
3661 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
3662 !strncmp(startBuf, "define", strlen("define")) ||
3663 !strncmp(startBuf, "undef", strlen("undef")) ||
3664 !strncmp(startBuf, "else", strlen("else")) ||
3665 !strncmp(startBuf, "elif", strlen("elif")) ||
3666 !strncmp(startBuf, "endif", strlen("endif")) ||
3667 !strncmp(startBuf, "pragma", strlen("pragma")) ||
3668 !strncmp(startBuf, "include", strlen("include")) ||
3669 !strncmp(startBuf, "import", strlen("import")) ||
3670 !strncmp(startBuf, "include_next", strlen("include_next")))
3671 return true;
3672 }
3673 startBuf++;
3674 }
3675 return false;
3676}
3677
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003678/// IsTagDefinedInsideClass - This routine checks that a named tagged type
3679/// is defined inside an objective-c class. If so, it returns true.
Fariborz Jahanianb68258f2012-05-01 17:46:45 +00003680bool RewriteModernObjC::IsTagDefinedInsideClass(ObjCContainerDecl *IDecl,
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003681 TagDecl *Tag,
3682 bool &IsNamedDefinition) {
Fariborz Jahanian89585e802012-04-30 19:46:53 +00003683 if (!IDecl)
3684 return false;
3685 SourceLocation TagLocation;
3686 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) {
3687 RD = RD->getDefinition();
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003688 if (!RD || !RD->getDeclName().getAsIdentifierInfo())
Fariborz Jahanian89585e802012-04-30 19:46:53 +00003689 return false;
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003690 IsNamedDefinition = true;
Fariborz Jahanian89585e802012-04-30 19:46:53 +00003691 TagLocation = RD->getLocation();
3692 return Context->getSourceManager().isBeforeInTranslationUnit(
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003693 IDecl->getLocation(), TagLocation);
3694 }
3695 if (EnumDecl *ED = dyn_cast<EnumDecl>(Tag)) {
3696 if (!ED || !ED->getDeclName().getAsIdentifierInfo())
3697 return false;
3698 IsNamedDefinition = true;
3699 TagLocation = ED->getLocation();
3700 return Context->getSourceManager().isBeforeInTranslationUnit(
3701 IDecl->getLocation(), TagLocation);
3702
Fariborz Jahanian89585e802012-04-30 19:46:53 +00003703 }
3704 return false;
3705}
3706
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003707/// RewriteObjCFieldDeclType - This routine rewrites a type into the buffer.
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003708/// It handles elaborated types, as well as enum types in the process.
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003709bool RewriteModernObjC::RewriteObjCFieldDeclType(QualType &Type,
3710 std::string &Result) {
Fariborz Jahanianf5eac482012-05-02 17:34:59 +00003711 if (isa<TypedefType>(Type)) {
3712 Result += "\t";
3713 return false;
3714 }
3715
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003716 if (Type->isArrayType()) {
3717 QualType ElemTy = Context->getBaseElementType(Type);
3718 return RewriteObjCFieldDeclType(ElemTy, Result);
3719 }
3720 else if (Type->isRecordType()) {
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003721 RecordDecl *RD = Type->getAs<RecordType>()->getDecl();
3722 if (RD->isCompleteDefinition()) {
3723 if (RD->isStruct())
3724 Result += "\n\tstruct ";
3725 else if (RD->isUnion())
3726 Result += "\n\tunion ";
3727 else
3728 assert(false && "class not allowed as an ivar type");
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003729
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003730 Result += RD->getName();
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003731 if (GlobalDefinedTags.count(RD)) {
3732 // struct/union is defined globally, use it.
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003733 Result += " ";
3734 return true;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003735 }
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003736 Result += " {\n";
3737 for (RecordDecl::field_iterator i = RD->field_begin(),
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003738 e = RD->field_end(); i != e; ++i) {
David Blaikie581deb32012-06-06 20:45:41 +00003739 FieldDecl *FD = *i;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003740 RewriteObjCFieldDecl(FD, Result);
3741 }
3742 Result += "\t} ";
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003743 return true;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003744 }
3745 }
3746 else if (Type->isEnumeralType()) {
3747 EnumDecl *ED = Type->getAs<EnumType>()->getDecl();
3748 if (ED->isCompleteDefinition()) {
3749 Result += "\n\tenum ";
3750 Result += ED->getName();
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003751 if (GlobalDefinedTags.count(ED)) {
3752 // Enum is globall defined, use it.
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003753 Result += " ";
3754 return true;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003755 }
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003756
3757 Result += " {\n";
3758 for (EnumDecl::enumerator_iterator EC = ED->enumerator_begin(),
3759 ECEnd = ED->enumerator_end(); EC != ECEnd; ++EC) {
3760 Result += "\t"; Result += EC->getName(); Result += " = ";
3761 llvm::APSInt Val = EC->getInitVal();
3762 Result += Val.toString(10);
3763 Result += ",\n";
3764 }
3765 Result += "\t} ";
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003766 return true;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003767 }
3768 }
3769
3770 Result += "\t";
3771 convertObjCTypeToCStyleType(Type);
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003772 return false;
3773}
3774
3775
3776/// RewriteObjCFieldDecl - This routine rewrites a field into the buffer.
3777/// It handles elaborated types, as well as enum types in the process.
3778void RewriteModernObjC::RewriteObjCFieldDecl(FieldDecl *fieldDecl,
3779 std::string &Result) {
3780 QualType Type = fieldDecl->getType();
3781 std::string Name = fieldDecl->getNameAsString();
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003782
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003783 bool EleboratedType = RewriteObjCFieldDeclType(Type, Result);
3784 if (!EleboratedType)
3785 Type.getAsStringInternal(Name, Context->getPrintingPolicy());
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003786 Result += Name;
3787 if (fieldDecl->isBitField()) {
3788 Result += " : "; Result += utostr(fieldDecl->getBitWidthValue(*Context));
3789 }
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003790 else if (EleboratedType && Type->isArrayType()) {
3791 CanQualType CType = Context->getCanonicalType(Type);
3792 while (isa<ArrayType>(CType)) {
3793 if (const ConstantArrayType *CAT = Context->getAsConstantArrayType(CType)) {
3794 Result += "[";
3795 llvm::APInt Dim = CAT->getSize();
3796 Result += utostr(Dim.getZExtValue());
3797 Result += "]";
3798 }
3799 CType = CType->getAs<ArrayType>()->getElementType();
3800 }
3801 }
3802
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003803 Result += ";\n";
3804}
3805
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003806/// RewriteLocallyDefinedNamedAggregates - This routine rewrites locally defined
3807/// named aggregate types into the input buffer.
3808void RewriteModernObjC::RewriteLocallyDefinedNamedAggregates(FieldDecl *fieldDecl,
3809 std::string &Result) {
3810 QualType Type = fieldDecl->getType();
Fariborz Jahanianf5eac482012-05-02 17:34:59 +00003811 if (isa<TypedefType>(Type))
3812 return;
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003813 if (Type->isArrayType())
3814 Type = Context->getBaseElementType(Type);
Fariborz Jahanianb68258f2012-05-01 17:46:45 +00003815 ObjCContainerDecl *IDecl =
3816 dyn_cast<ObjCContainerDecl>(fieldDecl->getDeclContext());
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003817
3818 TagDecl *TD = 0;
3819 if (Type->isRecordType()) {
3820 TD = Type->getAs<RecordType>()->getDecl();
3821 }
3822 else if (Type->isEnumeralType()) {
3823 TD = Type->getAs<EnumType>()->getDecl();
3824 }
3825
3826 if (TD) {
3827 if (GlobalDefinedTags.count(TD))
3828 return;
3829
3830 bool IsNamedDefinition = false;
3831 if (IsTagDefinedInsideClass(IDecl, TD, IsNamedDefinition)) {
3832 RewriteObjCFieldDeclType(Type, Result);
3833 Result += ";";
3834 }
3835 if (IsNamedDefinition)
3836 GlobalDefinedTags.insert(TD);
3837 }
3838
3839}
3840
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003841/// RewriteObjCInternalStruct - Rewrite one internal struct corresponding to
3842/// an objective-c class with ivars.
3843void RewriteModernObjC::RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
3844 std::string &Result) {
3845 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
3846 assert(CDecl->getName() != "" &&
3847 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003848 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003849 SmallVector<ObjCIvarDecl *, 8> IVars;
3850 for (ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
Fariborz Jahanian9a2105b2012-03-06 17:16:27 +00003851 IVD; IVD = IVD->getNextIvar())
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003852 IVars.push_back(IVD);
Fariborz Jahanian9a2105b2012-03-06 17:16:27 +00003853
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003854 SourceLocation LocStart = CDecl->getLocStart();
3855 SourceLocation LocEnd = CDecl->getEndOfDefinitionLoc();
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003856
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003857 const char *startBuf = SM->getCharacterData(LocStart);
3858 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003859
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003860 // If no ivars and no root or if its root, directly or indirectly,
3861 // have no ivars (thus not synthesized) then no need to synthesize this class.
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003862 if ((!CDecl->isThisDeclarationADefinition() || IVars.size() == 0) &&
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003863 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
3864 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
3865 ReplaceText(LocStart, endBuf-startBuf, Result);
3866 return;
3867 }
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003868
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003869 // Insert named struct/union definitions inside class to
3870 // outer scope. This follows semantics of locally defined
3871 // struct/unions in objective-c classes.
3872 for (unsigned i = 0, e = IVars.size(); i < e; i++)
3873 RewriteLocallyDefinedNamedAggregates(IVars[i], Result);
3874
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003875 Result += "\nstruct ";
3876 Result += CDecl->getNameAsString();
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003877 Result += "_IMPL {\n";
3878
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00003879 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003880 Result += "\tstruct "; Result += RCDecl->getNameAsString();
3881 Result += "_IMPL "; Result += RCDecl->getNameAsString();
3882 Result += "_IVARS;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003883 }
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003884
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003885 for (unsigned i = 0, e = IVars.size(); i < e; i++)
3886 RewriteObjCFieldDecl(IVars[i], Result);
Fariborz Jahanian0b17b9a2012-02-12 21:36:23 +00003887
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003888 Result += "};\n";
3889 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
3890 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00003891 // Mark this struct as having been generated.
3892 if (!ObjCSynthesizedStructs.insert(CDecl))
3893 llvm_unreachable("struct already synthesize- RewriteObjCInternalStruct");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003894}
3895
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00003896/// RewriteIvarOffsetSymbols - Rewrite ivar offset symbols of those ivars which
3897/// have been referenced in an ivar access expression.
3898void RewriteModernObjC::RewriteIvarOffsetSymbols(ObjCInterfaceDecl *CDecl,
3899 std::string &Result) {
3900 // write out ivar offset symbols which have been referenced in an ivar
3901 // access expression.
3902 llvm::SmallPtrSet<ObjCIvarDecl *, 8> Ivars = ReferencedIvars[CDecl];
3903 if (Ivars.empty())
3904 return;
3905 for (llvm::SmallPtrSet<ObjCIvarDecl *, 8>::iterator i = Ivars.begin(),
3906 e = Ivars.end(); i != e; i++) {
3907 ObjCIvarDecl *IvarDecl = (*i);
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00003908 Result += "\n";
3909 if (LangOpts.MicrosoftExt)
3910 Result += "__declspec(allocate(\".objc_ivar$B\")) ";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00003911 Result += "extern \"C\" ";
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00003912 if (LangOpts.MicrosoftExt &&
3913 IvarDecl->getAccessControl() != ObjCIvarDecl::Private &&
Fariborz Jahanian297976d2012-03-29 17:51:09 +00003914 IvarDecl->getAccessControl() != ObjCIvarDecl::Package)
3915 Result += "__declspec(dllimport) ";
3916
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00003917 Result += "unsigned long ";
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00003918 WriteInternalIvarName(CDecl, IvarDecl, Result);
3919 Result += ";";
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00003920 }
3921}
3922
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003923//===----------------------------------------------------------------------===//
3924// Meta Data Emission
3925//===----------------------------------------------------------------------===//
3926
3927
3928/// RewriteImplementations - This routine rewrites all method implementations
3929/// and emits meta-data.
3930
3931void RewriteModernObjC::RewriteImplementations() {
3932 int ClsDefCount = ClassImplementation.size();
3933 int CatDefCount = CategoryImplementation.size();
3934
3935 // Rewrite implemented methods
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00003936 for (int i = 0; i < ClsDefCount; i++) {
3937 ObjCImplementationDecl *OIMP = ClassImplementation[i];
3938 ObjCInterfaceDecl *CDecl = OIMP->getClassInterface();
3939 if (CDecl->isImplicitInterfaceDecl())
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +00003940 assert(false &&
3941 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00003942 RewriteImplementationDecl(OIMP);
3943 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003944
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00003945 for (int i = 0; i < CatDefCount; i++) {
3946 ObjCCategoryImplDecl *CIMP = CategoryImplementation[i];
3947 ObjCInterfaceDecl *CDecl = CIMP->getClassInterface();
3948 if (CDecl->isImplicitInterfaceDecl())
3949 assert(false &&
3950 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00003951 RewriteImplementationDecl(CIMP);
3952 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003953}
3954
3955void RewriteModernObjC::RewriteByRefString(std::string &ResultStr,
3956 const std::string &Name,
3957 ValueDecl *VD, bool def) {
3958 assert(BlockByRefDeclNo.count(VD) &&
3959 "RewriteByRefString: ByRef decl missing");
3960 if (def)
3961 ResultStr += "struct ";
3962 ResultStr += "__Block_byref_" + Name +
3963 "_" + utostr(BlockByRefDeclNo[VD]) ;
3964}
3965
3966static bool HasLocalVariableExternalStorage(ValueDecl *VD) {
3967 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
3968 return (Var->isFunctionOrMethodVarDecl() && !Var->hasLocalStorage());
3969 return false;
3970}
3971
3972std::string RewriteModernObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
3973 StringRef funcName,
3974 std::string Tag) {
3975 const FunctionType *AFT = CE->getFunctionType();
3976 QualType RT = AFT->getResultType();
3977 std::string StructRef = "struct " + Tag;
3978 std::string S = "static " + RT.getAsString(Context->getPrintingPolicy()) + " __" +
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00003979 funcName.str() + "_block_func_" + utostr(i);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003980
3981 BlockDecl *BD = CE->getBlockDecl();
3982
3983 if (isa<FunctionNoProtoType>(AFT)) {
3984 // No user-supplied arguments. Still need to pass in a pointer to the
3985 // block (to reference imported block decl refs).
3986 S += "(" + StructRef + " *__cself)";
3987 } else if (BD->param_empty()) {
3988 S += "(" + StructRef + " *__cself)";
3989 } else {
3990 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
3991 assert(FT && "SynthesizeBlockFunc: No function proto");
3992 S += '(';
3993 // first add the implicit argument.
3994 S += StructRef + " *__cself, ";
3995 std::string ParamStr;
3996 for (BlockDecl::param_iterator AI = BD->param_begin(),
3997 E = BD->param_end(); AI != E; ++AI) {
3998 if (AI != BD->param_begin()) S += ", ";
3999 ParamStr = (*AI)->getNameAsString();
4000 QualType QT = (*AI)->getType();
Fariborz Jahanian2610f902012-03-27 16:42:20 +00004001 (void)convertBlockPointerToFunctionPointer(QT);
4002 QT.getAsStringInternal(ParamStr, Context->getPrintingPolicy());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004003 S += ParamStr;
4004 }
4005 if (FT->isVariadic()) {
4006 if (!BD->param_empty()) S += ", ";
4007 S += "...";
4008 }
4009 S += ')';
4010 }
4011 S += " {\n";
4012
4013 // Create local declarations to avoid rewriting all closure decl ref exprs.
4014 // First, emit a declaration for all "by ref" decls.
4015 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
4016 E = BlockByRefDecls.end(); I != E; ++I) {
4017 S += " ";
4018 std::string Name = (*I)->getNameAsString();
4019 std::string TypeString;
4020 RewriteByRefString(TypeString, Name, (*I));
4021 TypeString += " *";
4022 Name = TypeString + Name;
4023 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
4024 }
4025 // Next, emit a declaration for all "by copy" declarations.
4026 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
4027 E = BlockByCopyDecls.end(); I != E; ++I) {
4028 S += " ";
4029 // Handle nested closure invocation. For example:
4030 //
4031 // void (^myImportedClosure)(void);
4032 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
4033 //
4034 // void (^anotherClosure)(void);
4035 // anotherClosure = ^(void) {
4036 // myImportedClosure(); // import and invoke the closure
4037 // };
4038 //
4039 if (isTopLevelBlockPointerType((*I)->getType())) {
4040 RewriteBlockPointerTypeVariable(S, (*I));
4041 S += " = (";
4042 RewriteBlockPointerType(S, (*I)->getType());
4043 S += ")";
4044 S += "__cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
4045 }
4046 else {
4047 std::string Name = (*I)->getNameAsString();
4048 QualType QT = (*I)->getType();
4049 if (HasLocalVariableExternalStorage(*I))
4050 QT = Context->getPointerType(QT);
4051 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
4052 S += Name + " = __cself->" +
4053 (*I)->getNameAsString() + "; // bound by copy\n";
4054 }
4055 }
4056 std::string RewrittenStr = RewrittenBlockExprs[CE];
4057 const char *cstr = RewrittenStr.c_str();
4058 while (*cstr++ != '{') ;
4059 S += cstr;
4060 S += "\n";
4061 return S;
4062}
4063
4064std::string RewriteModernObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
4065 StringRef funcName,
4066 std::string Tag) {
4067 std::string StructRef = "struct " + Tag;
4068 std::string S = "static void __";
4069
4070 S += funcName;
4071 S += "_block_copy_" + utostr(i);
4072 S += "(" + StructRef;
4073 S += "*dst, " + StructRef;
4074 S += "*src) {";
4075 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
4076 E = ImportedBlockDecls.end(); I != E; ++I) {
4077 ValueDecl *VD = (*I);
4078 S += "_Block_object_assign((void*)&dst->";
4079 S += (*I)->getNameAsString();
4080 S += ", (void*)src->";
4081 S += (*I)->getNameAsString();
4082 if (BlockByRefDeclsPtrSet.count((*I)))
4083 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
4084 else if (VD->getType()->isBlockPointerType())
4085 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
4086 else
4087 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
4088 }
4089 S += "}\n";
4090
4091 S += "\nstatic void __";
4092 S += funcName;
4093 S += "_block_dispose_" + utostr(i);
4094 S += "(" + 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_dispose((void*)src->";
4100 S += (*I)->getNameAsString();
4101 if (BlockByRefDeclsPtrSet.count((*I)))
4102 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
4103 else if (VD->getType()->isBlockPointerType())
4104 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
4105 else
4106 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
4107 }
4108 S += "}\n";
4109 return S;
4110}
4111
4112std::string RewriteModernObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
4113 std::string Desc) {
4114 std::string S = "\nstruct " + Tag;
4115 std::string Constructor = " " + Tag;
4116
4117 S += " {\n struct __block_impl impl;\n";
4118 S += " struct " + Desc;
4119 S += "* Desc;\n";
4120
4121 Constructor += "(void *fp, "; // Invoke function pointer.
4122 Constructor += "struct " + Desc; // Descriptor pointer.
4123 Constructor += " *desc";
4124
4125 if (BlockDeclRefs.size()) {
4126 // Output all "by copy" declarations.
4127 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
4128 E = BlockByCopyDecls.end(); I != E; ++I) {
4129 S += " ";
4130 std::string FieldName = (*I)->getNameAsString();
4131 std::string ArgName = "_" + FieldName;
4132 // Handle nested closure invocation. For example:
4133 //
4134 // void (^myImportedBlock)(void);
4135 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
4136 //
4137 // void (^anotherBlock)(void);
4138 // anotherBlock = ^(void) {
4139 // myImportedBlock(); // import and invoke the closure
4140 // };
4141 //
4142 if (isTopLevelBlockPointerType((*I)->getType())) {
4143 S += "struct __block_impl *";
4144 Constructor += ", void *" + ArgName;
4145 } else {
4146 QualType QT = (*I)->getType();
4147 if (HasLocalVariableExternalStorage(*I))
4148 QT = Context->getPointerType(QT);
4149 QT.getAsStringInternal(FieldName, Context->getPrintingPolicy());
4150 QT.getAsStringInternal(ArgName, Context->getPrintingPolicy());
4151 Constructor += ", " + ArgName;
4152 }
4153 S += FieldName + ";\n";
4154 }
4155 // Output all "by ref" declarations.
4156 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
4157 E = BlockByRefDecls.end(); I != E; ++I) {
4158 S += " ";
4159 std::string FieldName = (*I)->getNameAsString();
4160 std::string ArgName = "_" + FieldName;
4161 {
4162 std::string TypeString;
4163 RewriteByRefString(TypeString, FieldName, (*I));
4164 TypeString += " *";
4165 FieldName = TypeString + FieldName;
4166 ArgName = TypeString + ArgName;
4167 Constructor += ", " + ArgName;
4168 }
4169 S += FieldName + "; // by ref\n";
4170 }
4171 // Finish writing the constructor.
4172 Constructor += ", int flags=0)";
4173 // Initialize all "by copy" arguments.
4174 bool firsTime = true;
4175 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
4176 E = BlockByCopyDecls.end(); I != E; ++I) {
4177 std::string Name = (*I)->getNameAsString();
4178 if (firsTime) {
4179 Constructor += " : ";
4180 firsTime = false;
4181 }
4182 else
4183 Constructor += ", ";
4184 if (isTopLevelBlockPointerType((*I)->getType()))
4185 Constructor += Name + "((struct __block_impl *)_" + Name + ")";
4186 else
4187 Constructor += Name + "(_" + Name + ")";
4188 }
4189 // Initialize all "by ref" arguments.
4190 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
4191 E = BlockByRefDecls.end(); I != E; ++I) {
4192 std::string Name = (*I)->getNameAsString();
4193 if (firsTime) {
4194 Constructor += " : ";
4195 firsTime = false;
4196 }
4197 else
4198 Constructor += ", ";
4199 Constructor += Name + "(_" + Name + "->__forwarding)";
4200 }
4201
4202 Constructor += " {\n";
4203 if (GlobalVarDecl)
4204 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4205 else
4206 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
4207 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
4208
4209 Constructor += " Desc = desc;\n";
4210 } else {
4211 // Finish writing the constructor.
4212 Constructor += ", int flags=0) {\n";
4213 if (GlobalVarDecl)
4214 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4215 else
4216 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
4217 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
4218 Constructor += " Desc = desc;\n";
4219 }
4220 Constructor += " ";
4221 Constructor += "}\n";
4222 S += Constructor;
4223 S += "};\n";
4224 return S;
4225}
4226
4227std::string RewriteModernObjC::SynthesizeBlockDescriptor(std::string DescTag,
4228 std::string ImplTag, int i,
4229 StringRef FunName,
4230 unsigned hasCopy) {
4231 std::string S = "\nstatic struct " + DescTag;
4232
Fariborz Jahanian8b08adb2012-05-03 21:44:12 +00004233 S += " {\n size_t reserved;\n";
4234 S += " size_t Block_size;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004235 if (hasCopy) {
4236 S += " void (*copy)(struct ";
4237 S += ImplTag; S += "*, struct ";
4238 S += ImplTag; S += "*);\n";
4239
4240 S += " void (*dispose)(struct ";
4241 S += ImplTag; S += "*);\n";
4242 }
4243 S += "} ";
4244
4245 S += DescTag + "_DATA = { 0, sizeof(struct ";
4246 S += ImplTag + ")";
4247 if (hasCopy) {
4248 S += ", __" + FunName.str() + "_block_copy_" + utostr(i);
4249 S += ", __" + FunName.str() + "_block_dispose_" + utostr(i);
4250 }
4251 S += "};\n";
4252 return S;
4253}
4254
4255void RewriteModernObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
4256 StringRef FunName) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004257 bool RewriteSC = (GlobalVarDecl &&
4258 !Blocks.empty() &&
4259 GlobalVarDecl->getStorageClass() == SC_Static &&
4260 GlobalVarDecl->getType().getCVRQualifiers());
4261 if (RewriteSC) {
4262 std::string SC(" void __");
4263 SC += GlobalVarDecl->getNameAsString();
4264 SC += "() {}";
4265 InsertText(FunLocStart, SC);
4266 }
4267
4268 // Insert closures that were part of the function.
4269 for (unsigned i = 0, count=0; i < Blocks.size(); i++) {
4270 CollectBlockDeclRefInfo(Blocks[i]);
4271 // Need to copy-in the inner copied-in variables not actually used in this
4272 // block.
4273 for (int j = 0; j < InnerDeclRefsCount[i]; j++) {
John McCallf4b88a42012-03-10 09:33:50 +00004274 DeclRefExpr *Exp = InnerDeclRefs[count++];
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004275 ValueDecl *VD = Exp->getDecl();
4276 BlockDeclRefs.push_back(Exp);
John McCallf4b88a42012-03-10 09:33:50 +00004277 if (!VD->hasAttr<BlocksAttr>()) {
4278 if (!BlockByCopyDeclsPtrSet.count(VD)) {
4279 BlockByCopyDeclsPtrSet.insert(VD);
4280 BlockByCopyDecls.push_back(VD);
4281 }
4282 continue;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004283 }
John McCallf4b88a42012-03-10 09:33:50 +00004284
4285 if (!BlockByRefDeclsPtrSet.count(VD)) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004286 BlockByRefDeclsPtrSet.insert(VD);
4287 BlockByRefDecls.push_back(VD);
4288 }
John McCallf4b88a42012-03-10 09:33:50 +00004289
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004290 // imported objects in the inner blocks not used in the outer
4291 // blocks must be copied/disposed in the outer block as well.
John McCallf4b88a42012-03-10 09:33:50 +00004292 if (VD->getType()->isObjCObjectPointerType() ||
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004293 VD->getType()->isBlockPointerType())
4294 ImportedBlockDecls.insert(VD);
4295 }
4296
4297 std::string ImplTag = "__" + FunName.str() + "_block_impl_" + utostr(i);
4298 std::string DescTag = "__" + FunName.str() + "_block_desc_" + utostr(i);
4299
4300 std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
4301
4302 InsertText(FunLocStart, CI);
4303
4304 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
4305
4306 InsertText(FunLocStart, CF);
4307
4308 if (ImportedBlockDecls.size()) {
4309 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
4310 InsertText(FunLocStart, HF);
4311 }
4312 std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
4313 ImportedBlockDecls.size() > 0);
4314 InsertText(FunLocStart, BD);
4315
4316 BlockDeclRefs.clear();
4317 BlockByRefDecls.clear();
4318 BlockByRefDeclsPtrSet.clear();
4319 BlockByCopyDecls.clear();
4320 BlockByCopyDeclsPtrSet.clear();
4321 ImportedBlockDecls.clear();
4322 }
4323 if (RewriteSC) {
4324 // Must insert any 'const/volatile/static here. Since it has been
4325 // removed as result of rewriting of block literals.
4326 std::string SC;
4327 if (GlobalVarDecl->getStorageClass() == SC_Static)
4328 SC = "static ";
4329 if (GlobalVarDecl->getType().isConstQualified())
4330 SC += "const ";
4331 if (GlobalVarDecl->getType().isVolatileQualified())
4332 SC += "volatile ";
4333 if (GlobalVarDecl->getType().isRestrictQualified())
4334 SC += "restrict ";
4335 InsertText(FunLocStart, SC);
4336 }
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00004337 if (GlobalConstructionExp) {
4338 // extra fancy dance for global literal expression.
4339
4340 // Always the latest block expression on the block stack.
4341 std::string Tag = "__";
4342 Tag += FunName;
4343 Tag += "_block_impl_";
4344 Tag += utostr(Blocks.size()-1);
4345 std::string globalBuf = "static ";
4346 globalBuf += Tag; globalBuf += " ";
4347 std::string SStr;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004348
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00004349 llvm::raw_string_ostream constructorExprBuf(SStr);
Richard Smithd1420c62012-08-16 03:56:14 +00004350 GlobalConstructionExp->printPretty(constructorExprBuf, 0,
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00004351 PrintingPolicy(LangOpts));
4352 globalBuf += constructorExprBuf.str();
4353 globalBuf += ";\n";
4354 InsertText(FunLocStart, globalBuf);
4355 GlobalConstructionExp = 0;
4356 }
4357
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004358 Blocks.clear();
4359 InnerDeclRefsCount.clear();
4360 InnerDeclRefs.clear();
4361 RewrittenBlockExprs.clear();
4362}
4363
4364void RewriteModernObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
Fariborz Jahanian04189532012-04-25 17:56:48 +00004365 SourceLocation FunLocStart =
4366 (!Blocks.empty()) ? getFunctionSourceLocation(*this, FD)
4367 : FD->getTypeSpecStartLoc();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004368 StringRef FuncName = FD->getName();
4369
4370 SynthesizeBlockLiterals(FunLocStart, FuncName);
4371}
4372
4373static void BuildUniqueMethodName(std::string &Name,
4374 ObjCMethodDecl *MD) {
4375 ObjCInterfaceDecl *IFace = MD->getClassInterface();
4376 Name = IFace->getName();
4377 Name += "__" + MD->getSelector().getAsString();
4378 // Convert colons to underscores.
4379 std::string::size_type loc = 0;
4380 while ((loc = Name.find(":", loc)) != std::string::npos)
4381 Name.replace(loc, 1, "_");
4382}
4383
4384void RewriteModernObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
4385 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
4386 //SourceLocation FunLocStart = MD->getLocStart();
4387 SourceLocation FunLocStart = MD->getLocStart();
4388 std::string FuncName;
4389 BuildUniqueMethodName(FuncName, MD);
4390 SynthesizeBlockLiterals(FunLocStart, FuncName);
4391}
4392
4393void RewriteModernObjC::GetBlockDeclRefExprs(Stmt *S) {
4394 for (Stmt::child_range CI = S->children(); CI; ++CI)
4395 if (*CI) {
4396 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
4397 GetBlockDeclRefExprs(CBE->getBody());
4398 else
4399 GetBlockDeclRefExprs(*CI);
4400 }
4401 // Handle specific things.
Fariborz Jahanian0e976812012-04-16 23:00:57 +00004402 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4403 if (DRE->refersToEnclosingLocal()) {
4404 // FIXME: Handle enums.
4405 if (!isa<FunctionDecl>(DRE->getDecl()))
4406 BlockDeclRefs.push_back(DRE);
4407 if (HasLocalVariableExternalStorage(DRE->getDecl()))
4408 BlockDeclRefs.push_back(DRE);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004409 }
Fariborz Jahanian0e976812012-04-16 23:00:57 +00004410 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004411
4412 return;
4413}
4414
4415void RewriteModernObjC::GetInnerBlockDeclRefExprs(Stmt *S,
John McCallf4b88a42012-03-10 09:33:50 +00004416 SmallVector<DeclRefExpr *, 8> &InnerBlockDeclRefs,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004417 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts) {
4418 for (Stmt::child_range CI = S->children(); CI; ++CI)
4419 if (*CI) {
4420 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI)) {
4421 InnerContexts.insert(cast<DeclContext>(CBE->getBlockDecl()));
4422 GetInnerBlockDeclRefExprs(CBE->getBody(),
4423 InnerBlockDeclRefs,
4424 InnerContexts);
4425 }
4426 else
4427 GetInnerBlockDeclRefExprs(*CI,
4428 InnerBlockDeclRefs,
4429 InnerContexts);
4430
4431 }
4432 // Handle specific things.
John McCallf4b88a42012-03-10 09:33:50 +00004433 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4434 if (DRE->refersToEnclosingLocal()) {
4435 if (!isa<FunctionDecl>(DRE->getDecl()) &&
4436 !InnerContexts.count(DRE->getDecl()->getDeclContext()))
4437 InnerBlockDeclRefs.push_back(DRE);
4438 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl()))
4439 if (Var->isFunctionOrMethodVarDecl())
4440 ImportedLocalExternalDecls.insert(Var);
4441 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004442 }
4443
4444 return;
4445}
4446
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00004447/// convertObjCTypeToCStyleType - This routine converts such objc types
4448/// as qualified objects, and blocks to their closest c/c++ types that
4449/// it can. It returns true if input type was modified.
4450bool RewriteModernObjC::convertObjCTypeToCStyleType(QualType &T) {
4451 QualType oldT = T;
4452 convertBlockPointerToFunctionPointer(T);
4453 if (T->isFunctionPointerType()) {
4454 QualType PointeeTy;
4455 if (const PointerType* PT = T->getAs<PointerType>()) {
4456 PointeeTy = PT->getPointeeType();
4457 if (const FunctionType *FT = PointeeTy->getAs<FunctionType>()) {
4458 T = convertFunctionTypeOfBlocks(FT);
4459 T = Context->getPointerType(T);
4460 }
4461 }
4462 }
4463
4464 convertToUnqualifiedObjCType(T);
4465 return T != oldT;
4466}
4467
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004468/// convertFunctionTypeOfBlocks - This routine converts a function type
4469/// whose result type may be a block pointer or whose argument type(s)
4470/// might be block pointers to an equivalent function type replacing
4471/// all block pointers to function pointers.
4472QualType RewriteModernObjC::convertFunctionTypeOfBlocks(const FunctionType *FT) {
4473 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
4474 // FTP will be null for closures that don't take arguments.
4475 // Generate a funky cast.
4476 SmallVector<QualType, 8> ArgTypes;
4477 QualType Res = FT->getResultType();
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00004478 bool modified = convertObjCTypeToCStyleType(Res);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004479
4480 if (FTP) {
4481 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4482 E = FTP->arg_type_end(); I && (I != E); ++I) {
4483 QualType t = *I;
4484 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00004485 if (convertObjCTypeToCStyleType(t))
4486 modified = true;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004487 ArgTypes.push_back(t);
4488 }
4489 }
4490 QualType FuncType;
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00004491 if (modified)
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004492 FuncType = getSimpleFunctionType(Res, &ArgTypes[0], ArgTypes.size());
4493 else FuncType = QualType(FT, 0);
4494 return FuncType;
4495}
4496
4497Stmt *RewriteModernObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
4498 // Navigate to relevant type information.
4499 const BlockPointerType *CPT = 0;
4500
4501 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
4502 CPT = DRE->getType()->getAs<BlockPointerType>();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004503 } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
4504 CPT = MExpr->getType()->getAs<BlockPointerType>();
4505 }
4506 else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
4507 return SynthesizeBlockCall(Exp, PRE->getSubExpr());
4508 }
4509 else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
4510 CPT = IEXPR->getType()->getAs<BlockPointerType>();
4511 else if (const ConditionalOperator *CEXPR =
4512 dyn_cast<ConditionalOperator>(BlockExp)) {
4513 Expr *LHSExp = CEXPR->getLHS();
4514 Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
4515 Expr *RHSExp = CEXPR->getRHS();
4516 Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
4517 Expr *CONDExp = CEXPR->getCond();
4518 ConditionalOperator *CondExpr =
4519 new (Context) ConditionalOperator(CONDExp,
4520 SourceLocation(), cast<Expr>(LHSStmt),
4521 SourceLocation(), cast<Expr>(RHSStmt),
4522 Exp->getType(), VK_RValue, OK_Ordinary);
4523 return CondExpr;
4524 } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
4525 CPT = IRE->getType()->getAs<BlockPointerType>();
4526 } else if (const PseudoObjectExpr *POE
4527 = dyn_cast<PseudoObjectExpr>(BlockExp)) {
4528 CPT = POE->getType()->castAs<BlockPointerType>();
4529 } else {
4530 assert(1 && "RewriteBlockClass: Bad type");
4531 }
4532 assert(CPT && "RewriteBlockClass: Bad type");
4533 const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
4534 assert(FT && "RewriteBlockClass: Bad type");
4535 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
4536 // FTP will be null for closures that don't take arguments.
4537
4538 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
4539 SourceLocation(), SourceLocation(),
4540 &Context->Idents.get("__block_impl"));
4541 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
4542
4543 // Generate a funky cast.
4544 SmallVector<QualType, 8> ArgTypes;
4545
4546 // Push the block argument type.
4547 ArgTypes.push_back(PtrBlock);
4548 if (FTP) {
4549 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4550 E = FTP->arg_type_end(); I && (I != E); ++I) {
4551 QualType t = *I;
4552 // Make sure we convert "t (^)(...)" to "t (*)(...)".
4553 if (!convertBlockPointerToFunctionPointer(t))
4554 convertToUnqualifiedObjCType(t);
4555 ArgTypes.push_back(t);
4556 }
4557 }
4558 // Now do the pointer to function cast.
4559 QualType PtrToFuncCastType
4560 = getSimpleFunctionType(Exp->getType(), &ArgTypes[0], ArgTypes.size());
4561
4562 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
4563
4564 CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock,
4565 CK_BitCast,
4566 const_cast<Expr*>(BlockExp));
4567 // Don't forget the parens to enforce the proper binding.
4568 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4569 BlkCast);
4570 //PE->dump();
4571
4572 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4573 SourceLocation(),
4574 &Context->Idents.get("FuncPtr"),
4575 Context->VoidPtrTy, 0,
4576 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smithca523302012-06-10 03:12:00 +00004577 ICIS_NoInit);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004578 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
4579 FD->getType(), VK_LValue,
4580 OK_Ordinary);
4581
4582
4583 CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType,
4584 CK_BitCast, ME);
4585 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
4586
4587 SmallVector<Expr*, 8> BlkExprs;
4588 // Add the implicit argument.
4589 BlkExprs.push_back(BlkCast);
4590 // Add the user arguments.
4591 for (CallExpr::arg_iterator I = Exp->arg_begin(),
4592 E = Exp->arg_end(); I != E; ++I) {
4593 BlkExprs.push_back(*I);
4594 }
4595 CallExpr *CE = new (Context) CallExpr(*Context, PE, &BlkExprs[0],
4596 BlkExprs.size(),
4597 Exp->getType(), VK_RValue,
4598 SourceLocation());
4599 return CE;
4600}
4601
4602// We need to return the rewritten expression to handle cases where the
John McCallf4b88a42012-03-10 09:33:50 +00004603// DeclRefExpr is embedded in another expression being rewritten.
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004604// For example:
4605//
4606// int main() {
4607// __block Foo *f;
4608// __block int i;
4609//
4610// void (^myblock)() = ^() {
John McCallf4b88a42012-03-10 09:33:50 +00004611// [f test]; // f is a DeclRefExpr embedded in a message (which is being rewritten).
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004612// i = 77;
4613// };
4614//}
John McCallf4b88a42012-03-10 09:33:50 +00004615Stmt *RewriteModernObjC::RewriteBlockDeclRefExpr(DeclRefExpr *DeclRefExp) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004616 // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
4617 // for each DeclRefExp where BYREFVAR is name of the variable.
John McCallf4b88a42012-03-10 09:33:50 +00004618 ValueDecl *VD = DeclRefExp->getDecl();
4619 bool isArrow = DeclRefExp->refersToEnclosingLocal();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004620
4621 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4622 SourceLocation(),
4623 &Context->Idents.get("__forwarding"),
4624 Context->VoidPtrTy, 0,
4625 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smithca523302012-06-10 03:12:00 +00004626 ICIS_NoInit);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004627 MemberExpr *ME = new (Context) MemberExpr(DeclRefExp, isArrow,
4628 FD, SourceLocation(),
4629 FD->getType(), VK_LValue,
4630 OK_Ordinary);
4631
4632 StringRef Name = VD->getName();
4633 FD = FieldDecl::Create(*Context, 0, SourceLocation(), SourceLocation(),
4634 &Context->Idents.get(Name),
4635 Context->VoidPtrTy, 0,
4636 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smithca523302012-06-10 03:12:00 +00004637 ICIS_NoInit);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004638 ME = new (Context) MemberExpr(ME, true, FD, SourceLocation(),
4639 DeclRefExp->getType(), VK_LValue, OK_Ordinary);
4640
4641
4642
4643 // Need parens to enforce precedence.
4644 ParenExpr *PE = new (Context) ParenExpr(DeclRefExp->getExprLoc(),
4645 DeclRefExp->getExprLoc(),
4646 ME);
4647 ReplaceStmt(DeclRefExp, PE);
4648 return PE;
4649}
4650
4651// Rewrites the imported local variable V with external storage
4652// (static, extern, etc.) as *V
4653//
4654Stmt *RewriteModernObjC::RewriteLocalVariableExternalStorage(DeclRefExpr *DRE) {
4655 ValueDecl *VD = DRE->getDecl();
4656 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4657 if (!ImportedLocalExternalDecls.count(Var))
4658 return DRE;
4659 Expr *Exp = new (Context) UnaryOperator(DRE, UO_Deref, DRE->getType(),
4660 VK_LValue, OK_Ordinary,
4661 DRE->getLocation());
4662 // Need parens to enforce precedence.
4663 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4664 Exp);
4665 ReplaceStmt(DRE, PE);
4666 return PE;
4667}
4668
4669void RewriteModernObjC::RewriteCastExpr(CStyleCastExpr *CE) {
4670 SourceLocation LocStart = CE->getLParenLoc();
4671 SourceLocation LocEnd = CE->getRParenLoc();
4672
4673 // Need to avoid trying to rewrite synthesized casts.
4674 if (LocStart.isInvalid())
4675 return;
4676 // Need to avoid trying to rewrite casts contained in macros.
4677 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
4678 return;
4679
4680 const char *startBuf = SM->getCharacterData(LocStart);
4681 const char *endBuf = SM->getCharacterData(LocEnd);
4682 QualType QT = CE->getType();
4683 const Type* TypePtr = QT->getAs<Type>();
4684 if (isa<TypeOfExprType>(TypePtr)) {
4685 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
4686 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
4687 std::string TypeAsString = "(";
4688 RewriteBlockPointerType(TypeAsString, QT);
4689 TypeAsString += ")";
4690 ReplaceText(LocStart, endBuf-startBuf+1, TypeAsString);
4691 return;
4692 }
4693 // advance the location to startArgList.
4694 const char *argPtr = startBuf;
4695
4696 while (*argPtr++ && (argPtr < endBuf)) {
4697 switch (*argPtr) {
4698 case '^':
4699 // Replace the '^' with '*'.
4700 LocStart = LocStart.getLocWithOffset(argPtr-startBuf);
4701 ReplaceText(LocStart, 1, "*");
4702 break;
4703 }
4704 }
4705 return;
4706}
4707
Fariborz Jahanianf1ee6872012-04-10 00:08:18 +00004708void RewriteModernObjC::RewriteImplicitCastObjCExpr(CastExpr *IC) {
4709 CastKind CastKind = IC->getCastKind();
Fariborz Jahanian43aa1c32012-04-16 22:14:01 +00004710 if (CastKind != CK_BlockPointerToObjCPointerCast &&
4711 CastKind != CK_AnyPointerToBlockPointerCast)
4712 return;
Fariborz Jahanianf1ee6872012-04-10 00:08:18 +00004713
Fariborz Jahanian43aa1c32012-04-16 22:14:01 +00004714 QualType QT = IC->getType();
4715 (void)convertBlockPointerToFunctionPointer(QT);
4716 std::string TypeString(QT.getAsString(Context->getPrintingPolicy()));
4717 std::string Str = "(";
4718 Str += TypeString;
4719 Str += ")";
4720 InsertText(IC->getSubExpr()->getLocStart(), &Str[0], Str.size());
4721
Fariborz Jahanianf1ee6872012-04-10 00:08:18 +00004722 return;
4723}
4724
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004725void RewriteModernObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
4726 SourceLocation DeclLoc = FD->getLocation();
4727 unsigned parenCount = 0;
4728
4729 // We have 1 or more arguments that have closure pointers.
4730 const char *startBuf = SM->getCharacterData(DeclLoc);
4731 const char *startArgList = strchr(startBuf, '(');
4732
4733 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
4734
4735 parenCount++;
4736 // advance the location to startArgList.
4737 DeclLoc = DeclLoc.getLocWithOffset(startArgList-startBuf);
4738 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
4739
4740 const char *argPtr = startArgList;
4741
4742 while (*argPtr++ && parenCount) {
4743 switch (*argPtr) {
4744 case '^':
4745 // Replace the '^' with '*'.
4746 DeclLoc = DeclLoc.getLocWithOffset(argPtr-startArgList);
4747 ReplaceText(DeclLoc, 1, "*");
4748 break;
4749 case '(':
4750 parenCount++;
4751 break;
4752 case ')':
4753 parenCount--;
4754 break;
4755 }
4756 }
4757 return;
4758}
4759
4760bool RewriteModernObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
4761 const FunctionProtoType *FTP;
4762 const PointerType *PT = QT->getAs<PointerType>();
4763 if (PT) {
4764 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4765 } else {
4766 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4767 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4768 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4769 }
4770 if (FTP) {
4771 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4772 E = FTP->arg_type_end(); I != E; ++I)
4773 if (isTopLevelBlockPointerType(*I))
4774 return true;
4775 }
4776 return false;
4777}
4778
4779bool RewriteModernObjC::PointerTypeTakesAnyObjCQualifiedType(QualType QT) {
4780 const FunctionProtoType *FTP;
4781 const PointerType *PT = QT->getAs<PointerType>();
4782 if (PT) {
4783 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4784 } else {
4785 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4786 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4787 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4788 }
4789 if (FTP) {
4790 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4791 E = FTP->arg_type_end(); I != E; ++I) {
4792 if ((*I)->isObjCQualifiedIdType())
4793 return true;
4794 if ((*I)->isObjCObjectPointerType() &&
4795 (*I)->getPointeeType()->isObjCQualifiedInterfaceType())
4796 return true;
4797 }
4798
4799 }
4800 return false;
4801}
4802
4803void RewriteModernObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
4804 const char *&RParen) {
4805 const char *argPtr = strchr(Name, '(');
4806 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
4807
4808 LParen = argPtr; // output the start.
4809 argPtr++; // skip past the left paren.
4810 unsigned parenCount = 1;
4811
4812 while (*argPtr && parenCount) {
4813 switch (*argPtr) {
4814 case '(': parenCount++; break;
4815 case ')': parenCount--; break;
4816 default: break;
4817 }
4818 if (parenCount) argPtr++;
4819 }
4820 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
4821 RParen = argPtr; // output the end
4822}
4823
4824void RewriteModernObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
4825 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4826 RewriteBlockPointerFunctionArgs(FD);
4827 return;
4828 }
4829 // Handle Variables and Typedefs.
4830 SourceLocation DeclLoc = ND->getLocation();
4831 QualType DeclT;
4832 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
4833 DeclT = VD->getType();
4834 else if (TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(ND))
4835 DeclT = TDD->getUnderlyingType();
4836 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
4837 DeclT = FD->getType();
4838 else
4839 llvm_unreachable("RewriteBlockPointerDecl(): Decl type not yet handled");
4840
4841 const char *startBuf = SM->getCharacterData(DeclLoc);
4842 const char *endBuf = startBuf;
4843 // scan backward (from the decl location) for the end of the previous decl.
4844 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
4845 startBuf--;
4846 SourceLocation Start = DeclLoc.getLocWithOffset(startBuf-endBuf);
4847 std::string buf;
4848 unsigned OrigLength=0;
4849 // *startBuf != '^' if we are dealing with a pointer to function that
4850 // may take block argument types (which will be handled below).
4851 if (*startBuf == '^') {
4852 // Replace the '^' with '*', computing a negative offset.
4853 buf = '*';
4854 startBuf++;
4855 OrigLength++;
4856 }
4857 while (*startBuf != ')') {
4858 buf += *startBuf;
4859 startBuf++;
4860 OrigLength++;
4861 }
4862 buf += ')';
4863 OrigLength++;
4864
4865 if (PointerTypeTakesAnyBlockArguments(DeclT) ||
4866 PointerTypeTakesAnyObjCQualifiedType(DeclT)) {
4867 // Replace the '^' with '*' for arguments.
4868 // Replace id<P> with id/*<>*/
4869 DeclLoc = ND->getLocation();
4870 startBuf = SM->getCharacterData(DeclLoc);
4871 const char *argListBegin, *argListEnd;
4872 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
4873 while (argListBegin < argListEnd) {
4874 if (*argListBegin == '^')
4875 buf += '*';
4876 else if (*argListBegin == '<') {
4877 buf += "/*";
4878 buf += *argListBegin++;
4879 OrigLength++;;
4880 while (*argListBegin != '>') {
4881 buf += *argListBegin++;
4882 OrigLength++;
4883 }
4884 buf += *argListBegin;
4885 buf += "*/";
4886 }
4887 else
4888 buf += *argListBegin;
4889 argListBegin++;
4890 OrigLength++;
4891 }
4892 buf += ')';
4893 OrigLength++;
4894 }
4895 ReplaceText(Start, OrigLength, buf);
4896
4897 return;
4898}
4899
4900
4901/// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
4902/// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
4903/// struct Block_byref_id_object *src) {
4904/// _Block_object_assign (&_dest->object, _src->object,
4905/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4906/// [|BLOCK_FIELD_IS_WEAK]) // object
4907/// _Block_object_assign(&_dest->object, _src->object,
4908/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4909/// [|BLOCK_FIELD_IS_WEAK]) // block
4910/// }
4911/// And:
4912/// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
4913/// _Block_object_dispose(_src->object,
4914/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4915/// [|BLOCK_FIELD_IS_WEAK]) // object
4916/// _Block_object_dispose(_src->object,
4917/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4918/// [|BLOCK_FIELD_IS_WEAK]) // block
4919/// }
4920
4921std::string RewriteModernObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
4922 int flag) {
4923 std::string S;
4924 if (CopyDestroyCache.count(flag))
4925 return S;
4926 CopyDestroyCache.insert(flag);
4927 S = "static void __Block_byref_id_object_copy_";
4928 S += utostr(flag);
4929 S += "(void *dst, void *src) {\n";
4930
4931 // offset into the object pointer is computed as:
4932 // void * + void* + int + int + void* + void *
4933 unsigned IntSize =
4934 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
4935 unsigned VoidPtrSize =
4936 static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
4937
4938 unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/Context->getCharWidth();
4939 S += " _Block_object_assign((char*)dst + ";
4940 S += utostr(offset);
4941 S += ", *(void * *) ((char*)src + ";
4942 S += utostr(offset);
4943 S += "), ";
4944 S += utostr(flag);
4945 S += ");\n}\n";
4946
4947 S += "static void __Block_byref_id_object_dispose_";
4948 S += utostr(flag);
4949 S += "(void *src) {\n";
4950 S += " _Block_object_dispose(*(void * *) ((char*)src + ";
4951 S += utostr(offset);
4952 S += "), ";
4953 S += utostr(flag);
4954 S += ");\n}\n";
4955 return S;
4956}
4957
4958/// RewriteByRefVar - For each __block typex ND variable this routine transforms
4959/// the declaration into:
4960/// struct __Block_byref_ND {
4961/// void *__isa; // NULL for everything except __weak pointers
4962/// struct __Block_byref_ND *__forwarding;
4963/// int32_t __flags;
4964/// int32_t __size;
4965/// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
4966/// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
4967/// typex ND;
4968/// };
4969///
4970/// It then replaces declaration of ND variable with:
4971/// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
4972/// __size=sizeof(struct __Block_byref_ND),
4973/// ND=initializer-if-any};
4974///
4975///
Fariborz Jahanian4fe261c2012-04-24 19:38:45 +00004976void RewriteModernObjC::RewriteByRefVar(VarDecl *ND, bool firstDecl,
4977 bool lastDecl) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004978 int flag = 0;
4979 int isa = 0;
4980 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
4981 if (DeclLoc.isInvalid())
4982 // If type location is missing, it is because of missing type (a warning).
4983 // Use variable's location which is good for this case.
4984 DeclLoc = ND->getLocation();
4985 const char *startBuf = SM->getCharacterData(DeclLoc);
4986 SourceLocation X = ND->getLocEnd();
4987 X = SM->getExpansionLoc(X);
4988 const char *endBuf = SM->getCharacterData(X);
4989 std::string Name(ND->getNameAsString());
4990 std::string ByrefType;
4991 RewriteByRefString(ByrefType, Name, ND, true);
4992 ByrefType += " {\n";
4993 ByrefType += " void *__isa;\n";
4994 RewriteByRefString(ByrefType, Name, ND);
4995 ByrefType += " *__forwarding;\n";
4996 ByrefType += " int __flags;\n";
4997 ByrefType += " int __size;\n";
4998 // Add void *__Block_byref_id_object_copy;
4999 // void *__Block_byref_id_object_dispose; if needed.
5000 QualType Ty = ND->getType();
5001 bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty);
5002 if (HasCopyAndDispose) {
5003 ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
5004 ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
5005 }
5006
5007 QualType T = Ty;
5008 (void)convertBlockPointerToFunctionPointer(T);
5009 T.getAsStringInternal(Name, Context->getPrintingPolicy());
5010
5011 ByrefType += " " + Name + ";\n";
5012 ByrefType += "};\n";
5013 // Insert this type in global scope. It is needed by helper function.
5014 SourceLocation FunLocStart;
5015 if (CurFunctionDef)
Fariborz Jahanianb75f8de2012-04-19 00:50:01 +00005016 FunLocStart = getFunctionSourceLocation(*this, CurFunctionDef);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005017 else {
5018 assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null");
5019 FunLocStart = CurMethodDef->getLocStart();
5020 }
5021 InsertText(FunLocStart, ByrefType);
Fariborz Jahanian8247c4e2012-04-24 16:45:27 +00005022
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005023 if (Ty.isObjCGCWeak()) {
5024 flag |= BLOCK_FIELD_IS_WEAK;
5025 isa = 1;
5026 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005027 if (HasCopyAndDispose) {
5028 flag = BLOCK_BYREF_CALLER;
5029 QualType Ty = ND->getType();
5030 // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
5031 if (Ty->isBlockPointerType())
5032 flag |= BLOCK_FIELD_IS_BLOCK;
5033 else
5034 flag |= BLOCK_FIELD_IS_OBJECT;
5035 std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
5036 if (!HF.empty())
5037 InsertText(FunLocStart, HF);
5038 }
5039
5040 // struct __Block_byref_ND ND =
5041 // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
5042 // initializer-if-any};
5043 bool hasInit = (ND->getInit() != 0);
Fariborz Jahanian104dbf92012-04-11 23:57:12 +00005044 // FIXME. rewriter does not support __block c++ objects which
5045 // require construction.
Fariborz Jahanian65a7c682012-04-26 23:20:25 +00005046 if (hasInit)
5047 if (CXXConstructExpr *CExp = dyn_cast<CXXConstructExpr>(ND->getInit())) {
5048 CXXConstructorDecl *CXXDecl = CExp->getConstructor();
5049 if (CXXDecl && CXXDecl->isDefaultConstructor())
5050 hasInit = false;
5051 }
5052
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005053 unsigned flags = 0;
5054 if (HasCopyAndDispose)
5055 flags |= BLOCK_HAS_COPY_DISPOSE;
5056 Name = ND->getNameAsString();
5057 ByrefType.clear();
5058 RewriteByRefString(ByrefType, Name, ND);
5059 std::string ForwardingCastType("(");
5060 ForwardingCastType += ByrefType + " *)";
Fariborz Jahanian8247c4e2012-04-24 16:45:27 +00005061 ByrefType += " " + Name + " = {(void*)";
5062 ByrefType += utostr(isa);
5063 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
5064 ByrefType += utostr(flags);
5065 ByrefType += ", ";
5066 ByrefType += "sizeof(";
5067 RewriteByRefString(ByrefType, Name, ND);
5068 ByrefType += ")";
5069 if (HasCopyAndDispose) {
5070 ByrefType += ", __Block_byref_id_object_copy_";
5071 ByrefType += utostr(flag);
5072 ByrefType += ", __Block_byref_id_object_dispose_";
5073 ByrefType += utostr(flag);
5074 }
5075
Fariborz Jahanian4fe261c2012-04-24 19:38:45 +00005076 if (!firstDecl) {
5077 // In multiple __block declarations, and for all but 1st declaration,
5078 // find location of the separating comma. This would be start location
5079 // where new text is to be inserted.
5080 DeclLoc = ND->getLocation();
5081 const char *startDeclBuf = SM->getCharacterData(DeclLoc);
5082 const char *commaBuf = startDeclBuf;
5083 while (*commaBuf != ',')
5084 commaBuf--;
5085 assert((*commaBuf == ',') && "RewriteByRefVar: can't find ','");
5086 DeclLoc = DeclLoc.getLocWithOffset(commaBuf - startDeclBuf);
5087 startBuf = commaBuf;
5088 }
5089
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005090 if (!hasInit) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005091 ByrefType += "};\n";
5092 unsigned nameSize = Name.size();
5093 // for block or function pointer declaration. Name is aleady
5094 // part of the declaration.
5095 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType())
5096 nameSize = 1;
5097 ReplaceText(DeclLoc, endBuf-startBuf+nameSize, ByrefType);
5098 }
5099 else {
Fariborz Jahanian8247c4e2012-04-24 16:45:27 +00005100 ByrefType += ", ";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005101 SourceLocation startLoc;
5102 Expr *E = ND->getInit();
5103 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
5104 startLoc = ECE->getLParenLoc();
5105 else
5106 startLoc = E->getLocStart();
5107 startLoc = SM->getExpansionLoc(startLoc);
5108 endBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005109 ReplaceText(DeclLoc, endBuf-startBuf, ByrefType);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005110
Fariborz Jahanian4fe261c2012-04-24 19:38:45 +00005111 const char separator = lastDecl ? ';' : ',';
5112 const char *startInitializerBuf = SM->getCharacterData(startLoc);
5113 const char *separatorBuf = strchr(startInitializerBuf, separator);
5114 assert((*separatorBuf == separator) &&
5115 "RewriteByRefVar: can't find ';' or ','");
5116 SourceLocation separatorLoc =
5117 startLoc.getLocWithOffset(separatorBuf-startInitializerBuf);
5118
5119 InsertText(separatorLoc, lastDecl ? "}" : "};\n");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005120 }
5121 return;
5122}
5123
5124void RewriteModernObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
5125 // Add initializers for any closure decl refs.
5126 GetBlockDeclRefExprs(Exp->getBody());
5127 if (BlockDeclRefs.size()) {
5128 // Unique all "by copy" declarations.
5129 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00005130 if (!BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005131 if (!BlockByCopyDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
5132 BlockByCopyDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
5133 BlockByCopyDecls.push_back(BlockDeclRefs[i]->getDecl());
5134 }
5135 }
5136 // Unique all "by ref" declarations.
5137 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00005138 if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005139 if (!BlockByRefDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
5140 BlockByRefDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
5141 BlockByRefDecls.push_back(BlockDeclRefs[i]->getDecl());
5142 }
5143 }
5144 // Find any imported blocks...they will need special attention.
5145 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00005146 if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005147 BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
5148 BlockDeclRefs[i]->getType()->isBlockPointerType())
5149 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
5150 }
5151}
5152
5153FunctionDecl *RewriteModernObjC::SynthBlockInitFunctionDecl(StringRef name) {
5154 IdentifierInfo *ID = &Context->Idents.get(name);
5155 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
5156 return FunctionDecl::Create(*Context, TUDecl, SourceLocation(),
5157 SourceLocation(), ID, FType, 0, SC_Extern,
5158 SC_None, false, false);
5159}
5160
5161Stmt *RewriteModernObjC::SynthBlockInitExpr(BlockExpr *Exp,
John McCallf4b88a42012-03-10 09:33:50 +00005162 const SmallVector<DeclRefExpr *, 8> &InnerBlockDeclRefs) {
Fariborz Jahaniand13c2c22012-03-22 19:54:39 +00005163
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005164 const BlockDecl *block = Exp->getBlockDecl();
Fariborz Jahaniand13c2c22012-03-22 19:54:39 +00005165
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005166 Blocks.push_back(Exp);
5167
5168 CollectBlockDeclRefInfo(Exp);
5169
5170 // Add inner imported variables now used in current block.
5171 int countOfInnerDecls = 0;
5172 if (!InnerBlockDeclRefs.empty()) {
5173 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++) {
John McCallf4b88a42012-03-10 09:33:50 +00005174 DeclRefExpr *Exp = InnerBlockDeclRefs[i];
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005175 ValueDecl *VD = Exp->getDecl();
John McCallf4b88a42012-03-10 09:33:50 +00005176 if (!VD->hasAttr<BlocksAttr>() && !BlockByCopyDeclsPtrSet.count(VD)) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005177 // We need to save the copied-in variables in nested
5178 // blocks because it is needed at the end for some of the API generations.
5179 // See SynthesizeBlockLiterals routine.
5180 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5181 BlockDeclRefs.push_back(Exp);
5182 BlockByCopyDeclsPtrSet.insert(VD);
5183 BlockByCopyDecls.push_back(VD);
5184 }
John McCallf4b88a42012-03-10 09:33:50 +00005185 if (VD->hasAttr<BlocksAttr>() && !BlockByRefDeclsPtrSet.count(VD)) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005186 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5187 BlockDeclRefs.push_back(Exp);
5188 BlockByRefDeclsPtrSet.insert(VD);
5189 BlockByRefDecls.push_back(VD);
5190 }
5191 }
5192 // Find any imported blocks...they will need special attention.
5193 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00005194 if (InnerBlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005195 InnerBlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
5196 InnerBlockDeclRefs[i]->getType()->isBlockPointerType())
5197 ImportedBlockDecls.insert(InnerBlockDeclRefs[i]->getDecl());
5198 }
5199 InnerDeclRefsCount.push_back(countOfInnerDecls);
5200
5201 std::string FuncName;
5202
5203 if (CurFunctionDef)
5204 FuncName = CurFunctionDef->getNameAsString();
5205 else if (CurMethodDef)
5206 BuildUniqueMethodName(FuncName, CurMethodDef);
5207 else if (GlobalVarDecl)
5208 FuncName = std::string(GlobalVarDecl->getNameAsString());
5209
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00005210 bool GlobalBlockExpr =
5211 block->getDeclContext()->getRedeclContext()->isFileContext();
5212
5213 if (GlobalBlockExpr && !GlobalVarDecl) {
5214 Diags.Report(block->getLocation(), GlobalBlockRewriteFailedDiag);
5215 GlobalBlockExpr = false;
5216 }
5217
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005218 std::string BlockNumber = utostr(Blocks.size()-1);
5219
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005220 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
5221
5222 // Get a pointer to the function type so we can cast appropriately.
5223 QualType BFT = convertFunctionTypeOfBlocks(Exp->getFunctionType());
5224 QualType FType = Context->getPointerType(BFT);
5225
5226 FunctionDecl *FD;
5227 Expr *NewRep;
5228
5229 // Simulate a contructor call...
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00005230 std::string Tag;
5231
5232 if (GlobalBlockExpr)
5233 Tag = "__global_";
5234 else
5235 Tag = "__";
5236 Tag += FuncName + "_block_impl_" + BlockNumber;
5237
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005238 FD = SynthBlockInitFunctionDecl(Tag);
John McCallf4b88a42012-03-10 09:33:50 +00005239 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, false, FType, VK_RValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005240 SourceLocation());
5241
5242 SmallVector<Expr*, 4> InitExprs;
5243
5244 // Initialize the block function.
5245 FD = SynthBlockInitFunctionDecl(Func);
John McCallf4b88a42012-03-10 09:33:50 +00005246 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, false, FD->getType(),
5247 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005248 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
5249 CK_BitCast, Arg);
5250 InitExprs.push_back(castExpr);
5251
5252 // Initialize the block descriptor.
5253 std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
5254
5255 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl,
5256 SourceLocation(), SourceLocation(),
5257 &Context->Idents.get(DescData.c_str()),
5258 Context->VoidPtrTy, 0,
5259 SC_Static, SC_None);
5260 UnaryOperator *DescRefExpr =
John McCallf4b88a42012-03-10 09:33:50 +00005261 new (Context) UnaryOperator(new (Context) DeclRefExpr(NewVD, false,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005262 Context->VoidPtrTy,
5263 VK_LValue,
5264 SourceLocation()),
5265 UO_AddrOf,
5266 Context->getPointerType(Context->VoidPtrTy),
5267 VK_RValue, OK_Ordinary,
5268 SourceLocation());
5269 InitExprs.push_back(DescRefExpr);
5270
5271 // Add initializers for any closure decl refs.
5272 if (BlockDeclRefs.size()) {
5273 Expr *Exp;
5274 // Output all "by copy" declarations.
5275 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
5276 E = BlockByCopyDecls.end(); I != E; ++I) {
5277 if (isObjCType((*I)->getType())) {
5278 // FIXME: Conform to ABI ([[obj retain] autorelease]).
5279 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00005280 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(),
5281 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005282 if (HasLocalVariableExternalStorage(*I)) {
5283 QualType QT = (*I)->getType();
5284 QT = Context->getPointerType(QT);
5285 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
5286 OK_Ordinary, SourceLocation());
5287 }
5288 } else if (isTopLevelBlockPointerType((*I)->getType())) {
5289 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00005290 Arg = new (Context) DeclRefExpr(FD, false, FD->getType(),
5291 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005292 Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
5293 CK_BitCast, Arg);
5294 } else {
5295 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00005296 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(),
5297 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005298 if (HasLocalVariableExternalStorage(*I)) {
5299 QualType QT = (*I)->getType();
5300 QT = Context->getPointerType(QT);
5301 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
5302 OK_Ordinary, SourceLocation());
5303 }
5304
5305 }
5306 InitExprs.push_back(Exp);
5307 }
5308 // Output all "by ref" declarations.
5309 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
5310 E = BlockByRefDecls.end(); I != E; ++I) {
5311 ValueDecl *ND = (*I);
5312 std::string Name(ND->getNameAsString());
5313 std::string RecName;
5314 RewriteByRefString(RecName, Name, ND, true);
5315 IdentifierInfo *II = &Context->Idents.get(RecName.c_str()
5316 + sizeof("struct"));
5317 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
5318 SourceLocation(), SourceLocation(),
5319 II);
5320 assert(RD && "SynthBlockInitExpr(): Can't find RecordDecl");
5321 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
5322
5323 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00005324 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(), VK_LValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005325 SourceLocation());
5326 bool isNestedCapturedVar = false;
5327 if (block)
5328 for (BlockDecl::capture_const_iterator ci = block->capture_begin(),
5329 ce = block->capture_end(); ci != ce; ++ci) {
5330 const VarDecl *variable = ci->getVariable();
5331 if (variable == ND && ci->isNested()) {
5332 assert (ci->isByRef() &&
5333 "SynthBlockInitExpr - captured block variable is not byref");
5334 isNestedCapturedVar = true;
5335 break;
5336 }
5337 }
5338 // captured nested byref variable has its address passed. Do not take
5339 // its address again.
5340 if (!isNestedCapturedVar)
5341 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf,
5342 Context->getPointerType(Exp->getType()),
5343 VK_RValue, OK_Ordinary, SourceLocation());
5344 Exp = NoTypeInfoCStyleCastExpr(Context, castT, CK_BitCast, Exp);
5345 InitExprs.push_back(Exp);
5346 }
5347 }
5348 if (ImportedBlockDecls.size()) {
5349 // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
5350 int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
5351 unsigned IntSize =
5352 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
5353 Expr *FlagExp = IntegerLiteral::Create(*Context, llvm::APInt(IntSize, flag),
5354 Context->IntTy, SourceLocation());
5355 InitExprs.push_back(FlagExp);
5356 }
5357 NewRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0], InitExprs.size(),
5358 FType, VK_LValue, SourceLocation());
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00005359
5360 if (GlobalBlockExpr) {
5361 assert (GlobalConstructionExp == 0 &&
5362 "SynthBlockInitExpr - GlobalConstructionExp must be null");
5363 GlobalConstructionExp = NewRep;
5364 NewRep = DRE;
5365 }
5366
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005367 NewRep = new (Context) UnaryOperator(NewRep, UO_AddrOf,
5368 Context->getPointerType(NewRep->getType()),
5369 VK_RValue, OK_Ordinary, SourceLocation());
5370 NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CK_BitCast,
5371 NewRep);
5372 BlockDeclRefs.clear();
5373 BlockByRefDecls.clear();
5374 BlockByRefDeclsPtrSet.clear();
5375 BlockByCopyDecls.clear();
5376 BlockByCopyDeclsPtrSet.clear();
5377 ImportedBlockDecls.clear();
5378 return NewRep;
5379}
5380
5381bool RewriteModernObjC::IsDeclStmtInForeachHeader(DeclStmt *DS) {
5382 if (const ObjCForCollectionStmt * CS =
5383 dyn_cast<ObjCForCollectionStmt>(Stmts.back()))
5384 return CS->getElement() == DS;
5385 return false;
5386}
5387
5388//===----------------------------------------------------------------------===//
5389// Function Body / Expression rewriting
5390//===----------------------------------------------------------------------===//
5391
5392Stmt *RewriteModernObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
5393 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
5394 isa<DoStmt>(S) || isa<ForStmt>(S))
5395 Stmts.push_back(S);
5396 else if (isa<ObjCForCollectionStmt>(S)) {
5397 Stmts.push_back(S);
5398 ObjCBcLabelNo.push_back(++BcLabelCount);
5399 }
5400
5401 // Pseudo-object operations and ivar references need special
5402 // treatment because we're going to recursively rewrite them.
5403 if (PseudoObjectExpr *PseudoOp = dyn_cast<PseudoObjectExpr>(S)) {
5404 if (isa<BinaryOperator>(PseudoOp->getSyntacticForm())) {
5405 return RewritePropertyOrImplicitSetter(PseudoOp);
5406 } else {
5407 return RewritePropertyOrImplicitGetter(PseudoOp);
5408 }
5409 } else if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
5410 return RewriteObjCIvarRefExpr(IvarRefExpr);
5411 }
5412
5413 SourceRange OrigStmtRange = S->getSourceRange();
5414
5415 // Perform a bottom up rewrite of all children.
5416 for (Stmt::child_range CI = S->children(); CI; ++CI)
5417 if (*CI) {
5418 Stmt *childStmt = (*CI);
5419 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(childStmt);
5420 if (newStmt) {
5421 *CI = newStmt;
5422 }
5423 }
5424
5425 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
John McCallf4b88a42012-03-10 09:33:50 +00005426 SmallVector<DeclRefExpr *, 8> InnerBlockDeclRefs;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005427 llvm::SmallPtrSet<const DeclContext *, 8> InnerContexts;
5428 InnerContexts.insert(BE->getBlockDecl());
5429 ImportedLocalExternalDecls.clear();
5430 GetInnerBlockDeclRefExprs(BE->getBody(),
5431 InnerBlockDeclRefs, InnerContexts);
5432 // Rewrite the block body in place.
5433 Stmt *SaveCurrentBody = CurrentBody;
5434 CurrentBody = BE->getBody();
5435 PropParentMap = 0;
5436 // block literal on rhs of a property-dot-sytax assignment
5437 // must be replaced by its synthesize ast so getRewrittenText
5438 // works as expected. In this case, what actually ends up on RHS
5439 // is the blockTranscribed which is the helper function for the
5440 // block literal; as in: self.c = ^() {[ace ARR];};
5441 bool saveDisableReplaceStmt = DisableReplaceStmt;
5442 DisableReplaceStmt = false;
5443 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
5444 DisableReplaceStmt = saveDisableReplaceStmt;
5445 CurrentBody = SaveCurrentBody;
5446 PropParentMap = 0;
5447 ImportedLocalExternalDecls.clear();
5448 // Now we snarf the rewritten text and stash it away for later use.
5449 std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
5450 RewrittenBlockExprs[BE] = Str;
5451
5452 Stmt *blockTranscribed = SynthBlockInitExpr(BE, InnerBlockDeclRefs);
5453
5454 //blockTranscribed->dump();
5455 ReplaceStmt(S, blockTranscribed);
5456 return blockTranscribed;
5457 }
5458 // Handle specific things.
5459 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
5460 return RewriteAtEncode(AtEncode);
5461
5462 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
5463 return RewriteAtSelector(AtSelector);
5464
5465 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
5466 return RewriteObjCStringLiteral(AtString);
Fariborz Jahanian55947042012-03-27 20:17:30 +00005467
5468 if (ObjCBoolLiteralExpr *BoolLitExpr = dyn_cast<ObjCBoolLiteralExpr>(S))
5469 return RewriteObjCBoolLiteralExpr(BoolLitExpr);
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00005470
Patrick Beardeb382ec2012-04-19 00:25:12 +00005471 if (ObjCBoxedExpr *BoxedExpr = dyn_cast<ObjCBoxedExpr>(S))
5472 return RewriteObjCBoxedExpr(BoxedExpr);
Fariborz Jahanian86cff602012-03-30 23:35:47 +00005473
5474 if (ObjCArrayLiteral *ArrayLitExpr = dyn_cast<ObjCArrayLiteral>(S))
5475 return RewriteObjCArrayLiteralExpr(ArrayLitExpr);
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00005476
5477 if (ObjCDictionaryLiteral *DictionaryLitExpr =
5478 dyn_cast<ObjCDictionaryLiteral>(S))
5479 return RewriteObjCDictionaryLiteralExpr(DictionaryLitExpr);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005480
5481 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
5482#if 0
5483 // Before we rewrite it, put the original message expression in a comment.
5484 SourceLocation startLoc = MessExpr->getLocStart();
5485 SourceLocation endLoc = MessExpr->getLocEnd();
5486
5487 const char *startBuf = SM->getCharacterData(startLoc);
5488 const char *endBuf = SM->getCharacterData(endLoc);
5489
5490 std::string messString;
5491 messString += "// ";
5492 messString.append(startBuf, endBuf-startBuf+1);
5493 messString += "\n";
5494
5495 // FIXME: Missing definition of
5496 // InsertText(clang::SourceLocation, char const*, unsigned int).
5497 // InsertText(startLoc, messString.c_str(), messString.size());
5498 // Tried this, but it didn't work either...
5499 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
5500#endif
5501 return RewriteMessageExpr(MessExpr);
5502 }
5503
Fariborz Jahanian042b91d2012-05-23 23:47:20 +00005504 if (ObjCAutoreleasePoolStmt *StmtAutoRelease =
5505 dyn_cast<ObjCAutoreleasePoolStmt>(S)) {
5506 return RewriteObjCAutoreleasePoolStmt(StmtAutoRelease);
5507 }
5508
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005509 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
5510 return RewriteObjCTryStmt(StmtTry);
5511
5512 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
5513 return RewriteObjCSynchronizedStmt(StmtTry);
5514
5515 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
5516 return RewriteObjCThrowStmt(StmtThrow);
5517
5518 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
5519 return RewriteObjCProtocolExpr(ProtocolExp);
5520
5521 if (ObjCForCollectionStmt *StmtForCollection =
5522 dyn_cast<ObjCForCollectionStmt>(S))
5523 return RewriteObjCForCollectionStmt(StmtForCollection,
5524 OrigStmtRange.getEnd());
5525 if (BreakStmt *StmtBreakStmt =
5526 dyn_cast<BreakStmt>(S))
5527 return RewriteBreakStmt(StmtBreakStmt);
5528 if (ContinueStmt *StmtContinueStmt =
5529 dyn_cast<ContinueStmt>(S))
5530 return RewriteContinueStmt(StmtContinueStmt);
5531
5532 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
5533 // and cast exprs.
5534 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
5535 // FIXME: What we're doing here is modifying the type-specifier that
5536 // precedes the first Decl. In the future the DeclGroup should have
5537 // a separate type-specifier that we can rewrite.
5538 // NOTE: We need to avoid rewriting the DeclStmt if it is within
5539 // the context of an ObjCForCollectionStmt. For example:
5540 // NSArray *someArray;
5541 // for (id <FooProtocol> index in someArray) ;
5542 // This is because RewriteObjCForCollectionStmt() does textual rewriting
5543 // and it depends on the original text locations/positions.
5544 if (Stmts.empty() || !IsDeclStmtInForeachHeader(DS))
5545 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
5546
5547 // Blocks rewrite rules.
5548 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
5549 DI != DE; ++DI) {
5550 Decl *SD = *DI;
5551 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
5552 if (isTopLevelBlockPointerType(ND->getType()))
5553 RewriteBlockPointerDecl(ND);
5554 else if (ND->getType()->isFunctionPointerType())
5555 CheckFunctionPointerDecl(ND->getType(), ND);
5556 if (VarDecl *VD = dyn_cast<VarDecl>(SD)) {
5557 if (VD->hasAttr<BlocksAttr>()) {
5558 static unsigned uniqueByrefDeclCount = 0;
5559 assert(!BlockByRefDeclNo.count(ND) &&
5560 "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl");
5561 BlockByRefDeclNo[ND] = uniqueByrefDeclCount++;
Fariborz Jahanian4fe261c2012-04-24 19:38:45 +00005562 RewriteByRefVar(VD, (DI == DS->decl_begin()), ((DI+1) == DE));
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005563 }
5564 else
5565 RewriteTypeOfDecl(VD);
5566 }
5567 }
5568 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(SD)) {
5569 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
5570 RewriteBlockPointerDecl(TD);
5571 else if (TD->getUnderlyingType()->isFunctionPointerType())
5572 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5573 }
5574 }
5575 }
5576
5577 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
5578 RewriteObjCQualifiedInterfaceTypes(CE);
5579
5580 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
5581 isa<DoStmt>(S) || isa<ForStmt>(S)) {
5582 assert(!Stmts.empty() && "Statement stack is empty");
5583 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
5584 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
5585 && "Statement stack mismatch");
5586 Stmts.pop_back();
5587 }
5588 // Handle blocks rewriting.
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005589 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
5590 ValueDecl *VD = DRE->getDecl();
5591 if (VD->hasAttr<BlocksAttr>())
5592 return RewriteBlockDeclRefExpr(DRE);
5593 if (HasLocalVariableExternalStorage(VD))
5594 return RewriteLocalVariableExternalStorage(DRE);
5595 }
5596
5597 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
5598 if (CE->getCallee()->getType()->isBlockPointerType()) {
5599 Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
5600 ReplaceStmt(S, BlockCall);
5601 return BlockCall;
5602 }
5603 }
5604 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
5605 RewriteCastExpr(CE);
5606 }
Fariborz Jahanianf1ee6872012-04-10 00:08:18 +00005607 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
5608 RewriteImplicitCastObjCExpr(ICE);
5609 }
Fariborz Jahanian43aa1c32012-04-16 22:14:01 +00005610#if 0
Fariborz Jahanian653b7cf2012-04-13 18:00:54 +00005611
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005612 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
5613 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(),
5614 ICE->getSubExpr(),
5615 SourceLocation());
5616 // Get the new text.
5617 std::string SStr;
5618 llvm::raw_string_ostream Buf(SStr);
Richard Smithd1420c62012-08-16 03:56:14 +00005619 Replacement->printPretty(Buf);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005620 const std::string &Str = Buf.str();
5621
5622 printf("CAST = %s\n", &Str[0]);
5623 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
5624 delete S;
5625 return Replacement;
5626 }
5627#endif
5628 // Return this stmt unmodified.
5629 return S;
5630}
5631
5632void RewriteModernObjC::RewriteRecordBody(RecordDecl *RD) {
5633 for (RecordDecl::field_iterator i = RD->field_begin(),
5634 e = RD->field_end(); i != e; ++i) {
David Blaikie581deb32012-06-06 20:45:41 +00005635 FieldDecl *FD = *i;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005636 if (isTopLevelBlockPointerType(FD->getType()))
5637 RewriteBlockPointerDecl(FD);
5638 if (FD->getType()->isObjCQualifiedIdType() ||
5639 FD->getType()->isObjCQualifiedInterfaceType())
5640 RewriteObjCQualifiedInterfaceTypes(FD);
5641 }
5642}
5643
5644/// HandleDeclInMainFile - This is called for each top-level decl defined in the
5645/// main file of the input.
5646void RewriteModernObjC::HandleDeclInMainFile(Decl *D) {
5647 switch (D->getKind()) {
5648 case Decl::Function: {
5649 FunctionDecl *FD = cast<FunctionDecl>(D);
5650 if (FD->isOverloadedOperator())
5651 return;
5652
5653 // Since function prototypes don't have ParmDecl's, we check the function
5654 // prototype. This enables us to rewrite function declarations and
5655 // definitions using the same code.
5656 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
5657
Argyrios Kyrtzidis9335df32012-02-12 04:48:45 +00005658 if (!FD->isThisDeclarationADefinition())
5659 break;
5660
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005661 // FIXME: If this should support Obj-C++, support CXXTryStmt
5662 if (CompoundStmt *Body = dyn_cast_or_null<CompoundStmt>(FD->getBody())) {
5663 CurFunctionDef = FD;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005664 CurrentBody = Body;
5665 Body =
5666 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5667 FD->setBody(Body);
5668 CurrentBody = 0;
5669 if (PropParentMap) {
5670 delete PropParentMap;
5671 PropParentMap = 0;
5672 }
5673 // This synthesizes and inserts the block "impl" struct, invoke function,
5674 // and any copy/dispose helper functions.
5675 InsertBlockLiteralsWithinFunction(FD);
5676 CurFunctionDef = 0;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005677 }
5678 break;
5679 }
5680 case Decl::ObjCMethod: {
5681 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(D);
5682 if (CompoundStmt *Body = MD->getCompoundBody()) {
5683 CurMethodDef = MD;
5684 CurrentBody = Body;
5685 Body =
5686 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5687 MD->setBody(Body);
5688 CurrentBody = 0;
5689 if (PropParentMap) {
5690 delete PropParentMap;
5691 PropParentMap = 0;
5692 }
5693 InsertBlockLiteralsWithinMethod(MD);
5694 CurMethodDef = 0;
5695 }
5696 break;
5697 }
5698 case Decl::ObjCImplementation: {
5699 ObjCImplementationDecl *CI = cast<ObjCImplementationDecl>(D);
5700 ClassImplementation.push_back(CI);
5701 break;
5702 }
5703 case Decl::ObjCCategoryImpl: {
5704 ObjCCategoryImplDecl *CI = cast<ObjCCategoryImplDecl>(D);
5705 CategoryImplementation.push_back(CI);
5706 break;
5707 }
5708 case Decl::Var: {
5709 VarDecl *VD = cast<VarDecl>(D);
5710 RewriteObjCQualifiedInterfaceTypes(VD);
5711 if (isTopLevelBlockPointerType(VD->getType()))
5712 RewriteBlockPointerDecl(VD);
5713 else if (VD->getType()->isFunctionPointerType()) {
5714 CheckFunctionPointerDecl(VD->getType(), VD);
5715 if (VD->getInit()) {
5716 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
5717 RewriteCastExpr(CE);
5718 }
5719 }
5720 } else if (VD->getType()->isRecordType()) {
5721 RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
5722 if (RD->isCompleteDefinition())
5723 RewriteRecordBody(RD);
5724 }
5725 if (VD->getInit()) {
5726 GlobalVarDecl = VD;
5727 CurrentBody = VD->getInit();
5728 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
5729 CurrentBody = 0;
5730 if (PropParentMap) {
5731 delete PropParentMap;
5732 PropParentMap = 0;
5733 }
5734 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(), VD->getName());
5735 GlobalVarDecl = 0;
5736
5737 // This is needed for blocks.
5738 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
5739 RewriteCastExpr(CE);
5740 }
5741 }
5742 break;
5743 }
5744 case Decl::TypeAlias:
5745 case Decl::Typedef: {
5746 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
5747 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
5748 RewriteBlockPointerDecl(TD);
5749 else if (TD->getUnderlyingType()->isFunctionPointerType())
5750 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5751 }
5752 break;
5753 }
5754 case Decl::CXXRecord:
5755 case Decl::Record: {
5756 RecordDecl *RD = cast<RecordDecl>(D);
5757 if (RD->isCompleteDefinition())
5758 RewriteRecordBody(RD);
5759 break;
5760 }
5761 default:
5762 break;
5763 }
5764 // Nothing yet.
5765}
5766
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00005767/// Write_ProtocolExprReferencedMetadata - This routine writer out the
5768/// protocol reference symbols in the for of:
5769/// struct _protocol_t *PROTOCOL_REF = &PROTOCOL_METADATA.
5770static void Write_ProtocolExprReferencedMetadata(ASTContext *Context,
5771 ObjCProtocolDecl *PDecl,
5772 std::string &Result) {
5773 // Also output .objc_protorefs$B section and its meta-data.
5774 if (Context->getLangOpts().MicrosoftExt)
Fariborz Jahanianbd78cfa2012-04-27 21:39:49 +00005775 Result += "static ";
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00005776 Result += "struct _protocol_t *";
5777 Result += "_OBJC_PROTOCOL_REFERENCE_$_";
5778 Result += PDecl->getNameAsString();
5779 Result += " = &";
5780 Result += "_OBJC_PROTOCOL_"; Result += PDecl->getNameAsString();
5781 Result += ";\n";
5782}
5783
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005784void RewriteModernObjC::HandleTranslationUnit(ASTContext &C) {
5785 if (Diags.hasErrorOccurred())
5786 return;
5787
5788 RewriteInclude();
5789
5790 // Here's a great place to add any extra declarations that may be needed.
5791 // Write out meta data for each @protocol(<expr>).
5792 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00005793 E = ProtocolExprDecls.end(); I != E; ++I) {
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00005794 RewriteObjCProtocolMetaData(*I, Preamble);
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00005795 Write_ProtocolExprReferencedMetadata(Context, (*I), Preamble);
5796 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005797
5798 InsertText(SM->getLocForStartOfFile(MainFileID), Preamble, false);
Fariborz Jahanian163d3ce2012-05-08 23:54:35 +00005799
5800 if (ClassImplementation.size() || CategoryImplementation.size())
5801 RewriteImplementations();
5802
Fariborz Jahanian57317782012-02-21 23:58:41 +00005803 for (unsigned i = 0, e = ObjCInterfacesSeen.size(); i < e; i++) {
5804 ObjCInterfaceDecl *CDecl = ObjCInterfacesSeen[i];
5805 // Write struct declaration for the class matching its ivar declarations.
5806 // Note that for modern abi, this is postponed until the end of TU
5807 // because class extensions and the implementation might declare their own
5808 // private ivars.
5809 RewriteInterfaceDecl(CDecl);
5810 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005811
5812 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
5813 // we are done.
5814 if (const RewriteBuffer *RewriteBuf =
5815 Rewrite.getRewriteBufferFor(MainFileID)) {
5816 //printf("Changed:\n");
5817 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
5818 } else {
5819 llvm::errs() << "No changes\n";
5820 }
5821
5822 if (ClassImplementation.size() || CategoryImplementation.size() ||
5823 ProtocolExprDecls.size()) {
5824 // Rewrite Objective-c meta data*
5825 std::string ResultStr;
5826 RewriteMetaDataIntoBuffer(ResultStr);
5827 // Emit metadata.
5828 *OutFile << ResultStr;
5829 }
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005830 // Emit ImageInfo;
5831 {
5832 std::string ResultStr;
5833 WriteImageInfo(ResultStr);
5834 *OutFile << ResultStr;
5835 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005836 OutFile->flush();
5837}
5838
5839void RewriteModernObjC::Initialize(ASTContext &context) {
5840 InitializeCommon(context);
5841
Fariborz Jahanian6991bc52012-03-10 17:45:38 +00005842 Preamble += "#ifndef __OBJC2__\n";
5843 Preamble += "#define __OBJC2__\n";
5844 Preamble += "#endif\n";
5845
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005846 // declaring objc_selector outside the parameter list removes a silly
5847 // scope related warning...
5848 if (IsHeader)
5849 Preamble = "#pragma once\n";
5850 Preamble += "struct objc_selector; struct objc_class;\n";
Fariborz Jahaniane2d87bc2012-04-12 23:52:52 +00005851 Preamble += "struct __rw_objc_super { \n\tstruct objc_object *object; ";
5852 Preamble += "\n\tstruct objc_object *superClass; ";
5853 // Add a constructor for creating temporary objects.
5854 Preamble += "\n\t__rw_objc_super(struct objc_object *o, struct objc_object *s) ";
5855 Preamble += ": object(o), superClass(s) {} ";
5856 Preamble += "\n};\n";
5857
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005858 if (LangOpts.MicrosoftExt) {
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00005859 // Define all sections using syntax that makes sense.
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005860 // These are currently generated.
5861 Preamble += "\n#pragma section(\".objc_classlist$B\", long, read, write)\n";
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00005862 Preamble += "#pragma section(\".objc_catlist$B\", long, read, write)\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005863 Preamble += "#pragma section(\".objc_imageinfo$B\", long, read, write)\n";
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00005864 Preamble += "#pragma section(\".objc_nlclslist$B\", long, read, write)\n";
5865 Preamble += "#pragma section(\".objc_nlcatlist$B\", long, read, write)\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005866 // These are generated but not necessary for functionality.
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005867 Preamble += "#pragma section(\".cat_cls_meth$B\", long, read, write)\n";
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00005868 Preamble += "#pragma section(\".inst_meth$B\", long, read, write)\n";
5869 Preamble += "#pragma section(\".cls_meth$B\", long, read, write)\n";
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00005870 Preamble += "#pragma section(\".objc_ivar$B\", long, read, write)\n";
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00005871
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00005872 // These need be generated for performance. Currently they are not,
5873 // using API calls instead.
5874 Preamble += "#pragma section(\".objc_selrefs$B\", long, read, write)\n";
5875 Preamble += "#pragma section(\".objc_classrefs$B\", long, read, write)\n";
5876 Preamble += "#pragma section(\".objc_superrefs$B\", long, read, write)\n";
5877
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005878 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005879 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
5880 Preamble += "typedef struct objc_object Protocol;\n";
5881 Preamble += "#define _REWRITER_typedef_Protocol\n";
5882 Preamble += "#endif\n";
5883 if (LangOpts.MicrosoftExt) {
5884 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
5885 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
Fariborz Jahanian5cf6b6c2012-03-21 23:41:04 +00005886 }
5887 else
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005888 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
Fariborz Jahanian5cf6b6c2012-03-21 23:41:04 +00005889
5890 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend(void);\n";
5891 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSendSuper(void);\n";
5892 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend_stret(void);\n";
5893 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSendSuper_stret(void);\n";
5894 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend_fpret(void);\n";
5895
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00005896 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *objc_getClass";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005897 Preamble += "(const char *);\n";
5898 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *class_getSuperclass";
5899 Preamble += "(struct objc_class *);\n";
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00005900 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *objc_getMetaClass";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005901 Preamble += "(const char *);\n";
Fariborz Jahanian55261af2012-03-19 18:11:32 +00005902 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw( struct objc_object *);\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005903 // @synchronized hooks.
Fariborz Jahanian55261af2012-03-19 18:11:32 +00005904 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_enter( struct objc_object *);\n";
5905 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_exit( struct objc_object *);\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005906 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
5907 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
5908 Preamble += "struct __objcFastEnumerationState {\n\t";
5909 Preamble += "unsigned long state;\n\t";
5910 Preamble += "void **itemsPtr;\n\t";
5911 Preamble += "unsigned long *mutationsPtr;\n\t";
5912 Preamble += "unsigned long extra[5];\n};\n";
5913 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
5914 Preamble += "#define __FASTENUMERATIONSTATE\n";
5915 Preamble += "#endif\n";
5916 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
5917 Preamble += "struct __NSConstantStringImpl {\n";
5918 Preamble += " int *isa;\n";
5919 Preamble += " int flags;\n";
5920 Preamble += " char *str;\n";
5921 Preamble += " long length;\n";
5922 Preamble += "};\n";
5923 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
5924 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
5925 Preamble += "#else\n";
5926 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
5927 Preamble += "#endif\n";
5928 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
5929 Preamble += "#endif\n";
5930 // Blocks preamble.
5931 Preamble += "#ifndef BLOCK_IMPL\n";
5932 Preamble += "#define BLOCK_IMPL\n";
5933 Preamble += "struct __block_impl {\n";
5934 Preamble += " void *isa;\n";
5935 Preamble += " int Flags;\n";
5936 Preamble += " int Reserved;\n";
5937 Preamble += " void *FuncPtr;\n";
5938 Preamble += "};\n";
5939 Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
5940 Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n";
5941 Preamble += "extern \"C\" __declspec(dllexport) "
5942 "void _Block_object_assign(void *, const void *, const int);\n";
5943 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
5944 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
5945 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
5946 Preamble += "#else\n";
5947 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n";
5948 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n";
5949 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
5950 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
5951 Preamble += "#endif\n";
5952 Preamble += "#endif\n";
5953 if (LangOpts.MicrosoftExt) {
5954 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
5955 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
5956 Preamble += "#ifndef KEEP_ATTRIBUTES\n"; // We use this for clang tests.
5957 Preamble += "#define __attribute__(X)\n";
5958 Preamble += "#endif\n";
Fariborz Jahanian5ce28272012-04-12 16:33:31 +00005959 Preamble += "#ifndef __weak\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005960 Preamble += "#define __weak\n";
Fariborz Jahanian5ce28272012-04-12 16:33:31 +00005961 Preamble += "#endif\n";
5962 Preamble += "#ifndef __block\n";
5963 Preamble += "#define __block\n";
5964 Preamble += "#endif\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005965 }
5966 else {
5967 Preamble += "#define __block\n";
5968 Preamble += "#define __weak\n";
5969 }
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +00005970
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00005971 // Declarations required for modern objective-c array and dictionary literals.
5972 Preamble += "\n#include <stdarg.h>\n";
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00005973 Preamble += "struct __NSContainer_literal {\n";
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00005974 Preamble += " void * *arr;\n";
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00005975 Preamble += " __NSContainer_literal (unsigned int count, ...) {\n";
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00005976 Preamble += "\tva_list marker;\n";
5977 Preamble += "\tva_start(marker, count);\n";
5978 Preamble += "\tarr = new void *[count];\n";
5979 Preamble += "\tfor (unsigned i = 0; i < count; i++)\n";
5980 Preamble += "\t arr[i] = va_arg(marker, void *);\n";
5981 Preamble += "\tva_end( marker );\n";
5982 Preamble += " };\n";
Fariborz Jahanian13a9c022012-05-02 23:53:46 +00005983 Preamble += " ~__NSContainer_literal() {\n";
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00005984 Preamble += "\tdelete[] arr;\n";
5985 Preamble += " }\n";
5986 Preamble += "};\n";
5987
Fariborz Jahanian042b91d2012-05-23 23:47:20 +00005988 // Declaration required for implementation of @autoreleasepool statement.
5989 Preamble += "extern \"C\" __declspec(dllimport) void * objc_autoreleasePoolPush(void);\n";
5990 Preamble += "extern \"C\" __declspec(dllimport) void objc_autoreleasePoolPop(void *);\n\n";
5991 Preamble += "struct __AtAutoreleasePool {\n";
5992 Preamble += " __AtAutoreleasePool() {atautoreleasepoolobj = objc_autoreleasePoolPush();}\n";
5993 Preamble += " ~__AtAutoreleasePool() {objc_autoreleasePoolPop(atautoreleasepoolobj);}\n";
5994 Preamble += " void * atautoreleasepoolobj;\n";
5995 Preamble += "};\n";
5996
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005997 // NOTE! Windows uses LLP64 for 64bit mode. So, cast pointer to long long
5998 // as this avoids warning in any 64bit/32bit compilation model.
5999 Preamble += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long long) &((TYPE *)0)->MEMBER)\n";
6000}
6001
6002/// RewriteIvarOffsetComputation - This rutine synthesizes computation of
6003/// ivar offset.
6004void RewriteModernObjC::RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
6005 std::string &Result) {
6006 if (ivar->isBitField()) {
6007 // FIXME: The hack below doesn't work for bitfields. For now, we simply
6008 // place all bitfields at offset 0.
6009 Result += "0";
6010 } else {
6011 Result += "__OFFSETOFIVAR__(struct ";
6012 Result += ivar->getContainingInterface()->getNameAsString();
6013 if (LangOpts.MicrosoftExt)
6014 Result += "_IMPL";
6015 Result += ", ";
6016 Result += ivar->getNameAsString();
6017 Result += ")";
6018 }
6019}
6020
6021/// WriteModernMetadataDeclarations - Writes out metadata declarations for modern ABI.
6022/// struct _prop_t {
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006023/// const char *name;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006024/// char *attributes;
6025/// }
6026
6027/// struct _prop_list_t {
6028/// uint32_t entsize; // sizeof(struct _prop_t)
6029/// uint32_t count_of_properties;
6030/// struct _prop_t prop_list[count_of_properties];
6031/// }
6032
6033/// struct _protocol_t;
6034
6035/// struct _protocol_list_t {
6036/// long protocol_count; // Note, this is 32/64 bit
6037/// struct _protocol_t * protocol_list[protocol_count];
6038/// }
6039
6040/// struct _objc_method {
6041/// SEL _cmd;
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006042/// const char *method_type;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006043/// char *_imp;
6044/// }
6045
6046/// struct _method_list_t {
6047/// uint32_t entsize; // sizeof(struct _objc_method)
6048/// uint32_t method_count;
6049/// struct _objc_method method_list[method_count];
6050/// }
6051
6052/// struct _protocol_t {
6053/// id isa; // NULL
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006054/// const char *protocol_name;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006055/// const struct _protocol_list_t * protocol_list; // super protocols
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006056/// const struct method_list_t *instance_methods;
6057/// const struct method_list_t *class_methods;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006058/// const struct method_list_t *optionalInstanceMethods;
6059/// const struct method_list_t *optionalClassMethods;
6060/// const struct _prop_list_t * properties;
6061/// const uint32_t size; // sizeof(struct _protocol_t)
6062/// const uint32_t flags; // = 0
6063/// const char ** extendedMethodTypes;
6064/// }
6065
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006066/// struct _ivar_t {
6067/// unsigned long int *offset; // pointer to ivar offset location
Fariborz Jahanianae932952012-02-10 20:47:10 +00006068/// const char *name;
6069/// const char *type;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006070/// uint32_t alignment;
6071/// uint32_t size;
6072/// }
6073
6074/// struct _ivar_list_t {
6075/// uint32 entsize; // sizeof(struct _ivar_t)
6076/// uint32 count;
Fariborz Jahanianae932952012-02-10 20:47:10 +00006077/// struct _ivar_t list[count];
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006078/// }
6079
6080/// struct _class_ro_t {
Fariborz Jahanian249cd102012-03-24 16:53:16 +00006081/// uint32_t flags;
6082/// uint32_t instanceStart;
6083/// uint32_t instanceSize;
6084/// uint32_t reserved; // only when building for 64bit targets
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006085/// const uint8_t *ivarLayout;
6086/// const char *name;
6087/// const struct _method_list_t *baseMethods;
6088/// const struct _protocol_list_t *baseProtocols;
6089/// const struct _ivar_list_t *ivars;
6090/// const uint8_t *weakIvarLayout;
6091/// const struct _prop_list_t *properties;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006092/// }
6093
6094/// struct _class_t {
6095/// struct _class_t *isa;
Fariborz Jahanianfd4ce2c2012-03-20 17:34:50 +00006096/// struct _class_t *superclass;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006097/// void *cache;
6098/// IMP *vtable;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006099/// struct _class_ro_t *ro;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006100/// }
6101
6102/// struct _category_t {
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006103/// const char *name;
Fariborz Jahanian4b2fe6e2012-03-20 21:41:28 +00006104/// struct _class_t *cls;
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006105/// const struct _method_list_t *instance_methods;
6106/// const struct _method_list_t *class_methods;
6107/// const struct _protocol_list_t *protocols;
6108/// const struct _prop_list_t *properties;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006109/// }
6110
6111/// MessageRefTy - LLVM for:
6112/// struct _message_ref_t {
6113/// IMP messenger;
6114/// SEL name;
6115/// };
6116
6117/// SuperMessageRefTy - LLVM for:
6118/// struct _super_message_ref_t {
6119/// SUPER_IMP messenger;
6120/// SEL name;
6121/// };
6122
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00006123static void WriteModernMetadataDeclarations(ASTContext *Context, std::string &Result) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006124 static bool meta_data_declared = false;
6125 if (meta_data_declared)
6126 return;
6127
6128 Result += "\nstruct _prop_t {\n";
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006129 Result += "\tconst char *name;\n";
6130 Result += "\tconst char *attributes;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006131 Result += "};\n";
6132
6133 Result += "\nstruct _protocol_t;\n";
6134
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006135 Result += "\nstruct _objc_method {\n";
6136 Result += "\tstruct objc_selector * _cmd;\n";
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006137 Result += "\tconst char *method_type;\n";
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006138 Result += "\tvoid *_imp;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006139 Result += "};\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006140
6141 Result += "\nstruct _protocol_t {\n";
6142 Result += "\tvoid * isa; // NULL\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006143 Result += "\tconst char *protocol_name;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006144 Result += "\tconst struct _protocol_list_t * protocol_list; // super protocols\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006145 Result += "\tconst struct method_list_t *instance_methods;\n";
6146 Result += "\tconst struct method_list_t *class_methods;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006147 Result += "\tconst struct method_list_t *optionalInstanceMethods;\n";
6148 Result += "\tconst struct method_list_t *optionalClassMethods;\n";
6149 Result += "\tconst struct _prop_list_t * properties;\n";
6150 Result += "\tconst unsigned int size; // sizeof(struct _protocol_t)\n";
6151 Result += "\tconst unsigned int flags; // = 0\n";
6152 Result += "\tconst char ** extendedMethodTypes;\n";
6153 Result += "};\n";
6154
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006155 Result += "\nstruct _ivar_t {\n";
6156 Result += "\tunsigned long int *offset; // pointer to ivar offset location\n";
Fariborz Jahanianae932952012-02-10 20:47:10 +00006157 Result += "\tconst char *name;\n";
6158 Result += "\tconst char *type;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006159 Result += "\tunsigned int alignment;\n";
6160 Result += "\tunsigned int size;\n";
6161 Result += "};\n";
6162
6163 Result += "\nstruct _class_ro_t {\n";
Fariborz Jahanian249cd102012-03-24 16:53:16 +00006164 Result += "\tunsigned int flags;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006165 Result += "\tunsigned int instanceStart;\n";
Fariborz Jahanian249cd102012-03-24 16:53:16 +00006166 Result += "\tunsigned int instanceSize;\n";
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00006167 const llvm::Triple &Triple(Context->getTargetInfo().getTriple());
6168 if (Triple.getArch() == llvm::Triple::x86_64)
Fariborz Jahanian249cd102012-03-24 16:53:16 +00006169 Result += "\tunsigned int reserved;\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006170 Result += "\tconst unsigned char *ivarLayout;\n";
6171 Result += "\tconst char *name;\n";
6172 Result += "\tconst struct _method_list_t *baseMethods;\n";
6173 Result += "\tconst struct _objc_protocol_list *baseProtocols;\n";
6174 Result += "\tconst struct _ivar_list_t *ivars;\n";
6175 Result += "\tconst unsigned char *weakIvarLayout;\n";
6176 Result += "\tconst struct _prop_list_t *properties;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006177 Result += "};\n";
6178
6179 Result += "\nstruct _class_t {\n";
6180 Result += "\tstruct _class_t *isa;\n";
Fariborz Jahanianfd4ce2c2012-03-20 17:34:50 +00006181 Result += "\tstruct _class_t *superclass;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006182 Result += "\tvoid *cache;\n";
6183 Result += "\tvoid *vtable;\n";
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006184 Result += "\tstruct _class_ro_t *ro;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006185 Result += "};\n";
6186
6187 Result += "\nstruct _category_t {\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006188 Result += "\tconst char *name;\n";
Fariborz Jahanian4b2fe6e2012-03-20 21:41:28 +00006189 Result += "\tstruct _class_t *cls;\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006190 Result += "\tconst struct _method_list_t *instance_methods;\n";
6191 Result += "\tconst struct _method_list_t *class_methods;\n";
6192 Result += "\tconst struct _protocol_list_t *protocols;\n";
6193 Result += "\tconst struct _prop_list_t *properties;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006194 Result += "};\n";
6195
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006196 Result += "extern \"C\" __declspec(dllimport) struct objc_cache _objc_empty_cache;\n";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006197 Result += "#pragma warning(disable:4273)\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006198 meta_data_declared = true;
6199}
6200
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006201static void Write_protocol_list_t_TypeDecl(std::string &Result,
6202 long super_protocol_count) {
6203 Result += "struct /*_protocol_list_t*/"; Result += " {\n";
6204 Result += "\tlong protocol_count; // Note, this is 32/64 bit\n";
6205 Result += "\tstruct _protocol_t *super_protocols[";
6206 Result += utostr(super_protocol_count); Result += "];\n";
6207 Result += "}";
6208}
6209
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006210static void Write_method_list_t_TypeDecl(std::string &Result,
6211 unsigned int method_count) {
6212 Result += "struct /*_method_list_t*/"; Result += " {\n";
6213 Result += "\tunsigned int entsize; // sizeof(struct _objc_method)\n";
6214 Result += "\tunsigned int method_count;\n";
6215 Result += "\tstruct _objc_method method_list[";
6216 Result += utostr(method_count); Result += "];\n";
6217 Result += "}";
6218}
6219
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006220static void Write__prop_list_t_TypeDecl(std::string &Result,
6221 unsigned int property_count) {
6222 Result += "struct /*_prop_list_t*/"; Result += " {\n";
6223 Result += "\tunsigned int entsize; // sizeof(struct _prop_t)\n";
6224 Result += "\tunsigned int count_of_properties;\n";
6225 Result += "\tstruct _prop_t prop_list[";
6226 Result += utostr(property_count); Result += "];\n";
6227 Result += "}";
6228}
6229
Fariborz Jahanianae932952012-02-10 20:47:10 +00006230static void Write__ivar_list_t_TypeDecl(std::string &Result,
6231 unsigned int ivar_count) {
6232 Result += "struct /*_ivar_list_t*/"; Result += " {\n";
6233 Result += "\tunsigned int entsize; // sizeof(struct _prop_t)\n";
6234 Result += "\tunsigned int count;\n";
6235 Result += "\tstruct _ivar_t ivar_list[";
6236 Result += utostr(ivar_count); Result += "];\n";
6237 Result += "}";
6238}
6239
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006240static void Write_protocol_list_initializer(ASTContext *Context, std::string &Result,
6241 ArrayRef<ObjCProtocolDecl *> SuperProtocols,
6242 StringRef VarName,
6243 StringRef ProtocolName) {
6244 if (SuperProtocols.size() > 0) {
6245 Result += "\nstatic ";
6246 Write_protocol_list_t_TypeDecl(Result, SuperProtocols.size());
6247 Result += " "; Result += VarName;
6248 Result += ProtocolName;
6249 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6250 Result += "\t"; Result += utostr(SuperProtocols.size()); Result += ",\n";
6251 for (unsigned i = 0, e = SuperProtocols.size(); i < e; i++) {
6252 ObjCProtocolDecl *SuperPD = SuperProtocols[i];
6253 Result += "\t&"; Result += "_OBJC_PROTOCOL_";
6254 Result += SuperPD->getNameAsString();
6255 if (i == e-1)
6256 Result += "\n};\n";
6257 else
6258 Result += ",\n";
6259 }
6260 }
6261}
6262
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006263static void Write_method_list_t_initializer(RewriteModernObjC &RewriteObj,
6264 ASTContext *Context, std::string &Result,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006265 ArrayRef<ObjCMethodDecl *> Methods,
6266 StringRef VarName,
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006267 StringRef TopLevelDeclName,
6268 bool MethodImpl) {
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006269 if (Methods.size() > 0) {
6270 Result += "\nstatic ";
6271 Write_method_list_t_TypeDecl(Result, Methods.size());
6272 Result += " "; Result += VarName;
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006273 Result += TopLevelDeclName;
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006274 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6275 Result += "\t"; Result += "sizeof(_objc_method)"; Result += ",\n";
6276 Result += "\t"; Result += utostr(Methods.size()); Result += ",\n";
6277 for (unsigned i = 0, e = Methods.size(); i < e; i++) {
6278 ObjCMethodDecl *MD = Methods[i];
6279 if (i == 0)
6280 Result += "\t{{(struct objc_selector *)\"";
6281 else
6282 Result += "\t{(struct objc_selector *)\"";
6283 Result += (MD)->getSelector().getAsString(); Result += "\"";
6284 Result += ", ";
6285 std::string MethodTypeString;
6286 Context->getObjCEncodingForMethodDecl(MD, MethodTypeString);
6287 Result += "\""; Result += MethodTypeString; Result += "\"";
6288 Result += ", ";
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006289 if (!MethodImpl)
6290 Result += "0";
6291 else {
6292 Result += "(void *)";
6293 Result += RewriteObj.MethodInternalNames[MD];
6294 }
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006295 if (i == e-1)
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006296 Result += "}}\n";
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006297 else
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006298 Result += "},\n";
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006299 }
6300 Result += "};\n";
6301 }
6302}
6303
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006304static void Write_prop_list_t_initializer(RewriteModernObjC &RewriteObj,
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006305 ASTContext *Context, std::string &Result,
6306 ArrayRef<ObjCPropertyDecl *> Properties,
6307 const Decl *Container,
6308 StringRef VarName,
6309 StringRef ProtocolName) {
6310 if (Properties.size() > 0) {
6311 Result += "\nstatic ";
6312 Write__prop_list_t_TypeDecl(Result, Properties.size());
6313 Result += " "; Result += VarName;
6314 Result += ProtocolName;
6315 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6316 Result += "\t"; Result += "sizeof(_prop_t)"; Result += ",\n";
6317 Result += "\t"; Result += utostr(Properties.size()); Result += ",\n";
6318 for (unsigned i = 0, e = Properties.size(); i < e; i++) {
6319 ObjCPropertyDecl *PropDecl = Properties[i];
6320 if (i == 0)
6321 Result += "\t{{\"";
6322 else
6323 Result += "\t{\"";
6324 Result += PropDecl->getName(); Result += "\",";
6325 std::string PropertyTypeString, QuotePropertyTypeString;
6326 Context->getObjCEncodingForPropertyDecl(PropDecl, Container, PropertyTypeString);
6327 RewriteObj.QuoteDoublequotes(PropertyTypeString, QuotePropertyTypeString);
6328 Result += "\""; Result += QuotePropertyTypeString; Result += "\"";
6329 if (i == e-1)
6330 Result += "}}\n";
6331 else
6332 Result += "},\n";
6333 }
6334 Result += "};\n";
6335 }
6336}
6337
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006338// Metadata flags
6339enum MetaDataDlags {
6340 CLS = 0x0,
6341 CLS_META = 0x1,
6342 CLS_ROOT = 0x2,
6343 OBJC2_CLS_HIDDEN = 0x10,
6344 CLS_EXCEPTION = 0x20,
6345
6346 /// (Obsolete) ARC-specific: this class has a .release_ivars method
6347 CLS_HAS_IVAR_RELEASER = 0x40,
6348 /// class was compiled with -fobjc-arr
6349 CLS_COMPILED_BY_ARC = 0x80 // (1<<7)
6350};
6351
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006352static void Write__class_ro_t_initializer(ASTContext *Context, std::string &Result,
6353 unsigned int flags,
6354 const std::string &InstanceStart,
6355 const std::string &InstanceSize,
6356 ArrayRef<ObjCMethodDecl *>baseMethods,
6357 ArrayRef<ObjCProtocolDecl *>baseProtocols,
6358 ArrayRef<ObjCIvarDecl *>ivars,
6359 ArrayRef<ObjCPropertyDecl *>Properties,
6360 StringRef VarName,
6361 StringRef ClassName) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006362 Result += "\nstatic struct _class_ro_t ";
6363 Result += VarName; Result += ClassName;
6364 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6365 Result += "\t";
6366 Result += llvm::utostr(flags); Result += ", ";
6367 Result += InstanceStart; Result += ", ";
6368 Result += InstanceSize; Result += ", \n";
6369 Result += "\t";
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00006370 const llvm::Triple &Triple(Context->getTargetInfo().getTriple());
6371 if (Triple.getArch() == llvm::Triple::x86_64)
6372 // uint32_t const reserved; // only when building for 64bit targets
6373 Result += "(unsigned int)0, \n\t";
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006374 // const uint8_t * const ivarLayout;
6375 Result += "0, \n\t";
6376 Result += "\""; Result += ClassName; Result += "\",\n\t";
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006377 bool metaclass = ((flags & CLS_META) != 0);
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006378 if (baseMethods.size() > 0) {
6379 Result += "(const struct _method_list_t *)&";
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006380 if (metaclass)
6381 Result += "_OBJC_$_CLASS_METHODS_";
6382 else
6383 Result += "_OBJC_$_INSTANCE_METHODS_";
6384 Result += ClassName;
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006385 Result += ",\n\t";
6386 }
6387 else
6388 Result += "0, \n\t";
6389
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006390 if (!metaclass && baseProtocols.size() > 0) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006391 Result += "(const struct _objc_protocol_list *)&";
6392 Result += "_OBJC_CLASS_PROTOCOLS_$_"; Result += ClassName;
6393 Result += ",\n\t";
6394 }
6395 else
6396 Result += "0, \n\t";
6397
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006398 if (!metaclass && ivars.size() > 0) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006399 Result += "(const struct _ivar_list_t *)&";
6400 Result += "_OBJC_$_INSTANCE_VARIABLES_"; Result += ClassName;
6401 Result += ",\n\t";
6402 }
6403 else
6404 Result += "0, \n\t";
6405
6406 // weakIvarLayout
6407 Result += "0, \n\t";
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006408 if (!metaclass && Properties.size() > 0) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006409 Result += "(const struct _prop_list_t *)&";
Fariborz Jahanianeeabf382012-02-16 21:57:59 +00006410 Result += "_OBJC_$_PROP_LIST_"; Result += ClassName;
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006411 Result += ",\n";
6412 }
6413 else
6414 Result += "0, \n";
6415
6416 Result += "};\n";
6417}
6418
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006419static void Write_class_t(ASTContext *Context, std::string &Result,
6420 StringRef VarName,
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006421 const ObjCInterfaceDecl *CDecl, bool metaclass) {
6422 bool rootClass = (!CDecl->getSuperClass());
6423 const ObjCInterfaceDecl *RootClass = CDecl;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006424
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006425 if (!rootClass) {
6426 // Find the Root class
6427 RootClass = CDecl->getSuperClass();
6428 while (RootClass->getSuperClass()) {
6429 RootClass = RootClass->getSuperClass();
6430 }
6431 }
6432
6433 if (metaclass && rootClass) {
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006434 // Need to handle a case of use of forward declaration.
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00006435 Result += "\n";
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006436 Result += "extern \"C\" ";
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00006437 if (CDecl->getImplementation())
6438 Result += "__declspec(dllexport) ";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006439 else
6440 Result += "__declspec(dllimport) ";
6441
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006442 Result += "struct _class_t OBJC_CLASS_$_";
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006443 Result += CDecl->getNameAsString();
6444 Result += ";\n";
6445 }
6446 // Also, for possibility of 'super' metadata class not having been defined yet.
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006447 if (!rootClass) {
Fariborz Jahanian868e9852012-03-29 19:04:10 +00006448 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00006449 Result += "\n";
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006450 Result += "extern \"C\" ";
Fariborz Jahanian868e9852012-03-29 19:04:10 +00006451 if (SuperClass->getImplementation())
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00006452 Result += "__declspec(dllexport) ";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006453 else
6454 Result += "__declspec(dllimport) ";
6455
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006456 Result += "struct _class_t ";
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00006457 Result += VarName;
Fariborz Jahanian868e9852012-03-29 19:04:10 +00006458 Result += SuperClass->getNameAsString();
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006459 Result += ";\n";
Fariborz Jahanian452eac12012-03-20 21:09:58 +00006460
Fariborz Jahanian868e9852012-03-29 19:04:10 +00006461 if (metaclass && RootClass != SuperClass) {
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006462 Result += "extern \"C\" ";
Fariborz Jahanian452eac12012-03-20 21:09:58 +00006463 if (RootClass->getImplementation())
6464 Result += "__declspec(dllexport) ";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006465 else
6466 Result += "__declspec(dllimport) ";
6467
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006468 Result += "struct _class_t ";
Fariborz Jahanian452eac12012-03-20 21:09:58 +00006469 Result += VarName;
6470 Result += RootClass->getNameAsString();
6471 Result += ";\n";
6472 }
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006473 }
6474
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006475 Result += "\nextern \"C\" __declspec(dllexport) struct _class_t ";
6476 Result += VarName; Result += CDecl->getNameAsString();
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006477 Result += " __attribute__ ((used, section (\"__DATA,__objc_data\"))) = {\n";
6478 Result += "\t";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006479 if (metaclass) {
6480 if (!rootClass) {
6481 Result += "0, // &"; Result += VarName;
6482 Result += RootClass->getNameAsString();
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006483 Result += ",\n\t";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006484 Result += "0, // &"; Result += VarName;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006485 Result += CDecl->getSuperClass()->getNameAsString();
6486 Result += ",\n\t";
6487 }
6488 else {
Fariborz Jahanian452eac12012-03-20 21:09:58 +00006489 Result += "0, // &"; Result += VarName;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006490 Result += CDecl->getNameAsString();
6491 Result += ",\n\t";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006492 Result += "0, // &OBJC_CLASS_$_"; Result += CDecl->getNameAsString();
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006493 Result += ",\n\t";
6494 }
6495 }
6496 else {
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006497 Result += "0, // &OBJC_METACLASS_$_";
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006498 Result += CDecl->getNameAsString();
6499 Result += ",\n\t";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006500 if (!rootClass) {
6501 Result += "0, // &"; Result += VarName;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006502 Result += CDecl->getSuperClass()->getNameAsString();
6503 Result += ",\n\t";
6504 }
6505 else
6506 Result += "0,\n\t";
6507 }
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006508 Result += "0, // (void *)&_objc_empty_cache,\n\t";
6509 Result += "0, // unused, was (void *)&_objc_empty_vtable,\n\t";
6510 if (metaclass)
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006511 Result += "&_OBJC_METACLASS_RO_$_";
6512 else
6513 Result += "&_OBJC_CLASS_RO_$_";
6514 Result += CDecl->getNameAsString();
6515 Result += ",\n};\n";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006516
6517 // Add static function to initialize some of the meta-data fields.
6518 // avoid doing it twice.
6519 if (metaclass)
6520 return;
6521
6522 const ObjCInterfaceDecl *SuperClass =
6523 rootClass ? CDecl : CDecl->getSuperClass();
6524
6525 Result += "static void OBJC_CLASS_SETUP_$_";
6526 Result += CDecl->getNameAsString();
6527 Result += "(void ) {\n";
6528 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
6529 Result += ".isa = "; Result += "&OBJC_METACLASS_$_";
Fariborz Jahanian452eac12012-03-20 21:09:58 +00006530 Result += RootClass->getNameAsString(); Result += ";\n";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006531
6532 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
Fariborz Jahanian452eac12012-03-20 21:09:58 +00006533 Result += ".superclass = ";
6534 if (rootClass)
6535 Result += "&OBJC_CLASS_$_";
6536 else
6537 Result += "&OBJC_METACLASS_$_";
6538
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006539 Result += SuperClass->getNameAsString(); Result += ";\n";
6540
6541 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
6542 Result += ".cache = "; Result += "&_objc_empty_cache"; Result += ";\n";
6543
6544 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6545 Result += ".isa = "; Result += "&OBJC_METACLASS_$_";
6546 Result += CDecl->getNameAsString(); Result += ";\n";
6547
6548 if (!rootClass) {
6549 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6550 Result += ".superclass = "; Result += "&OBJC_CLASS_$_";
6551 Result += SuperClass->getNameAsString(); Result += ";\n";
6552 }
6553
6554 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6555 Result += ".cache = "; Result += "&_objc_empty_cache"; Result += ";\n";
6556 Result += "}\n";
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006557}
6558
Fariborz Jahanian61186122012-02-17 18:40:41 +00006559static void Write_category_t(RewriteModernObjC &RewriteObj, ASTContext *Context,
6560 std::string &Result,
Fariborz Jahaniane0335782012-03-27 18:41:05 +00006561 ObjCCategoryDecl *CatDecl,
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006562 ObjCInterfaceDecl *ClassDecl,
Fariborz Jahanian61186122012-02-17 18:40:41 +00006563 ArrayRef<ObjCMethodDecl *> InstanceMethods,
6564 ArrayRef<ObjCMethodDecl *> ClassMethods,
6565 ArrayRef<ObjCProtocolDecl *> RefedProtocols,
6566 ArrayRef<ObjCPropertyDecl *> ClassProperties) {
Fariborz Jahaniane0335782012-03-27 18:41:05 +00006567 StringRef CatName = CatDecl->getName();
NAKAMURA Takumi20f89392012-03-21 03:21:46 +00006568 StringRef ClassName = ClassDecl->getName();
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00006569 // must declare an extern class object in case this class is not implemented
6570 // in this TU.
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006571 Result += "\n";
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006572 Result += "extern \"C\" ";
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006573 if (ClassDecl->getImplementation())
6574 Result += "__declspec(dllexport) ";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006575 else
6576 Result += "__declspec(dllimport) ";
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006577
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006578 Result += "struct _class_t ";
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00006579 Result += "OBJC_CLASS_$_"; Result += ClassName;
6580 Result += ";\n";
6581
Fariborz Jahanian61186122012-02-17 18:40:41 +00006582 Result += "\nstatic struct _category_t ";
6583 Result += "_OBJC_$_CATEGORY_";
6584 Result += ClassName; Result += "_$_"; Result += CatName;
6585 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = \n";
6586 Result += "{\n";
6587 Result += "\t\""; Result += ClassName; Result += "\",\n";
Fariborz Jahanian4b2fe6e2012-03-20 21:41:28 +00006588 Result += "\t0, // &"; Result += "OBJC_CLASS_$_"; Result += ClassName;
Fariborz Jahanian61186122012-02-17 18:40:41 +00006589 Result += ",\n";
6590 if (InstanceMethods.size() > 0) {
6591 Result += "\t(const struct _method_list_t *)&";
6592 Result += "_OBJC_$_CATEGORY_INSTANCE_METHODS_";
6593 Result += ClassName; Result += "_$_"; Result += CatName;
6594 Result += ",\n";
6595 }
6596 else
6597 Result += "\t0,\n";
6598
6599 if (ClassMethods.size() > 0) {
6600 Result += "\t(const struct _method_list_t *)&";
6601 Result += "_OBJC_$_CATEGORY_CLASS_METHODS_";
6602 Result += ClassName; Result += "_$_"; Result += CatName;
6603 Result += ",\n";
6604 }
6605 else
6606 Result += "\t0,\n";
6607
6608 if (RefedProtocols.size() > 0) {
6609 Result += "\t(const struct _protocol_list_t *)&";
6610 Result += "_OBJC_CATEGORY_PROTOCOLS_$_";
6611 Result += ClassName; Result += "_$_"; Result += CatName;
6612 Result += ",\n";
6613 }
6614 else
6615 Result += "\t0,\n";
6616
6617 if (ClassProperties.size() > 0) {
6618 Result += "\t(const struct _prop_list_t *)&"; Result += "_OBJC_$_PROP_LIST_";
6619 Result += ClassName; Result += "_$_"; Result += CatName;
6620 Result += ",\n";
6621 }
6622 else
6623 Result += "\t0,\n";
6624
6625 Result += "};\n";
Fariborz Jahanian4b2fe6e2012-03-20 21:41:28 +00006626
6627 // Add static function to initialize the class pointer in the category structure.
6628 Result += "static void OBJC_CATEGORY_SETUP_$_";
6629 Result += ClassDecl->getNameAsString();
6630 Result += "_$_";
6631 Result += CatName;
6632 Result += "(void ) {\n";
6633 Result += "\t_OBJC_$_CATEGORY_";
6634 Result += ClassDecl->getNameAsString();
6635 Result += "_$_";
6636 Result += CatName;
6637 Result += ".cls = "; Result += "&OBJC_CLASS_$_"; Result += ClassName;
6638 Result += ";\n}\n";
Fariborz Jahanian61186122012-02-17 18:40:41 +00006639}
6640
Fariborz Jahaniane0adbd82012-02-08 22:23:26 +00006641static void Write__extendedMethodTypes_initializer(RewriteModernObjC &RewriteObj,
6642 ASTContext *Context, std::string &Result,
6643 ArrayRef<ObjCMethodDecl *> Methods,
6644 StringRef VarName,
6645 StringRef ProtocolName) {
6646 if (Methods.size() == 0)
6647 return;
6648
6649 Result += "\nstatic const char *";
6650 Result += VarName; Result += ProtocolName;
6651 Result += " [] __attribute__ ((used, section (\"__DATA,__objc_const\"))) = \n";
6652 Result += "{\n";
6653 for (unsigned i = 0, e = Methods.size(); i < e; i++) {
6654 ObjCMethodDecl *MD = Methods[i];
6655 std::string MethodTypeString, QuoteMethodTypeString;
6656 Context->getObjCEncodingForMethodDecl(MD, MethodTypeString, true);
6657 RewriteObj.QuoteDoublequotes(MethodTypeString, QuoteMethodTypeString);
6658 Result += "\t\""; Result += QuoteMethodTypeString; Result += "\"";
6659 if (i == e-1)
6660 Result += "\n};\n";
6661 else {
6662 Result += ",\n";
6663 }
6664 }
6665}
6666
Fariborz Jahanianacee1c92012-04-11 21:12:36 +00006667static void Write_IvarOffsetVar(RewriteModernObjC &RewriteObj,
6668 ASTContext *Context,
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00006669 std::string &Result,
Fariborz Jahaniandb649232012-02-13 20:59:02 +00006670 ArrayRef<ObjCIvarDecl *> Ivars,
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006671 ObjCInterfaceDecl *CDecl) {
Fariborz Jahaniandb649232012-02-13 20:59:02 +00006672 // FIXME. visibilty of offset symbols may have to be set; for Darwin
6673 // this is what happens:
6674 /**
6675 if (Ivar->getAccessControl() == ObjCIvarDecl::Private ||
6676 Ivar->getAccessControl() == ObjCIvarDecl::Package ||
6677 Class->getVisibility() == HiddenVisibility)
6678 Visibility shoud be: HiddenVisibility;
6679 else
6680 Visibility shoud be: DefaultVisibility;
6681 */
6682
Fariborz Jahanian07e52882012-02-13 21:34:45 +00006683 Result += "\n";
6684 for (unsigned i =0, e = Ivars.size(); i < e; i++) {
6685 ObjCIvarDecl *IvarDecl = Ivars[i];
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00006686 if (Context->getLangOpts().MicrosoftExt)
6687 Result += "__declspec(allocate(\".objc_ivar$B\")) ";
6688
6689 if (!Context->getLangOpts().MicrosoftExt ||
6690 IvarDecl->getAccessControl() == ObjCIvarDecl::Private ||
Fariborz Jahanian117591f2012-03-10 01:34:42 +00006691 IvarDecl->getAccessControl() == ObjCIvarDecl::Package)
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006692 Result += "extern \"C\" unsigned long int ";
Fariborz Jahaniand1c84d32012-03-10 00:53:02 +00006693 else
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006694 Result += "extern \"C\" __declspec(dllexport) unsigned long int ";
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006695 WriteInternalIvarName(CDecl, IvarDecl, Result);
Fariborz Jahanian07e52882012-02-13 21:34:45 +00006696 Result += " __attribute__ ((used, section (\"__DATA,__objc_ivar\")))";
6697 Result += " = ";
Fariborz Jahanianacee1c92012-04-11 21:12:36 +00006698 RewriteObj.RewriteIvarOffsetComputation(IvarDecl, Result);
6699 Result += ";\n";
Fariborz Jahaniandb649232012-02-13 20:59:02 +00006700 }
6701}
6702
Fariborz Jahanianae932952012-02-10 20:47:10 +00006703static void Write__ivar_list_t_initializer(RewriteModernObjC &RewriteObj,
6704 ASTContext *Context, std::string &Result,
6705 ArrayRef<ObjCIvarDecl *> Ivars,
6706 StringRef VarName,
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006707 ObjCInterfaceDecl *CDecl) {
Fariborz Jahanianae932952012-02-10 20:47:10 +00006708 if (Ivars.size() > 0) {
Fariborz Jahanianacee1c92012-04-11 21:12:36 +00006709 Write_IvarOffsetVar(RewriteObj, Context, Result, Ivars, CDecl);
Fariborz Jahanian07e52882012-02-13 21:34:45 +00006710
Fariborz Jahanianae932952012-02-10 20:47:10 +00006711 Result += "\nstatic ";
6712 Write__ivar_list_t_TypeDecl(Result, Ivars.size());
6713 Result += " "; Result += VarName;
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006714 Result += CDecl->getNameAsString();
Fariborz Jahanianae932952012-02-10 20:47:10 +00006715 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6716 Result += "\t"; Result += "sizeof(_ivar_t)"; Result += ",\n";
6717 Result += "\t"; Result += utostr(Ivars.size()); Result += ",\n";
6718 for (unsigned i =0, e = Ivars.size(); i < e; i++) {
6719 ObjCIvarDecl *IvarDecl = Ivars[i];
6720 if (i == 0)
6721 Result += "\t{{";
6722 else
6723 Result += "\t {";
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006724 Result += "(unsigned long int *)&";
6725 WriteInternalIvarName(CDecl, IvarDecl, Result);
Fariborz Jahaniandb649232012-02-13 20:59:02 +00006726 Result += ", ";
Fariborz Jahanianae932952012-02-10 20:47:10 +00006727
6728 Result += "\""; Result += IvarDecl->getName(); Result += "\", ";
6729 std::string IvarTypeString, QuoteIvarTypeString;
6730 Context->getObjCEncodingForType(IvarDecl->getType(), IvarTypeString,
6731 IvarDecl);
6732 RewriteObj.QuoteDoublequotes(IvarTypeString, QuoteIvarTypeString);
6733 Result += "\""; Result += QuoteIvarTypeString; Result += "\", ";
6734
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00006735 // FIXME. this alignment represents the host alignment and need be changed to
6736 // represent the target alignment.
6737 unsigned Align = Context->getTypeAlign(IvarDecl->getType())/8;
6738 Align = llvm::Log2_32(Align);
Fariborz Jahanianae932952012-02-10 20:47:10 +00006739 Result += llvm::utostr(Align); Result += ", ";
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00006740 CharUnits Size = Context->getTypeSizeInChars(IvarDecl->getType());
6741 Result += llvm::utostr(Size.getQuantity());
Fariborz Jahanianae932952012-02-10 20:47:10 +00006742 if (i == e-1)
6743 Result += "}}\n";
6744 else
6745 Result += "},\n";
6746 }
6747 Result += "};\n";
6748 }
6749}
6750
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006751/// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006752void RewriteModernObjC::RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl,
6753 std::string &Result) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006754
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006755 // Do not synthesize the protocol more than once.
6756 if (ObjCSynthesizedProtocols.count(PDecl->getCanonicalDecl()))
6757 return;
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00006758 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006759
6760 if (ObjCProtocolDecl *Def = PDecl->getDefinition())
6761 PDecl = Def;
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006762 // Must write out all protocol definitions in current qualifier list,
6763 // and in their nested qualifiers before writing out current definition.
6764 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
6765 E = PDecl->protocol_end(); I != E; ++I)
6766 RewriteObjCProtocolMetaData(*I, Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006767
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006768 // Construct method lists.
6769 std::vector<ObjCMethodDecl *> InstanceMethods, ClassMethods;
6770 std::vector<ObjCMethodDecl *> OptInstanceMethods, OptClassMethods;
6771 for (ObjCProtocolDecl::instmeth_iterator
6772 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
6773 I != E; ++I) {
6774 ObjCMethodDecl *MD = *I;
6775 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
6776 OptInstanceMethods.push_back(MD);
6777 } else {
6778 InstanceMethods.push_back(MD);
6779 }
6780 }
6781
6782 for (ObjCProtocolDecl::classmeth_iterator
6783 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
6784 I != E; ++I) {
6785 ObjCMethodDecl *MD = *I;
6786 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
6787 OptClassMethods.push_back(MD);
6788 } else {
6789 ClassMethods.push_back(MD);
6790 }
6791 }
Fariborz Jahaniane0adbd82012-02-08 22:23:26 +00006792 std::vector<ObjCMethodDecl *> AllMethods;
6793 for (unsigned i = 0, e = InstanceMethods.size(); i < e; i++)
6794 AllMethods.push_back(InstanceMethods[i]);
6795 for (unsigned i = 0, e = ClassMethods.size(); i < e; i++)
6796 AllMethods.push_back(ClassMethods[i]);
6797 for (unsigned i = 0, e = OptInstanceMethods.size(); i < e; i++)
6798 AllMethods.push_back(OptInstanceMethods[i]);
6799 for (unsigned i = 0, e = OptClassMethods.size(); i < e; i++)
6800 AllMethods.push_back(OptClassMethods[i]);
6801
6802 Write__extendedMethodTypes_initializer(*this, Context, Result,
6803 AllMethods,
6804 "_OBJC_PROTOCOL_METHOD_TYPES_",
6805 PDecl->getNameAsString());
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006806 // Protocol's super protocol list
6807 std::vector<ObjCProtocolDecl *> SuperProtocols;
6808 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
6809 E = PDecl->protocol_end(); I != E; ++I)
6810 SuperProtocols.push_back(*I);
6811
6812 Write_protocol_list_initializer(Context, Result, SuperProtocols,
6813 "_OBJC_PROTOCOL_REFS_",
6814 PDecl->getNameAsString());
6815
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006816 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006817 "_OBJC_PROTOCOL_INSTANCE_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006818 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006819
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006820 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006821 "_OBJC_PROTOCOL_CLASS_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006822 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006823
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006824 Write_method_list_t_initializer(*this, Context, Result, OptInstanceMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006825 "_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006826 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006827
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006828 Write_method_list_t_initializer(*this, Context, Result, OptClassMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006829 "_OBJC_PROTOCOL_OPT_CLASS_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006830 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006831
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006832 // Protocol's property metadata.
6833 std::vector<ObjCPropertyDecl *> ProtocolProperties;
6834 for (ObjCContainerDecl::prop_iterator I = PDecl->prop_begin(),
6835 E = PDecl->prop_end(); I != E; ++I)
David Blaikie581deb32012-06-06 20:45:41 +00006836 ProtocolProperties.push_back(*I);
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006837
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006838 Write_prop_list_t_initializer(*this, Context, Result, ProtocolProperties,
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006839 /* Container */0,
6840 "_OBJC_PROTOCOL_PROPERTIES_",
6841 PDecl->getNameAsString());
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006842
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006843 // Writer out root metadata for current protocol: struct _protocol_t
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00006844 Result += "\n";
6845 if (LangOpts.MicrosoftExt)
Fariborz Jahanian8590d862012-04-14 17:13:08 +00006846 Result += "static ";
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00006847 Result += "struct _protocol_t _OBJC_PROTOCOL_";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006848 Result += PDecl->getNameAsString();
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006849 Result += " __attribute__ ((used, section (\"__DATA,__datacoal_nt,coalesced\"))) = {\n";
6850 Result += "\t0,\n"; // id is; is null
6851 Result += "\t\""; Result += PDecl->getNameAsString(); Result += "\",\n";
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006852 if (SuperProtocols.size() > 0) {
6853 Result += "\t(const struct _protocol_list_t *)&"; Result += "_OBJC_PROTOCOL_REFS_";
6854 Result += PDecl->getNameAsString(); Result += ",\n";
6855 }
6856 else
6857 Result += "\t0,\n";
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006858 if (InstanceMethods.size() > 0) {
6859 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
6860 Result += PDecl->getNameAsString(); Result += ",\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006861 }
6862 else
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006863 Result += "\t0,\n";
6864
6865 if (ClassMethods.size() > 0) {
6866 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_CLASS_METHODS_";
6867 Result += PDecl->getNameAsString(); Result += ",\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006868 }
6869 else
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006870 Result += "\t0,\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006871
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006872 if (OptInstanceMethods.size() > 0) {
6873 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_";
6874 Result += PDecl->getNameAsString(); Result += ",\n";
6875 }
6876 else
6877 Result += "\t0,\n";
6878
6879 if (OptClassMethods.size() > 0) {
6880 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_CLASS_METHODS_";
6881 Result += PDecl->getNameAsString(); Result += ",\n";
6882 }
6883 else
6884 Result += "\t0,\n";
6885
6886 if (ProtocolProperties.size() > 0) {
6887 Result += "\t(const struct _prop_list_t *)&_OBJC_PROTOCOL_PROPERTIES_";
6888 Result += PDecl->getNameAsString(); Result += ",\n";
6889 }
6890 else
6891 Result += "\t0,\n";
6892
6893 Result += "\t"; Result += "sizeof(_protocol_t)"; Result += ",\n";
6894 Result += "\t0,\n";
6895
Fariborz Jahaniane0adbd82012-02-08 22:23:26 +00006896 if (AllMethods.size() > 0) {
6897 Result += "\t(const char **)&"; Result += "_OBJC_PROTOCOL_METHOD_TYPES_";
6898 Result += PDecl->getNameAsString();
6899 Result += "\n};\n";
6900 }
6901 else
6902 Result += "\t0\n};\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00006903
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00006904 if (LangOpts.MicrosoftExt)
Fariborz Jahanian8590d862012-04-14 17:13:08 +00006905 Result += "static ";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00006906 Result += "struct _protocol_t *";
6907 Result += "_OBJC_LABEL_PROTOCOL_$_"; Result += PDecl->getNameAsString();
6908 Result += " = &_OBJC_PROTOCOL_"; Result += PDecl->getNameAsString();
6909 Result += ";\n";
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006910
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006911 // Mark this protocol as having been generated.
6912 if (!ObjCSynthesizedProtocols.insert(PDecl->getCanonicalDecl()))
6913 llvm_unreachable("protocol already synthesized");
6914
6915}
6916
6917void RewriteModernObjC::RewriteObjCProtocolListMetaData(
6918 const ObjCList<ObjCProtocolDecl> &Protocols,
6919 StringRef prefix, StringRef ClassName,
6920 std::string &Result) {
6921 if (Protocols.empty()) return;
6922
6923 for (unsigned i = 0; i != Protocols.size(); i++)
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006924 RewriteObjCProtocolMetaData(Protocols[i], Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006925
6926 // Output the top lovel protocol meta-data for the class.
6927 /* struct _objc_protocol_list {
6928 struct _objc_protocol_list *next;
6929 int protocol_count;
6930 struct _objc_protocol *class_protocols[];
6931 }
6932 */
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00006933 Result += "\n";
6934 if (LangOpts.MicrosoftExt)
6935 Result += "__declspec(allocate(\".cat_cls_meth$B\")) ";
6936 Result += "static struct {\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006937 Result += "\tstruct _objc_protocol_list *next;\n";
6938 Result += "\tint protocol_count;\n";
6939 Result += "\tstruct _objc_protocol *class_protocols[";
6940 Result += utostr(Protocols.size());
6941 Result += "];\n} _OBJC_";
6942 Result += prefix;
6943 Result += "_PROTOCOLS_";
6944 Result += ClassName;
6945 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
6946 "{\n\t0, ";
6947 Result += utostr(Protocols.size());
6948 Result += "\n";
6949
6950 Result += "\t,{&_OBJC_PROTOCOL_";
6951 Result += Protocols[0]->getNameAsString();
6952 Result += " \n";
6953
6954 for (unsigned i = 1; i != Protocols.size(); i++) {
6955 Result += "\t ,&_OBJC_PROTOCOL_";
6956 Result += Protocols[i]->getNameAsString();
6957 Result += "\n";
6958 }
6959 Result += "\t }\n};\n";
6960}
6961
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006962/// hasObjCExceptionAttribute - Return true if this class or any super
6963/// class has the __objc_exception__ attribute.
6964/// FIXME. Move this to ASTContext.cpp as it is also used for IRGen.
6965static bool hasObjCExceptionAttribute(ASTContext &Context,
6966 const ObjCInterfaceDecl *OID) {
6967 if (OID->hasAttr<ObjCExceptionAttr>())
6968 return true;
6969 if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
6970 return hasObjCExceptionAttribute(Context, Super);
6971 return false;
6972}
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006973
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006974void RewriteModernObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
6975 std::string &Result) {
6976 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
6977
6978 // Explicitly declared @interface's are already synthesized.
Fariborz Jahanianae932952012-02-10 20:47:10 +00006979 if (CDecl->isImplicitInterfaceDecl())
6980 assert(false &&
6981 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00006982
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00006983 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanianae932952012-02-10 20:47:10 +00006984 SmallVector<ObjCIvarDecl *, 8> IVars;
6985
6986 for (ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
6987 IVD; IVD = IVD->getNextIvar()) {
6988 // Ignore unnamed bit-fields.
6989 if (!IVD->getDeclName())
6990 continue;
6991 IVars.push_back(IVD);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006992 }
6993
Fariborz Jahanianae932952012-02-10 20:47:10 +00006994 Write__ivar_list_t_initializer(*this, Context, Result, IVars,
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006995 "_OBJC_$_INSTANCE_VARIABLES_",
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006996 CDecl);
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006997
6998 // Build _objc_method_list for class's instance methods if needed
6999 SmallVector<ObjCMethodDecl *, 32>
7000 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
7001
7002 // If any of our property implementations have associated getters or
7003 // setters, produce metadata for them as well.
7004 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
7005 PropEnd = IDecl->propimpl_end();
7006 Prop != PropEnd; ++Prop) {
David Blaikie262bc182012-04-30 02:36:29 +00007007 if (Prop->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00007008 continue;
David Blaikie262bc182012-04-30 02:36:29 +00007009 if (!Prop->getPropertyIvarDecl())
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00007010 continue;
David Blaikie262bc182012-04-30 02:36:29 +00007011 ObjCPropertyDecl *PD = Prop->getPropertyDecl();
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00007012 if (!PD)
7013 continue;
7014 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
Fariborz Jahanian301e2e42012-05-03 22:52:13 +00007015 if (mustSynthesizeSetterGetterMethod(IDecl, PD, true /*getter*/))
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00007016 InstanceMethods.push_back(Getter);
7017 if (PD->isReadOnly())
7018 continue;
7019 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
Fariborz Jahanian301e2e42012-05-03 22:52:13 +00007020 if (mustSynthesizeSetterGetterMethod(IDecl, PD, false /*setter*/))
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00007021 InstanceMethods.push_back(Setter);
7022 }
7023
7024 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
7025 "_OBJC_$_INSTANCE_METHODS_",
7026 IDecl->getNameAsString(), true);
7027
7028 SmallVector<ObjCMethodDecl *, 32>
7029 ClassMethods(IDecl->classmeth_begin(), IDecl->classmeth_end());
7030
7031 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
7032 "_OBJC_$_CLASS_METHODS_",
7033 IDecl->getNameAsString(), true);
Fariborz Jahanian0a525342012-02-14 19:31:35 +00007034
7035 // Protocols referenced in class declaration?
7036 // Protocol's super protocol list
7037 std::vector<ObjCProtocolDecl *> RefedProtocols;
7038 const ObjCList<ObjCProtocolDecl> &Protocols = CDecl->getReferencedProtocols();
7039 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
7040 E = Protocols.end();
7041 I != E; ++I) {
7042 RefedProtocols.push_back(*I);
7043 // Must write out all protocol definitions in current qualifier list,
7044 // and in their nested qualifiers before writing out current definition.
7045 RewriteObjCProtocolMetaData(*I, Result);
7046 }
7047
7048 Write_protocol_list_initializer(Context, Result,
7049 RefedProtocols,
7050 "_OBJC_CLASS_PROTOCOLS_$_",
7051 IDecl->getNameAsString());
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00007052
7053 // Protocol's property metadata.
7054 std::vector<ObjCPropertyDecl *> ClassProperties;
7055 for (ObjCContainerDecl::prop_iterator I = CDecl->prop_begin(),
7056 E = CDecl->prop_end(); I != E; ++I)
David Blaikie581deb32012-06-06 20:45:41 +00007057 ClassProperties.push_back(*I);
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00007058
7059 Write_prop_list_t_initializer(*this, Context, Result, ClassProperties,
Fariborz Jahanian2df089d2012-03-22 17:39:35 +00007060 /* Container */IDecl,
Fariborz Jahanianeeabf382012-02-16 21:57:59 +00007061 "_OBJC_$_PROP_LIST_",
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00007062 CDecl->getNameAsString());
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00007063
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00007064
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00007065 // Data for initializing _class_ro_t metaclass meta-data
7066 uint32_t flags = CLS_META;
7067 std::string InstanceSize;
7068 std::string InstanceStart;
7069
7070
7071 bool classIsHidden = CDecl->getVisibility() == HiddenVisibility;
7072 if (classIsHidden)
7073 flags |= OBJC2_CLS_HIDDEN;
7074
7075 if (!CDecl->getSuperClass())
7076 // class is root
7077 flags |= CLS_ROOT;
7078 InstanceSize = "sizeof(struct _class_t)";
7079 InstanceStart = InstanceSize;
7080 Write__class_ro_t_initializer(Context, Result, flags,
7081 InstanceStart, InstanceSize,
7082 ClassMethods,
7083 0,
7084 0,
7085 0,
7086 "_OBJC_METACLASS_RO_$_",
7087 CDecl->getNameAsString());
7088
7089
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00007090 // Data for initializing _class_ro_t meta-data
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00007091 flags = CLS;
7092 if (classIsHidden)
7093 flags |= OBJC2_CLS_HIDDEN;
7094
7095 if (hasObjCExceptionAttribute(*Context, CDecl))
7096 flags |= CLS_EXCEPTION;
7097
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00007098 if (!CDecl->getSuperClass())
7099 // class is root
7100 flags |= CLS_ROOT;
7101
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00007102 InstanceSize.clear();
7103 InstanceStart.clear();
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00007104 if (!ObjCSynthesizedStructs.count(CDecl)) {
7105 InstanceSize = "0";
7106 InstanceStart = "0";
7107 }
7108 else {
7109 InstanceSize = "sizeof(struct ";
7110 InstanceSize += CDecl->getNameAsString();
7111 InstanceSize += "_IMPL)";
7112
7113 ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
7114 if (IVD) {
Fariborz Jahanianacee1c92012-04-11 21:12:36 +00007115 RewriteIvarOffsetComputation(IVD, InstanceStart);
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00007116 }
7117 else
7118 InstanceStart = InstanceSize;
7119 }
7120 Write__class_ro_t_initializer(Context, Result, flags,
7121 InstanceStart, InstanceSize,
7122 InstanceMethods,
7123 RefedProtocols,
7124 IVars,
7125 ClassProperties,
7126 "_OBJC_CLASS_RO_$_",
7127 CDecl->getNameAsString());
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00007128
7129 Write_class_t(Context, Result,
7130 "OBJC_METACLASS_$_",
7131 CDecl, /*metaclass*/true);
7132
7133 Write_class_t(Context, Result,
7134 "OBJC_CLASS_$_",
7135 CDecl, /*metaclass*/false);
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00007136
7137 if (ImplementationIsNonLazy(IDecl))
7138 DefinedNonLazyClasses.push_back(CDecl);
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00007139
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007140}
7141
Fariborz Jahaniane0335782012-03-27 18:41:05 +00007142void RewriteModernObjC::RewriteClassSetupInitHook(std::string &Result) {
7143 int ClsDefCount = ClassImplementation.size();
7144 if (!ClsDefCount)
7145 return;
7146 Result += "#pragma section(\".objc_inithooks$B\", long, read, write)\n";
7147 Result += "__declspec(allocate(\".objc_inithooks$B\")) ";
7148 Result += "static void *OBJC_CLASS_SETUP[] = {\n";
7149 for (int i = 0; i < ClsDefCount; i++) {
7150 ObjCImplementationDecl *IDecl = ClassImplementation[i];
7151 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
7152 Result += "\t(void *)&OBJC_CLASS_SETUP_$_";
7153 Result += CDecl->getName(); Result += ",\n";
7154 }
7155 Result += "};\n";
7156}
7157
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007158void RewriteModernObjC::RewriteMetaDataIntoBuffer(std::string &Result) {
7159 int ClsDefCount = ClassImplementation.size();
7160 int CatDefCount = CategoryImplementation.size();
7161
7162 // For each implemented class, write out all its meta data.
7163 for (int i = 0; i < ClsDefCount; i++)
7164 RewriteObjCClassMetaData(ClassImplementation[i], Result);
7165
Fariborz Jahaniane0335782012-03-27 18:41:05 +00007166 RewriteClassSetupInitHook(Result);
7167
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007168 // For each implemented category, write out all its meta data.
7169 for (int i = 0; i < CatDefCount; i++)
7170 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
7171
Fariborz Jahaniane0335782012-03-27 18:41:05 +00007172 RewriteCategorySetupInitHook(Result);
7173
Fariborz Jahaniandf795672012-02-17 00:06:14 +00007174 if (ClsDefCount > 0) {
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00007175 if (LangOpts.MicrosoftExt)
7176 Result += "__declspec(allocate(\".objc_classlist$B\")) ";
Fariborz Jahaniandf795672012-02-17 00:06:14 +00007177 Result += "static struct _class_t *L_OBJC_LABEL_CLASS_$ [";
7178 Result += llvm::utostr(ClsDefCount); Result += "]";
7179 Result +=
7180 " __attribute__((used, section (\"__DATA, __objc_classlist,"
7181 "regular,no_dead_strip\")))= {\n";
7182 for (int i = 0; i < ClsDefCount; i++) {
7183 Result += "\t&OBJC_CLASS_$_";
7184 Result += ClassImplementation[i]->getNameAsString();
7185 Result += ",\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007186 }
Fariborz Jahaniandf795672012-02-17 00:06:14 +00007187 Result += "};\n";
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00007188
7189 if (!DefinedNonLazyClasses.empty()) {
7190 if (LangOpts.MicrosoftExt)
7191 Result += "__declspec(allocate(\".objc_nlclslist$B\")) \n";
7192 Result += "static struct _class_t *_OBJC_LABEL_NONLAZY_CLASS_$[] = {\n\t";
7193 for (unsigned i = 0, e = DefinedNonLazyClasses.size(); i < e; i++) {
7194 Result += "\t&OBJC_CLASS_$_"; Result += DefinedNonLazyClasses[i]->getNameAsString();
7195 Result += ",\n";
7196 }
7197 Result += "};\n";
7198 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007199 }
Fariborz Jahanian61186122012-02-17 18:40:41 +00007200
7201 if (CatDefCount > 0) {
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00007202 if (LangOpts.MicrosoftExt)
7203 Result += "__declspec(allocate(\".objc_catlist$B\")) ";
Fariborz Jahanian61186122012-02-17 18:40:41 +00007204 Result += "static struct _category_t *L_OBJC_LABEL_CATEGORY_$ [";
7205 Result += llvm::utostr(CatDefCount); Result += "]";
7206 Result +=
7207 " __attribute__((used, section (\"__DATA, __objc_catlist,"
7208 "regular,no_dead_strip\")))= {\n";
7209 for (int i = 0; i < CatDefCount; i++) {
7210 Result += "\t&_OBJC_$_CATEGORY_";
7211 Result +=
7212 CategoryImplementation[i]->getClassInterface()->getNameAsString();
7213 Result += "_$_";
7214 Result += CategoryImplementation[i]->getNameAsString();
7215 Result += ",\n";
7216 }
7217 Result += "};\n";
7218 }
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00007219
7220 if (!DefinedNonLazyCategories.empty()) {
7221 if (LangOpts.MicrosoftExt)
7222 Result += "__declspec(allocate(\".objc_nlcatlist$B\")) \n";
7223 Result += "static struct _category_t *_OBJC_LABEL_NONLAZY_CATEGORY_$[] = {\n\t";
7224 for (unsigned i = 0, e = DefinedNonLazyCategories.size(); i < e; i++) {
7225 Result += "\t&_OBJC_$_CATEGORY_";
7226 Result +=
7227 DefinedNonLazyCategories[i]->getClassInterface()->getNameAsString();
7228 Result += "_$_";
7229 Result += DefinedNonLazyCategories[i]->getNameAsString();
7230 Result += ",\n";
7231 }
7232 Result += "};\n";
7233 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007234}
7235
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00007236void RewriteModernObjC::WriteImageInfo(std::string &Result) {
7237 if (LangOpts.MicrosoftExt)
7238 Result += "__declspec(allocate(\".objc_imageinfo$B\")) \n";
7239
7240 Result += "static struct IMAGE_INFO { unsigned version; unsigned flag; } ";
7241 // version 0, ObjCABI is 2
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00007242 Result += "_OBJC_IMAGE_INFO = { 0, 2 };\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00007243}
7244
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007245/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
7246/// implementation.
7247void RewriteModernObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
7248 std::string &Result) {
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00007249 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007250 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
7251 // Find category declaration for this implementation.
Fariborz Jahanian61186122012-02-17 18:40:41 +00007252 ObjCCategoryDecl *CDecl=0;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007253 for (CDecl = ClassDecl->getCategoryList(); CDecl;
7254 CDecl = CDecl->getNextClassCategory())
7255 if (CDecl->getIdentifier() == IDecl->getIdentifier())
7256 break;
7257
7258 std::string FullCategoryName = ClassDecl->getNameAsString();
Fariborz Jahanian61186122012-02-17 18:40:41 +00007259 FullCategoryName += "_$_";
7260 FullCategoryName += CDecl->getNameAsString();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007261
7262 // Build _objc_method_list for class's instance methods if needed
7263 SmallVector<ObjCMethodDecl *, 32>
7264 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
7265
7266 // If any of our property implementations have associated getters or
7267 // setters, produce metadata for them as well.
7268 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
7269 PropEnd = IDecl->propimpl_end();
7270 Prop != PropEnd; ++Prop) {
David Blaikie262bc182012-04-30 02:36:29 +00007271 if (Prop->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007272 continue;
David Blaikie262bc182012-04-30 02:36:29 +00007273 if (!Prop->getPropertyIvarDecl())
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007274 continue;
David Blaikie262bc182012-04-30 02:36:29 +00007275 ObjCPropertyDecl *PD = Prop->getPropertyDecl();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007276 if (!PD)
7277 continue;
7278 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
7279 InstanceMethods.push_back(Getter);
7280 if (PD->isReadOnly())
7281 continue;
7282 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
7283 InstanceMethods.push_back(Setter);
7284 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007285
Fariborz Jahanian61186122012-02-17 18:40:41 +00007286 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
7287 "_OBJC_$_CATEGORY_INSTANCE_METHODS_",
7288 FullCategoryName, true);
7289
7290 SmallVector<ObjCMethodDecl *, 32>
7291 ClassMethods(IDecl->classmeth_begin(), IDecl->classmeth_end());
7292
7293 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
7294 "_OBJC_$_CATEGORY_CLASS_METHODS_",
7295 FullCategoryName, true);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007296
7297 // Protocols referenced in class declaration?
Fariborz Jahanian61186122012-02-17 18:40:41 +00007298 // Protocol's super protocol list
7299 std::vector<ObjCProtocolDecl *> RefedProtocols;
Argyrios Kyrtzidisa5f44412012-03-13 01:09:41 +00007300 for (ObjCInterfaceDecl::protocol_iterator I = CDecl->protocol_begin(),
7301 E = CDecl->protocol_end();
7302
7303 I != E; ++I) {
Fariborz Jahanian61186122012-02-17 18:40:41 +00007304 RefedProtocols.push_back(*I);
7305 // Must write out all protocol definitions in current qualifier list,
7306 // and in their nested qualifiers before writing out current definition.
7307 RewriteObjCProtocolMetaData(*I, Result);
7308 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007309
Fariborz Jahanian61186122012-02-17 18:40:41 +00007310 Write_protocol_list_initializer(Context, Result,
7311 RefedProtocols,
7312 "_OBJC_CATEGORY_PROTOCOLS_$_",
7313 FullCategoryName);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007314
Fariborz Jahanian61186122012-02-17 18:40:41 +00007315 // Protocol's property metadata.
7316 std::vector<ObjCPropertyDecl *> ClassProperties;
7317 for (ObjCContainerDecl::prop_iterator I = CDecl->prop_begin(),
7318 E = CDecl->prop_end(); I != E; ++I)
David Blaikie581deb32012-06-06 20:45:41 +00007319 ClassProperties.push_back(*I);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007320
Fariborz Jahanian61186122012-02-17 18:40:41 +00007321 Write_prop_list_t_initializer(*this, Context, Result, ClassProperties,
Fariborz Jahanianebfa2722012-05-03 23:19:33 +00007322 /* Container */IDecl,
Fariborz Jahanian61186122012-02-17 18:40:41 +00007323 "_OBJC_$_PROP_LIST_",
7324 FullCategoryName);
7325
7326 Write_category_t(*this, Context, Result,
Fariborz Jahaniane0335782012-03-27 18:41:05 +00007327 CDecl,
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00007328 ClassDecl,
Fariborz Jahanian61186122012-02-17 18:40:41 +00007329 InstanceMethods,
7330 ClassMethods,
7331 RefedProtocols,
7332 ClassProperties);
7333
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00007334 // Determine if this category is also "non-lazy".
7335 if (ImplementationIsNonLazy(IDecl))
7336 DefinedNonLazyCategories.push_back(CDecl);
Fariborz Jahaniane0335782012-03-27 18:41:05 +00007337
7338}
7339
7340void RewriteModernObjC::RewriteCategorySetupInitHook(std::string &Result) {
7341 int CatDefCount = CategoryImplementation.size();
7342 if (!CatDefCount)
7343 return;
7344 Result += "#pragma section(\".objc_inithooks$B\", long, read, write)\n";
7345 Result += "__declspec(allocate(\".objc_inithooks$B\")) ";
7346 Result += "static void *OBJC_CATEGORY_SETUP[] = {\n";
7347 for (int i = 0; i < CatDefCount; i++) {
7348 ObjCCategoryImplDecl *IDecl = CategoryImplementation[i];
7349 ObjCCategoryDecl *CatDecl= IDecl->getCategoryDecl();
7350 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
7351 Result += "\t(void *)&OBJC_CATEGORY_SETUP_$_";
7352 Result += ClassDecl->getName();
7353 Result += "_$_";
7354 Result += CatDecl->getName();
7355 Result += ",\n";
7356 }
7357 Result += "};\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007358}
7359
7360// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
7361/// class methods.
7362template<typename MethodIterator>
7363void RewriteModernObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
7364 MethodIterator MethodEnd,
7365 bool IsInstanceMethod,
7366 StringRef prefix,
7367 StringRef ClassName,
7368 std::string &Result) {
7369 if (MethodBegin == MethodEnd) return;
7370
7371 if (!objc_impl_method) {
7372 /* struct _objc_method {
7373 SEL _cmd;
7374 char *method_types;
7375 void *_imp;
7376 }
7377 */
7378 Result += "\nstruct _objc_method {\n";
7379 Result += "\tSEL _cmd;\n";
7380 Result += "\tchar *method_types;\n";
7381 Result += "\tvoid *_imp;\n";
7382 Result += "};\n";
7383
7384 objc_impl_method = true;
7385 }
7386
7387 // Build _objc_method_list for class's methods if needed
7388
7389 /* struct {
7390 struct _objc_method_list *next_method;
7391 int method_count;
7392 struct _objc_method method_list[];
7393 }
7394 */
7395 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00007396 Result += "\n";
7397 if (LangOpts.MicrosoftExt) {
7398 if (IsInstanceMethod)
7399 Result += "__declspec(allocate(\".inst_meth$B\")) ";
7400 else
7401 Result += "__declspec(allocate(\".cls_meth$B\")) ";
7402 }
7403 Result += "static struct {\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007404 Result += "\tstruct _objc_method_list *next_method;\n";
7405 Result += "\tint method_count;\n";
7406 Result += "\tstruct _objc_method method_list[";
7407 Result += utostr(NumMethods);
7408 Result += "];\n} _OBJC_";
7409 Result += prefix;
7410 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
7411 Result += "_METHODS_";
7412 Result += ClassName;
7413 Result += " __attribute__ ((used, section (\"__OBJC, __";
7414 Result += IsInstanceMethod ? "inst" : "cls";
7415 Result += "_meth\")))= ";
7416 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
7417
7418 Result += "\t,{{(SEL)\"";
7419 Result += (*MethodBegin)->getSelector().getAsString().c_str();
7420 std::string MethodTypeString;
7421 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
7422 Result += "\", \"";
7423 Result += MethodTypeString;
7424 Result += "\", (void *)";
7425 Result += MethodInternalNames[*MethodBegin];
7426 Result += "}\n";
7427 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
7428 Result += "\t ,{(SEL)\"";
7429 Result += (*MethodBegin)->getSelector().getAsString().c_str();
7430 std::string MethodTypeString;
7431 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
7432 Result += "\", \"";
7433 Result += MethodTypeString;
7434 Result += "\", (void *)";
7435 Result += MethodInternalNames[*MethodBegin];
7436 Result += "}\n";
7437 }
7438 Result += "\t }\n};\n";
7439}
7440
7441Stmt *RewriteModernObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) {
7442 SourceRange OldRange = IV->getSourceRange();
7443 Expr *BaseExpr = IV->getBase();
7444
7445 // Rewrite the base, but without actually doing replaces.
7446 {
7447 DisableReplaceStmtScope S(*this);
7448 BaseExpr = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(BaseExpr));
7449 IV->setBase(BaseExpr);
7450 }
7451
7452 ObjCIvarDecl *D = IV->getDecl();
7453
7454 Expr *Replacement = IV;
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007455
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007456 if (BaseExpr->getType()->isObjCObjectPointerType()) {
7457 const ObjCInterfaceType *iFaceDecl =
Fariborz Jahanian163d3ce2012-05-08 23:54:35 +00007458 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007459 assert(iFaceDecl && "RewriteObjCIvarRefExpr - iFaceDecl is null");
7460 // lookup which class implements the instance variable.
7461 ObjCInterfaceDecl *clsDeclared = 0;
7462 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
7463 clsDeclared);
7464 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
7465
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007466 // Build name of symbol holding ivar offset.
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00007467 std::string IvarOffsetName;
7468 WriteInternalIvarName(clsDeclared, D, IvarOffsetName);
7469
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00007470 ReferencedIvars[clsDeclared].insert(D);
7471
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007472 // cast offset to "char *".
7473 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context,
7474 Context->getPointerType(Context->CharTy),
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007475 CK_BitCast,
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007476 BaseExpr);
7477 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
7478 SourceLocation(), &Context->Idents.get(IvarOffsetName),
7479 Context->UnsignedLongTy, 0, SC_Extern, SC_None);
John McCallf4b88a42012-03-10 09:33:50 +00007480 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, false,
7481 Context->UnsignedLongTy, VK_LValue,
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007482 SourceLocation());
7483 BinaryOperator *addExpr =
7484 new (Context) BinaryOperator(castExpr, DRE, BO_Add,
7485 Context->getPointerType(Context->CharTy),
7486 VK_RValue, OK_Ordinary, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007487 // Don't forget the parens to enforce the proper binding.
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007488 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(),
7489 SourceLocation(),
7490 addExpr);
Fariborz Jahanian0d6e22a2012-02-24 17:35:35 +00007491 QualType IvarT = D->getType();
Fariborz Jahanian27fc81b2012-04-27 22:48:54 +00007492
Fariborz Jahanianf5eac482012-05-02 17:34:59 +00007493 if (!isa<TypedefType>(IvarT) && IvarT->isRecordType()) {
Fariborz Jahanian27fc81b2012-04-27 22:48:54 +00007494 RecordDecl *RD = IvarT->getAs<RecordType>()->getDecl();
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00007495 RD = RD->getDefinition();
7496 if (RD && !RD->getDeclName().getAsIdentifierInfo()) {
Fariborz Jahanian27fc81b2012-04-27 22:48:54 +00007497 // decltype(((Foo_IMPL*)0)->bar) *
Fariborz Jahanianf5eac482012-05-02 17:34:59 +00007498 ObjCContainerDecl *CDecl =
7499 dyn_cast<ObjCContainerDecl>(D->getDeclContext());
7500 // ivar in class extensions requires special treatment.
7501 if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(CDecl))
7502 CDecl = CatDecl->getClassInterface();
7503 std::string RecName = CDecl->getName();
Fariborz Jahanian27fc81b2012-04-27 22:48:54 +00007504 RecName += "_IMPL";
7505 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
7506 SourceLocation(), SourceLocation(),
7507 &Context->Idents.get(RecName.c_str()));
7508 QualType PtrStructIMPL = Context->getPointerType(Context->getTagDeclType(RD));
7509 unsigned UnsignedIntSize =
7510 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
7511 Expr *Zero = IntegerLiteral::Create(*Context,
7512 llvm::APInt(UnsignedIntSize, 0),
7513 Context->UnsignedIntTy, SourceLocation());
7514 Zero = NoTypeInfoCStyleCastExpr(Context, PtrStructIMPL, CK_BitCast, Zero);
7515 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
7516 Zero);
7517 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
7518 SourceLocation(),
7519 &Context->Idents.get(D->getNameAsString()),
7520 IvarT, 0,
7521 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smithca523302012-06-10 03:12:00 +00007522 ICIS_NoInit);
Fariborz Jahanian27fc81b2012-04-27 22:48:54 +00007523 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
7524 FD->getType(), VK_LValue,
7525 OK_Ordinary);
7526 IvarT = Context->getDecltypeType(ME, ME->getType());
7527 }
7528 }
Fariborz Jahanian8e0913d2012-02-29 00:26:20 +00007529 convertObjCTypeToCStyleType(IvarT);
Fariborz Jahanian0d6e22a2012-02-24 17:35:35 +00007530 QualType castT = Context->getPointerType(IvarT);
Fariborz Jahanian27fc81b2012-04-27 22:48:54 +00007531
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007532 castExpr = NoTypeInfoCStyleCastExpr(Context,
7533 castT,
7534 CK_BitCast,
7535 PE);
Fariborz Jahanian27fc81b2012-04-27 22:48:54 +00007536
7537
Fariborz Jahanian8e0913d2012-02-29 00:26:20 +00007538 Expr *Exp = new (Context) UnaryOperator(castExpr, UO_Deref, IvarT,
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007539 VK_LValue, OK_Ordinary,
7540 SourceLocation());
7541 PE = new (Context) ParenExpr(OldRange.getBegin(),
7542 OldRange.getEnd(),
7543 Exp);
7544
7545 Replacement = PE;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007546 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007547
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007548 ReplaceStmtWithRange(IV, Replacement, OldRange);
7549 return Replacement;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007550}