blob: 14dba8f0a0936f965c8193296b0a0b91cac02ab5 [file] [log] [blame]
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001//===--- RewriteObjC.cpp - Playground for the code rewriter ---------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// Hacks and fun related to the code rewriter.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/Rewrite/ASTConsumers.h"
15#include "clang/Rewrite/Rewriter.h"
16#include "clang/AST/AST.h"
17#include "clang/AST/ASTConsumer.h"
18#include "clang/AST/ParentMap.h"
19#include "clang/Basic/SourceManager.h"
20#include "clang/Basic/IdentifierTable.h"
21#include "clang/Basic/Diagnostic.h"
22#include "clang/Lex/Lexer.h"
23#include "llvm/Support/MemoryBuffer.h"
24#include "llvm/Support/raw_ostream.h"
25#include "llvm/ADT/StringExtras.h"
26#include "llvm/ADT/SmallPtrSet.h"
27#include "llvm/ADT/OwningPtr.h"
28#include "llvm/ADT/DenseSet.h"
29
30using namespace clang;
31using llvm::utostr;
32
33namespace {
34 class RewriteModernObjC : public ASTConsumer {
35 protected:
36
37 enum {
38 BLOCK_FIELD_IS_OBJECT = 3, /* id, NSObject, __attribute__((NSObject)),
39 block, ... */
40 BLOCK_FIELD_IS_BLOCK = 7, /* a block variable */
41 BLOCK_FIELD_IS_BYREF = 8, /* the on stack structure holding the
42 __block variable */
43 BLOCK_FIELD_IS_WEAK = 16, /* declared __weak, only used in byref copy
44 helpers */
45 BLOCK_BYREF_CALLER = 128, /* called from __block (byref) copy/dispose
46 support routines */
47 BLOCK_BYREF_CURRENT_MAX = 256
48 };
49
50 enum {
51 BLOCK_NEEDS_FREE = (1 << 24),
52 BLOCK_HAS_COPY_DISPOSE = (1 << 25),
53 BLOCK_HAS_CXX_OBJ = (1 << 26),
54 BLOCK_IS_GC = (1 << 27),
55 BLOCK_IS_GLOBAL = (1 << 28),
56 BLOCK_HAS_DESCRIPTOR = (1 << 29)
57 };
58 static const int OBJC_ABI_VERSION = 7;
59
60 Rewriter Rewrite;
61 DiagnosticsEngine &Diags;
62 const LangOptions &LangOpts;
63 ASTContext *Context;
64 SourceManager *SM;
65 TranslationUnitDecl *TUDecl;
66 FileID MainFileID;
67 const char *MainFileStart, *MainFileEnd;
68 Stmt *CurrentBody;
69 ParentMap *PropParentMap; // created lazily.
70 std::string InFileName;
71 raw_ostream* OutFile;
72 std::string Preamble;
73
74 TypeDecl *ProtocolTypeDecl;
75 VarDecl *GlobalVarDecl;
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +000076 Expr *GlobalConstructionExp;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +000077 unsigned RewriteFailedDiag;
Fariborz Jahaniand13c2c22012-03-22 19:54:39 +000078 unsigned GlobalBlockRewriteFailedDiag;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +000079 // ObjC string constant support.
80 unsigned NumObjCStringLiterals;
81 VarDecl *ConstantStringClassReference;
82 RecordDecl *NSStringRecord;
83
84 // ObjC foreach break/continue generation support.
85 int BcLabelCount;
86
87 unsigned TryFinallyContainsReturnDiag;
88 // Needed for super.
89 ObjCMethodDecl *CurMethodDef;
90 RecordDecl *SuperStructDecl;
91 RecordDecl *ConstantStringDecl;
92
93 FunctionDecl *MsgSendFunctionDecl;
94 FunctionDecl *MsgSendSuperFunctionDecl;
95 FunctionDecl *MsgSendStretFunctionDecl;
96 FunctionDecl *MsgSendSuperStretFunctionDecl;
97 FunctionDecl *MsgSendFpretFunctionDecl;
98 FunctionDecl *GetClassFunctionDecl;
99 FunctionDecl *GetMetaClassFunctionDecl;
100 FunctionDecl *GetSuperClassFunctionDecl;
101 FunctionDecl *SelGetUidFunctionDecl;
102 FunctionDecl *CFStringFunctionDecl;
103 FunctionDecl *SuperContructorFunctionDecl;
104 FunctionDecl *CurFunctionDef;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000105
106 /* Misc. containers needed for meta-data rewrite. */
107 SmallVector<ObjCImplementationDecl *, 8> ClassImplementation;
108 SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation;
109 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCSynthesizedStructs;
110 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> ObjCSynthesizedProtocols;
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +0000111 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCWrittenInterfaces;
Fariborz Jahanian8fba8942012-04-30 23:20:30 +0000112 llvm::SmallPtrSet<TagDecl*, 32> GlobalDefinedTags;
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +0000113 SmallVector<ObjCInterfaceDecl*, 32> ObjCInterfacesSeen;
Fariborz Jahanian88f7f752012-03-14 23:18:19 +0000114 /// DefinedNonLazyClasses - List of defined "non-lazy" classes.
115 SmallVector<ObjCInterfaceDecl*, 8> DefinedNonLazyClasses;
116
117 /// DefinedNonLazyCategories - List of defined "non-lazy" categories.
118 llvm::SmallVector<ObjCCategoryDecl*, 8> DefinedNonLazyCategories;
119
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000120 SmallVector<Stmt *, 32> Stmts;
121 SmallVector<int, 8> ObjCBcLabelNo;
122 // Remember all the @protocol(<expr>) expressions.
123 llvm::SmallPtrSet<ObjCProtocolDecl *, 32> ProtocolExprDecls;
124
125 llvm::DenseSet<uint64_t> CopyDestroyCache;
126
127 // Block expressions.
128 SmallVector<BlockExpr *, 32> Blocks;
129 SmallVector<int, 32> InnerDeclRefsCount;
John McCallf4b88a42012-03-10 09:33:50 +0000130 SmallVector<DeclRefExpr *, 32> InnerDeclRefs;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000131
John McCallf4b88a42012-03-10 09:33:50 +0000132 SmallVector<DeclRefExpr *, 32> BlockDeclRefs;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000133
134 // Block related declarations.
135 SmallVector<ValueDecl *, 8> BlockByCopyDecls;
136 llvm::SmallPtrSet<ValueDecl *, 8> BlockByCopyDeclsPtrSet;
137 SmallVector<ValueDecl *, 8> BlockByRefDecls;
138 llvm::SmallPtrSet<ValueDecl *, 8> BlockByRefDeclsPtrSet;
139 llvm::DenseMap<ValueDecl *, unsigned> BlockByRefDeclNo;
140 llvm::SmallPtrSet<ValueDecl *, 8> ImportedBlockDecls;
141 llvm::SmallPtrSet<VarDecl *, 8> ImportedLocalExternalDecls;
142
143 llvm::DenseMap<BlockExpr *, std::string> RewrittenBlockExprs;
Fariborz Jahanian72c88f12012-02-22 18:13:25 +0000144 llvm::DenseMap<ObjCInterfaceDecl *,
145 llvm::SmallPtrSet<ObjCIvarDecl *, 8> > ReferencedIvars;
146
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000147 // This maps an original source AST to it's rewritten form. This allows
148 // us to avoid rewriting the same node twice (which is very uncommon).
149 // This is needed to support some of the exotic property rewriting.
150 llvm::DenseMap<Stmt *, Stmt *> ReplacedNodes;
151
152 // Needed for header files being rewritten
153 bool IsHeader;
154 bool SilenceRewriteMacroWarning;
155 bool objc_impl_method;
156
157 bool DisableReplaceStmt;
158 class DisableReplaceStmtScope {
159 RewriteModernObjC &R;
160 bool SavedValue;
161
162 public:
163 DisableReplaceStmtScope(RewriteModernObjC &R)
164 : R(R), SavedValue(R.DisableReplaceStmt) {
165 R.DisableReplaceStmt = true;
166 }
167 ~DisableReplaceStmtScope() {
168 R.DisableReplaceStmt = SavedValue;
169 }
170 };
171 void InitializeCommon(ASTContext &context);
172
173 public:
Fariborz Jahanian90af4e22012-02-14 17:19:02 +0000174 llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000175 // Top Level Driver code.
176 virtual bool HandleTopLevelDecl(DeclGroupRef D) {
177 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
178 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(*I)) {
179 if (!Class->isThisDeclarationADefinition()) {
180 RewriteForwardClassDecl(D);
181 break;
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +0000182 } else {
183 // Keep track of all interface declarations seen.
Fariborz Jahanianf3295272012-02-24 21:42:38 +0000184 ObjCInterfacesSeen.push_back(Class);
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +0000185 break;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000186 }
187 }
188
189 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>(*I)) {
190 if (!Proto->isThisDeclarationADefinition()) {
191 RewriteForwardProtocolDecl(D);
192 break;
193 }
194 }
195
196 HandleTopLevelSingleDecl(*I);
197 }
198 return true;
199 }
200 void HandleTopLevelSingleDecl(Decl *D);
201 void HandleDeclInMainFile(Decl *D);
202 RewriteModernObjC(std::string inFile, raw_ostream *OS,
203 DiagnosticsEngine &D, const LangOptions &LOpts,
204 bool silenceMacroWarn);
205
206 ~RewriteModernObjC() {}
207
208 virtual void HandleTranslationUnit(ASTContext &C);
209
210 void ReplaceStmt(Stmt *Old, Stmt *New) {
211 Stmt *ReplacingStmt = ReplacedNodes[Old];
212
213 if (ReplacingStmt)
214 return; // We can't rewrite the same node twice.
215
216 if (DisableReplaceStmt)
217 return;
218
219 // If replacement succeeded or warning disabled return with no warning.
220 if (!Rewrite.ReplaceStmt(Old, New)) {
221 ReplacedNodes[Old] = New;
222 return;
223 }
224 if (SilenceRewriteMacroWarning)
225 return;
226 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
227 << Old->getSourceRange();
228 }
229
230 void ReplaceStmtWithRange(Stmt *Old, Stmt *New, SourceRange SrcRange) {
231 if (DisableReplaceStmt)
232 return;
233
234 // Measure the old text.
235 int Size = Rewrite.getRangeSize(SrcRange);
236 if (Size == -1) {
237 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
238 << Old->getSourceRange();
239 return;
240 }
241 // Get the new text.
242 std::string SStr;
243 llvm::raw_string_ostream S(SStr);
244 New->printPretty(S, *Context, 0, PrintingPolicy(LangOpts));
245 const std::string &Str = S.str();
246
247 // If replacement succeeded or warning disabled return with no warning.
248 if (!Rewrite.ReplaceText(SrcRange.getBegin(), Size, Str)) {
249 ReplacedNodes[Old] = New;
250 return;
251 }
252 if (SilenceRewriteMacroWarning)
253 return;
254 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
255 << Old->getSourceRange();
256 }
257
258 void InsertText(SourceLocation Loc, StringRef Str,
259 bool InsertAfter = true) {
260 // If insertion succeeded or warning disabled return with no warning.
261 if (!Rewrite.InsertText(Loc, Str, InsertAfter) ||
262 SilenceRewriteMacroWarning)
263 return;
264
265 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
266 }
267
268 void ReplaceText(SourceLocation Start, unsigned OrigLength,
269 StringRef Str) {
270 // If removal succeeded or warning disabled return with no warning.
271 if (!Rewrite.ReplaceText(Start, OrigLength, Str) ||
272 SilenceRewriteMacroWarning)
273 return;
274
275 Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
276 }
277
278 // Syntactic Rewriting.
279 void RewriteRecordBody(RecordDecl *RD);
280 void RewriteInclude();
281 void RewriteForwardClassDecl(DeclGroupRef D);
282 void RewriteForwardClassDecl(const llvm::SmallVector<Decl*, 8> &DG);
283 void RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
284 const std::string &typedefString);
285 void RewriteImplementations();
286 void RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
287 ObjCImplementationDecl *IMD,
288 ObjCCategoryImplDecl *CID);
289 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
290 void RewriteImplementationDecl(Decl *Dcl);
291 void RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
292 ObjCMethodDecl *MDecl, std::string &ResultStr);
293 void RewriteTypeIntoString(QualType T, std::string &ResultStr,
294 const FunctionType *&FPRetType);
295 void RewriteByRefString(std::string &ResultStr, const std::string &Name,
296 ValueDecl *VD, bool def=false);
297 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
298 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
299 void RewriteForwardProtocolDecl(DeclGroupRef D);
300 void RewriteForwardProtocolDecl(const llvm::SmallVector<Decl*, 8> &DG);
301 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
302 void RewriteProperty(ObjCPropertyDecl *prop);
303 void RewriteFunctionDecl(FunctionDecl *FD);
304 void RewriteBlockPointerType(std::string& Str, QualType Type);
305 void RewriteBlockPointerTypeVariable(std::string& Str, ValueDecl *VD);
Fariborz Jahanianb75f8de2012-04-19 00:50:01 +0000306 void RewriteBlockLiteralFunctionDecl(FunctionDecl *FD);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000307 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
308 void RewriteTypeOfDecl(VarDecl *VD);
309 void RewriteObjCQualifiedInterfaceTypes(Expr *E);
310
311 // Expression Rewriting.
312 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
313 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
314 Stmt *RewritePropertyOrImplicitGetter(PseudoObjectExpr *Pseudo);
315 Stmt *RewritePropertyOrImplicitSetter(PseudoObjectExpr *Pseudo);
316 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
317 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
318 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian55947042012-03-27 20:17:30 +0000319 Stmt *RewriteObjCBoolLiteralExpr(ObjCBoolLiteralExpr *Exp);
Patrick Beardeb382ec2012-04-19 00:25:12 +0000320 Stmt *RewriteObjCBoxedExpr(ObjCBoxedExpr *Exp);
Fariborz Jahanian86cff602012-03-30 23:35:47 +0000321 Stmt *RewriteObjCArrayLiteralExpr(ObjCArrayLiteral *Exp);
Fariborz Jahaniane35abe12012-04-06 22:29:36 +0000322 Stmt *RewriteObjCDictionaryLiteralExpr(ObjCDictionaryLiteral *Exp);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000323 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000324 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
325 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
326 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
327 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
328 SourceLocation OrigEnd);
329 Stmt *RewriteBreakStmt(BreakStmt *S);
330 Stmt *RewriteContinueStmt(ContinueStmt *S);
331 void RewriteCastExpr(CStyleCastExpr *CE);
Fariborz Jahanianf1ee6872012-04-10 00:08:18 +0000332 void RewriteImplicitCastObjCExpr(CastExpr *IE);
Fariborz Jahanianb3f904f2012-04-03 17:35:38 +0000333 void RewriteLinkageSpec(LinkageSpecDecl *LSD);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000334
335 // Block rewriting.
336 void RewriteBlocksInFunctionProtoType(QualType funcType, NamedDecl *D);
337
338 // Block specific rewrite rules.
339 void RewriteBlockPointerDecl(NamedDecl *VD);
Fariborz Jahanian4fe261c2012-04-24 19:38:45 +0000340 void RewriteByRefVar(VarDecl *VD, bool firstDecl, bool lastDecl);
John McCallf4b88a42012-03-10 09:33:50 +0000341 Stmt *RewriteBlockDeclRefExpr(DeclRefExpr *VD);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000342 Stmt *RewriteLocalVariableExternalStorage(DeclRefExpr *DRE);
343 void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
344
345 void RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
346 std::string &Result);
347
Fariborz Jahanian15f87772012-02-28 22:45:07 +0000348 void RewriteObjCFieldDecl(FieldDecl *fieldDecl, std::string &Result);
Fariborz Jahanianb68258f2012-05-01 17:46:45 +0000349 bool IsTagDefinedInsideClass(ObjCContainerDecl *IDecl, TagDecl *Tag,
Fariborz Jahanian8fba8942012-04-30 23:20:30 +0000350 bool &IsNamedDefinition);
351 void RewriteLocallyDefinedNamedAggregates(FieldDecl *fieldDecl,
352 std::string &Result);
Fariborz Jahanian15f87772012-02-28 22:45:07 +0000353
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +0000354 bool RewriteObjCFieldDeclType(QualType &Type, std::string &Result);
355
Fariborz Jahanian72c88f12012-02-22 18:13:25 +0000356 void RewriteIvarOffsetSymbols(ObjCInterfaceDecl *CDecl,
357 std::string &Result);
358
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000359 virtual void Initialize(ASTContext &context);
360
361 // Misc. AST transformation routines. Somtimes they end up calling
362 // rewriting routines on the new ASTs.
363 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
364 Expr **args, unsigned nargs,
365 SourceLocation StartLoc=SourceLocation(),
366 SourceLocation EndLoc=SourceLocation());
367
368 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp,
369 SourceLocation StartLoc=SourceLocation(),
370 SourceLocation EndLoc=SourceLocation());
371
372 void SynthCountByEnumWithState(std::string &buf);
373 void SynthMsgSendFunctionDecl();
374 void SynthMsgSendSuperFunctionDecl();
375 void SynthMsgSendStretFunctionDecl();
376 void SynthMsgSendFpretFunctionDecl();
377 void SynthMsgSendSuperStretFunctionDecl();
378 void SynthGetClassFunctionDecl();
379 void SynthGetMetaClassFunctionDecl();
380 void SynthGetSuperClassFunctionDecl();
381 void SynthSelGetUidFunctionDecl();
382 void SynthSuperContructorFunctionDecl();
383
384 // Rewriting metadata
385 template<typename MethodIterator>
386 void RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
387 MethodIterator MethodEnd,
388 bool IsInstanceMethod,
389 StringRef prefix,
390 StringRef ClassName,
391 std::string &Result);
Fariborz Jahanianda9624a2012-02-08 19:53:58 +0000392 void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
393 std::string &Result);
Fariborz Jahanianb4ee8802012-04-30 16:57:52 +0000394 void RewriteObjCProtocolListMetaData(
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000395 const ObjCList<ObjCProtocolDecl> &Prots,
396 StringRef prefix, StringRef ClassName, std::string &Result);
Fariborz Jahanianb4ee8802012-04-30 16:57:52 +0000397 void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000398 std::string &Result);
Fariborz Jahanianb4ee8802012-04-30 16:57:52 +0000399 void RewriteClassSetupInitHook(std::string &Result);
Fariborz Jahaniane0335782012-03-27 18:41:05 +0000400
Fariborz Jahanianb4ee8802012-04-30 16:57:52 +0000401 void RewriteMetaDataIntoBuffer(std::string &Result);
402 void WriteImageInfo(std::string &Result);
403 void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000404 std::string &Result);
Fariborz Jahanianb4ee8802012-04-30 16:57:52 +0000405 void RewriteCategorySetupInitHook(std::string &Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000406
407 // Rewriting ivar
Fariborz Jahanianb4ee8802012-04-30 16:57:52 +0000408 void RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000409 std::string &Result);
Fariborz Jahanianb4ee8802012-04-30 16:57:52 +0000410 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000411
412
413 std::string SynthesizeByrefCopyDestroyHelper(VarDecl *VD, int flag);
414 std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
415 StringRef funcName, std::string Tag);
416 std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
417 StringRef funcName, std::string Tag);
418 std::string SynthesizeBlockImpl(BlockExpr *CE,
419 std::string Tag, std::string Desc);
420 std::string SynthesizeBlockDescriptor(std::string DescTag,
421 std::string ImplTag,
422 int i, StringRef funcName,
423 unsigned hasCopy);
424 Stmt *SynthesizeBlockCall(CallExpr *Exp, const Expr* BlockExp);
425 void SynthesizeBlockLiterals(SourceLocation FunLocStart,
426 StringRef FunName);
427 FunctionDecl *SynthBlockInitFunctionDecl(StringRef name);
428 Stmt *SynthBlockInitExpr(BlockExpr *Exp,
John McCallf4b88a42012-03-10 09:33:50 +0000429 const SmallVector<DeclRefExpr *, 8> &InnerBlockDeclRefs);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000430
431 // Misc. helper routines.
432 QualType getProtocolType();
433 void WarnAboutReturnGotoStmts(Stmt *S);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000434 void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
435 void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
436 void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
437
438 bool IsDeclStmtInForeachHeader(DeclStmt *DS);
439 void CollectBlockDeclRefInfo(BlockExpr *Exp);
440 void GetBlockDeclRefExprs(Stmt *S);
441 void GetInnerBlockDeclRefExprs(Stmt *S,
John McCallf4b88a42012-03-10 09:33:50 +0000442 SmallVector<DeclRefExpr *, 8> &InnerBlockDeclRefs,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000443 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts);
444
445 // We avoid calling Type::isBlockPointerType(), since it operates on the
446 // canonical type. We only care if the top-level type is a closure pointer.
447 bool isTopLevelBlockPointerType(QualType T) {
448 return isa<BlockPointerType>(T);
449 }
450
451 /// convertBlockPointerToFunctionPointer - Converts a block-pointer type
452 /// to a function pointer type and upon success, returns true; false
453 /// otherwise.
454 bool convertBlockPointerToFunctionPointer(QualType &T) {
455 if (isTopLevelBlockPointerType(T)) {
456 const BlockPointerType *BPT = T->getAs<BlockPointerType>();
457 T = Context->getPointerType(BPT->getPointeeType());
458 return true;
459 }
460 return false;
461 }
462
Fariborz Jahanian164d6f82012-02-13 18:57:49 +0000463 bool convertObjCTypeToCStyleType(QualType &T);
464
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000465 bool needToScanForQualifiers(QualType T);
466 QualType getSuperStructType();
467 QualType getConstantStringStructType();
468 QualType convertFunctionTypeOfBlocks(const FunctionType *FT);
469 bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf);
470
471 void convertToUnqualifiedObjCType(QualType &T) {
Fariborz Jahaniane35abe12012-04-06 22:29:36 +0000472 if (T->isObjCQualifiedIdType()) {
473 bool isConst = T.isConstQualified();
474 T = isConst ? Context->getObjCIdType().withConst()
475 : Context->getObjCIdType();
476 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000477 else if (T->isObjCQualifiedClassType())
478 T = Context->getObjCClassType();
479 else if (T->isObjCObjectPointerType() &&
480 T->getPointeeType()->isObjCQualifiedInterfaceType()) {
481 if (const ObjCObjectPointerType * OBJPT =
482 T->getAsObjCInterfacePointerType()) {
483 const ObjCInterfaceType *IFaceT = OBJPT->getInterfaceType();
484 T = QualType(IFaceT, 0);
485 T = Context->getPointerType(T);
486 }
487 }
488 }
489
490 // FIXME: This predicate seems like it would be useful to add to ASTContext.
491 bool isObjCType(QualType T) {
492 if (!LangOpts.ObjC1 && !LangOpts.ObjC2)
493 return false;
494
495 QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
496
497 if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
498 OCT == Context->getCanonicalType(Context->getObjCClassType()))
499 return true;
500
501 if (const PointerType *PT = OCT->getAs<PointerType>()) {
502 if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
503 PT->getPointeeType()->isObjCQualifiedIdType())
504 return true;
505 }
506 return false;
507 }
508 bool PointerTypeTakesAnyBlockArguments(QualType QT);
509 bool PointerTypeTakesAnyObjCQualifiedType(QualType QT);
510 void GetExtentOfArgList(const char *Name, const char *&LParen,
511 const char *&RParen);
512
513 void QuoteDoublequotes(std::string &From, std::string &To) {
514 for (unsigned i = 0; i < From.length(); i++) {
515 if (From[i] == '"')
516 To += "\\\"";
517 else
518 To += From[i];
519 }
520 }
521
522 QualType getSimpleFunctionType(QualType result,
523 const QualType *args,
524 unsigned numArgs,
525 bool variadic = false) {
526 if (result == Context->getObjCInstanceType())
527 result = Context->getObjCIdType();
528 FunctionProtoType::ExtProtoInfo fpi;
529 fpi.Variadic = variadic;
530 return Context->getFunctionType(result, args, numArgs, fpi);
531 }
532
533 // Helper function: create a CStyleCastExpr with trivial type source info.
534 CStyleCastExpr* NoTypeInfoCStyleCastExpr(ASTContext *Ctx, QualType Ty,
535 CastKind Kind, Expr *E) {
536 TypeSourceInfo *TInfo = Ctx->getTrivialTypeSourceInfo(Ty, SourceLocation());
537 return CStyleCastExpr::Create(*Ctx, Ty, VK_RValue, Kind, E, 0, TInfo,
538 SourceLocation(), SourceLocation());
539 }
Fariborz Jahanian88f7f752012-03-14 23:18:19 +0000540
541 bool ImplementationIsNonLazy(const ObjCImplDecl *OD) const {
542 IdentifierInfo* II = &Context->Idents.get("load");
543 Selector LoadSel = Context->Selectors.getSelector(0, &II);
544 return OD->getClassMethod(LoadSel) != 0;
545 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000546 };
547
548}
549
550void RewriteModernObjC::RewriteBlocksInFunctionProtoType(QualType funcType,
551 NamedDecl *D) {
552 if (const FunctionProtoType *fproto
553 = dyn_cast<FunctionProtoType>(funcType.IgnoreParens())) {
554 for (FunctionProtoType::arg_type_iterator I = fproto->arg_type_begin(),
555 E = fproto->arg_type_end(); I && (I != E); ++I)
556 if (isTopLevelBlockPointerType(*I)) {
557 // All the args are checked/rewritten. Don't call twice!
558 RewriteBlockPointerDecl(D);
559 break;
560 }
561 }
562}
563
564void RewriteModernObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
565 const PointerType *PT = funcType->getAs<PointerType>();
566 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
567 RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND);
568}
569
570static bool IsHeaderFile(const std::string &Filename) {
571 std::string::size_type DotPos = Filename.rfind('.');
572
573 if (DotPos == std::string::npos) {
574 // no file extension
575 return false;
576 }
577
578 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
579 // C header: .h
580 // C++ header: .hh or .H;
581 return Ext == "h" || Ext == "hh" || Ext == "H";
582}
583
584RewriteModernObjC::RewriteModernObjC(std::string inFile, raw_ostream* OS,
585 DiagnosticsEngine &D, const LangOptions &LOpts,
586 bool silenceMacroWarn)
587 : Diags(D), LangOpts(LOpts), InFileName(inFile), OutFile(OS),
588 SilenceRewriteMacroWarning(silenceMacroWarn) {
589 IsHeader = IsHeaderFile(inFile);
590 RewriteFailedDiag = Diags.getCustomDiagID(DiagnosticsEngine::Warning,
591 "rewriting sub-expression within a macro (may not be correct)");
Fariborz Jahaniand13c2c22012-03-22 19:54:39 +0000592 // FIXME. This should be an error. But if block is not called, it is OK. And it
593 // may break including some headers.
594 GlobalBlockRewriteFailedDiag = Diags.getCustomDiagID(DiagnosticsEngine::Warning,
595 "rewriting block literal declared in global scope is not implemented");
596
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000597 TryFinallyContainsReturnDiag = Diags.getCustomDiagID(
598 DiagnosticsEngine::Warning,
599 "rewriter doesn't support user-specified control flow semantics "
600 "for @try/@finally (code may not execute properly)");
601}
602
603ASTConsumer *clang::CreateModernObjCRewriter(const std::string& InFile,
604 raw_ostream* OS,
605 DiagnosticsEngine &Diags,
606 const LangOptions &LOpts,
607 bool SilenceRewriteMacroWarning) {
608 return new RewriteModernObjC(InFile, OS, Diags, LOpts, SilenceRewriteMacroWarning);
609}
610
611void RewriteModernObjC::InitializeCommon(ASTContext &context) {
612 Context = &context;
613 SM = &Context->getSourceManager();
614 TUDecl = Context->getTranslationUnitDecl();
615 MsgSendFunctionDecl = 0;
616 MsgSendSuperFunctionDecl = 0;
617 MsgSendStretFunctionDecl = 0;
618 MsgSendSuperStretFunctionDecl = 0;
619 MsgSendFpretFunctionDecl = 0;
620 GetClassFunctionDecl = 0;
621 GetMetaClassFunctionDecl = 0;
622 GetSuperClassFunctionDecl = 0;
623 SelGetUidFunctionDecl = 0;
624 CFStringFunctionDecl = 0;
625 ConstantStringClassReference = 0;
626 NSStringRecord = 0;
627 CurMethodDef = 0;
628 CurFunctionDef = 0;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000629 GlobalVarDecl = 0;
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +0000630 GlobalConstructionExp = 0;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000631 SuperStructDecl = 0;
632 ProtocolTypeDecl = 0;
633 ConstantStringDecl = 0;
634 BcLabelCount = 0;
635 SuperContructorFunctionDecl = 0;
636 NumObjCStringLiterals = 0;
637 PropParentMap = 0;
638 CurrentBody = 0;
639 DisableReplaceStmt = false;
640 objc_impl_method = false;
641
642 // Get the ID and start/end of the main file.
643 MainFileID = SM->getMainFileID();
644 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
645 MainFileStart = MainBuf->getBufferStart();
646 MainFileEnd = MainBuf->getBufferEnd();
647
David Blaikie4e4d0842012-03-11 07:00:24 +0000648 Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOpts());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000649}
650
651//===----------------------------------------------------------------------===//
652// Top Level Driver Code
653//===----------------------------------------------------------------------===//
654
655void RewriteModernObjC::HandleTopLevelSingleDecl(Decl *D) {
656 if (Diags.hasErrorOccurred())
657 return;
658
659 // Two cases: either the decl could be in the main file, or it could be in a
660 // #included file. If the former, rewrite it now. If the later, check to see
661 // if we rewrote the #include/#import.
662 SourceLocation Loc = D->getLocation();
663 Loc = SM->getExpansionLoc(Loc);
664
665 // If this is for a builtin, ignore it.
666 if (Loc.isInvalid()) return;
667
668 // Look for built-in declarations that we need to refer during the rewrite.
669 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
670 RewriteFunctionDecl(FD);
671 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
672 // declared in <Foundation/NSString.h>
673 if (FVD->getName() == "_NSConstantStringClassReference") {
674 ConstantStringClassReference = FVD;
675 return;
676 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000677 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
678 RewriteCategoryDecl(CD);
679 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
680 if (PD->isThisDeclarationADefinition())
681 RewriteProtocolDecl(PD);
682 } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) {
Fariborz Jahanian8e86b2d2012-04-04 17:16:15 +0000683 // FIXME. This will not work in all situations and leaving it out
684 // is harmless.
685 // RewriteLinkageSpec(LSD);
686
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000687 // Recurse into linkage specifications
688 for (DeclContext::decl_iterator DI = LSD->decls_begin(),
689 DIEnd = LSD->decls_end();
690 DI != DIEnd; ) {
691 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>((*DI))) {
692 if (!IFace->isThisDeclarationADefinition()) {
693 SmallVector<Decl *, 8> DG;
694 SourceLocation StartLoc = IFace->getLocStart();
695 do {
696 if (isa<ObjCInterfaceDecl>(*DI) &&
697 !cast<ObjCInterfaceDecl>(*DI)->isThisDeclarationADefinition() &&
698 StartLoc == (*DI)->getLocStart())
699 DG.push_back(*DI);
700 else
701 break;
702
703 ++DI;
704 } while (DI != DIEnd);
705 RewriteForwardClassDecl(DG);
706 continue;
707 }
Fariborz Jahanianb3f904f2012-04-03 17:35:38 +0000708 else {
709 // Keep track of all interface declarations seen.
710 ObjCInterfacesSeen.push_back(IFace);
711 ++DI;
712 continue;
713 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000714 }
715
716 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>((*DI))) {
717 if (!Proto->isThisDeclarationADefinition()) {
718 SmallVector<Decl *, 8> DG;
719 SourceLocation StartLoc = Proto->getLocStart();
720 do {
721 if (isa<ObjCProtocolDecl>(*DI) &&
722 !cast<ObjCProtocolDecl>(*DI)->isThisDeclarationADefinition() &&
723 StartLoc == (*DI)->getLocStart())
724 DG.push_back(*DI);
725 else
726 break;
727
728 ++DI;
729 } while (DI != DIEnd);
730 RewriteForwardProtocolDecl(DG);
731 continue;
732 }
733 }
734
735 HandleTopLevelSingleDecl(*DI);
736 ++DI;
737 }
738 }
739 // If we have a decl in the main file, see if we should rewrite it.
740 if (SM->isFromMainFile(Loc))
741 return HandleDeclInMainFile(D);
742}
743
744//===----------------------------------------------------------------------===//
745// Syntactic (non-AST) Rewriting Code
746//===----------------------------------------------------------------------===//
747
748void RewriteModernObjC::RewriteInclude() {
749 SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID);
750 StringRef MainBuf = SM->getBufferData(MainFileID);
751 const char *MainBufStart = MainBuf.begin();
752 const char *MainBufEnd = MainBuf.end();
753 size_t ImportLen = strlen("import");
754
755 // Loop over the whole file, looking for includes.
756 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
757 if (*BufPtr == '#') {
758 if (++BufPtr == MainBufEnd)
759 return;
760 while (*BufPtr == ' ' || *BufPtr == '\t')
761 if (++BufPtr == MainBufEnd)
762 return;
763 if (!strncmp(BufPtr, "import", ImportLen)) {
764 // replace import with include
765 SourceLocation ImportLoc =
766 LocStart.getLocWithOffset(BufPtr-MainBufStart);
767 ReplaceText(ImportLoc, ImportLen, "include");
768 BufPtr += ImportLen;
769 }
770 }
771 }
772}
773
774static std::string getIvarAccessString(ObjCIvarDecl *OID) {
775 const ObjCInterfaceDecl *ClassDecl = OID->getContainingInterface();
776 std::string S;
777 S = "((struct ";
778 S += ClassDecl->getIdentifier()->getName();
779 S += "_IMPL *)self)->";
780 S += OID->getName();
781 return S;
782}
783
Fariborz Jahanian301e2e42012-05-03 22:52:13 +0000784/// mustSynthesizeSetterGetterMethod - returns true if setter or getter has not
785/// been found in the class implementation. In this case, it must be synthesized.
786static bool mustSynthesizeSetterGetterMethod(ObjCImplementationDecl *IMP,
787 ObjCPropertyDecl *PD,
788 bool getter) {
789 return getter ? !IMP->getInstanceMethod(PD->getGetterName())
790 : !IMP->getInstanceMethod(PD->getSetterName());
791
792}
793
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000794void RewriteModernObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
795 ObjCImplementationDecl *IMD,
796 ObjCCategoryImplDecl *CID) {
797 static bool objcGetPropertyDefined = false;
798 static bool objcSetPropertyDefined = false;
Fariborz Jahanian301e2e42012-05-03 22:52:13 +0000799 SourceLocation startGetterSetterLoc;
800
801 if (PID->getLocStart().isValid()) {
802 SourceLocation startLoc = PID->getLocStart();
803 InsertText(startLoc, "// ");
804 const char *startBuf = SM->getCharacterData(startLoc);
805 assert((*startBuf == '@') && "bogus @synthesize location");
806 const char *semiBuf = strchr(startBuf, ';');
807 assert((*semiBuf == ';') && "@synthesize: can't find ';'");
808 startGetterSetterLoc = startLoc.getLocWithOffset(semiBuf-startBuf+1);
809 }
810 else
811 startGetterSetterLoc = IMD ? IMD->getLocEnd() : CID->getLocEnd();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000812
813 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
814 return; // FIXME: is this correct?
815
816 // Generate the 'getter' function.
817 ObjCPropertyDecl *PD = PID->getPropertyDecl();
818 ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
819
820 if (!OID)
821 return;
822 unsigned Attributes = PD->getPropertyAttributes();
Fariborz Jahanian301e2e42012-05-03 22:52:13 +0000823 if (mustSynthesizeSetterGetterMethod(IMD, PD, true /*getter*/)) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000824 bool GenGetProperty = !(Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic) &&
825 (Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
826 ObjCPropertyDecl::OBJC_PR_copy));
827 std::string Getr;
828 if (GenGetProperty && !objcGetPropertyDefined) {
829 objcGetPropertyDefined = true;
830 // FIXME. Is this attribute correct in all cases?
831 Getr = "\nextern \"C\" __declspec(dllimport) "
832 "id objc_getProperty(id, SEL, long, bool);\n";
833 }
834 RewriteObjCMethodDecl(OID->getContainingInterface(),
835 PD->getGetterMethodDecl(), Getr);
836 Getr += "{ ";
837 // Synthesize an explicit cast to gain access to the ivar.
838 // See objc-act.c:objc_synthesize_new_getter() for details.
839 if (GenGetProperty) {
840 // return objc_getProperty(self, _cmd, offsetof(ClassDecl, OID), 1)
841 Getr += "typedef ";
842 const FunctionType *FPRetType = 0;
843 RewriteTypeIntoString(PD->getGetterMethodDecl()->getResultType(), Getr,
844 FPRetType);
845 Getr += " _TYPE";
846 if (FPRetType) {
847 Getr += ")"; // close the precedence "scope" for "*".
848
849 // Now, emit the argument types (if any).
850 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)){
851 Getr += "(";
852 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
853 if (i) Getr += ", ";
854 std::string ParamStr = FT->getArgType(i).getAsString(
855 Context->getPrintingPolicy());
856 Getr += ParamStr;
857 }
858 if (FT->isVariadic()) {
859 if (FT->getNumArgs()) Getr += ", ";
860 Getr += "...";
861 }
862 Getr += ")";
863 } else
864 Getr += "()";
865 }
866 Getr += ";\n";
867 Getr += "return (_TYPE)";
868 Getr += "objc_getProperty(self, _cmd, ";
869 RewriteIvarOffsetComputation(OID, Getr);
870 Getr += ", 1)";
871 }
872 else
873 Getr += "return " + getIvarAccessString(OID);
874 Getr += "; }";
Fariborz Jahanian301e2e42012-05-03 22:52:13 +0000875 InsertText(startGetterSetterLoc, Getr);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000876 }
877
Fariborz Jahanian301e2e42012-05-03 22:52:13 +0000878 if (PD->isReadOnly() ||
879 !mustSynthesizeSetterGetterMethod(IMD, PD, false /*setter*/))
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000880 return;
881
882 // Generate the 'setter' function.
883 std::string Setr;
884 bool GenSetProperty = Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
885 ObjCPropertyDecl::OBJC_PR_copy);
886 if (GenSetProperty && !objcSetPropertyDefined) {
887 objcSetPropertyDefined = true;
888 // FIXME. Is this attribute correct in all cases?
889 Setr = "\nextern \"C\" __declspec(dllimport) "
890 "void objc_setProperty (id, SEL, long, id, bool, bool);\n";
891 }
892
893 RewriteObjCMethodDecl(OID->getContainingInterface(),
894 PD->getSetterMethodDecl(), Setr);
895 Setr += "{ ";
896 // Synthesize an explicit cast to initialize the ivar.
897 // See objc-act.c:objc_synthesize_new_setter() for details.
898 if (GenSetProperty) {
899 Setr += "objc_setProperty (self, _cmd, ";
900 RewriteIvarOffsetComputation(OID, Setr);
901 Setr += ", (id)";
902 Setr += PD->getName();
903 Setr += ", ";
904 if (Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic)
905 Setr += "0, ";
906 else
907 Setr += "1, ";
908 if (Attributes & ObjCPropertyDecl::OBJC_PR_copy)
909 Setr += "1)";
910 else
911 Setr += "0)";
912 }
913 else {
914 Setr += getIvarAccessString(OID) + " = ";
915 Setr += PD->getName();
916 }
Fariborz Jahanian301e2e42012-05-03 22:52:13 +0000917 Setr += "; }\n";
918 InsertText(startGetterSetterLoc, Setr);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000919}
920
921static void RewriteOneForwardClassDecl(ObjCInterfaceDecl *ForwardDecl,
922 std::string &typedefString) {
923 typedefString += "#ifndef _REWRITER_typedef_";
924 typedefString += ForwardDecl->getNameAsString();
925 typedefString += "\n";
926 typedefString += "#define _REWRITER_typedef_";
927 typedefString += ForwardDecl->getNameAsString();
928 typedefString += "\n";
929 typedefString += "typedef struct objc_object ";
930 typedefString += ForwardDecl->getNameAsString();
Fariborz Jahanianc38503b2012-03-12 23:58:28 +0000931 // typedef struct { } _objc_exc_Classname;
932 typedefString += ";\ntypedef struct {} _objc_exc_";
933 typedefString += ForwardDecl->getNameAsString();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000934 typedefString += ";\n#endif\n";
935}
936
937void RewriteModernObjC::RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
938 const std::string &typedefString) {
939 SourceLocation startLoc = ClassDecl->getLocStart();
940 const char *startBuf = SM->getCharacterData(startLoc);
941 const char *semiPtr = strchr(startBuf, ';');
942 // Replace the @class with typedefs corresponding to the classes.
943 ReplaceText(startLoc, semiPtr-startBuf+1, typedefString);
944}
945
946void RewriteModernObjC::RewriteForwardClassDecl(DeclGroupRef D) {
947 std::string typedefString;
948 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
949 ObjCInterfaceDecl *ForwardDecl = cast<ObjCInterfaceDecl>(*I);
950 if (I == D.begin()) {
951 // Translate to typedef's that forward reference structs with the same name
952 // as the class. As a convenience, we include the original declaration
953 // as a comment.
954 typedefString += "// @class ";
955 typedefString += ForwardDecl->getNameAsString();
956 typedefString += ";\n";
957 }
958 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
959 }
960 DeclGroupRef::iterator I = D.begin();
961 RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(*I), typedefString);
962}
963
964void RewriteModernObjC::RewriteForwardClassDecl(
965 const llvm::SmallVector<Decl*, 8> &D) {
966 std::string typedefString;
967 for (unsigned i = 0; i < D.size(); i++) {
968 ObjCInterfaceDecl *ForwardDecl = cast<ObjCInterfaceDecl>(D[i]);
969 if (i == 0) {
970 typedefString += "// @class ";
971 typedefString += ForwardDecl->getNameAsString();
972 typedefString += ";\n";
973 }
974 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
975 }
976 RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(D[0]), typedefString);
977}
978
979void RewriteModernObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
980 // When method is a synthesized one, such as a getter/setter there is
981 // nothing to rewrite.
982 if (Method->isImplicit())
983 return;
984 SourceLocation LocStart = Method->getLocStart();
985 SourceLocation LocEnd = Method->getLocEnd();
986
987 if (SM->getExpansionLineNumber(LocEnd) >
988 SM->getExpansionLineNumber(LocStart)) {
989 InsertText(LocStart, "#if 0\n");
990 ReplaceText(LocEnd, 1, ";\n#endif\n");
991 } else {
992 InsertText(LocStart, "// ");
993 }
994}
995
996void RewriteModernObjC::RewriteProperty(ObjCPropertyDecl *prop) {
997 SourceLocation Loc = prop->getAtLoc();
998
999 ReplaceText(Loc, 0, "// ");
1000 // FIXME: handle properties that are declared across multiple lines.
1001}
1002
1003void RewriteModernObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
1004 SourceLocation LocStart = CatDecl->getLocStart();
1005
1006 // FIXME: handle category headers that are declared across multiple lines.
Fariborz Jahanianb68258f2012-05-01 17:46:45 +00001007 if (CatDecl->getIvarRBraceLoc().isValid()) {
1008 ReplaceText(LocStart, 1, "/** ");
1009 ReplaceText(CatDecl->getIvarRBraceLoc(), 1, "**/ ");
1010 }
1011 else {
Fariborz Jahaniand2aea122012-02-19 19:00:05 +00001012 ReplaceText(LocStart, 0, "// ");
Fariborz Jahanianb68258f2012-05-01 17:46:45 +00001013 }
Fariborz Jahanianaf300292012-02-20 20:09:20 +00001014
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001015 for (ObjCCategoryDecl::prop_iterator I = CatDecl->prop_begin(),
1016 E = CatDecl->prop_end(); I != E; ++I)
David Blaikie262bc182012-04-30 02:36:29 +00001017 RewriteProperty(&*I);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001018
1019 for (ObjCCategoryDecl::instmeth_iterator
1020 I = CatDecl->instmeth_begin(), E = CatDecl->instmeth_end();
1021 I != E; ++I)
1022 RewriteMethodDeclaration(*I);
1023 for (ObjCCategoryDecl::classmeth_iterator
1024 I = CatDecl->classmeth_begin(), E = CatDecl->classmeth_end();
1025 I != E; ++I)
1026 RewriteMethodDeclaration(*I);
1027
1028 // Lastly, comment out the @end.
1029 ReplaceText(CatDecl->getAtEndRange().getBegin(),
1030 strlen("@end"), "/* @end */");
1031}
1032
1033void RewriteModernObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
1034 SourceLocation LocStart = PDecl->getLocStart();
1035 assert(PDecl->isThisDeclarationADefinition());
1036
1037 // FIXME: handle protocol headers that are declared across multiple lines.
1038 ReplaceText(LocStart, 0, "// ");
1039
1040 for (ObjCProtocolDecl::instmeth_iterator
1041 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
1042 I != E; ++I)
1043 RewriteMethodDeclaration(*I);
1044 for (ObjCProtocolDecl::classmeth_iterator
1045 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
1046 I != E; ++I)
1047 RewriteMethodDeclaration(*I);
1048
1049 for (ObjCInterfaceDecl::prop_iterator I = PDecl->prop_begin(),
1050 E = PDecl->prop_end(); I != E; ++I)
David Blaikie262bc182012-04-30 02:36:29 +00001051 RewriteProperty(&*I);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001052
1053 // Lastly, comment out the @end.
1054 SourceLocation LocEnd = PDecl->getAtEndRange().getBegin();
1055 ReplaceText(LocEnd, strlen("@end"), "/* @end */");
1056
1057 // Must comment out @optional/@required
1058 const char *startBuf = SM->getCharacterData(LocStart);
1059 const char *endBuf = SM->getCharacterData(LocEnd);
1060 for (const char *p = startBuf; p < endBuf; p++) {
1061 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
1062 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
1063 ReplaceText(OptionalLoc, strlen("@optional"), "/* @optional */");
1064
1065 }
1066 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
1067 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
1068 ReplaceText(OptionalLoc, strlen("@required"), "/* @required */");
1069
1070 }
1071 }
1072}
1073
1074void RewriteModernObjC::RewriteForwardProtocolDecl(DeclGroupRef D) {
1075 SourceLocation LocStart = (*D.begin())->getLocStart();
1076 if (LocStart.isInvalid())
1077 llvm_unreachable("Invalid SourceLocation");
1078 // FIXME: handle forward protocol that are declared across multiple lines.
1079 ReplaceText(LocStart, 0, "// ");
1080}
1081
1082void
1083RewriteModernObjC::RewriteForwardProtocolDecl(const llvm::SmallVector<Decl*, 8> &DG) {
1084 SourceLocation LocStart = DG[0]->getLocStart();
1085 if (LocStart.isInvalid())
1086 llvm_unreachable("Invalid SourceLocation");
1087 // FIXME: handle forward protocol that are declared across multiple lines.
1088 ReplaceText(LocStart, 0, "// ");
1089}
1090
Fariborz Jahanianb3f904f2012-04-03 17:35:38 +00001091void
1092RewriteModernObjC::RewriteLinkageSpec(LinkageSpecDecl *LSD) {
1093 SourceLocation LocStart = LSD->getExternLoc();
1094 if (LocStart.isInvalid())
1095 llvm_unreachable("Invalid extern SourceLocation");
1096
1097 ReplaceText(LocStart, 0, "// ");
1098 if (!LSD->hasBraces())
1099 return;
1100 // FIXME. We don't rewrite well if '{' is not on same line as 'extern'.
1101 SourceLocation LocRBrace = LSD->getRBraceLoc();
1102 if (LocRBrace.isInvalid())
1103 llvm_unreachable("Invalid rbrace SourceLocation");
1104 ReplaceText(LocRBrace, 0, "// ");
1105}
1106
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001107void RewriteModernObjC::RewriteTypeIntoString(QualType T, std::string &ResultStr,
1108 const FunctionType *&FPRetType) {
1109 if (T->isObjCQualifiedIdType())
1110 ResultStr += "id";
1111 else if (T->isFunctionPointerType() ||
1112 T->isBlockPointerType()) {
1113 // needs special handling, since pointer-to-functions have special
1114 // syntax (where a decaration models use).
1115 QualType retType = T;
1116 QualType PointeeTy;
1117 if (const PointerType* PT = retType->getAs<PointerType>())
1118 PointeeTy = PT->getPointeeType();
1119 else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>())
1120 PointeeTy = BPT->getPointeeType();
1121 if ((FPRetType = PointeeTy->getAs<FunctionType>())) {
1122 ResultStr += FPRetType->getResultType().getAsString(
1123 Context->getPrintingPolicy());
1124 ResultStr += "(*";
1125 }
1126 } else
1127 ResultStr += T.getAsString(Context->getPrintingPolicy());
1128}
1129
1130void RewriteModernObjC::RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
1131 ObjCMethodDecl *OMD,
1132 std::string &ResultStr) {
1133 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
1134 const FunctionType *FPRetType = 0;
1135 ResultStr += "\nstatic ";
1136 RewriteTypeIntoString(OMD->getResultType(), ResultStr, FPRetType);
1137 ResultStr += " ";
1138
1139 // Unique method name
1140 std::string NameStr;
1141
1142 if (OMD->isInstanceMethod())
1143 NameStr += "_I_";
1144 else
1145 NameStr += "_C_";
1146
1147 NameStr += IDecl->getNameAsString();
1148 NameStr += "_";
1149
1150 if (ObjCCategoryImplDecl *CID =
1151 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
1152 NameStr += CID->getNameAsString();
1153 NameStr += "_";
1154 }
1155 // Append selector names, replacing ':' with '_'
1156 {
1157 std::string selString = OMD->getSelector().getAsString();
1158 int len = selString.size();
1159 for (int i = 0; i < len; i++)
1160 if (selString[i] == ':')
1161 selString[i] = '_';
1162 NameStr += selString;
1163 }
1164 // Remember this name for metadata emission
1165 MethodInternalNames[OMD] = NameStr;
1166 ResultStr += NameStr;
1167
1168 // Rewrite arguments
1169 ResultStr += "(";
1170
1171 // invisible arguments
1172 if (OMD->isInstanceMethod()) {
1173 QualType selfTy = Context->getObjCInterfaceType(IDecl);
1174 selfTy = Context->getPointerType(selfTy);
1175 if (!LangOpts.MicrosoftExt) {
1176 if (ObjCSynthesizedStructs.count(const_cast<ObjCInterfaceDecl*>(IDecl)))
1177 ResultStr += "struct ";
1178 }
1179 // When rewriting for Microsoft, explicitly omit the structure name.
1180 ResultStr += IDecl->getNameAsString();
1181 ResultStr += " *";
1182 }
1183 else
1184 ResultStr += Context->getObjCClassType().getAsString(
1185 Context->getPrintingPolicy());
1186
1187 ResultStr += " self, ";
1188 ResultStr += Context->getObjCSelType().getAsString(Context->getPrintingPolicy());
1189 ResultStr += " _cmd";
1190
1191 // Method arguments.
1192 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
1193 E = OMD->param_end(); PI != E; ++PI) {
1194 ParmVarDecl *PDecl = *PI;
1195 ResultStr += ", ";
1196 if (PDecl->getType()->isObjCQualifiedIdType()) {
1197 ResultStr += "id ";
1198 ResultStr += PDecl->getNameAsString();
1199 } else {
1200 std::string Name = PDecl->getNameAsString();
1201 QualType QT = PDecl->getType();
1202 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian2610f902012-03-27 16:42:20 +00001203 (void)convertBlockPointerToFunctionPointer(QT);
1204 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001205 ResultStr += Name;
1206 }
1207 }
1208 if (OMD->isVariadic())
1209 ResultStr += ", ...";
1210 ResultStr += ") ";
1211
1212 if (FPRetType) {
1213 ResultStr += ")"; // close the precedence "scope" for "*".
1214
1215 // Now, emit the argument types (if any).
1216 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
1217 ResultStr += "(";
1218 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
1219 if (i) ResultStr += ", ";
1220 std::string ParamStr = FT->getArgType(i).getAsString(
1221 Context->getPrintingPolicy());
1222 ResultStr += ParamStr;
1223 }
1224 if (FT->isVariadic()) {
1225 if (FT->getNumArgs()) ResultStr += ", ";
1226 ResultStr += "...";
1227 }
1228 ResultStr += ")";
1229 } else {
1230 ResultStr += "()";
1231 }
1232 }
1233}
1234void RewriteModernObjC::RewriteImplementationDecl(Decl *OID) {
1235 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
1236 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
1237
Fariborz Jahaniand2aea122012-02-19 19:00:05 +00001238 if (IMD) {
Fariborz Jahanianb68258f2012-05-01 17:46:45 +00001239 if (IMD->getIvarRBraceLoc().isValid()) {
1240 ReplaceText(IMD->getLocStart(), 1, "/** ");
1241 ReplaceText(IMD->getIvarRBraceLoc(), 1, "**/ ");
Fariborz Jahaniand2aea122012-02-19 19:00:05 +00001242 }
Fariborz Jahanianb68258f2012-05-01 17:46:45 +00001243 else {
1244 InsertText(IMD->getLocStart(), "// ");
1245 }
Fariborz Jahaniand2aea122012-02-19 19:00:05 +00001246 }
1247 else
1248 InsertText(CID->getLocStart(), "// ");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001249
1250 for (ObjCCategoryImplDecl::instmeth_iterator
1251 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
1252 E = IMD ? IMD->instmeth_end() : CID->instmeth_end();
1253 I != E; ++I) {
1254 std::string ResultStr;
1255 ObjCMethodDecl *OMD = *I;
1256 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
1257 SourceLocation LocStart = OMD->getLocStart();
1258 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
1259
1260 const char *startBuf = SM->getCharacterData(LocStart);
1261 const char *endBuf = SM->getCharacterData(LocEnd);
1262 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
1263 }
1264
1265 for (ObjCCategoryImplDecl::classmeth_iterator
1266 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
1267 E = IMD ? IMD->classmeth_end() : CID->classmeth_end();
1268 I != E; ++I) {
1269 std::string ResultStr;
1270 ObjCMethodDecl *OMD = *I;
1271 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
1272 SourceLocation LocStart = OMD->getLocStart();
1273 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
1274
1275 const char *startBuf = SM->getCharacterData(LocStart);
1276 const char *endBuf = SM->getCharacterData(LocEnd);
1277 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
1278 }
1279 for (ObjCCategoryImplDecl::propimpl_iterator
1280 I = IMD ? IMD->propimpl_begin() : CID->propimpl_begin(),
1281 E = IMD ? IMD->propimpl_end() : CID->propimpl_end();
1282 I != E; ++I) {
David Blaikie262bc182012-04-30 02:36:29 +00001283 RewritePropertyImplDecl(&*I, IMD, CID);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001284 }
1285
1286 InsertText(IMD ? IMD->getLocEnd() : CID->getLocEnd(), "// ");
1287}
1288
1289void RewriteModernObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00001290 // Do not synthesize more than once.
1291 if (ObjCSynthesizedStructs.count(ClassDecl))
1292 return;
1293 // Make sure super class's are written before current class is written.
1294 ObjCInterfaceDecl *SuperClass = ClassDecl->getSuperClass();
1295 while (SuperClass) {
1296 RewriteInterfaceDecl(SuperClass);
1297 SuperClass = SuperClass->getSuperClass();
1298 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001299 std::string ResultStr;
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +00001300 if (!ObjCWrittenInterfaces.count(ClassDecl->getCanonicalDecl())) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001301 // we haven't seen a forward decl - generate a typedef.
Fariborz Jahanianc38503b2012-03-12 23:58:28 +00001302 RewriteOneForwardClassDecl(ClassDecl, ResultStr);
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00001303 RewriteIvarOffsetSymbols(ClassDecl, ResultStr);
1304
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001305 RewriteObjCInternalStruct(ClassDecl, ResultStr);
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +00001306 // Mark this typedef as having been written into its c++ equivalent.
1307 ObjCWrittenInterfaces.insert(ClassDecl->getCanonicalDecl());
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001308
1309 for (ObjCInterfaceDecl::prop_iterator I = ClassDecl->prop_begin(),
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001310 E = ClassDecl->prop_end(); I != E; ++I)
David Blaikie262bc182012-04-30 02:36:29 +00001311 RewriteProperty(&*I);
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001312 for (ObjCInterfaceDecl::instmeth_iterator
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001313 I = ClassDecl->instmeth_begin(), E = ClassDecl->instmeth_end();
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001314 I != E; ++I)
1315 RewriteMethodDeclaration(*I);
1316 for (ObjCInterfaceDecl::classmeth_iterator
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001317 I = ClassDecl->classmeth_begin(), E = ClassDecl->classmeth_end();
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001318 I != E; ++I)
1319 RewriteMethodDeclaration(*I);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001320
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001321 // Lastly, comment out the @end.
1322 ReplaceText(ClassDecl->getAtEndRange().getBegin(), strlen("@end"),
1323 "/* @end */");
1324 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001325}
1326
1327Stmt *RewriteModernObjC::RewritePropertyOrImplicitSetter(PseudoObjectExpr *PseudoOp) {
1328 SourceRange OldRange = PseudoOp->getSourceRange();
1329
1330 // We just magically know some things about the structure of this
1331 // expression.
1332 ObjCMessageExpr *OldMsg =
1333 cast<ObjCMessageExpr>(PseudoOp->getSemanticExpr(
1334 PseudoOp->getNumSemanticExprs() - 1));
1335
1336 // Because the rewriter doesn't allow us to rewrite rewritten code,
1337 // we need to suppress rewriting the sub-statements.
Fariborz Jahanian88ec6102012-04-10 22:06:54 +00001338 Expr *Base;
1339 SmallVector<Expr*, 2> Args;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001340 {
1341 DisableReplaceStmtScope S(*this);
1342
1343 // Rebuild the base expression if we have one.
1344 Base = 0;
1345 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1346 Base = OldMsg->getInstanceReceiver();
1347 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1348 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1349 }
Fariborz Jahanian88ec6102012-04-10 22:06:54 +00001350
1351 unsigned numArgs = OldMsg->getNumArgs();
1352 for (unsigned i = 0; i < numArgs; i++) {
1353 Expr *Arg = OldMsg->getArg(i);
1354 if (isa<OpaqueValueExpr>(Arg))
1355 Arg = cast<OpaqueValueExpr>(Arg)->getSourceExpr();
1356 Arg = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Arg));
1357 Args.push_back(Arg);
1358 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001359 }
1360
1361 // TODO: avoid this copy.
1362 SmallVector<SourceLocation, 1> SelLocs;
1363 OldMsg->getSelectorLocs(SelLocs);
1364
1365 ObjCMessageExpr *NewMsg = 0;
1366 switch (OldMsg->getReceiverKind()) {
1367 case ObjCMessageExpr::Class:
1368 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1369 OldMsg->getValueKind(),
1370 OldMsg->getLeftLoc(),
1371 OldMsg->getClassReceiverTypeInfo(),
1372 OldMsg->getSelector(),
1373 SelLocs,
1374 OldMsg->getMethodDecl(),
Fariborz Jahanian88ec6102012-04-10 22:06:54 +00001375 Args,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001376 OldMsg->getRightLoc(),
1377 OldMsg->isImplicit());
1378 break;
1379
1380 case ObjCMessageExpr::Instance:
1381 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1382 OldMsg->getValueKind(),
1383 OldMsg->getLeftLoc(),
1384 Base,
1385 OldMsg->getSelector(),
1386 SelLocs,
1387 OldMsg->getMethodDecl(),
Fariborz Jahanian88ec6102012-04-10 22:06:54 +00001388 Args,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001389 OldMsg->getRightLoc(),
1390 OldMsg->isImplicit());
1391 break;
1392
1393 case ObjCMessageExpr::SuperClass:
1394 case ObjCMessageExpr::SuperInstance:
1395 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1396 OldMsg->getValueKind(),
1397 OldMsg->getLeftLoc(),
1398 OldMsg->getSuperLoc(),
1399 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1400 OldMsg->getSuperType(),
1401 OldMsg->getSelector(),
1402 SelLocs,
1403 OldMsg->getMethodDecl(),
Fariborz Jahanian88ec6102012-04-10 22:06:54 +00001404 Args,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001405 OldMsg->getRightLoc(),
1406 OldMsg->isImplicit());
1407 break;
1408 }
1409
1410 Stmt *Replacement = SynthMessageExpr(NewMsg);
1411 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1412 return Replacement;
1413}
1414
1415Stmt *RewriteModernObjC::RewritePropertyOrImplicitGetter(PseudoObjectExpr *PseudoOp) {
1416 SourceRange OldRange = PseudoOp->getSourceRange();
1417
1418 // We just magically know some things about the structure of this
1419 // expression.
1420 ObjCMessageExpr *OldMsg =
1421 cast<ObjCMessageExpr>(PseudoOp->getResultExpr()->IgnoreImplicit());
1422
1423 // Because the rewriter doesn't allow us to rewrite rewritten code,
1424 // we need to suppress rewriting the sub-statements.
1425 Expr *Base = 0;
Fariborz Jahanian88ec6102012-04-10 22:06:54 +00001426 SmallVector<Expr*, 1> Args;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001427 {
1428 DisableReplaceStmtScope S(*this);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001429 // Rebuild the base expression if we have one.
1430 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1431 Base = OldMsg->getInstanceReceiver();
1432 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1433 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1434 }
Fariborz Jahanian88ec6102012-04-10 22:06:54 +00001435 unsigned numArgs = OldMsg->getNumArgs();
1436 for (unsigned i = 0; i < numArgs; i++) {
1437 Expr *Arg = OldMsg->getArg(i);
1438 if (isa<OpaqueValueExpr>(Arg))
1439 Arg = cast<OpaqueValueExpr>(Arg)->getSourceExpr();
1440 Arg = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Arg));
1441 Args.push_back(Arg);
1442 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001443 }
1444
1445 // Intentionally empty.
1446 SmallVector<SourceLocation, 1> SelLocs;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001447
1448 ObjCMessageExpr *NewMsg = 0;
1449 switch (OldMsg->getReceiverKind()) {
1450 case ObjCMessageExpr::Class:
1451 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1452 OldMsg->getValueKind(),
1453 OldMsg->getLeftLoc(),
1454 OldMsg->getClassReceiverTypeInfo(),
1455 OldMsg->getSelector(),
1456 SelLocs,
1457 OldMsg->getMethodDecl(),
1458 Args,
1459 OldMsg->getRightLoc(),
1460 OldMsg->isImplicit());
1461 break;
1462
1463 case ObjCMessageExpr::Instance:
1464 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1465 OldMsg->getValueKind(),
1466 OldMsg->getLeftLoc(),
1467 Base,
1468 OldMsg->getSelector(),
1469 SelLocs,
1470 OldMsg->getMethodDecl(),
1471 Args,
1472 OldMsg->getRightLoc(),
1473 OldMsg->isImplicit());
1474 break;
1475
1476 case ObjCMessageExpr::SuperClass:
1477 case ObjCMessageExpr::SuperInstance:
1478 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1479 OldMsg->getValueKind(),
1480 OldMsg->getLeftLoc(),
1481 OldMsg->getSuperLoc(),
1482 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1483 OldMsg->getSuperType(),
1484 OldMsg->getSelector(),
1485 SelLocs,
1486 OldMsg->getMethodDecl(),
1487 Args,
1488 OldMsg->getRightLoc(),
1489 OldMsg->isImplicit());
1490 break;
1491 }
1492
1493 Stmt *Replacement = SynthMessageExpr(NewMsg);
1494 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1495 return Replacement;
1496}
1497
1498/// SynthCountByEnumWithState - To print:
1499/// ((unsigned int (*)
1500/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1501/// (void *)objc_msgSend)((id)l_collection,
1502/// sel_registerName(
1503/// "countByEnumeratingWithState:objects:count:"),
1504/// &enumState,
1505/// (id *)__rw_items, (unsigned int)16)
1506///
1507void RewriteModernObjC::SynthCountByEnumWithState(std::string &buf) {
1508 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1509 "id *, unsigned int))(void *)objc_msgSend)";
1510 buf += "\n\t\t";
1511 buf += "((id)l_collection,\n\t\t";
1512 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1513 buf += "\n\t\t";
1514 buf += "&enumState, "
1515 "(id *)__rw_items, (unsigned int)16)";
1516}
1517
1518/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1519/// statement to exit to its outer synthesized loop.
1520///
1521Stmt *RewriteModernObjC::RewriteBreakStmt(BreakStmt *S) {
1522 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1523 return S;
1524 // replace break with goto __break_label
1525 std::string buf;
1526
1527 SourceLocation startLoc = S->getLocStart();
1528 buf = "goto __break_label_";
1529 buf += utostr(ObjCBcLabelNo.back());
1530 ReplaceText(startLoc, strlen("break"), buf);
1531
1532 return 0;
1533}
1534
1535/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1536/// statement to continue with its inner synthesized loop.
1537///
1538Stmt *RewriteModernObjC::RewriteContinueStmt(ContinueStmt *S) {
1539 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1540 return S;
1541 // replace continue with goto __continue_label
1542 std::string buf;
1543
1544 SourceLocation startLoc = S->getLocStart();
1545 buf = "goto __continue_label_";
1546 buf += utostr(ObjCBcLabelNo.back());
1547 ReplaceText(startLoc, strlen("continue"), buf);
1548
1549 return 0;
1550}
1551
1552/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
1553/// It rewrites:
1554/// for ( type elem in collection) { stmts; }
1555
1556/// Into:
1557/// {
1558/// type elem;
1559/// struct __objcFastEnumerationState enumState = { 0 };
1560/// id __rw_items[16];
1561/// id l_collection = (id)collection;
1562/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1563/// objects:__rw_items count:16];
1564/// if (limit) {
1565/// unsigned long startMutations = *enumState.mutationsPtr;
1566/// do {
1567/// unsigned long counter = 0;
1568/// do {
1569/// if (startMutations != *enumState.mutationsPtr)
1570/// objc_enumerationMutation(l_collection);
1571/// elem = (type)enumState.itemsPtr[counter++];
1572/// stmts;
1573/// __continue_label: ;
1574/// } while (counter < limit);
1575/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1576/// objects:__rw_items count:16]);
1577/// elem = nil;
1578/// __break_label: ;
1579/// }
1580/// else
1581/// elem = nil;
1582/// }
1583///
1584Stmt *RewriteModernObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
1585 SourceLocation OrigEnd) {
1586 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
1587 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
1588 "ObjCForCollectionStmt Statement stack mismatch");
1589 assert(!ObjCBcLabelNo.empty() &&
1590 "ObjCForCollectionStmt - Label No stack empty");
1591
1592 SourceLocation startLoc = S->getLocStart();
1593 const char *startBuf = SM->getCharacterData(startLoc);
1594 StringRef elementName;
1595 std::string elementTypeAsString;
1596 std::string buf;
1597 buf = "\n{\n\t";
1598 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1599 // type elem;
1600 NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
1601 QualType ElementType = cast<ValueDecl>(D)->getType();
1602 if (ElementType->isObjCQualifiedIdType() ||
1603 ElementType->isObjCQualifiedInterfaceType())
1604 // Simply use 'id' for all qualified types.
1605 elementTypeAsString = "id";
1606 else
1607 elementTypeAsString = ElementType.getAsString(Context->getPrintingPolicy());
1608 buf += elementTypeAsString;
1609 buf += " ";
1610 elementName = D->getName();
1611 buf += elementName;
1612 buf += ";\n\t";
1613 }
1614 else {
1615 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
1616 elementName = DR->getDecl()->getName();
1617 ValueDecl *VD = cast<ValueDecl>(DR->getDecl());
1618 if (VD->getType()->isObjCQualifiedIdType() ||
1619 VD->getType()->isObjCQualifiedInterfaceType())
1620 // Simply use 'id' for all qualified types.
1621 elementTypeAsString = "id";
1622 else
1623 elementTypeAsString = VD->getType().getAsString(Context->getPrintingPolicy());
1624 }
1625
1626 // struct __objcFastEnumerationState enumState = { 0 };
1627 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1628 // id __rw_items[16];
1629 buf += "id __rw_items[16];\n\t";
1630 // id l_collection = (id)
1631 buf += "id l_collection = (id)";
1632 // Find start location of 'collection' the hard way!
1633 const char *startCollectionBuf = startBuf;
1634 startCollectionBuf += 3; // skip 'for'
1635 startCollectionBuf = strchr(startCollectionBuf, '(');
1636 startCollectionBuf++; // skip '('
1637 // find 'in' and skip it.
1638 while (*startCollectionBuf != ' ' ||
1639 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1640 (*(startCollectionBuf+3) != ' ' &&
1641 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1642 startCollectionBuf++;
1643 startCollectionBuf += 3;
1644
1645 // Replace: "for (type element in" with string constructed thus far.
1646 ReplaceText(startLoc, startCollectionBuf - startBuf, buf);
1647 // Replace ')' in for '(' type elem in collection ')' with ';'
1648 SourceLocation rightParenLoc = S->getRParenLoc();
1649 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1650 SourceLocation lparenLoc = startLoc.getLocWithOffset(rparenBuf-startBuf);
1651 buf = ";\n\t";
1652
1653 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1654 // objects:__rw_items count:16];
1655 // which is synthesized into:
1656 // unsigned int limit =
1657 // ((unsigned int (*)
1658 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1659 // (void *)objc_msgSend)((id)l_collection,
1660 // sel_registerName(
1661 // "countByEnumeratingWithState:objects:count:"),
1662 // (struct __objcFastEnumerationState *)&state,
1663 // (id *)__rw_items, (unsigned int)16);
1664 buf += "unsigned long limit =\n\t\t";
1665 SynthCountByEnumWithState(buf);
1666 buf += ";\n\t";
1667 /// if (limit) {
1668 /// unsigned long startMutations = *enumState.mutationsPtr;
1669 /// do {
1670 /// unsigned long counter = 0;
1671 /// do {
1672 /// if (startMutations != *enumState.mutationsPtr)
1673 /// objc_enumerationMutation(l_collection);
1674 /// elem = (type)enumState.itemsPtr[counter++];
1675 buf += "if (limit) {\n\t";
1676 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1677 buf += "do {\n\t\t";
1678 buf += "unsigned long counter = 0;\n\t\t";
1679 buf += "do {\n\t\t\t";
1680 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1681 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1682 buf += elementName;
1683 buf += " = (";
1684 buf += elementTypeAsString;
1685 buf += ")enumState.itemsPtr[counter++];";
1686 // Replace ')' in for '(' type elem in collection ')' with all of these.
1687 ReplaceText(lparenLoc, 1, buf);
1688
1689 /// __continue_label: ;
1690 /// } while (counter < limit);
1691 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1692 /// objects:__rw_items count:16]);
1693 /// elem = nil;
1694 /// __break_label: ;
1695 /// }
1696 /// else
1697 /// elem = nil;
1698 /// }
1699 ///
1700 buf = ";\n\t";
1701 buf += "__continue_label_";
1702 buf += utostr(ObjCBcLabelNo.back());
1703 buf += ": ;";
1704 buf += "\n\t\t";
1705 buf += "} while (counter < limit);\n\t";
1706 buf += "} while (limit = ";
1707 SynthCountByEnumWithState(buf);
1708 buf += ");\n\t";
1709 buf += elementName;
1710 buf += " = ((";
1711 buf += elementTypeAsString;
1712 buf += ")0);\n\t";
1713 buf += "__break_label_";
1714 buf += utostr(ObjCBcLabelNo.back());
1715 buf += ": ;\n\t";
1716 buf += "}\n\t";
1717 buf += "else\n\t\t";
1718 buf += elementName;
1719 buf += " = ((";
1720 buf += elementTypeAsString;
1721 buf += ")0);\n\t";
1722 buf += "}\n";
1723
1724 // Insert all these *after* the statement body.
1725 // FIXME: If this should support Obj-C++, support CXXTryStmt
1726 if (isa<CompoundStmt>(S->getBody())) {
1727 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(1);
1728 InsertText(endBodyLoc, buf);
1729 } else {
1730 /* Need to treat single statements specially. For example:
1731 *
1732 * for (A *a in b) if (stuff()) break;
1733 * for (A *a in b) xxxyy;
1734 *
1735 * The following code simply scans ahead to the semi to find the actual end.
1736 */
1737 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1738 const char *semiBuf = strchr(stmtBuf, ';');
1739 assert(semiBuf && "Can't find ';'");
1740 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(semiBuf-stmtBuf+1);
1741 InsertText(endBodyLoc, buf);
1742 }
1743 Stmts.pop_back();
1744 ObjCBcLabelNo.pop_back();
1745 return 0;
1746}
1747
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001748static void Write_RethrowObject(std::string &buf) {
1749 buf += "{ struct _FIN { _FIN(id reth) : rethrow(reth) {}\n";
1750 buf += "\t~_FIN() { if (rethrow) objc_exception_throw(rethrow); }\n";
1751 buf += "\tid rethrow;\n";
1752 buf += "\t} _fin_force_rethow(_rethrow);";
1753}
1754
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001755/// RewriteObjCSynchronizedStmt -
1756/// This routine rewrites @synchronized(expr) stmt;
1757/// into:
1758/// objc_sync_enter(expr);
1759/// @try stmt @finally { objc_sync_exit(expr); }
1760///
1761Stmt *RewriteModernObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
1762 // Get the start location and compute the semi location.
1763 SourceLocation startLoc = S->getLocStart();
1764 const char *startBuf = SM->getCharacterData(startLoc);
1765
1766 assert((*startBuf == '@') && "bogus @synchronized location");
1767
1768 std::string buf;
Fariborz Jahanian22e2f852012-03-17 17:46:02 +00001769 buf = "{ id _rethrow = 0; id _sync_obj = ";
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001770
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001771 const char *lparenBuf = startBuf;
1772 while (*lparenBuf != '(') lparenBuf++;
1773 ReplaceText(startLoc, lparenBuf-startBuf+1, buf);
Fariborz Jahanian22e2f852012-03-17 17:46:02 +00001774
1775 buf = "; objc_sync_enter(_sync_obj);\n";
1776 buf += "try {\n\tstruct _SYNC_EXIT { _SYNC_EXIT(id arg) : sync_exit(arg) {}";
1777 buf += "\n\t~_SYNC_EXIT() {objc_sync_exit(sync_exit);}";
1778 buf += "\n\tid sync_exit;";
1779 buf += "\n\t} _sync_exit(_sync_obj);\n";
1780
1781 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1782 // the sync expression is typically a message expression that's already
1783 // been rewritten! (which implies the SourceLocation's are invalid).
1784 SourceLocation RParenExprLoc = S->getSynchBody()->getLocStart();
1785 const char *RParenExprLocBuf = SM->getCharacterData(RParenExprLoc);
1786 while (*RParenExprLocBuf != ')') RParenExprLocBuf--;
1787 RParenExprLoc = startLoc.getLocWithOffset(RParenExprLocBuf-startBuf);
1788
1789 SourceLocation LBranceLoc = S->getSynchBody()->getLocStart();
1790 const char *LBraceLocBuf = SM->getCharacterData(LBranceLoc);
1791 assert (*LBraceLocBuf == '{');
1792 ReplaceText(RParenExprLoc, (LBraceLocBuf - SM->getCharacterData(RParenExprLoc) + 1), buf);
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001793
Fariborz Jahanianb655bf02012-03-16 21:43:45 +00001794 SourceLocation startRBraceLoc = S->getSynchBody()->getLocEnd();
Matt Beaumont-Gay9ab511c2012-03-16 22:20:39 +00001795 assert((*SM->getCharacterData(startRBraceLoc) == '}') &&
1796 "bogus @synchronized block");
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001797
1798 buf = "} catch (id e) {_rethrow = e;}\n";
1799 Write_RethrowObject(buf);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001800 buf += "}\n";
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001801 buf += "}\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001802
Fariborz Jahanianb655bf02012-03-16 21:43:45 +00001803 ReplaceText(startRBraceLoc, 1, buf);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001804
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001805 return 0;
1806}
1807
1808void RewriteModernObjC::WarnAboutReturnGotoStmts(Stmt *S)
1809{
1810 // Perform a bottom up traversal of all children.
1811 for (Stmt::child_range CI = S->children(); CI; ++CI)
1812 if (*CI)
1813 WarnAboutReturnGotoStmts(*CI);
1814
1815 if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
1816 Diags.Report(Context->getFullLoc(S->getLocStart()),
1817 TryFinallyContainsReturnDiag);
1818 }
1819 return;
1820}
1821
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001822Stmt *RewriteModernObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Fariborz Jahanianb1228182012-03-15 22:42:15 +00001823 ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt();
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001824 bool noCatch = S->getNumCatchStmts() == 0;
Fariborz Jahanianb1228182012-03-15 22:42:15 +00001825 std::string buf;
1826
1827 if (finalStmt) {
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001828 if (noCatch)
1829 buf = "{ id volatile _rethrow = 0;\n";
1830 else {
1831 buf = "{ id volatile _rethrow = 0;\ntry {\n";
1832 }
Fariborz Jahanianb1228182012-03-15 22:42:15 +00001833 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001834 // Get the start location and compute the semi location.
1835 SourceLocation startLoc = S->getLocStart();
1836 const char *startBuf = SM->getCharacterData(startLoc);
1837
1838 assert((*startBuf == '@') && "bogus @try location");
Fariborz Jahanianb1228182012-03-15 22:42:15 +00001839 if (finalStmt)
1840 ReplaceText(startLoc, 1, buf);
1841 else
1842 // @try -> try
1843 ReplaceText(startLoc, 1, "");
1844
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001845 for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I) {
1846 ObjCAtCatchStmt *Catch = S->getCatchStmt(I);
Fariborz Jahanian4c148812012-03-15 20:11:10 +00001847 VarDecl *catchDecl = Catch->getCatchParamDecl();
Fariborz Jahanianc38503b2012-03-12 23:58:28 +00001848
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001849 startLoc = Catch->getLocStart();
Fariborz Jahanian4c148812012-03-15 20:11:10 +00001850 bool AtRemoved = false;
1851 if (catchDecl) {
1852 QualType t = catchDecl->getType();
1853 if (const ObjCObjectPointerType *Ptr = t->getAs<ObjCObjectPointerType>()) {
1854 // Should be a pointer to a class.
1855 ObjCInterfaceDecl *IDecl = Ptr->getObjectType()->getInterface();
1856 if (IDecl) {
1857 std::string Result;
1858 startBuf = SM->getCharacterData(startLoc);
1859 assert((*startBuf == '@') && "bogus @catch location");
1860 SourceLocation rParenLoc = Catch->getRParenLoc();
1861 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1862
1863 // _objc_exc_Foo *_e as argument to catch.
1864 Result = "catch (_objc_exc_"; Result += IDecl->getNameAsString();
1865 Result += " *_"; Result += catchDecl->getNameAsString();
1866 Result += ")";
1867 ReplaceText(startLoc, rParenBuf-startBuf+1, Result);
1868 // Foo *e = (Foo *)_e;
1869 Result.clear();
1870 Result = "{ ";
1871 Result += IDecl->getNameAsString();
1872 Result += " *"; Result += catchDecl->getNameAsString();
1873 Result += " = ("; Result += IDecl->getNameAsString(); Result += "*)";
1874 Result += "_"; Result += catchDecl->getNameAsString();
1875
1876 Result += "; ";
1877 SourceLocation lBraceLoc = Catch->getCatchBody()->getLocStart();
1878 ReplaceText(lBraceLoc, 1, Result);
1879 AtRemoved = true;
1880 }
1881 }
1882 }
1883 if (!AtRemoved)
1884 // @catch -> catch
1885 ReplaceText(startLoc, 1, "");
Fariborz Jahanianc38503b2012-03-12 23:58:28 +00001886
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001887 }
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001888 if (finalStmt) {
1889 buf.clear();
1890 if (noCatch)
1891 buf = "catch (id e) {_rethrow = e;}\n";
1892 else
1893 buf = "}\ncatch (id e) {_rethrow = e;}\n";
1894
1895 SourceLocation startFinalLoc = finalStmt->getLocStart();
1896 ReplaceText(startFinalLoc, 8, buf);
1897 Stmt *body = finalStmt->getFinallyBody();
1898 SourceLocation startFinalBodyLoc = body->getLocStart();
1899 buf.clear();
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001900 Write_RethrowObject(buf);
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001901 ReplaceText(startFinalBodyLoc, 1, buf);
1902
1903 SourceLocation endFinalBodyLoc = body->getLocEnd();
1904 ReplaceText(endFinalBodyLoc, 1, "}\n}");
Fariborz Jahanian22e2f852012-03-17 17:46:02 +00001905 // Now check for any return/continue/go statements within the @try.
1906 WarnAboutReturnGotoStmts(S->getTryBody());
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001907 }
1908
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001909 return 0;
1910}
1911
1912// This can't be done with ReplaceStmt(S, ThrowExpr), since
1913// the throw expression is typically a message expression that's already
1914// been rewritten! (which implies the SourceLocation's are invalid).
1915Stmt *RewriteModernObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
1916 // Get the start location and compute the semi location.
1917 SourceLocation startLoc = S->getLocStart();
1918 const char *startBuf = SM->getCharacterData(startLoc);
1919
1920 assert((*startBuf == '@') && "bogus @throw location");
1921
1922 std::string buf;
1923 /* void objc_exception_throw(id) __attribute__((noreturn)); */
1924 if (S->getThrowExpr())
1925 buf = "objc_exception_throw(";
Fariborz Jahanian40539462012-03-16 16:52:06 +00001926 else
1927 buf = "throw";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001928
1929 // handle "@ throw" correctly.
1930 const char *wBuf = strchr(startBuf, 'w');
1931 assert((*wBuf == 'w') && "@throw: can't find 'w'");
1932 ReplaceText(startLoc, wBuf-startBuf+1, buf);
1933
1934 const char *semiBuf = strchr(startBuf, ';');
1935 assert((*semiBuf == ';') && "@throw: can't find ';'");
1936 SourceLocation semiLoc = startLoc.getLocWithOffset(semiBuf-startBuf);
Fariborz Jahanian40539462012-03-16 16:52:06 +00001937 if (S->getThrowExpr())
1938 ReplaceText(semiLoc, 1, ");");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001939 return 0;
1940}
1941
1942Stmt *RewriteModernObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
1943 // Create a new string expression.
1944 QualType StrType = Context->getPointerType(Context->CharTy);
1945 std::string StrEncoding;
1946 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
1947 Expr *Replacement = StringLiteral::Create(*Context, StrEncoding,
1948 StringLiteral::Ascii, false,
1949 StrType, SourceLocation());
1950 ReplaceStmt(Exp, Replacement);
1951
1952 // Replace this subexpr in the parent.
1953 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
1954 return Replacement;
1955}
1956
1957Stmt *RewriteModernObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
1958 if (!SelGetUidFunctionDecl)
1959 SynthSelGetUidFunctionDecl();
1960 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
1961 // Create a call to sel_registerName("selName").
1962 SmallVector<Expr*, 8> SelExprs;
1963 QualType argType = Context->getPointerType(Context->CharTy);
1964 SelExprs.push_back(StringLiteral::Create(*Context,
1965 Exp->getSelector().getAsString(),
1966 StringLiteral::Ascii, false,
1967 argType, SourceLocation()));
1968 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1969 &SelExprs[0], SelExprs.size());
1970 ReplaceStmt(Exp, SelExp);
1971 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
1972 return SelExp;
1973}
1974
1975CallExpr *RewriteModernObjC::SynthesizeCallToFunctionDecl(
1976 FunctionDecl *FD, Expr **args, unsigned nargs, SourceLocation StartLoc,
1977 SourceLocation EndLoc) {
1978 // Get the type, we will need to reference it in a couple spots.
1979 QualType msgSendType = FD->getType();
1980
1981 // Create a reference to the objc_msgSend() declaration.
1982 DeclRefExpr *DRE =
John McCallf4b88a42012-03-10 09:33:50 +00001983 new (Context) DeclRefExpr(FD, false, msgSendType, VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001984
1985 // Now, we cast the reference to a pointer to the objc_msgSend type.
1986 QualType pToFunc = Context->getPointerType(msgSendType);
1987 ImplicitCastExpr *ICE =
1988 ImplicitCastExpr::Create(*Context, pToFunc, CK_FunctionToPointerDecay,
1989 DRE, 0, VK_RValue);
1990
1991 const FunctionType *FT = msgSendType->getAs<FunctionType>();
1992
1993 CallExpr *Exp =
1994 new (Context) CallExpr(*Context, ICE, args, nargs,
1995 FT->getCallResultType(*Context),
1996 VK_RValue, EndLoc);
1997 return Exp;
1998}
1999
2000static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
2001 const char *&startRef, const char *&endRef) {
2002 while (startBuf < endBuf) {
2003 if (*startBuf == '<')
2004 startRef = startBuf; // mark the start.
2005 if (*startBuf == '>') {
2006 if (startRef && *startRef == '<') {
2007 endRef = startBuf; // mark the end.
2008 return true;
2009 }
2010 return false;
2011 }
2012 startBuf++;
2013 }
2014 return false;
2015}
2016
2017static void scanToNextArgument(const char *&argRef) {
2018 int angle = 0;
2019 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
2020 if (*argRef == '<')
2021 angle++;
2022 else if (*argRef == '>')
2023 angle--;
2024 argRef++;
2025 }
2026 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
2027}
2028
2029bool RewriteModernObjC::needToScanForQualifiers(QualType T) {
2030 if (T->isObjCQualifiedIdType())
2031 return true;
2032 if (const PointerType *PT = T->getAs<PointerType>()) {
2033 if (PT->getPointeeType()->isObjCQualifiedIdType())
2034 return true;
2035 }
2036 if (T->isObjCObjectPointerType()) {
2037 T = T->getPointeeType();
2038 return T->isObjCQualifiedInterfaceType();
2039 }
2040 if (T->isArrayType()) {
2041 QualType ElemTy = Context->getBaseElementType(T);
2042 return needToScanForQualifiers(ElemTy);
2043 }
2044 return false;
2045}
2046
2047void RewriteModernObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
2048 QualType Type = E->getType();
2049 if (needToScanForQualifiers(Type)) {
2050 SourceLocation Loc, EndLoc;
2051
2052 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
2053 Loc = ECE->getLParenLoc();
2054 EndLoc = ECE->getRParenLoc();
2055 } else {
2056 Loc = E->getLocStart();
2057 EndLoc = E->getLocEnd();
2058 }
2059 // This will defend against trying to rewrite synthesized expressions.
2060 if (Loc.isInvalid() || EndLoc.isInvalid())
2061 return;
2062
2063 const char *startBuf = SM->getCharacterData(Loc);
2064 const char *endBuf = SM->getCharacterData(EndLoc);
2065 const char *startRef = 0, *endRef = 0;
2066 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2067 // Get the locations of the startRef, endRef.
2068 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-startBuf);
2069 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-startBuf+1);
2070 // Comment out the protocol references.
2071 InsertText(LessLoc, "/*");
2072 InsertText(GreaterLoc, "*/");
2073 }
2074 }
2075}
2076
2077void RewriteModernObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
2078 SourceLocation Loc;
2079 QualType Type;
2080 const FunctionProtoType *proto = 0;
2081 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
2082 Loc = VD->getLocation();
2083 Type = VD->getType();
2084 }
2085 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
2086 Loc = FD->getLocation();
2087 // Check for ObjC 'id' and class types that have been adorned with protocol
2088 // information (id<p>, C<p>*). The protocol references need to be rewritten!
2089 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2090 assert(funcType && "missing function type");
2091 proto = dyn_cast<FunctionProtoType>(funcType);
2092 if (!proto)
2093 return;
2094 Type = proto->getResultType();
2095 }
2096 else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
2097 Loc = FD->getLocation();
2098 Type = FD->getType();
2099 }
2100 else
2101 return;
2102
2103 if (needToScanForQualifiers(Type)) {
2104 // Since types are unique, we need to scan the buffer.
2105
2106 const char *endBuf = SM->getCharacterData(Loc);
2107 const char *startBuf = endBuf;
2108 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
2109 startBuf--; // scan backward (from the decl location) for return type.
2110 const char *startRef = 0, *endRef = 0;
2111 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2112 // Get the locations of the startRef, endRef.
2113 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-endBuf);
2114 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-endBuf+1);
2115 // Comment out the protocol references.
2116 InsertText(LessLoc, "/*");
2117 InsertText(GreaterLoc, "*/");
2118 }
2119 }
2120 if (!proto)
2121 return; // most likely, was a variable
2122 // Now check arguments.
2123 const char *startBuf = SM->getCharacterData(Loc);
2124 const char *startFuncBuf = startBuf;
2125 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
2126 if (needToScanForQualifiers(proto->getArgType(i))) {
2127 // Since types are unique, we need to scan the buffer.
2128
2129 const char *endBuf = startBuf;
2130 // scan forward (from the decl location) for argument types.
2131 scanToNextArgument(endBuf);
2132 const char *startRef = 0, *endRef = 0;
2133 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2134 // Get the locations of the startRef, endRef.
2135 SourceLocation LessLoc =
2136 Loc.getLocWithOffset(startRef-startFuncBuf);
2137 SourceLocation GreaterLoc =
2138 Loc.getLocWithOffset(endRef-startFuncBuf+1);
2139 // Comment out the protocol references.
2140 InsertText(LessLoc, "/*");
2141 InsertText(GreaterLoc, "*/");
2142 }
2143 startBuf = ++endBuf;
2144 }
2145 else {
2146 // If the function name is derived from a macro expansion, then the
2147 // argument buffer will not follow the name. Need to speak with Chris.
2148 while (*startBuf && *startBuf != ')' && *startBuf != ',')
2149 startBuf++; // scan forward (from the decl location) for argument types.
2150 startBuf++;
2151 }
2152 }
2153}
2154
2155void RewriteModernObjC::RewriteTypeOfDecl(VarDecl *ND) {
2156 QualType QT = ND->getType();
2157 const Type* TypePtr = QT->getAs<Type>();
2158 if (!isa<TypeOfExprType>(TypePtr))
2159 return;
2160 while (isa<TypeOfExprType>(TypePtr)) {
2161 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
2162 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
2163 TypePtr = QT->getAs<Type>();
2164 }
2165 // FIXME. This will not work for multiple declarators; as in:
2166 // __typeof__(a) b,c,d;
2167 std::string TypeAsString(QT.getAsString(Context->getPrintingPolicy()));
2168 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
2169 const char *startBuf = SM->getCharacterData(DeclLoc);
2170 if (ND->getInit()) {
2171 std::string Name(ND->getNameAsString());
2172 TypeAsString += " " + Name + " = ";
2173 Expr *E = ND->getInit();
2174 SourceLocation startLoc;
2175 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
2176 startLoc = ECE->getLParenLoc();
2177 else
2178 startLoc = E->getLocStart();
2179 startLoc = SM->getExpansionLoc(startLoc);
2180 const char *endBuf = SM->getCharacterData(startLoc);
2181 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
2182 }
2183 else {
2184 SourceLocation X = ND->getLocEnd();
2185 X = SM->getExpansionLoc(X);
2186 const char *endBuf = SM->getCharacterData(X);
2187 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
2188 }
2189}
2190
2191// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
2192void RewriteModernObjC::SynthSelGetUidFunctionDecl() {
2193 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
2194 SmallVector<QualType, 16> ArgTys;
2195 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2196 QualType getFuncType =
2197 getSimpleFunctionType(Context->getObjCSelType(), &ArgTys[0], ArgTys.size());
2198 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2199 SourceLocation(),
2200 SourceLocation(),
2201 SelGetUidIdent, getFuncType, 0,
2202 SC_Extern,
2203 SC_None, false);
2204}
2205
2206void RewriteModernObjC::RewriteFunctionDecl(FunctionDecl *FD) {
2207 // declared in <objc/objc.h>
2208 if (FD->getIdentifier() &&
2209 FD->getName() == "sel_registerName") {
2210 SelGetUidFunctionDecl = FD;
2211 return;
2212 }
2213 RewriteObjCQualifiedInterfaceTypes(FD);
2214}
2215
2216void RewriteModernObjC::RewriteBlockPointerType(std::string& Str, QualType Type) {
2217 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
2218 const char *argPtr = TypeString.c_str();
2219 if (!strchr(argPtr, '^')) {
2220 Str += TypeString;
2221 return;
2222 }
2223 while (*argPtr) {
2224 Str += (*argPtr == '^' ? '*' : *argPtr);
2225 argPtr++;
2226 }
2227}
2228
2229// FIXME. Consolidate this routine with RewriteBlockPointerType.
2230void RewriteModernObjC::RewriteBlockPointerTypeVariable(std::string& Str,
2231 ValueDecl *VD) {
2232 QualType Type = VD->getType();
2233 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
2234 const char *argPtr = TypeString.c_str();
2235 int paren = 0;
2236 while (*argPtr) {
2237 switch (*argPtr) {
2238 case '(':
2239 Str += *argPtr;
2240 paren++;
2241 break;
2242 case ')':
2243 Str += *argPtr;
2244 paren--;
2245 break;
2246 case '^':
2247 Str += '*';
2248 if (paren == 1)
2249 Str += VD->getNameAsString();
2250 break;
2251 default:
2252 Str += *argPtr;
2253 break;
2254 }
2255 argPtr++;
2256 }
2257}
2258
Fariborz Jahanianb75f8de2012-04-19 00:50:01 +00002259void RewriteModernObjC::RewriteBlockLiteralFunctionDecl(FunctionDecl *FD) {
2260 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
2261 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2262 const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(funcType);
2263 if (!proto)
2264 return;
2265 QualType Type = proto->getResultType();
2266 std::string FdStr = Type.getAsString(Context->getPrintingPolicy());
2267 FdStr += " ";
2268 FdStr += FD->getName();
2269 FdStr += "(";
2270 unsigned numArgs = proto->getNumArgs();
2271 for (unsigned i = 0; i < numArgs; i++) {
2272 QualType ArgType = proto->getArgType(i);
2273 RewriteBlockPointerType(FdStr, ArgType);
2274 if (i+1 < numArgs)
2275 FdStr += ", ";
2276 }
Fariborz Jahanianb5863da2012-04-19 16:30:28 +00002277 if (FD->isVariadic()) {
2278 FdStr += (numArgs > 0) ? ", ...);\n" : "...);\n";
2279 }
2280 else
2281 FdStr += ");\n";
Fariborz Jahanianb75f8de2012-04-19 00:50:01 +00002282 InsertText(FunLocStart, FdStr);
2283}
2284
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002285// SynthSuperContructorFunctionDecl - id __rw_objc_super(id obj, id super);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002286void RewriteModernObjC::SynthSuperContructorFunctionDecl() {
2287 if (SuperContructorFunctionDecl)
2288 return;
2289 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
2290 SmallVector<QualType, 16> ArgTys;
2291 QualType argT = Context->getObjCIdType();
2292 assert(!argT.isNull() && "Can't find 'id' type");
2293 ArgTys.push_back(argT);
2294 ArgTys.push_back(argT);
2295 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2296 &ArgTys[0], ArgTys.size());
2297 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2298 SourceLocation(),
2299 SourceLocation(),
2300 msgSendIdent, msgSendType, 0,
2301 SC_Extern,
2302 SC_None, false);
2303}
2304
2305// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
2306void RewriteModernObjC::SynthMsgSendFunctionDecl() {
2307 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
2308 SmallVector<QualType, 16> ArgTys;
2309 QualType argT = Context->getObjCIdType();
2310 assert(!argT.isNull() && "Can't find 'id' type");
2311 ArgTys.push_back(argT);
2312 argT = Context->getObjCSelType();
2313 assert(!argT.isNull() && "Can't find 'SEL' type");
2314 ArgTys.push_back(argT);
2315 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2316 &ArgTys[0], ArgTys.size(),
2317 true /*isVariadic*/);
2318 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2319 SourceLocation(),
2320 SourceLocation(),
2321 msgSendIdent, msgSendType, 0,
2322 SC_Extern,
2323 SC_None, false);
2324}
2325
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002326// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(void);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002327void RewriteModernObjC::SynthMsgSendSuperFunctionDecl() {
2328 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002329 SmallVector<QualType, 2> ArgTys;
2330 ArgTys.push_back(Context->VoidTy);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002331 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002332 &ArgTys[0], 1,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002333 true /*isVariadic*/);
2334 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2335 SourceLocation(),
2336 SourceLocation(),
2337 msgSendIdent, msgSendType, 0,
2338 SC_Extern,
2339 SC_None, false);
2340}
2341
2342// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
2343void RewriteModernObjC::SynthMsgSendStretFunctionDecl() {
2344 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
2345 SmallVector<QualType, 16> ArgTys;
2346 QualType argT = Context->getObjCIdType();
2347 assert(!argT.isNull() && "Can't find 'id' type");
2348 ArgTys.push_back(argT);
2349 argT = Context->getObjCSelType();
2350 assert(!argT.isNull() && "Can't find 'SEL' type");
2351 ArgTys.push_back(argT);
2352 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2353 &ArgTys[0], ArgTys.size(),
2354 true /*isVariadic*/);
2355 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2356 SourceLocation(),
2357 SourceLocation(),
2358 msgSendIdent, msgSendType, 0,
2359 SC_Extern,
2360 SC_None, false);
2361}
2362
2363// SynthMsgSendSuperStretFunctionDecl -
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002364// id objc_msgSendSuper_stret(void);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002365void RewriteModernObjC::SynthMsgSendSuperStretFunctionDecl() {
2366 IdentifierInfo *msgSendIdent =
2367 &Context->Idents.get("objc_msgSendSuper_stret");
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002368 SmallVector<QualType, 2> ArgTys;
2369 ArgTys.push_back(Context->VoidTy);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002370 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002371 &ArgTys[0], 1,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002372 true /*isVariadic*/);
2373 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2374 SourceLocation(),
2375 SourceLocation(),
2376 msgSendIdent, msgSendType, 0,
2377 SC_Extern,
2378 SC_None, false);
2379}
2380
2381// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
2382void RewriteModernObjC::SynthMsgSendFpretFunctionDecl() {
2383 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
2384 SmallVector<QualType, 16> ArgTys;
2385 QualType argT = Context->getObjCIdType();
2386 assert(!argT.isNull() && "Can't find 'id' type");
2387 ArgTys.push_back(argT);
2388 argT = Context->getObjCSelType();
2389 assert(!argT.isNull() && "Can't find 'SEL' type");
2390 ArgTys.push_back(argT);
2391 QualType msgSendType = getSimpleFunctionType(Context->DoubleTy,
2392 &ArgTys[0], ArgTys.size(),
2393 true /*isVariadic*/);
2394 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2395 SourceLocation(),
2396 SourceLocation(),
2397 msgSendIdent, msgSendType, 0,
2398 SC_Extern,
2399 SC_None, false);
2400}
2401
2402// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
2403void RewriteModernObjC::SynthGetClassFunctionDecl() {
2404 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
2405 SmallVector<QualType, 16> ArgTys;
2406 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2407 QualType getClassType = getSimpleFunctionType(Context->getObjCIdType(),
2408 &ArgTys[0], ArgTys.size());
2409 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2410 SourceLocation(),
2411 SourceLocation(),
2412 getClassIdent, getClassType, 0,
2413 SC_Extern,
2414 SC_None, false);
2415}
2416
2417// SynthGetSuperClassFunctionDecl - Class class_getSuperclass(Class cls);
2418void RewriteModernObjC::SynthGetSuperClassFunctionDecl() {
2419 IdentifierInfo *getSuperClassIdent =
2420 &Context->Idents.get("class_getSuperclass");
2421 SmallVector<QualType, 16> ArgTys;
2422 ArgTys.push_back(Context->getObjCClassType());
2423 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
2424 &ArgTys[0], ArgTys.size());
2425 GetSuperClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2426 SourceLocation(),
2427 SourceLocation(),
2428 getSuperClassIdent,
2429 getClassType, 0,
2430 SC_Extern,
2431 SC_None,
2432 false);
2433}
2434
2435// SynthGetMetaClassFunctionDecl - id objc_getMetaClass(const char *name);
2436void RewriteModernObjC::SynthGetMetaClassFunctionDecl() {
2437 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
2438 SmallVector<QualType, 16> ArgTys;
2439 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2440 QualType getClassType = getSimpleFunctionType(Context->getObjCIdType(),
2441 &ArgTys[0], ArgTys.size());
2442 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2443 SourceLocation(),
2444 SourceLocation(),
2445 getClassIdent, getClassType, 0,
2446 SC_Extern,
2447 SC_None, false);
2448}
2449
2450Stmt *RewriteModernObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
2451 QualType strType = getConstantStringStructType();
2452
2453 std::string S = "__NSConstantStringImpl_";
2454
2455 std::string tmpName = InFileName;
2456 unsigned i;
2457 for (i=0; i < tmpName.length(); i++) {
2458 char c = tmpName.at(i);
2459 // replace any non alphanumeric characters with '_'.
2460 if (!isalpha(c) && (c < '0' || c > '9'))
2461 tmpName[i] = '_';
2462 }
2463 S += tmpName;
2464 S += "_";
2465 S += utostr(NumObjCStringLiterals++);
2466
2467 Preamble += "static __NSConstantStringImpl " + S;
2468 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2469 Preamble += "0x000007c8,"; // utf8_str
2470 // The pretty printer for StringLiteral handles escape characters properly.
2471 std::string prettyBufS;
2472 llvm::raw_string_ostream prettyBuf(prettyBufS);
2473 Exp->getString()->printPretty(prettyBuf, *Context, 0,
2474 PrintingPolicy(LangOpts));
2475 Preamble += prettyBuf.str();
2476 Preamble += ",";
2477 Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
2478
2479 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
2480 SourceLocation(), &Context->Idents.get(S),
2481 strType, 0, SC_Static, SC_None);
John McCallf4b88a42012-03-10 09:33:50 +00002482 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, false, strType, VK_LValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002483 SourceLocation());
2484 Expr *Unop = new (Context) UnaryOperator(DRE, UO_AddrOf,
2485 Context->getPointerType(DRE->getType()),
2486 VK_RValue, OK_Ordinary,
2487 SourceLocation());
2488 // cast to NSConstantString *
2489 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Exp->getType(),
2490 CK_CPointerToObjCPointerCast, Unop);
2491 ReplaceStmt(Exp, cast);
2492 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2493 return cast;
2494}
2495
Fariborz Jahanian55947042012-03-27 20:17:30 +00002496Stmt *RewriteModernObjC::RewriteObjCBoolLiteralExpr(ObjCBoolLiteralExpr *Exp) {
2497 unsigned IntSize =
2498 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
2499
2500 Expr *FlagExp = IntegerLiteral::Create(*Context,
2501 llvm::APInt(IntSize, Exp->getValue()),
2502 Context->IntTy, Exp->getLocation());
2503 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Context->ObjCBuiltinBoolTy,
2504 CK_BitCast, FlagExp);
2505 ParenExpr *PE = new (Context) ParenExpr(Exp->getLocation(), Exp->getExprLoc(),
2506 cast);
2507 ReplaceStmt(Exp, PE);
2508 return PE;
2509}
2510
Patrick Beardeb382ec2012-04-19 00:25:12 +00002511Stmt *RewriteModernObjC::RewriteObjCBoxedExpr(ObjCBoxedExpr *Exp) {
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002512 // synthesize declaration of helper functions needed in this routine.
2513 if (!SelGetUidFunctionDecl)
2514 SynthSelGetUidFunctionDecl();
2515 // use objc_msgSend() for all.
2516 if (!MsgSendFunctionDecl)
2517 SynthMsgSendFunctionDecl();
2518 if (!GetClassFunctionDecl)
2519 SynthGetClassFunctionDecl();
2520
2521 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2522 SourceLocation StartLoc = Exp->getLocStart();
2523 SourceLocation EndLoc = Exp->getLocEnd();
2524
2525 // Synthesize a call to objc_msgSend().
2526 SmallVector<Expr*, 4> MsgExprs;
2527 SmallVector<Expr*, 4> ClsExprs;
2528 QualType argType = Context->getPointerType(Context->CharTy);
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002529
Patrick Beardeb382ec2012-04-19 00:25:12 +00002530 // Create a call to objc_getClass("<BoxingClass>"). It will be the 1st argument.
2531 ObjCMethodDecl *BoxingMethod = Exp->getBoxingMethod();
2532 ObjCInterfaceDecl *BoxingClass = BoxingMethod->getClassInterface();
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002533
Patrick Beardeb382ec2012-04-19 00:25:12 +00002534 IdentifierInfo *clsName = BoxingClass->getIdentifier();
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002535 ClsExprs.push_back(StringLiteral::Create(*Context,
2536 clsName->getName(),
2537 StringLiteral::Ascii, false,
2538 argType, SourceLocation()));
2539 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2540 &ClsExprs[0],
2541 ClsExprs.size(),
2542 StartLoc, EndLoc);
2543 MsgExprs.push_back(Cls);
2544
Patrick Beardeb382ec2012-04-19 00:25:12 +00002545 // Create a call to sel_registerName("<BoxingMethod>:"), etc.
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002546 // it will be the 2nd argument.
2547 SmallVector<Expr*, 4> SelExprs;
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002548 SelExprs.push_back(StringLiteral::Create(*Context,
Patrick Beardeb382ec2012-04-19 00:25:12 +00002549 BoxingMethod->getSelector().getAsString(),
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002550 StringLiteral::Ascii, false,
2551 argType, SourceLocation()));
2552 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2553 &SelExprs[0], SelExprs.size(),
2554 StartLoc, EndLoc);
2555 MsgExprs.push_back(SelExp);
2556
Patrick Beardeb382ec2012-04-19 00:25:12 +00002557 // User provided sub-expression is the 3rd, and last, argument.
2558 Expr *subExpr = Exp->getSubExpr();
2559 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(subExpr)) {
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002560 QualType type = ICE->getType();
2561 const Expr *SubExpr = ICE->IgnoreParenImpCasts();
2562 CastKind CK = CK_BitCast;
2563 if (SubExpr->getType()->isIntegralType(*Context) && type->isBooleanType())
2564 CK = CK_IntegralToBoolean;
Patrick Beardeb382ec2012-04-19 00:25:12 +00002565 subExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, subExpr);
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002566 }
Patrick Beardeb382ec2012-04-19 00:25:12 +00002567 MsgExprs.push_back(subExpr);
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002568
2569 SmallVector<QualType, 4> ArgTypes;
2570 ArgTypes.push_back(Context->getObjCIdType());
2571 ArgTypes.push_back(Context->getObjCSelType());
Patrick Beardeb382ec2012-04-19 00:25:12 +00002572 for (ObjCMethodDecl::param_iterator PI = BoxingMethod->param_begin(),
2573 E = BoxingMethod->param_end(); PI != E; ++PI)
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002574 ArgTypes.push_back((*PI)->getType());
Patrick Beardeb382ec2012-04-19 00:25:12 +00002575
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002576 QualType returnType = Exp->getType();
2577 // Get the type, we will need to reference it in a couple spots.
2578 QualType msgSendType = MsgSendFlavor->getType();
2579
2580 // Create a reference to the objc_msgSend() declaration.
2581 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
2582 VK_LValue, SourceLocation());
2583
2584 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
Patrick Beardeb382ec2012-04-19 00:25:12 +00002585 Context->getPointerType(Context->VoidTy),
2586 CK_BitCast, DRE);
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002587
2588 // Now do the "normal" pointer to function cast.
2589 QualType castType =
Patrick Beardeb382ec2012-04-19 00:25:12 +00002590 getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
2591 BoxingMethod->isVariadic());
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002592 castType = Context->getPointerType(castType);
2593 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2594 cast);
2595
2596 // Don't forget the parens to enforce the proper binding.
2597 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
2598
2599 const FunctionType *FT = msgSendType->getAs<FunctionType>();
2600 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
2601 MsgExprs.size(),
2602 FT->getResultType(), VK_RValue,
2603 EndLoc);
2604 ReplaceStmt(Exp, CE);
2605 return CE;
2606}
2607
Fariborz Jahanian86cff602012-03-30 23:35:47 +00002608Stmt *RewriteModernObjC::RewriteObjCArrayLiteralExpr(ObjCArrayLiteral *Exp) {
2609 // synthesize declaration of helper functions needed in this routine.
2610 if (!SelGetUidFunctionDecl)
2611 SynthSelGetUidFunctionDecl();
2612 // use objc_msgSend() for all.
2613 if (!MsgSendFunctionDecl)
2614 SynthMsgSendFunctionDecl();
2615 if (!GetClassFunctionDecl)
2616 SynthGetClassFunctionDecl();
2617
2618 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2619 SourceLocation StartLoc = Exp->getLocStart();
2620 SourceLocation EndLoc = Exp->getLocEnd();
2621
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00002622 // Build the expression: __NSContainer_literal(int, ...).arr
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00002623 QualType IntQT = Context->IntTy;
2624 QualType NSArrayFType =
2625 getSimpleFunctionType(Context->VoidTy, &IntQT, 1, true);
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00002626 std::string NSArrayFName("__NSContainer_literal");
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00002627 FunctionDecl *NSArrayFD = SynthBlockInitFunctionDecl(NSArrayFName);
2628 DeclRefExpr *NSArrayDRE =
2629 new (Context) DeclRefExpr(NSArrayFD, false, NSArrayFType, VK_RValue,
2630 SourceLocation());
2631
2632 SmallVector<Expr*, 16> InitExprs;
2633 unsigned NumElements = Exp->getNumElements();
2634 unsigned UnsignedIntSize =
2635 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
2636 Expr *count = IntegerLiteral::Create(*Context,
2637 llvm::APInt(UnsignedIntSize, NumElements),
2638 Context->UnsignedIntTy, SourceLocation());
2639 InitExprs.push_back(count);
2640 for (unsigned i = 0; i < NumElements; i++)
2641 InitExprs.push_back(Exp->getElement(i));
2642 Expr *NSArrayCallExpr =
2643 new (Context) CallExpr(*Context, NSArrayDRE, &InitExprs[0], InitExprs.size(),
2644 NSArrayFType, VK_LValue, SourceLocation());
2645
2646 FieldDecl *ARRFD = FieldDecl::Create(*Context, 0, SourceLocation(),
2647 SourceLocation(),
2648 &Context->Idents.get("arr"),
2649 Context->getPointerType(Context->VoidPtrTy), 0,
2650 /*BitWidth=*/0, /*Mutable=*/true,
2651 /*HasInit=*/false);
2652 MemberExpr *ArrayLiteralME =
2653 new (Context) MemberExpr(NSArrayCallExpr, false, ARRFD,
2654 SourceLocation(),
2655 ARRFD->getType(), VK_LValue,
2656 OK_Ordinary);
2657 QualType ConstIdT = Context->getObjCIdType().withConst();
2658 CStyleCastExpr * ArrayLiteralObjects =
2659 NoTypeInfoCStyleCastExpr(Context,
2660 Context->getPointerType(ConstIdT),
2661 CK_BitCast,
2662 ArrayLiteralME);
2663
Fariborz Jahanian86cff602012-03-30 23:35:47 +00002664 // Synthesize a call to objc_msgSend().
2665 SmallVector<Expr*, 32> MsgExprs;
2666 SmallVector<Expr*, 4> ClsExprs;
2667 QualType argType = Context->getPointerType(Context->CharTy);
2668 QualType expType = Exp->getType();
2669
2670 // Create a call to objc_getClass("NSArray"). It will be th 1st argument.
2671 ObjCInterfaceDecl *Class =
2672 expType->getPointeeType()->getAs<ObjCObjectType>()->getInterface();
2673
2674 IdentifierInfo *clsName = Class->getIdentifier();
2675 ClsExprs.push_back(StringLiteral::Create(*Context,
2676 clsName->getName(),
2677 StringLiteral::Ascii, false,
2678 argType, SourceLocation()));
2679 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2680 &ClsExprs[0],
2681 ClsExprs.size(),
2682 StartLoc, EndLoc);
2683 MsgExprs.push_back(Cls);
2684
2685 // Create a call to sel_registerName("arrayWithObjects:count:").
2686 // it will be the 2nd argument.
2687 SmallVector<Expr*, 4> SelExprs;
2688 ObjCMethodDecl *ArrayMethod = Exp->getArrayWithObjectsMethod();
2689 SelExprs.push_back(StringLiteral::Create(*Context,
2690 ArrayMethod->getSelector().getAsString(),
2691 StringLiteral::Ascii, false,
2692 argType, SourceLocation()));
2693 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2694 &SelExprs[0], SelExprs.size(),
2695 StartLoc, EndLoc);
2696 MsgExprs.push_back(SelExp);
2697
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00002698 // (const id [])objects
2699 MsgExprs.push_back(ArrayLiteralObjects);
Fariborz Jahanian86cff602012-03-30 23:35:47 +00002700
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00002701 // (NSUInteger)cnt
2702 Expr *cnt = IntegerLiteral::Create(*Context,
2703 llvm::APInt(UnsignedIntSize, NumElements),
2704 Context->UnsignedIntTy, SourceLocation());
2705 MsgExprs.push_back(cnt);
Fariborz Jahanian86cff602012-03-30 23:35:47 +00002706
2707
2708 SmallVector<QualType, 4> ArgTypes;
2709 ArgTypes.push_back(Context->getObjCIdType());
2710 ArgTypes.push_back(Context->getObjCSelType());
2711 for (ObjCMethodDecl::param_iterator PI = ArrayMethod->param_begin(),
2712 E = ArrayMethod->param_end(); PI != E; ++PI)
2713 ArgTypes.push_back((*PI)->getType());
2714
2715 QualType returnType = Exp->getType();
2716 // Get the type, we will need to reference it in a couple spots.
2717 QualType msgSendType = MsgSendFlavor->getType();
2718
2719 // Create a reference to the objc_msgSend() declaration.
2720 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
2721 VK_LValue, SourceLocation());
2722
2723 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
2724 Context->getPointerType(Context->VoidTy),
2725 CK_BitCast, DRE);
2726
2727 // Now do the "normal" pointer to function cast.
2728 QualType castType =
2729 getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
2730 ArrayMethod->isVariadic());
2731 castType = Context->getPointerType(castType);
2732 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2733 cast);
2734
2735 // Don't forget the parens to enforce the proper binding.
2736 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
2737
2738 const FunctionType *FT = msgSendType->getAs<FunctionType>();
2739 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
2740 MsgExprs.size(),
2741 FT->getResultType(), VK_RValue,
2742 EndLoc);
2743 ReplaceStmt(Exp, CE);
2744 return CE;
2745}
2746
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00002747Stmt *RewriteModernObjC::RewriteObjCDictionaryLiteralExpr(ObjCDictionaryLiteral *Exp) {
2748 // synthesize declaration of helper functions needed in this routine.
2749 if (!SelGetUidFunctionDecl)
2750 SynthSelGetUidFunctionDecl();
2751 // use objc_msgSend() for all.
2752 if (!MsgSendFunctionDecl)
2753 SynthMsgSendFunctionDecl();
2754 if (!GetClassFunctionDecl)
2755 SynthGetClassFunctionDecl();
2756
2757 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2758 SourceLocation StartLoc = Exp->getLocStart();
2759 SourceLocation EndLoc = Exp->getLocEnd();
2760
2761 // Build the expression: __NSContainer_literal(int, ...).arr
2762 QualType IntQT = Context->IntTy;
2763 QualType NSDictFType =
2764 getSimpleFunctionType(Context->VoidTy, &IntQT, 1, true);
2765 std::string NSDictFName("__NSContainer_literal");
2766 FunctionDecl *NSDictFD = SynthBlockInitFunctionDecl(NSDictFName);
2767 DeclRefExpr *NSDictDRE =
2768 new (Context) DeclRefExpr(NSDictFD, false, NSDictFType, VK_RValue,
2769 SourceLocation());
2770
2771 SmallVector<Expr*, 16> KeyExprs;
2772 SmallVector<Expr*, 16> ValueExprs;
2773
2774 unsigned NumElements = Exp->getNumElements();
2775 unsigned UnsignedIntSize =
2776 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
2777 Expr *count = IntegerLiteral::Create(*Context,
2778 llvm::APInt(UnsignedIntSize, NumElements),
2779 Context->UnsignedIntTy, SourceLocation());
2780 KeyExprs.push_back(count);
2781 ValueExprs.push_back(count);
2782 for (unsigned i = 0; i < NumElements; i++) {
2783 ObjCDictionaryElement Element = Exp->getKeyValueElement(i);
2784 KeyExprs.push_back(Element.Key);
2785 ValueExprs.push_back(Element.Value);
2786 }
2787
2788 // (const id [])objects
2789 Expr *NSValueCallExpr =
2790 new (Context) CallExpr(*Context, NSDictDRE, &ValueExprs[0], ValueExprs.size(),
2791 NSDictFType, VK_LValue, SourceLocation());
2792
2793 FieldDecl *ARRFD = FieldDecl::Create(*Context, 0, SourceLocation(),
2794 SourceLocation(),
2795 &Context->Idents.get("arr"),
2796 Context->getPointerType(Context->VoidPtrTy), 0,
2797 /*BitWidth=*/0, /*Mutable=*/true,
2798 /*HasInit=*/false);
2799 MemberExpr *DictLiteralValueME =
2800 new (Context) MemberExpr(NSValueCallExpr, false, ARRFD,
2801 SourceLocation(),
2802 ARRFD->getType(), VK_LValue,
2803 OK_Ordinary);
2804 QualType ConstIdT = Context->getObjCIdType().withConst();
2805 CStyleCastExpr * DictValueObjects =
2806 NoTypeInfoCStyleCastExpr(Context,
2807 Context->getPointerType(ConstIdT),
2808 CK_BitCast,
2809 DictLiteralValueME);
2810 // (const id <NSCopying> [])keys
2811 Expr *NSKeyCallExpr =
2812 new (Context) CallExpr(*Context, NSDictDRE, &KeyExprs[0], KeyExprs.size(),
2813 NSDictFType, VK_LValue, SourceLocation());
2814
2815 MemberExpr *DictLiteralKeyME =
2816 new (Context) MemberExpr(NSKeyCallExpr, false, ARRFD,
2817 SourceLocation(),
2818 ARRFD->getType(), VK_LValue,
2819 OK_Ordinary);
2820
2821 CStyleCastExpr * DictKeyObjects =
2822 NoTypeInfoCStyleCastExpr(Context,
2823 Context->getPointerType(ConstIdT),
2824 CK_BitCast,
2825 DictLiteralKeyME);
2826
2827
2828
2829 // Synthesize a call to objc_msgSend().
2830 SmallVector<Expr*, 32> MsgExprs;
2831 SmallVector<Expr*, 4> ClsExprs;
2832 QualType argType = Context->getPointerType(Context->CharTy);
2833 QualType expType = Exp->getType();
2834
2835 // Create a call to objc_getClass("NSArray"). It will be th 1st argument.
2836 ObjCInterfaceDecl *Class =
2837 expType->getPointeeType()->getAs<ObjCObjectType>()->getInterface();
2838
2839 IdentifierInfo *clsName = Class->getIdentifier();
2840 ClsExprs.push_back(StringLiteral::Create(*Context,
2841 clsName->getName(),
2842 StringLiteral::Ascii, false,
2843 argType, SourceLocation()));
2844 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2845 &ClsExprs[0],
2846 ClsExprs.size(),
2847 StartLoc, EndLoc);
2848 MsgExprs.push_back(Cls);
2849
2850 // Create a call to sel_registerName("arrayWithObjects:count:").
2851 // it will be the 2nd argument.
2852 SmallVector<Expr*, 4> SelExprs;
2853 ObjCMethodDecl *DictMethod = Exp->getDictWithObjectsMethod();
2854 SelExprs.push_back(StringLiteral::Create(*Context,
2855 DictMethod->getSelector().getAsString(),
2856 StringLiteral::Ascii, false,
2857 argType, SourceLocation()));
2858 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2859 &SelExprs[0], SelExprs.size(),
2860 StartLoc, EndLoc);
2861 MsgExprs.push_back(SelExp);
2862
2863 // (const id [])objects
2864 MsgExprs.push_back(DictValueObjects);
2865
2866 // (const id <NSCopying> [])keys
2867 MsgExprs.push_back(DictKeyObjects);
2868
2869 // (NSUInteger)cnt
2870 Expr *cnt = IntegerLiteral::Create(*Context,
2871 llvm::APInt(UnsignedIntSize, NumElements),
2872 Context->UnsignedIntTy, SourceLocation());
2873 MsgExprs.push_back(cnt);
2874
2875
2876 SmallVector<QualType, 8> ArgTypes;
2877 ArgTypes.push_back(Context->getObjCIdType());
2878 ArgTypes.push_back(Context->getObjCSelType());
2879 for (ObjCMethodDecl::param_iterator PI = DictMethod->param_begin(),
2880 E = DictMethod->param_end(); PI != E; ++PI) {
2881 QualType T = (*PI)->getType();
2882 if (const PointerType* PT = T->getAs<PointerType>()) {
2883 QualType PointeeTy = PT->getPointeeType();
2884 convertToUnqualifiedObjCType(PointeeTy);
2885 T = Context->getPointerType(PointeeTy);
2886 }
2887 ArgTypes.push_back(T);
2888 }
2889
2890 QualType returnType = Exp->getType();
2891 // Get the type, we will need to reference it in a couple spots.
2892 QualType msgSendType = MsgSendFlavor->getType();
2893
2894 // Create a reference to the objc_msgSend() declaration.
2895 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
2896 VK_LValue, SourceLocation());
2897
2898 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
2899 Context->getPointerType(Context->VoidTy),
2900 CK_BitCast, DRE);
2901
2902 // Now do the "normal" pointer to function cast.
2903 QualType castType =
2904 getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
2905 DictMethod->isVariadic());
2906 castType = Context->getPointerType(castType);
2907 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2908 cast);
2909
2910 // Don't forget the parens to enforce the proper binding.
2911 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
2912
2913 const FunctionType *FT = msgSendType->getAs<FunctionType>();
2914 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
2915 MsgExprs.size(),
2916 FT->getResultType(), VK_RValue,
2917 EndLoc);
2918 ReplaceStmt(Exp, CE);
2919 return CE;
2920}
2921
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002922// struct __rw_objc_super {
2923// struct objc_object *object; struct objc_object *superClass;
2924// };
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002925QualType RewriteModernObjC::getSuperStructType() {
2926 if (!SuperStructDecl) {
2927 SuperStructDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
2928 SourceLocation(), SourceLocation(),
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002929 &Context->Idents.get("__rw_objc_super"));
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002930 QualType FieldTypes[2];
2931
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002932 // struct objc_object *object;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002933 FieldTypes[0] = Context->getObjCIdType();
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002934 // struct objc_object *superClass;
2935 FieldTypes[1] = Context->getObjCIdType();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002936
2937 // Create fields
2938 for (unsigned i = 0; i < 2; ++i) {
2939 SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
2940 SourceLocation(),
2941 SourceLocation(), 0,
2942 FieldTypes[i], 0,
2943 /*BitWidth=*/0,
2944 /*Mutable=*/false,
2945 /*HasInit=*/false));
2946 }
2947
2948 SuperStructDecl->completeDefinition();
2949 }
2950 return Context->getTagDeclType(SuperStructDecl);
2951}
2952
2953QualType RewriteModernObjC::getConstantStringStructType() {
2954 if (!ConstantStringDecl) {
2955 ConstantStringDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
2956 SourceLocation(), SourceLocation(),
2957 &Context->Idents.get("__NSConstantStringImpl"));
2958 QualType FieldTypes[4];
2959
2960 // struct objc_object *receiver;
2961 FieldTypes[0] = Context->getObjCIdType();
2962 // int flags;
2963 FieldTypes[1] = Context->IntTy;
2964 // char *str;
2965 FieldTypes[2] = Context->getPointerType(Context->CharTy);
2966 // long length;
2967 FieldTypes[3] = Context->LongTy;
2968
2969 // Create fields
2970 for (unsigned i = 0; i < 4; ++i) {
2971 ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
2972 ConstantStringDecl,
2973 SourceLocation(),
2974 SourceLocation(), 0,
2975 FieldTypes[i], 0,
2976 /*BitWidth=*/0,
2977 /*Mutable=*/true,
2978 /*HasInit=*/false));
2979 }
2980
2981 ConstantStringDecl->completeDefinition();
2982 }
2983 return Context->getTagDeclType(ConstantStringDecl);
2984}
2985
2986Stmt *RewriteModernObjC::SynthMessageExpr(ObjCMessageExpr *Exp,
2987 SourceLocation StartLoc,
2988 SourceLocation EndLoc) {
2989 if (!SelGetUidFunctionDecl)
2990 SynthSelGetUidFunctionDecl();
2991 if (!MsgSendFunctionDecl)
2992 SynthMsgSendFunctionDecl();
2993 if (!MsgSendSuperFunctionDecl)
2994 SynthMsgSendSuperFunctionDecl();
2995 if (!MsgSendStretFunctionDecl)
2996 SynthMsgSendStretFunctionDecl();
2997 if (!MsgSendSuperStretFunctionDecl)
2998 SynthMsgSendSuperStretFunctionDecl();
2999 if (!MsgSendFpretFunctionDecl)
3000 SynthMsgSendFpretFunctionDecl();
3001 if (!GetClassFunctionDecl)
3002 SynthGetClassFunctionDecl();
3003 if (!GetSuperClassFunctionDecl)
3004 SynthGetSuperClassFunctionDecl();
3005 if (!GetMetaClassFunctionDecl)
3006 SynthGetMetaClassFunctionDecl();
3007
3008 // default to objc_msgSend().
3009 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
3010 // May need to use objc_msgSend_stret() as well.
3011 FunctionDecl *MsgSendStretFlavor = 0;
3012 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
3013 QualType resultType = mDecl->getResultType();
3014 if (resultType->isRecordType())
3015 MsgSendStretFlavor = MsgSendStretFunctionDecl;
3016 else if (resultType->isRealFloatingType())
3017 MsgSendFlavor = MsgSendFpretFunctionDecl;
3018 }
3019
3020 // Synthesize a call to objc_msgSend().
3021 SmallVector<Expr*, 8> MsgExprs;
3022 switch (Exp->getReceiverKind()) {
3023 case ObjCMessageExpr::SuperClass: {
3024 MsgSendFlavor = MsgSendSuperFunctionDecl;
3025 if (MsgSendStretFlavor)
3026 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
3027 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
3028
3029 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
3030
3031 SmallVector<Expr*, 4> InitExprs;
3032
3033 // set the receiver to self, the first argument to all methods.
3034 InitExprs.push_back(
3035 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3036 CK_BitCast,
3037 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCallf4b88a42012-03-10 09:33:50 +00003038 false,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003039 Context->getObjCIdType(),
3040 VK_RValue,
3041 SourceLocation()))
3042 ); // set the 'receiver'.
3043
3044 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3045 SmallVector<Expr*, 8> ClsExprs;
3046 QualType argType = Context->getPointerType(Context->CharTy);
3047 ClsExprs.push_back(StringLiteral::Create(*Context,
3048 ClassDecl->getIdentifier()->getName(),
3049 StringLiteral::Ascii, false,
3050 argType, SourceLocation()));
3051 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
3052 &ClsExprs[0],
3053 ClsExprs.size(),
3054 StartLoc,
3055 EndLoc);
3056 // (Class)objc_getClass("CurrentClass")
3057 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
3058 Context->getObjCClassType(),
3059 CK_BitCast, Cls);
3060 ClsExprs.clear();
3061 ClsExprs.push_back(ArgExpr);
3062 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
3063 &ClsExprs[0], ClsExprs.size(),
3064 StartLoc, EndLoc);
3065
3066 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3067 // To turn off a warning, type-cast to 'id'
3068 InitExprs.push_back( // set 'super class', using class_getSuperclass().
3069 NoTypeInfoCStyleCastExpr(Context,
3070 Context->getObjCIdType(),
3071 CK_BitCast, Cls));
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003072 // struct __rw_objc_super
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003073 QualType superType = getSuperStructType();
3074 Expr *SuperRep;
3075
3076 if (LangOpts.MicrosoftExt) {
3077 SynthSuperContructorFunctionDecl();
3078 // Simulate a contructor call...
3079 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
John McCallf4b88a42012-03-10 09:33:50 +00003080 false, superType, VK_LValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003081 SourceLocation());
3082 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
3083 InitExprs.size(),
3084 superType, VK_LValue,
3085 SourceLocation());
3086 // The code for super is a little tricky to prevent collision with
3087 // the structure definition in the header. The rewriter has it's own
3088 // internal definition (__rw_objc_super) that is uses. This is why
3089 // we need the cast below. For example:
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003090 // (struct __rw_objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003091 //
3092 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
3093 Context->getPointerType(SuperRep->getType()),
3094 VK_RValue, OK_Ordinary,
3095 SourceLocation());
3096 SuperRep = NoTypeInfoCStyleCastExpr(Context,
3097 Context->getPointerType(superType),
3098 CK_BitCast, SuperRep);
3099 } else {
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003100 // (struct __rw_objc_super) { <exprs from above> }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003101 InitListExpr *ILE =
3102 new (Context) InitListExpr(*Context, SourceLocation(),
3103 &InitExprs[0], InitExprs.size(),
3104 SourceLocation());
3105 TypeSourceInfo *superTInfo
3106 = Context->getTrivialTypeSourceInfo(superType);
3107 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
3108 superType, VK_LValue,
3109 ILE, false);
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003110 // struct __rw_objc_super *
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003111 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
3112 Context->getPointerType(SuperRep->getType()),
3113 VK_RValue, OK_Ordinary,
3114 SourceLocation());
3115 }
3116 MsgExprs.push_back(SuperRep);
3117 break;
3118 }
3119
3120 case ObjCMessageExpr::Class: {
3121 SmallVector<Expr*, 8> ClsExprs;
3122 QualType argType = Context->getPointerType(Context->CharTy);
3123 ObjCInterfaceDecl *Class
3124 = Exp->getClassReceiver()->getAs<ObjCObjectType>()->getInterface();
3125 IdentifierInfo *clsName = Class->getIdentifier();
3126 ClsExprs.push_back(StringLiteral::Create(*Context,
3127 clsName->getName(),
3128 StringLiteral::Ascii, false,
3129 argType, SourceLocation()));
3130 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
3131 &ClsExprs[0],
3132 ClsExprs.size(),
3133 StartLoc, EndLoc);
3134 MsgExprs.push_back(Cls);
3135 break;
3136 }
3137
3138 case ObjCMessageExpr::SuperInstance:{
3139 MsgSendFlavor = MsgSendSuperFunctionDecl;
3140 if (MsgSendStretFlavor)
3141 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
3142 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
3143 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
3144 SmallVector<Expr*, 4> InitExprs;
3145
3146 InitExprs.push_back(
3147 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3148 CK_BitCast,
3149 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCallf4b88a42012-03-10 09:33:50 +00003150 false,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003151 Context->getObjCIdType(),
3152 VK_RValue, SourceLocation()))
3153 ); // set the 'receiver'.
3154
3155 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3156 SmallVector<Expr*, 8> ClsExprs;
3157 QualType argType = Context->getPointerType(Context->CharTy);
3158 ClsExprs.push_back(StringLiteral::Create(*Context,
3159 ClassDecl->getIdentifier()->getName(),
3160 StringLiteral::Ascii, false, argType,
3161 SourceLocation()));
3162 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
3163 &ClsExprs[0],
3164 ClsExprs.size(),
3165 StartLoc, EndLoc);
3166 // (Class)objc_getClass("CurrentClass")
3167 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
3168 Context->getObjCClassType(),
3169 CK_BitCast, Cls);
3170 ClsExprs.clear();
3171 ClsExprs.push_back(ArgExpr);
3172 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
3173 &ClsExprs[0], ClsExprs.size(),
3174 StartLoc, EndLoc);
3175
3176 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3177 // To turn off a warning, type-cast to 'id'
3178 InitExprs.push_back(
3179 // set 'super class', using class_getSuperclass().
3180 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3181 CK_BitCast, Cls));
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003182 // struct __rw_objc_super
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003183 QualType superType = getSuperStructType();
3184 Expr *SuperRep;
3185
3186 if (LangOpts.MicrosoftExt) {
3187 SynthSuperContructorFunctionDecl();
3188 // Simulate a contructor call...
3189 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
John McCallf4b88a42012-03-10 09:33:50 +00003190 false, superType, VK_LValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003191 SourceLocation());
3192 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
3193 InitExprs.size(),
3194 superType, VK_LValue, SourceLocation());
3195 // The code for super is a little tricky to prevent collision with
3196 // the structure definition in the header. The rewriter has it's own
3197 // internal definition (__rw_objc_super) that is uses. This is why
3198 // we need the cast below. For example:
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003199 // (struct __rw_objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003200 //
3201 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
3202 Context->getPointerType(SuperRep->getType()),
3203 VK_RValue, OK_Ordinary,
3204 SourceLocation());
3205 SuperRep = NoTypeInfoCStyleCastExpr(Context,
3206 Context->getPointerType(superType),
3207 CK_BitCast, SuperRep);
3208 } else {
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003209 // (struct __rw_objc_super) { <exprs from above> }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003210 InitListExpr *ILE =
3211 new (Context) InitListExpr(*Context, SourceLocation(),
3212 &InitExprs[0], InitExprs.size(),
3213 SourceLocation());
3214 TypeSourceInfo *superTInfo
3215 = Context->getTrivialTypeSourceInfo(superType);
3216 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
3217 superType, VK_RValue, ILE,
3218 false);
3219 }
3220 MsgExprs.push_back(SuperRep);
3221 break;
3222 }
3223
3224 case ObjCMessageExpr::Instance: {
3225 // Remove all type-casts because it may contain objc-style types; e.g.
3226 // Foo<Proto> *.
3227 Expr *recExpr = Exp->getInstanceReceiver();
3228 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
3229 recExpr = CE->getSubExpr();
3230 CastKind CK = recExpr->getType()->isObjCObjectPointerType()
3231 ? CK_BitCast : recExpr->getType()->isBlockPointerType()
3232 ? CK_BlockPointerToObjCPointerCast
3233 : CK_CPointerToObjCPointerCast;
3234
3235 recExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3236 CK, recExpr);
3237 MsgExprs.push_back(recExpr);
3238 break;
3239 }
3240 }
3241
3242 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
3243 SmallVector<Expr*, 8> SelExprs;
3244 QualType argType = Context->getPointerType(Context->CharTy);
3245 SelExprs.push_back(StringLiteral::Create(*Context,
3246 Exp->getSelector().getAsString(),
3247 StringLiteral::Ascii, false,
3248 argType, SourceLocation()));
3249 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
3250 &SelExprs[0], SelExprs.size(),
3251 StartLoc,
3252 EndLoc);
3253 MsgExprs.push_back(SelExp);
3254
3255 // Now push any user supplied arguments.
3256 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
3257 Expr *userExpr = Exp->getArg(i);
3258 // Make all implicit casts explicit...ICE comes in handy:-)
3259 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
3260 // Reuse the ICE type, it is exactly what the doctor ordered.
3261 QualType type = ICE->getType();
3262 if (needToScanForQualifiers(type))
3263 type = Context->getObjCIdType();
3264 // Make sure we convert "type (^)(...)" to "type (*)(...)".
3265 (void)convertBlockPointerToFunctionPointer(type);
3266 const Expr *SubExpr = ICE->IgnoreParenImpCasts();
3267 CastKind CK;
3268 if (SubExpr->getType()->isIntegralType(*Context) &&
3269 type->isBooleanType()) {
3270 CK = CK_IntegralToBoolean;
3271 } else if (type->isObjCObjectPointerType()) {
3272 if (SubExpr->getType()->isBlockPointerType()) {
3273 CK = CK_BlockPointerToObjCPointerCast;
3274 } else if (SubExpr->getType()->isPointerType()) {
3275 CK = CK_CPointerToObjCPointerCast;
3276 } else {
3277 CK = CK_BitCast;
3278 }
3279 } else {
3280 CK = CK_BitCast;
3281 }
3282
3283 userExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, userExpr);
3284 }
3285 // Make id<P...> cast into an 'id' cast.
3286 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
3287 if (CE->getType()->isObjCQualifiedIdType()) {
3288 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
3289 userExpr = CE->getSubExpr();
3290 CastKind CK;
3291 if (userExpr->getType()->isIntegralType(*Context)) {
3292 CK = CK_IntegralToPointer;
3293 } else if (userExpr->getType()->isBlockPointerType()) {
3294 CK = CK_BlockPointerToObjCPointerCast;
3295 } else if (userExpr->getType()->isPointerType()) {
3296 CK = CK_CPointerToObjCPointerCast;
3297 } else {
3298 CK = CK_BitCast;
3299 }
3300 userExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3301 CK, userExpr);
3302 }
3303 }
3304 MsgExprs.push_back(userExpr);
3305 // We've transferred the ownership to MsgExprs. For now, we *don't* null
3306 // out the argument in the original expression (since we aren't deleting
3307 // the ObjCMessageExpr). See RewritePropertyOrImplicitSetter() usage for more info.
3308 //Exp->setArg(i, 0);
3309 }
3310 // Generate the funky cast.
3311 CastExpr *cast;
3312 SmallVector<QualType, 8> ArgTypes;
3313 QualType returnType;
3314
3315 // Push 'id' and 'SEL', the 2 implicit arguments.
3316 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
3317 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
3318 else
3319 ArgTypes.push_back(Context->getObjCIdType());
3320 ArgTypes.push_back(Context->getObjCSelType());
3321 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
3322 // Push any user argument types.
3323 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
3324 E = OMD->param_end(); PI != E; ++PI) {
3325 QualType t = (*PI)->getType()->isObjCQualifiedIdType()
3326 ? Context->getObjCIdType()
3327 : (*PI)->getType();
3328 // Make sure we convert "t (^)(...)" to "t (*)(...)".
3329 (void)convertBlockPointerToFunctionPointer(t);
3330 ArgTypes.push_back(t);
3331 }
3332 returnType = Exp->getType();
3333 convertToUnqualifiedObjCType(returnType);
3334 (void)convertBlockPointerToFunctionPointer(returnType);
3335 } else {
3336 returnType = Context->getObjCIdType();
3337 }
3338 // Get the type, we will need to reference it in a couple spots.
3339 QualType msgSendType = MsgSendFlavor->getType();
3340
3341 // Create a reference to the objc_msgSend() declaration.
John McCallf4b88a42012-03-10 09:33:50 +00003342 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003343 VK_LValue, SourceLocation());
3344
3345 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
3346 // If we don't do this cast, we get the following bizarre warning/note:
3347 // xx.m:13: warning: function called through a non-compatible type
3348 // xx.m:13: note: if this code is reached, the program will abort
3349 cast = NoTypeInfoCStyleCastExpr(Context,
3350 Context->getPointerType(Context->VoidTy),
3351 CK_BitCast, DRE);
3352
3353 // Now do the "normal" pointer to function cast.
3354 QualType castType =
3355 getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
3356 // If we don't have a method decl, force a variadic cast.
3357 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true);
3358 castType = Context->getPointerType(castType);
3359 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
3360 cast);
3361
3362 // Don't forget the parens to enforce the proper binding.
3363 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
3364
3365 const FunctionType *FT = msgSendType->getAs<FunctionType>();
3366 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
3367 MsgExprs.size(),
3368 FT->getResultType(), VK_RValue,
3369 EndLoc);
3370 Stmt *ReplacingStmt = CE;
3371 if (MsgSendStretFlavor) {
3372 // We have the method which returns a struct/union. Must also generate
3373 // call to objc_msgSend_stret and hang both varieties on a conditional
3374 // expression which dictate which one to envoke depending on size of
3375 // method's return type.
3376
3377 // Create a reference to the objc_msgSend_stret() declaration.
John McCallf4b88a42012-03-10 09:33:50 +00003378 DeclRefExpr *STDRE = new (Context) DeclRefExpr(MsgSendStretFlavor,
3379 false, msgSendType,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003380 VK_LValue, SourceLocation());
3381 // Need to cast objc_msgSend_stret to "void *" (see above comment).
3382 cast = NoTypeInfoCStyleCastExpr(Context,
3383 Context->getPointerType(Context->VoidTy),
3384 CK_BitCast, STDRE);
3385 // Now do the "normal" pointer to function cast.
3386 castType = getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
3387 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false);
3388 castType = Context->getPointerType(castType);
3389 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
3390 cast);
3391
3392 // Don't forget the parens to enforce the proper binding.
3393 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
3394
3395 FT = msgSendType->getAs<FunctionType>();
3396 CallExpr *STCE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
3397 MsgExprs.size(),
3398 FT->getResultType(), VK_RValue,
3399 SourceLocation());
3400
3401 // Build sizeof(returnType)
3402 UnaryExprOrTypeTraitExpr *sizeofExpr =
3403 new (Context) UnaryExprOrTypeTraitExpr(UETT_SizeOf,
3404 Context->getTrivialTypeSourceInfo(returnType),
3405 Context->getSizeType(), SourceLocation(),
3406 SourceLocation());
3407 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
3408 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
3409 // For X86 it is more complicated and some kind of target specific routine
3410 // is needed to decide what to do.
3411 unsigned IntSize =
3412 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
3413 IntegerLiteral *limit = IntegerLiteral::Create(*Context,
3414 llvm::APInt(IntSize, 8),
3415 Context->IntTy,
3416 SourceLocation());
3417 BinaryOperator *lessThanExpr =
3418 new (Context) BinaryOperator(sizeofExpr, limit, BO_LE, Context->IntTy,
3419 VK_RValue, OK_Ordinary, SourceLocation());
3420 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
3421 ConditionalOperator *CondExpr =
3422 new (Context) ConditionalOperator(lessThanExpr,
3423 SourceLocation(), CE,
3424 SourceLocation(), STCE,
3425 returnType, VK_RValue, OK_Ordinary);
3426 ReplacingStmt = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3427 CondExpr);
3428 }
3429 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3430 return ReplacingStmt;
3431}
3432
3433Stmt *RewriteModernObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
3434 Stmt *ReplacingStmt = SynthMessageExpr(Exp, Exp->getLocStart(),
3435 Exp->getLocEnd());
3436
3437 // Now do the actual rewrite.
3438 ReplaceStmt(Exp, ReplacingStmt);
3439
3440 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3441 return ReplacingStmt;
3442}
3443
3444// typedef struct objc_object Protocol;
3445QualType RewriteModernObjC::getProtocolType() {
3446 if (!ProtocolTypeDecl) {
3447 TypeSourceInfo *TInfo
3448 = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
3449 ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
3450 SourceLocation(), SourceLocation(),
3451 &Context->Idents.get("Protocol"),
3452 TInfo);
3453 }
3454 return Context->getTypeDeclType(ProtocolTypeDecl);
3455}
3456
3457/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
3458/// a synthesized/forward data reference (to the protocol's metadata).
3459/// The forward references (and metadata) are generated in
3460/// RewriteModernObjC::HandleTranslationUnit().
3461Stmt *RewriteModernObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00003462 std::string Name = "_OBJC_PROTOCOL_REFERENCE_$_" +
3463 Exp->getProtocol()->getNameAsString();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003464 IdentifierInfo *ID = &Context->Idents.get(Name);
3465 VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
3466 SourceLocation(), ID, getProtocolType(), 0,
3467 SC_Extern, SC_None);
John McCallf4b88a42012-03-10 09:33:50 +00003468 DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, false, getProtocolType(),
3469 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003470 Expr *DerefExpr = new (Context) UnaryOperator(DRE, UO_AddrOf,
3471 Context->getPointerType(DRE->getType()),
3472 VK_RValue, OK_Ordinary, SourceLocation());
3473 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, DerefExpr->getType(),
3474 CK_BitCast,
3475 DerefExpr);
3476 ReplaceStmt(Exp, castExpr);
3477 ProtocolExprDecls.insert(Exp->getProtocol()->getCanonicalDecl());
3478 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3479 return castExpr;
3480
3481}
3482
3483bool RewriteModernObjC::BufferContainsPPDirectives(const char *startBuf,
3484 const char *endBuf) {
3485 while (startBuf < endBuf) {
3486 if (*startBuf == '#') {
3487 // Skip whitespace.
3488 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
3489 ;
3490 if (!strncmp(startBuf, "if", strlen("if")) ||
3491 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
3492 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
3493 !strncmp(startBuf, "define", strlen("define")) ||
3494 !strncmp(startBuf, "undef", strlen("undef")) ||
3495 !strncmp(startBuf, "else", strlen("else")) ||
3496 !strncmp(startBuf, "elif", strlen("elif")) ||
3497 !strncmp(startBuf, "endif", strlen("endif")) ||
3498 !strncmp(startBuf, "pragma", strlen("pragma")) ||
3499 !strncmp(startBuf, "include", strlen("include")) ||
3500 !strncmp(startBuf, "import", strlen("import")) ||
3501 !strncmp(startBuf, "include_next", strlen("include_next")))
3502 return true;
3503 }
3504 startBuf++;
3505 }
3506 return false;
3507}
3508
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003509/// IsTagDefinedInsideClass - This routine checks that a named tagged type
3510/// is defined inside an objective-c class. If so, it returns true.
Fariborz Jahanianb68258f2012-05-01 17:46:45 +00003511bool RewriteModernObjC::IsTagDefinedInsideClass(ObjCContainerDecl *IDecl,
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003512 TagDecl *Tag,
3513 bool &IsNamedDefinition) {
Fariborz Jahanian89585e802012-04-30 19:46:53 +00003514 if (!IDecl)
3515 return false;
3516 SourceLocation TagLocation;
3517 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) {
3518 RD = RD->getDefinition();
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003519 if (!RD || !RD->getDeclName().getAsIdentifierInfo())
Fariborz Jahanian89585e802012-04-30 19:46:53 +00003520 return false;
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003521 IsNamedDefinition = true;
Fariborz Jahanian89585e802012-04-30 19:46:53 +00003522 TagLocation = RD->getLocation();
3523 return Context->getSourceManager().isBeforeInTranslationUnit(
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003524 IDecl->getLocation(), TagLocation);
3525 }
3526 if (EnumDecl *ED = dyn_cast<EnumDecl>(Tag)) {
3527 if (!ED || !ED->getDeclName().getAsIdentifierInfo())
3528 return false;
3529 IsNamedDefinition = true;
3530 TagLocation = ED->getLocation();
3531 return Context->getSourceManager().isBeforeInTranslationUnit(
3532 IDecl->getLocation(), TagLocation);
3533
Fariborz Jahanian89585e802012-04-30 19:46:53 +00003534 }
3535 return false;
3536}
3537
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003538/// RewriteObjCFieldDeclType - This routine rewrites a type into the buffer.
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003539/// It handles elaborated types, as well as enum types in the process.
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003540bool RewriteModernObjC::RewriteObjCFieldDeclType(QualType &Type,
3541 std::string &Result) {
Fariborz Jahanianf5eac482012-05-02 17:34:59 +00003542 if (isa<TypedefType>(Type)) {
3543 Result += "\t";
3544 return false;
3545 }
3546
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003547 if (Type->isArrayType()) {
3548 QualType ElemTy = Context->getBaseElementType(Type);
3549 return RewriteObjCFieldDeclType(ElemTy, Result);
3550 }
3551 else if (Type->isRecordType()) {
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003552 RecordDecl *RD = Type->getAs<RecordType>()->getDecl();
3553 if (RD->isCompleteDefinition()) {
3554 if (RD->isStruct())
3555 Result += "\n\tstruct ";
3556 else if (RD->isUnion())
3557 Result += "\n\tunion ";
3558 else
3559 assert(false && "class not allowed as an ivar type");
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003560
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003561 Result += RD->getName();
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003562 if (GlobalDefinedTags.count(RD)) {
3563 // struct/union is defined globally, use it.
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003564 Result += " ";
3565 return true;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003566 }
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003567 Result += " {\n";
3568 for (RecordDecl::field_iterator i = RD->field_begin(),
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003569 e = RD->field_end(); i != e; ++i) {
David Blaikie262bc182012-04-30 02:36:29 +00003570 FieldDecl *FD = &*i;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003571 RewriteObjCFieldDecl(FD, Result);
3572 }
3573 Result += "\t} ";
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003574 return true;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003575 }
3576 }
3577 else if (Type->isEnumeralType()) {
3578 EnumDecl *ED = Type->getAs<EnumType>()->getDecl();
3579 if (ED->isCompleteDefinition()) {
3580 Result += "\n\tenum ";
3581 Result += ED->getName();
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003582 if (GlobalDefinedTags.count(ED)) {
3583 // Enum is globall defined, use it.
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003584 Result += " ";
3585 return true;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003586 }
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003587
3588 Result += " {\n";
3589 for (EnumDecl::enumerator_iterator EC = ED->enumerator_begin(),
3590 ECEnd = ED->enumerator_end(); EC != ECEnd; ++EC) {
3591 Result += "\t"; Result += EC->getName(); Result += " = ";
3592 llvm::APSInt Val = EC->getInitVal();
3593 Result += Val.toString(10);
3594 Result += ",\n";
3595 }
3596 Result += "\t} ";
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003597 return true;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003598 }
3599 }
3600
3601 Result += "\t";
3602 convertObjCTypeToCStyleType(Type);
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003603 return false;
3604}
3605
3606
3607/// RewriteObjCFieldDecl - This routine rewrites a field into the buffer.
3608/// It handles elaborated types, as well as enum types in the process.
3609void RewriteModernObjC::RewriteObjCFieldDecl(FieldDecl *fieldDecl,
3610 std::string &Result) {
3611 QualType Type = fieldDecl->getType();
3612 std::string Name = fieldDecl->getNameAsString();
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003613
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003614 bool EleboratedType = RewriteObjCFieldDeclType(Type, Result);
3615 if (!EleboratedType)
3616 Type.getAsStringInternal(Name, Context->getPrintingPolicy());
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003617 Result += Name;
3618 if (fieldDecl->isBitField()) {
3619 Result += " : "; Result += utostr(fieldDecl->getBitWidthValue(*Context));
3620 }
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003621 else if (EleboratedType && Type->isArrayType()) {
3622 CanQualType CType = Context->getCanonicalType(Type);
3623 while (isa<ArrayType>(CType)) {
3624 if (const ConstantArrayType *CAT = Context->getAsConstantArrayType(CType)) {
3625 Result += "[";
3626 llvm::APInt Dim = CAT->getSize();
3627 Result += utostr(Dim.getZExtValue());
3628 Result += "]";
3629 }
3630 CType = CType->getAs<ArrayType>()->getElementType();
3631 }
3632 }
3633
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003634 Result += ";\n";
3635}
3636
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003637/// RewriteLocallyDefinedNamedAggregates - This routine rewrites locally defined
3638/// named aggregate types into the input buffer.
3639void RewriteModernObjC::RewriteLocallyDefinedNamedAggregates(FieldDecl *fieldDecl,
3640 std::string &Result) {
3641 QualType Type = fieldDecl->getType();
Fariborz Jahanianf5eac482012-05-02 17:34:59 +00003642 if (isa<TypedefType>(Type))
3643 return;
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003644 if (Type->isArrayType())
3645 Type = Context->getBaseElementType(Type);
Fariborz Jahanianb68258f2012-05-01 17:46:45 +00003646 ObjCContainerDecl *IDecl =
3647 dyn_cast<ObjCContainerDecl>(fieldDecl->getDeclContext());
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003648
3649 TagDecl *TD = 0;
3650 if (Type->isRecordType()) {
3651 TD = Type->getAs<RecordType>()->getDecl();
3652 }
3653 else if (Type->isEnumeralType()) {
3654 TD = Type->getAs<EnumType>()->getDecl();
3655 }
3656
3657 if (TD) {
3658 if (GlobalDefinedTags.count(TD))
3659 return;
3660
3661 bool IsNamedDefinition = false;
3662 if (IsTagDefinedInsideClass(IDecl, TD, IsNamedDefinition)) {
3663 RewriteObjCFieldDeclType(Type, Result);
3664 Result += ";";
3665 }
3666 if (IsNamedDefinition)
3667 GlobalDefinedTags.insert(TD);
3668 }
3669
3670}
3671
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003672/// RewriteObjCInternalStruct - Rewrite one internal struct corresponding to
3673/// an objective-c class with ivars.
3674void RewriteModernObjC::RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
3675 std::string &Result) {
3676 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
3677 assert(CDecl->getName() != "" &&
3678 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003679 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003680 SmallVector<ObjCIvarDecl *, 8> IVars;
3681 for (ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
Fariborz Jahanian9a2105b2012-03-06 17:16:27 +00003682 IVD; IVD = IVD->getNextIvar())
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003683 IVars.push_back(IVD);
Fariborz Jahanian9a2105b2012-03-06 17:16:27 +00003684
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003685 SourceLocation LocStart = CDecl->getLocStart();
3686 SourceLocation LocEnd = CDecl->getEndOfDefinitionLoc();
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003687
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003688 const char *startBuf = SM->getCharacterData(LocStart);
3689 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003690
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003691 // If no ivars and no root or if its root, directly or indirectly,
3692 // have no ivars (thus not synthesized) then no need to synthesize this class.
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003693 if ((!CDecl->isThisDeclarationADefinition() || IVars.size() == 0) &&
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003694 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
3695 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
3696 ReplaceText(LocStart, endBuf-startBuf, Result);
3697 return;
3698 }
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003699
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003700 // Insert named struct/union definitions inside class to
3701 // outer scope. This follows semantics of locally defined
3702 // struct/unions in objective-c classes.
3703 for (unsigned i = 0, e = IVars.size(); i < e; i++)
3704 RewriteLocallyDefinedNamedAggregates(IVars[i], Result);
3705
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003706 Result += "\nstruct ";
3707 Result += CDecl->getNameAsString();
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003708 Result += "_IMPL {\n";
3709
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00003710 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003711 Result += "\tstruct "; Result += RCDecl->getNameAsString();
3712 Result += "_IMPL "; Result += RCDecl->getNameAsString();
3713 Result += "_IVARS;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003714 }
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003715
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003716 for (unsigned i = 0, e = IVars.size(); i < e; i++)
3717 RewriteObjCFieldDecl(IVars[i], Result);
Fariborz Jahanian0b17b9a2012-02-12 21:36:23 +00003718
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003719 Result += "};\n";
3720 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
3721 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00003722 // Mark this struct as having been generated.
3723 if (!ObjCSynthesizedStructs.insert(CDecl))
3724 llvm_unreachable("struct already synthesize- RewriteObjCInternalStruct");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003725}
3726
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00003727static void WriteInternalIvarName(ObjCInterfaceDecl *IDecl,
3728 ObjCIvarDecl *IvarDecl, std::string &Result) {
3729 Result += "OBJC_IVAR_$_";
3730 Result += IDecl->getName();
3731 Result += "$";
3732 Result += IvarDecl->getName();
3733}
3734
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00003735/// RewriteIvarOffsetSymbols - Rewrite ivar offset symbols of those ivars which
3736/// have been referenced in an ivar access expression.
3737void RewriteModernObjC::RewriteIvarOffsetSymbols(ObjCInterfaceDecl *CDecl,
3738 std::string &Result) {
3739 // write out ivar offset symbols which have been referenced in an ivar
3740 // access expression.
3741 llvm::SmallPtrSet<ObjCIvarDecl *, 8> Ivars = ReferencedIvars[CDecl];
3742 if (Ivars.empty())
3743 return;
3744 for (llvm::SmallPtrSet<ObjCIvarDecl *, 8>::iterator i = Ivars.begin(),
3745 e = Ivars.end(); i != e; i++) {
3746 ObjCIvarDecl *IvarDecl = (*i);
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00003747 Result += "\n";
3748 if (LangOpts.MicrosoftExt)
3749 Result += "__declspec(allocate(\".objc_ivar$B\")) ";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00003750 Result += "extern \"C\" ";
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00003751 if (LangOpts.MicrosoftExt &&
3752 IvarDecl->getAccessControl() != ObjCIvarDecl::Private &&
Fariborz Jahanian297976d2012-03-29 17:51:09 +00003753 IvarDecl->getAccessControl() != ObjCIvarDecl::Package)
3754 Result += "__declspec(dllimport) ";
3755
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00003756 Result += "unsigned long ";
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00003757 WriteInternalIvarName(CDecl, IvarDecl, Result);
3758 Result += ";";
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00003759 }
3760}
3761
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003762//===----------------------------------------------------------------------===//
3763// Meta Data Emission
3764//===----------------------------------------------------------------------===//
3765
3766
3767/// RewriteImplementations - This routine rewrites all method implementations
3768/// and emits meta-data.
3769
3770void RewriteModernObjC::RewriteImplementations() {
3771 int ClsDefCount = ClassImplementation.size();
3772 int CatDefCount = CategoryImplementation.size();
3773
3774 // Rewrite implemented methods
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00003775 for (int i = 0; i < ClsDefCount; i++) {
3776 ObjCImplementationDecl *OIMP = ClassImplementation[i];
3777 ObjCInterfaceDecl *CDecl = OIMP->getClassInterface();
3778 if (CDecl->isImplicitInterfaceDecl())
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +00003779 assert(false &&
3780 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00003781 RewriteImplementationDecl(OIMP);
3782 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003783
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00003784 for (int i = 0; i < CatDefCount; i++) {
3785 ObjCCategoryImplDecl *CIMP = CategoryImplementation[i];
3786 ObjCInterfaceDecl *CDecl = CIMP->getClassInterface();
3787 if (CDecl->isImplicitInterfaceDecl())
3788 assert(false &&
3789 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00003790 RewriteImplementationDecl(CIMP);
3791 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003792}
3793
3794void RewriteModernObjC::RewriteByRefString(std::string &ResultStr,
3795 const std::string &Name,
3796 ValueDecl *VD, bool def) {
3797 assert(BlockByRefDeclNo.count(VD) &&
3798 "RewriteByRefString: ByRef decl missing");
3799 if (def)
3800 ResultStr += "struct ";
3801 ResultStr += "__Block_byref_" + Name +
3802 "_" + utostr(BlockByRefDeclNo[VD]) ;
3803}
3804
3805static bool HasLocalVariableExternalStorage(ValueDecl *VD) {
3806 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
3807 return (Var->isFunctionOrMethodVarDecl() && !Var->hasLocalStorage());
3808 return false;
3809}
3810
3811std::string RewriteModernObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
3812 StringRef funcName,
3813 std::string Tag) {
3814 const FunctionType *AFT = CE->getFunctionType();
3815 QualType RT = AFT->getResultType();
3816 std::string StructRef = "struct " + Tag;
3817 std::string S = "static " + RT.getAsString(Context->getPrintingPolicy()) + " __" +
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00003818 funcName.str() + "_block_func_" + utostr(i);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003819
3820 BlockDecl *BD = CE->getBlockDecl();
3821
3822 if (isa<FunctionNoProtoType>(AFT)) {
3823 // No user-supplied arguments. Still need to pass in a pointer to the
3824 // block (to reference imported block decl refs).
3825 S += "(" + StructRef + " *__cself)";
3826 } else if (BD->param_empty()) {
3827 S += "(" + StructRef + " *__cself)";
3828 } else {
3829 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
3830 assert(FT && "SynthesizeBlockFunc: No function proto");
3831 S += '(';
3832 // first add the implicit argument.
3833 S += StructRef + " *__cself, ";
3834 std::string ParamStr;
3835 for (BlockDecl::param_iterator AI = BD->param_begin(),
3836 E = BD->param_end(); AI != E; ++AI) {
3837 if (AI != BD->param_begin()) S += ", ";
3838 ParamStr = (*AI)->getNameAsString();
3839 QualType QT = (*AI)->getType();
Fariborz Jahanian2610f902012-03-27 16:42:20 +00003840 (void)convertBlockPointerToFunctionPointer(QT);
3841 QT.getAsStringInternal(ParamStr, Context->getPrintingPolicy());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003842 S += ParamStr;
3843 }
3844 if (FT->isVariadic()) {
3845 if (!BD->param_empty()) S += ", ";
3846 S += "...";
3847 }
3848 S += ')';
3849 }
3850 S += " {\n";
3851
3852 // Create local declarations to avoid rewriting all closure decl ref exprs.
3853 // First, emit a declaration for all "by ref" decls.
3854 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3855 E = BlockByRefDecls.end(); I != E; ++I) {
3856 S += " ";
3857 std::string Name = (*I)->getNameAsString();
3858 std::string TypeString;
3859 RewriteByRefString(TypeString, Name, (*I));
3860 TypeString += " *";
3861 Name = TypeString + Name;
3862 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
3863 }
3864 // Next, emit a declaration for all "by copy" declarations.
3865 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3866 E = BlockByCopyDecls.end(); I != E; ++I) {
3867 S += " ";
3868 // Handle nested closure invocation. For example:
3869 //
3870 // void (^myImportedClosure)(void);
3871 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
3872 //
3873 // void (^anotherClosure)(void);
3874 // anotherClosure = ^(void) {
3875 // myImportedClosure(); // import and invoke the closure
3876 // };
3877 //
3878 if (isTopLevelBlockPointerType((*I)->getType())) {
3879 RewriteBlockPointerTypeVariable(S, (*I));
3880 S += " = (";
3881 RewriteBlockPointerType(S, (*I)->getType());
3882 S += ")";
3883 S += "__cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
3884 }
3885 else {
3886 std::string Name = (*I)->getNameAsString();
3887 QualType QT = (*I)->getType();
3888 if (HasLocalVariableExternalStorage(*I))
3889 QT = Context->getPointerType(QT);
3890 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
3891 S += Name + " = __cself->" +
3892 (*I)->getNameAsString() + "; // bound by copy\n";
3893 }
3894 }
3895 std::string RewrittenStr = RewrittenBlockExprs[CE];
3896 const char *cstr = RewrittenStr.c_str();
3897 while (*cstr++ != '{') ;
3898 S += cstr;
3899 S += "\n";
3900 return S;
3901}
3902
3903std::string RewriteModernObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
3904 StringRef funcName,
3905 std::string Tag) {
3906 std::string StructRef = "struct " + Tag;
3907 std::string S = "static void __";
3908
3909 S += funcName;
3910 S += "_block_copy_" + utostr(i);
3911 S += "(" + StructRef;
3912 S += "*dst, " + StructRef;
3913 S += "*src) {";
3914 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
3915 E = ImportedBlockDecls.end(); I != E; ++I) {
3916 ValueDecl *VD = (*I);
3917 S += "_Block_object_assign((void*)&dst->";
3918 S += (*I)->getNameAsString();
3919 S += ", (void*)src->";
3920 S += (*I)->getNameAsString();
3921 if (BlockByRefDeclsPtrSet.count((*I)))
3922 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
3923 else if (VD->getType()->isBlockPointerType())
3924 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
3925 else
3926 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
3927 }
3928 S += "}\n";
3929
3930 S += "\nstatic void __";
3931 S += funcName;
3932 S += "_block_dispose_" + utostr(i);
3933 S += "(" + StructRef;
3934 S += "*src) {";
3935 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
3936 E = ImportedBlockDecls.end(); I != E; ++I) {
3937 ValueDecl *VD = (*I);
3938 S += "_Block_object_dispose((void*)src->";
3939 S += (*I)->getNameAsString();
3940 if (BlockByRefDeclsPtrSet.count((*I)))
3941 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
3942 else if (VD->getType()->isBlockPointerType())
3943 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
3944 else
3945 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
3946 }
3947 S += "}\n";
3948 return S;
3949}
3950
3951std::string RewriteModernObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
3952 std::string Desc) {
3953 std::string S = "\nstruct " + Tag;
3954 std::string Constructor = " " + Tag;
3955
3956 S += " {\n struct __block_impl impl;\n";
3957 S += " struct " + Desc;
3958 S += "* Desc;\n";
3959
3960 Constructor += "(void *fp, "; // Invoke function pointer.
3961 Constructor += "struct " + Desc; // Descriptor pointer.
3962 Constructor += " *desc";
3963
3964 if (BlockDeclRefs.size()) {
3965 // Output all "by copy" declarations.
3966 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3967 E = BlockByCopyDecls.end(); I != E; ++I) {
3968 S += " ";
3969 std::string FieldName = (*I)->getNameAsString();
3970 std::string ArgName = "_" + FieldName;
3971 // Handle nested closure invocation. For example:
3972 //
3973 // void (^myImportedBlock)(void);
3974 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
3975 //
3976 // void (^anotherBlock)(void);
3977 // anotherBlock = ^(void) {
3978 // myImportedBlock(); // import and invoke the closure
3979 // };
3980 //
3981 if (isTopLevelBlockPointerType((*I)->getType())) {
3982 S += "struct __block_impl *";
3983 Constructor += ", void *" + ArgName;
3984 } else {
3985 QualType QT = (*I)->getType();
3986 if (HasLocalVariableExternalStorage(*I))
3987 QT = Context->getPointerType(QT);
3988 QT.getAsStringInternal(FieldName, Context->getPrintingPolicy());
3989 QT.getAsStringInternal(ArgName, Context->getPrintingPolicy());
3990 Constructor += ", " + ArgName;
3991 }
3992 S += FieldName + ";\n";
3993 }
3994 // Output all "by ref" declarations.
3995 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3996 E = BlockByRefDecls.end(); I != E; ++I) {
3997 S += " ";
3998 std::string FieldName = (*I)->getNameAsString();
3999 std::string ArgName = "_" + FieldName;
4000 {
4001 std::string TypeString;
4002 RewriteByRefString(TypeString, FieldName, (*I));
4003 TypeString += " *";
4004 FieldName = TypeString + FieldName;
4005 ArgName = TypeString + ArgName;
4006 Constructor += ", " + ArgName;
4007 }
4008 S += FieldName + "; // by ref\n";
4009 }
4010 // Finish writing the constructor.
4011 Constructor += ", int flags=0)";
4012 // Initialize all "by copy" arguments.
4013 bool firsTime = true;
4014 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
4015 E = BlockByCopyDecls.end(); I != E; ++I) {
4016 std::string Name = (*I)->getNameAsString();
4017 if (firsTime) {
4018 Constructor += " : ";
4019 firsTime = false;
4020 }
4021 else
4022 Constructor += ", ";
4023 if (isTopLevelBlockPointerType((*I)->getType()))
4024 Constructor += Name + "((struct __block_impl *)_" + Name + ")";
4025 else
4026 Constructor += Name + "(_" + Name + ")";
4027 }
4028 // Initialize all "by ref" arguments.
4029 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
4030 E = BlockByRefDecls.end(); I != E; ++I) {
4031 std::string Name = (*I)->getNameAsString();
4032 if (firsTime) {
4033 Constructor += " : ";
4034 firsTime = false;
4035 }
4036 else
4037 Constructor += ", ";
4038 Constructor += Name + "(_" + Name + "->__forwarding)";
4039 }
4040
4041 Constructor += " {\n";
4042 if (GlobalVarDecl)
4043 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4044 else
4045 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
4046 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
4047
4048 Constructor += " Desc = desc;\n";
4049 } else {
4050 // Finish writing the constructor.
4051 Constructor += ", int flags=0) {\n";
4052 if (GlobalVarDecl)
4053 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4054 else
4055 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
4056 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
4057 Constructor += " Desc = desc;\n";
4058 }
4059 Constructor += " ";
4060 Constructor += "}\n";
4061 S += Constructor;
4062 S += "};\n";
4063 return S;
4064}
4065
4066std::string RewriteModernObjC::SynthesizeBlockDescriptor(std::string DescTag,
4067 std::string ImplTag, int i,
4068 StringRef FunName,
4069 unsigned hasCopy) {
4070 std::string S = "\nstatic struct " + DescTag;
4071
Fariborz Jahanian8b08adb2012-05-03 21:44:12 +00004072 S += " {\n size_t reserved;\n";
4073 S += " size_t Block_size;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004074 if (hasCopy) {
4075 S += " void (*copy)(struct ";
4076 S += ImplTag; S += "*, struct ";
4077 S += ImplTag; S += "*);\n";
4078
4079 S += " void (*dispose)(struct ";
4080 S += ImplTag; S += "*);\n";
4081 }
4082 S += "} ";
4083
4084 S += DescTag + "_DATA = { 0, sizeof(struct ";
4085 S += ImplTag + ")";
4086 if (hasCopy) {
4087 S += ", __" + FunName.str() + "_block_copy_" + utostr(i);
4088 S += ", __" + FunName.str() + "_block_dispose_" + utostr(i);
4089 }
4090 S += "};\n";
4091 return S;
4092}
4093
Fariborz Jahanian76a98be2012-04-17 18:40:53 +00004094/// getFunctionSourceLocation - returns start location of a function
4095/// definition. Complication arises when function has declared as
4096/// extern "C" or extern "C" {...}
Fariborz Jahanianb75f8de2012-04-19 00:50:01 +00004097static SourceLocation getFunctionSourceLocation (RewriteModernObjC &R,
4098 FunctionDecl *FD) {
Fariborz Jahanianb5863da2012-04-19 16:30:28 +00004099 if (FD->isExternC() && !FD->isMain()) {
4100 const DeclContext *DC = FD->getDeclContext();
4101 if (const LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(DC))
4102 // if it is extern "C" {...}, return function decl's own location.
4103 if (!LSD->getRBraceLoc().isValid())
4104 return LSD->getExternLoc();
Fariborz Jahanianb75f8de2012-04-19 00:50:01 +00004105 }
Fariborz Jahanianb5863da2012-04-19 16:30:28 +00004106 if (FD->getStorageClassAsWritten() != SC_None)
4107 R.RewriteBlockLiteralFunctionDecl(FD);
Fariborz Jahanian76a98be2012-04-17 18:40:53 +00004108 return FD->getTypeSpecStartLoc();
4109}
4110
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004111void RewriteModernObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
4112 StringRef FunName) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004113 bool RewriteSC = (GlobalVarDecl &&
4114 !Blocks.empty() &&
4115 GlobalVarDecl->getStorageClass() == SC_Static &&
4116 GlobalVarDecl->getType().getCVRQualifiers());
4117 if (RewriteSC) {
4118 std::string SC(" void __");
4119 SC += GlobalVarDecl->getNameAsString();
4120 SC += "() {}";
4121 InsertText(FunLocStart, SC);
4122 }
4123
4124 // Insert closures that were part of the function.
4125 for (unsigned i = 0, count=0; i < Blocks.size(); i++) {
4126 CollectBlockDeclRefInfo(Blocks[i]);
4127 // Need to copy-in the inner copied-in variables not actually used in this
4128 // block.
4129 for (int j = 0; j < InnerDeclRefsCount[i]; j++) {
John McCallf4b88a42012-03-10 09:33:50 +00004130 DeclRefExpr *Exp = InnerDeclRefs[count++];
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004131 ValueDecl *VD = Exp->getDecl();
4132 BlockDeclRefs.push_back(Exp);
John McCallf4b88a42012-03-10 09:33:50 +00004133 if (!VD->hasAttr<BlocksAttr>()) {
4134 if (!BlockByCopyDeclsPtrSet.count(VD)) {
4135 BlockByCopyDeclsPtrSet.insert(VD);
4136 BlockByCopyDecls.push_back(VD);
4137 }
4138 continue;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004139 }
John McCallf4b88a42012-03-10 09:33:50 +00004140
4141 if (!BlockByRefDeclsPtrSet.count(VD)) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004142 BlockByRefDeclsPtrSet.insert(VD);
4143 BlockByRefDecls.push_back(VD);
4144 }
John McCallf4b88a42012-03-10 09:33:50 +00004145
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004146 // imported objects in the inner blocks not used in the outer
4147 // blocks must be copied/disposed in the outer block as well.
John McCallf4b88a42012-03-10 09:33:50 +00004148 if (VD->getType()->isObjCObjectPointerType() ||
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004149 VD->getType()->isBlockPointerType())
4150 ImportedBlockDecls.insert(VD);
4151 }
4152
4153 std::string ImplTag = "__" + FunName.str() + "_block_impl_" + utostr(i);
4154 std::string DescTag = "__" + FunName.str() + "_block_desc_" + utostr(i);
4155
4156 std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
4157
4158 InsertText(FunLocStart, CI);
4159
4160 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
4161
4162 InsertText(FunLocStart, CF);
4163
4164 if (ImportedBlockDecls.size()) {
4165 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
4166 InsertText(FunLocStart, HF);
4167 }
4168 std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
4169 ImportedBlockDecls.size() > 0);
4170 InsertText(FunLocStart, BD);
4171
4172 BlockDeclRefs.clear();
4173 BlockByRefDecls.clear();
4174 BlockByRefDeclsPtrSet.clear();
4175 BlockByCopyDecls.clear();
4176 BlockByCopyDeclsPtrSet.clear();
4177 ImportedBlockDecls.clear();
4178 }
4179 if (RewriteSC) {
4180 // Must insert any 'const/volatile/static here. Since it has been
4181 // removed as result of rewriting of block literals.
4182 std::string SC;
4183 if (GlobalVarDecl->getStorageClass() == SC_Static)
4184 SC = "static ";
4185 if (GlobalVarDecl->getType().isConstQualified())
4186 SC += "const ";
4187 if (GlobalVarDecl->getType().isVolatileQualified())
4188 SC += "volatile ";
4189 if (GlobalVarDecl->getType().isRestrictQualified())
4190 SC += "restrict ";
4191 InsertText(FunLocStart, SC);
4192 }
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00004193 if (GlobalConstructionExp) {
4194 // extra fancy dance for global literal expression.
4195
4196 // Always the latest block expression on the block stack.
4197 std::string Tag = "__";
4198 Tag += FunName;
4199 Tag += "_block_impl_";
4200 Tag += utostr(Blocks.size()-1);
4201 std::string globalBuf = "static ";
4202 globalBuf += Tag; globalBuf += " ";
4203 std::string SStr;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004204
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00004205 llvm::raw_string_ostream constructorExprBuf(SStr);
4206 GlobalConstructionExp->printPretty(constructorExprBuf, *Context, 0,
4207 PrintingPolicy(LangOpts));
4208 globalBuf += constructorExprBuf.str();
4209 globalBuf += ";\n";
4210 InsertText(FunLocStart, globalBuf);
4211 GlobalConstructionExp = 0;
4212 }
4213
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004214 Blocks.clear();
4215 InnerDeclRefsCount.clear();
4216 InnerDeclRefs.clear();
4217 RewrittenBlockExprs.clear();
4218}
4219
4220void RewriteModernObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
Fariborz Jahanian04189532012-04-25 17:56:48 +00004221 SourceLocation FunLocStart =
4222 (!Blocks.empty()) ? getFunctionSourceLocation(*this, FD)
4223 : FD->getTypeSpecStartLoc();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004224 StringRef FuncName = FD->getName();
4225
4226 SynthesizeBlockLiterals(FunLocStart, FuncName);
4227}
4228
4229static void BuildUniqueMethodName(std::string &Name,
4230 ObjCMethodDecl *MD) {
4231 ObjCInterfaceDecl *IFace = MD->getClassInterface();
4232 Name = IFace->getName();
4233 Name += "__" + MD->getSelector().getAsString();
4234 // Convert colons to underscores.
4235 std::string::size_type loc = 0;
4236 while ((loc = Name.find(":", loc)) != std::string::npos)
4237 Name.replace(loc, 1, "_");
4238}
4239
4240void RewriteModernObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
4241 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
4242 //SourceLocation FunLocStart = MD->getLocStart();
4243 SourceLocation FunLocStart = MD->getLocStart();
4244 std::string FuncName;
4245 BuildUniqueMethodName(FuncName, MD);
4246 SynthesizeBlockLiterals(FunLocStart, FuncName);
4247}
4248
4249void RewriteModernObjC::GetBlockDeclRefExprs(Stmt *S) {
4250 for (Stmt::child_range CI = S->children(); CI; ++CI)
4251 if (*CI) {
4252 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
4253 GetBlockDeclRefExprs(CBE->getBody());
4254 else
4255 GetBlockDeclRefExprs(*CI);
4256 }
4257 // Handle specific things.
Fariborz Jahanian0e976812012-04-16 23:00:57 +00004258 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4259 if (DRE->refersToEnclosingLocal()) {
4260 // FIXME: Handle enums.
4261 if (!isa<FunctionDecl>(DRE->getDecl()))
4262 BlockDeclRefs.push_back(DRE);
4263 if (HasLocalVariableExternalStorage(DRE->getDecl()))
4264 BlockDeclRefs.push_back(DRE);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004265 }
Fariborz Jahanian0e976812012-04-16 23:00:57 +00004266 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004267
4268 return;
4269}
4270
4271void RewriteModernObjC::GetInnerBlockDeclRefExprs(Stmt *S,
John McCallf4b88a42012-03-10 09:33:50 +00004272 SmallVector<DeclRefExpr *, 8> &InnerBlockDeclRefs,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004273 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts) {
4274 for (Stmt::child_range CI = S->children(); CI; ++CI)
4275 if (*CI) {
4276 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI)) {
4277 InnerContexts.insert(cast<DeclContext>(CBE->getBlockDecl()));
4278 GetInnerBlockDeclRefExprs(CBE->getBody(),
4279 InnerBlockDeclRefs,
4280 InnerContexts);
4281 }
4282 else
4283 GetInnerBlockDeclRefExprs(*CI,
4284 InnerBlockDeclRefs,
4285 InnerContexts);
4286
4287 }
4288 // Handle specific things.
John McCallf4b88a42012-03-10 09:33:50 +00004289 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4290 if (DRE->refersToEnclosingLocal()) {
4291 if (!isa<FunctionDecl>(DRE->getDecl()) &&
4292 !InnerContexts.count(DRE->getDecl()->getDeclContext()))
4293 InnerBlockDeclRefs.push_back(DRE);
4294 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl()))
4295 if (Var->isFunctionOrMethodVarDecl())
4296 ImportedLocalExternalDecls.insert(Var);
4297 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004298 }
4299
4300 return;
4301}
4302
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00004303/// convertObjCTypeToCStyleType - This routine converts such objc types
4304/// as qualified objects, and blocks to their closest c/c++ types that
4305/// it can. It returns true if input type was modified.
4306bool RewriteModernObjC::convertObjCTypeToCStyleType(QualType &T) {
4307 QualType oldT = T;
4308 convertBlockPointerToFunctionPointer(T);
4309 if (T->isFunctionPointerType()) {
4310 QualType PointeeTy;
4311 if (const PointerType* PT = T->getAs<PointerType>()) {
4312 PointeeTy = PT->getPointeeType();
4313 if (const FunctionType *FT = PointeeTy->getAs<FunctionType>()) {
4314 T = convertFunctionTypeOfBlocks(FT);
4315 T = Context->getPointerType(T);
4316 }
4317 }
4318 }
4319
4320 convertToUnqualifiedObjCType(T);
4321 return T != oldT;
4322}
4323
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004324/// convertFunctionTypeOfBlocks - This routine converts a function type
4325/// whose result type may be a block pointer or whose argument type(s)
4326/// might be block pointers to an equivalent function type replacing
4327/// all block pointers to function pointers.
4328QualType RewriteModernObjC::convertFunctionTypeOfBlocks(const FunctionType *FT) {
4329 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
4330 // FTP will be null for closures that don't take arguments.
4331 // Generate a funky cast.
4332 SmallVector<QualType, 8> ArgTypes;
4333 QualType Res = FT->getResultType();
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00004334 bool modified = convertObjCTypeToCStyleType(Res);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004335
4336 if (FTP) {
4337 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4338 E = FTP->arg_type_end(); I && (I != E); ++I) {
4339 QualType t = *I;
4340 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00004341 if (convertObjCTypeToCStyleType(t))
4342 modified = true;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004343 ArgTypes.push_back(t);
4344 }
4345 }
4346 QualType FuncType;
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00004347 if (modified)
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004348 FuncType = getSimpleFunctionType(Res, &ArgTypes[0], ArgTypes.size());
4349 else FuncType = QualType(FT, 0);
4350 return FuncType;
4351}
4352
4353Stmt *RewriteModernObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
4354 // Navigate to relevant type information.
4355 const BlockPointerType *CPT = 0;
4356
4357 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
4358 CPT = DRE->getType()->getAs<BlockPointerType>();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004359 } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
4360 CPT = MExpr->getType()->getAs<BlockPointerType>();
4361 }
4362 else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
4363 return SynthesizeBlockCall(Exp, PRE->getSubExpr());
4364 }
4365 else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
4366 CPT = IEXPR->getType()->getAs<BlockPointerType>();
4367 else if (const ConditionalOperator *CEXPR =
4368 dyn_cast<ConditionalOperator>(BlockExp)) {
4369 Expr *LHSExp = CEXPR->getLHS();
4370 Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
4371 Expr *RHSExp = CEXPR->getRHS();
4372 Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
4373 Expr *CONDExp = CEXPR->getCond();
4374 ConditionalOperator *CondExpr =
4375 new (Context) ConditionalOperator(CONDExp,
4376 SourceLocation(), cast<Expr>(LHSStmt),
4377 SourceLocation(), cast<Expr>(RHSStmt),
4378 Exp->getType(), VK_RValue, OK_Ordinary);
4379 return CondExpr;
4380 } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
4381 CPT = IRE->getType()->getAs<BlockPointerType>();
4382 } else if (const PseudoObjectExpr *POE
4383 = dyn_cast<PseudoObjectExpr>(BlockExp)) {
4384 CPT = POE->getType()->castAs<BlockPointerType>();
4385 } else {
4386 assert(1 && "RewriteBlockClass: Bad type");
4387 }
4388 assert(CPT && "RewriteBlockClass: Bad type");
4389 const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
4390 assert(FT && "RewriteBlockClass: Bad type");
4391 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
4392 // FTP will be null for closures that don't take arguments.
4393
4394 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
4395 SourceLocation(), SourceLocation(),
4396 &Context->Idents.get("__block_impl"));
4397 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
4398
4399 // Generate a funky cast.
4400 SmallVector<QualType, 8> ArgTypes;
4401
4402 // Push the block argument type.
4403 ArgTypes.push_back(PtrBlock);
4404 if (FTP) {
4405 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4406 E = FTP->arg_type_end(); I && (I != E); ++I) {
4407 QualType t = *I;
4408 // Make sure we convert "t (^)(...)" to "t (*)(...)".
4409 if (!convertBlockPointerToFunctionPointer(t))
4410 convertToUnqualifiedObjCType(t);
4411 ArgTypes.push_back(t);
4412 }
4413 }
4414 // Now do the pointer to function cast.
4415 QualType PtrToFuncCastType
4416 = getSimpleFunctionType(Exp->getType(), &ArgTypes[0], ArgTypes.size());
4417
4418 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
4419
4420 CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock,
4421 CK_BitCast,
4422 const_cast<Expr*>(BlockExp));
4423 // Don't forget the parens to enforce the proper binding.
4424 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4425 BlkCast);
4426 //PE->dump();
4427
4428 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4429 SourceLocation(),
4430 &Context->Idents.get("FuncPtr"),
4431 Context->VoidPtrTy, 0,
4432 /*BitWidth=*/0, /*Mutable=*/true,
4433 /*HasInit=*/false);
4434 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
4435 FD->getType(), VK_LValue,
4436 OK_Ordinary);
4437
4438
4439 CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType,
4440 CK_BitCast, ME);
4441 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
4442
4443 SmallVector<Expr*, 8> BlkExprs;
4444 // Add the implicit argument.
4445 BlkExprs.push_back(BlkCast);
4446 // Add the user arguments.
4447 for (CallExpr::arg_iterator I = Exp->arg_begin(),
4448 E = Exp->arg_end(); I != E; ++I) {
4449 BlkExprs.push_back(*I);
4450 }
4451 CallExpr *CE = new (Context) CallExpr(*Context, PE, &BlkExprs[0],
4452 BlkExprs.size(),
4453 Exp->getType(), VK_RValue,
4454 SourceLocation());
4455 return CE;
4456}
4457
4458// We need to return the rewritten expression to handle cases where the
John McCallf4b88a42012-03-10 09:33:50 +00004459// DeclRefExpr is embedded in another expression being rewritten.
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004460// For example:
4461//
4462// int main() {
4463// __block Foo *f;
4464// __block int i;
4465//
4466// void (^myblock)() = ^() {
John McCallf4b88a42012-03-10 09:33:50 +00004467// [f test]; // f is a DeclRefExpr embedded in a message (which is being rewritten).
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004468// i = 77;
4469// };
4470//}
John McCallf4b88a42012-03-10 09:33:50 +00004471Stmt *RewriteModernObjC::RewriteBlockDeclRefExpr(DeclRefExpr *DeclRefExp) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004472 // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
4473 // for each DeclRefExp where BYREFVAR is name of the variable.
John McCallf4b88a42012-03-10 09:33:50 +00004474 ValueDecl *VD = DeclRefExp->getDecl();
4475 bool isArrow = DeclRefExp->refersToEnclosingLocal();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004476
4477 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4478 SourceLocation(),
4479 &Context->Idents.get("__forwarding"),
4480 Context->VoidPtrTy, 0,
4481 /*BitWidth=*/0, /*Mutable=*/true,
4482 /*HasInit=*/false);
4483 MemberExpr *ME = new (Context) MemberExpr(DeclRefExp, isArrow,
4484 FD, SourceLocation(),
4485 FD->getType(), VK_LValue,
4486 OK_Ordinary);
4487
4488 StringRef Name = VD->getName();
4489 FD = FieldDecl::Create(*Context, 0, SourceLocation(), SourceLocation(),
4490 &Context->Idents.get(Name),
4491 Context->VoidPtrTy, 0,
4492 /*BitWidth=*/0, /*Mutable=*/true,
4493 /*HasInit=*/false);
4494 ME = new (Context) MemberExpr(ME, true, FD, SourceLocation(),
4495 DeclRefExp->getType(), VK_LValue, OK_Ordinary);
4496
4497
4498
4499 // Need parens to enforce precedence.
4500 ParenExpr *PE = new (Context) ParenExpr(DeclRefExp->getExprLoc(),
4501 DeclRefExp->getExprLoc(),
4502 ME);
4503 ReplaceStmt(DeclRefExp, PE);
4504 return PE;
4505}
4506
4507// Rewrites the imported local variable V with external storage
4508// (static, extern, etc.) as *V
4509//
4510Stmt *RewriteModernObjC::RewriteLocalVariableExternalStorage(DeclRefExpr *DRE) {
4511 ValueDecl *VD = DRE->getDecl();
4512 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4513 if (!ImportedLocalExternalDecls.count(Var))
4514 return DRE;
4515 Expr *Exp = new (Context) UnaryOperator(DRE, UO_Deref, DRE->getType(),
4516 VK_LValue, OK_Ordinary,
4517 DRE->getLocation());
4518 // Need parens to enforce precedence.
4519 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4520 Exp);
4521 ReplaceStmt(DRE, PE);
4522 return PE;
4523}
4524
4525void RewriteModernObjC::RewriteCastExpr(CStyleCastExpr *CE) {
4526 SourceLocation LocStart = CE->getLParenLoc();
4527 SourceLocation LocEnd = CE->getRParenLoc();
4528
4529 // Need to avoid trying to rewrite synthesized casts.
4530 if (LocStart.isInvalid())
4531 return;
4532 // Need to avoid trying to rewrite casts contained in macros.
4533 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
4534 return;
4535
4536 const char *startBuf = SM->getCharacterData(LocStart);
4537 const char *endBuf = SM->getCharacterData(LocEnd);
4538 QualType QT = CE->getType();
4539 const Type* TypePtr = QT->getAs<Type>();
4540 if (isa<TypeOfExprType>(TypePtr)) {
4541 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
4542 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
4543 std::string TypeAsString = "(";
4544 RewriteBlockPointerType(TypeAsString, QT);
4545 TypeAsString += ")";
4546 ReplaceText(LocStart, endBuf-startBuf+1, TypeAsString);
4547 return;
4548 }
4549 // advance the location to startArgList.
4550 const char *argPtr = startBuf;
4551
4552 while (*argPtr++ && (argPtr < endBuf)) {
4553 switch (*argPtr) {
4554 case '^':
4555 // Replace the '^' with '*'.
4556 LocStart = LocStart.getLocWithOffset(argPtr-startBuf);
4557 ReplaceText(LocStart, 1, "*");
4558 break;
4559 }
4560 }
4561 return;
4562}
4563
Fariborz Jahanianf1ee6872012-04-10 00:08:18 +00004564void RewriteModernObjC::RewriteImplicitCastObjCExpr(CastExpr *IC) {
4565 CastKind CastKind = IC->getCastKind();
Fariborz Jahanian43aa1c32012-04-16 22:14:01 +00004566 if (CastKind != CK_BlockPointerToObjCPointerCast &&
4567 CastKind != CK_AnyPointerToBlockPointerCast)
4568 return;
Fariborz Jahanianf1ee6872012-04-10 00:08:18 +00004569
Fariborz Jahanian43aa1c32012-04-16 22:14:01 +00004570 QualType QT = IC->getType();
4571 (void)convertBlockPointerToFunctionPointer(QT);
4572 std::string TypeString(QT.getAsString(Context->getPrintingPolicy()));
4573 std::string Str = "(";
4574 Str += TypeString;
4575 Str += ")";
4576 InsertText(IC->getSubExpr()->getLocStart(), &Str[0], Str.size());
4577
Fariborz Jahanianf1ee6872012-04-10 00:08:18 +00004578 return;
4579}
4580
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004581void RewriteModernObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
4582 SourceLocation DeclLoc = FD->getLocation();
4583 unsigned parenCount = 0;
4584
4585 // We have 1 or more arguments that have closure pointers.
4586 const char *startBuf = SM->getCharacterData(DeclLoc);
4587 const char *startArgList = strchr(startBuf, '(');
4588
4589 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
4590
4591 parenCount++;
4592 // advance the location to startArgList.
4593 DeclLoc = DeclLoc.getLocWithOffset(startArgList-startBuf);
4594 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
4595
4596 const char *argPtr = startArgList;
4597
4598 while (*argPtr++ && parenCount) {
4599 switch (*argPtr) {
4600 case '^':
4601 // Replace the '^' with '*'.
4602 DeclLoc = DeclLoc.getLocWithOffset(argPtr-startArgList);
4603 ReplaceText(DeclLoc, 1, "*");
4604 break;
4605 case '(':
4606 parenCount++;
4607 break;
4608 case ')':
4609 parenCount--;
4610 break;
4611 }
4612 }
4613 return;
4614}
4615
4616bool RewriteModernObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
4617 const FunctionProtoType *FTP;
4618 const PointerType *PT = QT->getAs<PointerType>();
4619 if (PT) {
4620 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4621 } else {
4622 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4623 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4624 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4625 }
4626 if (FTP) {
4627 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4628 E = FTP->arg_type_end(); I != E; ++I)
4629 if (isTopLevelBlockPointerType(*I))
4630 return true;
4631 }
4632 return false;
4633}
4634
4635bool RewriteModernObjC::PointerTypeTakesAnyObjCQualifiedType(QualType QT) {
4636 const FunctionProtoType *FTP;
4637 const PointerType *PT = QT->getAs<PointerType>();
4638 if (PT) {
4639 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4640 } else {
4641 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4642 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4643 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4644 }
4645 if (FTP) {
4646 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4647 E = FTP->arg_type_end(); I != E; ++I) {
4648 if ((*I)->isObjCQualifiedIdType())
4649 return true;
4650 if ((*I)->isObjCObjectPointerType() &&
4651 (*I)->getPointeeType()->isObjCQualifiedInterfaceType())
4652 return true;
4653 }
4654
4655 }
4656 return false;
4657}
4658
4659void RewriteModernObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
4660 const char *&RParen) {
4661 const char *argPtr = strchr(Name, '(');
4662 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
4663
4664 LParen = argPtr; // output the start.
4665 argPtr++; // skip past the left paren.
4666 unsigned parenCount = 1;
4667
4668 while (*argPtr && parenCount) {
4669 switch (*argPtr) {
4670 case '(': parenCount++; break;
4671 case ')': parenCount--; break;
4672 default: break;
4673 }
4674 if (parenCount) argPtr++;
4675 }
4676 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
4677 RParen = argPtr; // output the end
4678}
4679
4680void RewriteModernObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
4681 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4682 RewriteBlockPointerFunctionArgs(FD);
4683 return;
4684 }
4685 // Handle Variables and Typedefs.
4686 SourceLocation DeclLoc = ND->getLocation();
4687 QualType DeclT;
4688 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
4689 DeclT = VD->getType();
4690 else if (TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(ND))
4691 DeclT = TDD->getUnderlyingType();
4692 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
4693 DeclT = FD->getType();
4694 else
4695 llvm_unreachable("RewriteBlockPointerDecl(): Decl type not yet handled");
4696
4697 const char *startBuf = SM->getCharacterData(DeclLoc);
4698 const char *endBuf = startBuf;
4699 // scan backward (from the decl location) for the end of the previous decl.
4700 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
4701 startBuf--;
4702 SourceLocation Start = DeclLoc.getLocWithOffset(startBuf-endBuf);
4703 std::string buf;
4704 unsigned OrigLength=0;
4705 // *startBuf != '^' if we are dealing with a pointer to function that
4706 // may take block argument types (which will be handled below).
4707 if (*startBuf == '^') {
4708 // Replace the '^' with '*', computing a negative offset.
4709 buf = '*';
4710 startBuf++;
4711 OrigLength++;
4712 }
4713 while (*startBuf != ')') {
4714 buf += *startBuf;
4715 startBuf++;
4716 OrigLength++;
4717 }
4718 buf += ')';
4719 OrigLength++;
4720
4721 if (PointerTypeTakesAnyBlockArguments(DeclT) ||
4722 PointerTypeTakesAnyObjCQualifiedType(DeclT)) {
4723 // Replace the '^' with '*' for arguments.
4724 // Replace id<P> with id/*<>*/
4725 DeclLoc = ND->getLocation();
4726 startBuf = SM->getCharacterData(DeclLoc);
4727 const char *argListBegin, *argListEnd;
4728 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
4729 while (argListBegin < argListEnd) {
4730 if (*argListBegin == '^')
4731 buf += '*';
4732 else if (*argListBegin == '<') {
4733 buf += "/*";
4734 buf += *argListBegin++;
4735 OrigLength++;;
4736 while (*argListBegin != '>') {
4737 buf += *argListBegin++;
4738 OrigLength++;
4739 }
4740 buf += *argListBegin;
4741 buf += "*/";
4742 }
4743 else
4744 buf += *argListBegin;
4745 argListBegin++;
4746 OrigLength++;
4747 }
4748 buf += ')';
4749 OrigLength++;
4750 }
4751 ReplaceText(Start, OrigLength, buf);
4752
4753 return;
4754}
4755
4756
4757/// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
4758/// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
4759/// struct Block_byref_id_object *src) {
4760/// _Block_object_assign (&_dest->object, _src->object,
4761/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4762/// [|BLOCK_FIELD_IS_WEAK]) // object
4763/// _Block_object_assign(&_dest->object, _src->object,
4764/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4765/// [|BLOCK_FIELD_IS_WEAK]) // block
4766/// }
4767/// And:
4768/// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
4769/// _Block_object_dispose(_src->object,
4770/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4771/// [|BLOCK_FIELD_IS_WEAK]) // object
4772/// _Block_object_dispose(_src->object,
4773/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4774/// [|BLOCK_FIELD_IS_WEAK]) // block
4775/// }
4776
4777std::string RewriteModernObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
4778 int flag) {
4779 std::string S;
4780 if (CopyDestroyCache.count(flag))
4781 return S;
4782 CopyDestroyCache.insert(flag);
4783 S = "static void __Block_byref_id_object_copy_";
4784 S += utostr(flag);
4785 S += "(void *dst, void *src) {\n";
4786
4787 // offset into the object pointer is computed as:
4788 // void * + void* + int + int + void* + void *
4789 unsigned IntSize =
4790 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
4791 unsigned VoidPtrSize =
4792 static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
4793
4794 unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/Context->getCharWidth();
4795 S += " _Block_object_assign((char*)dst + ";
4796 S += utostr(offset);
4797 S += ", *(void * *) ((char*)src + ";
4798 S += utostr(offset);
4799 S += "), ";
4800 S += utostr(flag);
4801 S += ");\n}\n";
4802
4803 S += "static void __Block_byref_id_object_dispose_";
4804 S += utostr(flag);
4805 S += "(void *src) {\n";
4806 S += " _Block_object_dispose(*(void * *) ((char*)src + ";
4807 S += utostr(offset);
4808 S += "), ";
4809 S += utostr(flag);
4810 S += ");\n}\n";
4811 return S;
4812}
4813
4814/// RewriteByRefVar - For each __block typex ND variable this routine transforms
4815/// the declaration into:
4816/// struct __Block_byref_ND {
4817/// void *__isa; // NULL for everything except __weak pointers
4818/// struct __Block_byref_ND *__forwarding;
4819/// int32_t __flags;
4820/// int32_t __size;
4821/// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
4822/// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
4823/// typex ND;
4824/// };
4825///
4826/// It then replaces declaration of ND variable with:
4827/// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
4828/// __size=sizeof(struct __Block_byref_ND),
4829/// ND=initializer-if-any};
4830///
4831///
Fariborz Jahanian4fe261c2012-04-24 19:38:45 +00004832void RewriteModernObjC::RewriteByRefVar(VarDecl *ND, bool firstDecl,
4833 bool lastDecl) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004834 int flag = 0;
4835 int isa = 0;
4836 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
4837 if (DeclLoc.isInvalid())
4838 // If type location is missing, it is because of missing type (a warning).
4839 // Use variable's location which is good for this case.
4840 DeclLoc = ND->getLocation();
4841 const char *startBuf = SM->getCharacterData(DeclLoc);
4842 SourceLocation X = ND->getLocEnd();
4843 X = SM->getExpansionLoc(X);
4844 const char *endBuf = SM->getCharacterData(X);
4845 std::string Name(ND->getNameAsString());
4846 std::string ByrefType;
4847 RewriteByRefString(ByrefType, Name, ND, true);
4848 ByrefType += " {\n";
4849 ByrefType += " void *__isa;\n";
4850 RewriteByRefString(ByrefType, Name, ND);
4851 ByrefType += " *__forwarding;\n";
4852 ByrefType += " int __flags;\n";
4853 ByrefType += " int __size;\n";
4854 // Add void *__Block_byref_id_object_copy;
4855 // void *__Block_byref_id_object_dispose; if needed.
4856 QualType Ty = ND->getType();
4857 bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty);
4858 if (HasCopyAndDispose) {
4859 ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
4860 ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
4861 }
4862
4863 QualType T = Ty;
4864 (void)convertBlockPointerToFunctionPointer(T);
4865 T.getAsStringInternal(Name, Context->getPrintingPolicy());
4866
4867 ByrefType += " " + Name + ";\n";
4868 ByrefType += "};\n";
4869 // Insert this type in global scope. It is needed by helper function.
4870 SourceLocation FunLocStart;
4871 if (CurFunctionDef)
Fariborz Jahanianb75f8de2012-04-19 00:50:01 +00004872 FunLocStart = getFunctionSourceLocation(*this, CurFunctionDef);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004873 else {
4874 assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null");
4875 FunLocStart = CurMethodDef->getLocStart();
4876 }
4877 InsertText(FunLocStart, ByrefType);
Fariborz Jahanian8247c4e2012-04-24 16:45:27 +00004878
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004879 if (Ty.isObjCGCWeak()) {
4880 flag |= BLOCK_FIELD_IS_WEAK;
4881 isa = 1;
4882 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004883 if (HasCopyAndDispose) {
4884 flag = BLOCK_BYREF_CALLER;
4885 QualType Ty = ND->getType();
4886 // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
4887 if (Ty->isBlockPointerType())
4888 flag |= BLOCK_FIELD_IS_BLOCK;
4889 else
4890 flag |= BLOCK_FIELD_IS_OBJECT;
4891 std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
4892 if (!HF.empty())
4893 InsertText(FunLocStart, HF);
4894 }
4895
4896 // struct __Block_byref_ND ND =
4897 // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
4898 // initializer-if-any};
4899 bool hasInit = (ND->getInit() != 0);
Fariborz Jahanian104dbf92012-04-11 23:57:12 +00004900 // FIXME. rewriter does not support __block c++ objects which
4901 // require construction.
Fariborz Jahanian65a7c682012-04-26 23:20:25 +00004902 if (hasInit)
4903 if (CXXConstructExpr *CExp = dyn_cast<CXXConstructExpr>(ND->getInit())) {
4904 CXXConstructorDecl *CXXDecl = CExp->getConstructor();
4905 if (CXXDecl && CXXDecl->isDefaultConstructor())
4906 hasInit = false;
4907 }
4908
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004909 unsigned flags = 0;
4910 if (HasCopyAndDispose)
4911 flags |= BLOCK_HAS_COPY_DISPOSE;
4912 Name = ND->getNameAsString();
4913 ByrefType.clear();
4914 RewriteByRefString(ByrefType, Name, ND);
4915 std::string ForwardingCastType("(");
4916 ForwardingCastType += ByrefType + " *)";
Fariborz Jahanian8247c4e2012-04-24 16:45:27 +00004917 ByrefType += " " + Name + " = {(void*)";
4918 ByrefType += utostr(isa);
4919 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
4920 ByrefType += utostr(flags);
4921 ByrefType += ", ";
4922 ByrefType += "sizeof(";
4923 RewriteByRefString(ByrefType, Name, ND);
4924 ByrefType += ")";
4925 if (HasCopyAndDispose) {
4926 ByrefType += ", __Block_byref_id_object_copy_";
4927 ByrefType += utostr(flag);
4928 ByrefType += ", __Block_byref_id_object_dispose_";
4929 ByrefType += utostr(flag);
4930 }
4931
Fariborz Jahanian4fe261c2012-04-24 19:38:45 +00004932 if (!firstDecl) {
4933 // In multiple __block declarations, and for all but 1st declaration,
4934 // find location of the separating comma. This would be start location
4935 // where new text is to be inserted.
4936 DeclLoc = ND->getLocation();
4937 const char *startDeclBuf = SM->getCharacterData(DeclLoc);
4938 const char *commaBuf = startDeclBuf;
4939 while (*commaBuf != ',')
4940 commaBuf--;
4941 assert((*commaBuf == ',') && "RewriteByRefVar: can't find ','");
4942 DeclLoc = DeclLoc.getLocWithOffset(commaBuf - startDeclBuf);
4943 startBuf = commaBuf;
4944 }
4945
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004946 if (!hasInit) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004947 ByrefType += "};\n";
4948 unsigned nameSize = Name.size();
4949 // for block or function pointer declaration. Name is aleady
4950 // part of the declaration.
4951 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType())
4952 nameSize = 1;
4953 ReplaceText(DeclLoc, endBuf-startBuf+nameSize, ByrefType);
4954 }
4955 else {
Fariborz Jahanian8247c4e2012-04-24 16:45:27 +00004956 ByrefType += ", ";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004957 SourceLocation startLoc;
4958 Expr *E = ND->getInit();
4959 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
4960 startLoc = ECE->getLParenLoc();
4961 else
4962 startLoc = E->getLocStart();
4963 startLoc = SM->getExpansionLoc(startLoc);
4964 endBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004965 ReplaceText(DeclLoc, endBuf-startBuf, ByrefType);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004966
Fariborz Jahanian4fe261c2012-04-24 19:38:45 +00004967 const char separator = lastDecl ? ';' : ',';
4968 const char *startInitializerBuf = SM->getCharacterData(startLoc);
4969 const char *separatorBuf = strchr(startInitializerBuf, separator);
4970 assert((*separatorBuf == separator) &&
4971 "RewriteByRefVar: can't find ';' or ','");
4972 SourceLocation separatorLoc =
4973 startLoc.getLocWithOffset(separatorBuf-startInitializerBuf);
4974
4975 InsertText(separatorLoc, lastDecl ? "}" : "};\n");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004976 }
4977 return;
4978}
4979
4980void RewriteModernObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
4981 // Add initializers for any closure decl refs.
4982 GetBlockDeclRefExprs(Exp->getBody());
4983 if (BlockDeclRefs.size()) {
4984 // Unique all "by copy" declarations.
4985 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00004986 if (!BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004987 if (!BlockByCopyDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
4988 BlockByCopyDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
4989 BlockByCopyDecls.push_back(BlockDeclRefs[i]->getDecl());
4990 }
4991 }
4992 // Unique all "by ref" declarations.
4993 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00004994 if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004995 if (!BlockByRefDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
4996 BlockByRefDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
4997 BlockByRefDecls.push_back(BlockDeclRefs[i]->getDecl());
4998 }
4999 }
5000 // Find any imported blocks...they will need special attention.
5001 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00005002 if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005003 BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
5004 BlockDeclRefs[i]->getType()->isBlockPointerType())
5005 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
5006 }
5007}
5008
5009FunctionDecl *RewriteModernObjC::SynthBlockInitFunctionDecl(StringRef name) {
5010 IdentifierInfo *ID = &Context->Idents.get(name);
5011 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
5012 return FunctionDecl::Create(*Context, TUDecl, SourceLocation(),
5013 SourceLocation(), ID, FType, 0, SC_Extern,
5014 SC_None, false, false);
5015}
5016
5017Stmt *RewriteModernObjC::SynthBlockInitExpr(BlockExpr *Exp,
John McCallf4b88a42012-03-10 09:33:50 +00005018 const SmallVector<DeclRefExpr *, 8> &InnerBlockDeclRefs) {
Fariborz Jahaniand13c2c22012-03-22 19:54:39 +00005019
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005020 const BlockDecl *block = Exp->getBlockDecl();
Fariborz Jahaniand13c2c22012-03-22 19:54:39 +00005021
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005022 Blocks.push_back(Exp);
5023
5024 CollectBlockDeclRefInfo(Exp);
5025
5026 // Add inner imported variables now used in current block.
5027 int countOfInnerDecls = 0;
5028 if (!InnerBlockDeclRefs.empty()) {
5029 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++) {
John McCallf4b88a42012-03-10 09:33:50 +00005030 DeclRefExpr *Exp = InnerBlockDeclRefs[i];
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005031 ValueDecl *VD = Exp->getDecl();
John McCallf4b88a42012-03-10 09:33:50 +00005032 if (!VD->hasAttr<BlocksAttr>() && !BlockByCopyDeclsPtrSet.count(VD)) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005033 // We need to save the copied-in variables in nested
5034 // blocks because it is needed at the end for some of the API generations.
5035 // See SynthesizeBlockLiterals routine.
5036 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5037 BlockDeclRefs.push_back(Exp);
5038 BlockByCopyDeclsPtrSet.insert(VD);
5039 BlockByCopyDecls.push_back(VD);
5040 }
John McCallf4b88a42012-03-10 09:33:50 +00005041 if (VD->hasAttr<BlocksAttr>() && !BlockByRefDeclsPtrSet.count(VD)) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005042 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5043 BlockDeclRefs.push_back(Exp);
5044 BlockByRefDeclsPtrSet.insert(VD);
5045 BlockByRefDecls.push_back(VD);
5046 }
5047 }
5048 // Find any imported blocks...they will need special attention.
5049 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00005050 if (InnerBlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005051 InnerBlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
5052 InnerBlockDeclRefs[i]->getType()->isBlockPointerType())
5053 ImportedBlockDecls.insert(InnerBlockDeclRefs[i]->getDecl());
5054 }
5055 InnerDeclRefsCount.push_back(countOfInnerDecls);
5056
5057 std::string FuncName;
5058
5059 if (CurFunctionDef)
5060 FuncName = CurFunctionDef->getNameAsString();
5061 else if (CurMethodDef)
5062 BuildUniqueMethodName(FuncName, CurMethodDef);
5063 else if (GlobalVarDecl)
5064 FuncName = std::string(GlobalVarDecl->getNameAsString());
5065
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00005066 bool GlobalBlockExpr =
5067 block->getDeclContext()->getRedeclContext()->isFileContext();
5068
5069 if (GlobalBlockExpr && !GlobalVarDecl) {
5070 Diags.Report(block->getLocation(), GlobalBlockRewriteFailedDiag);
5071 GlobalBlockExpr = false;
5072 }
5073
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005074 std::string BlockNumber = utostr(Blocks.size()-1);
5075
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005076 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
5077
5078 // Get a pointer to the function type so we can cast appropriately.
5079 QualType BFT = convertFunctionTypeOfBlocks(Exp->getFunctionType());
5080 QualType FType = Context->getPointerType(BFT);
5081
5082 FunctionDecl *FD;
5083 Expr *NewRep;
5084
5085 // Simulate a contructor call...
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00005086 std::string Tag;
5087
5088 if (GlobalBlockExpr)
5089 Tag = "__global_";
5090 else
5091 Tag = "__";
5092 Tag += FuncName + "_block_impl_" + BlockNumber;
5093
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005094 FD = SynthBlockInitFunctionDecl(Tag);
John McCallf4b88a42012-03-10 09:33:50 +00005095 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, false, FType, VK_RValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005096 SourceLocation());
5097
5098 SmallVector<Expr*, 4> InitExprs;
5099
5100 // Initialize the block function.
5101 FD = SynthBlockInitFunctionDecl(Func);
John McCallf4b88a42012-03-10 09:33:50 +00005102 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, false, FD->getType(),
5103 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005104 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
5105 CK_BitCast, Arg);
5106 InitExprs.push_back(castExpr);
5107
5108 // Initialize the block descriptor.
5109 std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
5110
5111 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl,
5112 SourceLocation(), SourceLocation(),
5113 &Context->Idents.get(DescData.c_str()),
5114 Context->VoidPtrTy, 0,
5115 SC_Static, SC_None);
5116 UnaryOperator *DescRefExpr =
John McCallf4b88a42012-03-10 09:33:50 +00005117 new (Context) UnaryOperator(new (Context) DeclRefExpr(NewVD, false,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005118 Context->VoidPtrTy,
5119 VK_LValue,
5120 SourceLocation()),
5121 UO_AddrOf,
5122 Context->getPointerType(Context->VoidPtrTy),
5123 VK_RValue, OK_Ordinary,
5124 SourceLocation());
5125 InitExprs.push_back(DescRefExpr);
5126
5127 // Add initializers for any closure decl refs.
5128 if (BlockDeclRefs.size()) {
5129 Expr *Exp;
5130 // Output all "by copy" declarations.
5131 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
5132 E = BlockByCopyDecls.end(); I != E; ++I) {
5133 if (isObjCType((*I)->getType())) {
5134 // FIXME: Conform to ABI ([[obj retain] autorelease]).
5135 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00005136 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(),
5137 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005138 if (HasLocalVariableExternalStorage(*I)) {
5139 QualType QT = (*I)->getType();
5140 QT = Context->getPointerType(QT);
5141 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
5142 OK_Ordinary, SourceLocation());
5143 }
5144 } else if (isTopLevelBlockPointerType((*I)->getType())) {
5145 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00005146 Arg = new (Context) DeclRefExpr(FD, false, FD->getType(),
5147 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005148 Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
5149 CK_BitCast, Arg);
5150 } else {
5151 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00005152 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(),
5153 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005154 if (HasLocalVariableExternalStorage(*I)) {
5155 QualType QT = (*I)->getType();
5156 QT = Context->getPointerType(QT);
5157 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
5158 OK_Ordinary, SourceLocation());
5159 }
5160
5161 }
5162 InitExprs.push_back(Exp);
5163 }
5164 // Output all "by ref" declarations.
5165 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
5166 E = BlockByRefDecls.end(); I != E; ++I) {
5167 ValueDecl *ND = (*I);
5168 std::string Name(ND->getNameAsString());
5169 std::string RecName;
5170 RewriteByRefString(RecName, Name, ND, true);
5171 IdentifierInfo *II = &Context->Idents.get(RecName.c_str()
5172 + sizeof("struct"));
5173 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
5174 SourceLocation(), SourceLocation(),
5175 II);
5176 assert(RD && "SynthBlockInitExpr(): Can't find RecordDecl");
5177 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
5178
5179 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00005180 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(), VK_LValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005181 SourceLocation());
5182 bool isNestedCapturedVar = false;
5183 if (block)
5184 for (BlockDecl::capture_const_iterator ci = block->capture_begin(),
5185 ce = block->capture_end(); ci != ce; ++ci) {
5186 const VarDecl *variable = ci->getVariable();
5187 if (variable == ND && ci->isNested()) {
5188 assert (ci->isByRef() &&
5189 "SynthBlockInitExpr - captured block variable is not byref");
5190 isNestedCapturedVar = true;
5191 break;
5192 }
5193 }
5194 // captured nested byref variable has its address passed. Do not take
5195 // its address again.
5196 if (!isNestedCapturedVar)
5197 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf,
5198 Context->getPointerType(Exp->getType()),
5199 VK_RValue, OK_Ordinary, SourceLocation());
5200 Exp = NoTypeInfoCStyleCastExpr(Context, castT, CK_BitCast, Exp);
5201 InitExprs.push_back(Exp);
5202 }
5203 }
5204 if (ImportedBlockDecls.size()) {
5205 // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
5206 int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
5207 unsigned IntSize =
5208 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
5209 Expr *FlagExp = IntegerLiteral::Create(*Context, llvm::APInt(IntSize, flag),
5210 Context->IntTy, SourceLocation());
5211 InitExprs.push_back(FlagExp);
5212 }
5213 NewRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0], InitExprs.size(),
5214 FType, VK_LValue, SourceLocation());
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00005215
5216 if (GlobalBlockExpr) {
5217 assert (GlobalConstructionExp == 0 &&
5218 "SynthBlockInitExpr - GlobalConstructionExp must be null");
5219 GlobalConstructionExp = NewRep;
5220 NewRep = DRE;
5221 }
5222
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005223 NewRep = new (Context) UnaryOperator(NewRep, UO_AddrOf,
5224 Context->getPointerType(NewRep->getType()),
5225 VK_RValue, OK_Ordinary, SourceLocation());
5226 NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CK_BitCast,
5227 NewRep);
5228 BlockDeclRefs.clear();
5229 BlockByRefDecls.clear();
5230 BlockByRefDeclsPtrSet.clear();
5231 BlockByCopyDecls.clear();
5232 BlockByCopyDeclsPtrSet.clear();
5233 ImportedBlockDecls.clear();
5234 return NewRep;
5235}
5236
5237bool RewriteModernObjC::IsDeclStmtInForeachHeader(DeclStmt *DS) {
5238 if (const ObjCForCollectionStmt * CS =
5239 dyn_cast<ObjCForCollectionStmt>(Stmts.back()))
5240 return CS->getElement() == DS;
5241 return false;
5242}
5243
5244//===----------------------------------------------------------------------===//
5245// Function Body / Expression rewriting
5246//===----------------------------------------------------------------------===//
5247
5248Stmt *RewriteModernObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
5249 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
5250 isa<DoStmt>(S) || isa<ForStmt>(S))
5251 Stmts.push_back(S);
5252 else if (isa<ObjCForCollectionStmt>(S)) {
5253 Stmts.push_back(S);
5254 ObjCBcLabelNo.push_back(++BcLabelCount);
5255 }
5256
5257 // Pseudo-object operations and ivar references need special
5258 // treatment because we're going to recursively rewrite them.
5259 if (PseudoObjectExpr *PseudoOp = dyn_cast<PseudoObjectExpr>(S)) {
5260 if (isa<BinaryOperator>(PseudoOp->getSyntacticForm())) {
5261 return RewritePropertyOrImplicitSetter(PseudoOp);
5262 } else {
5263 return RewritePropertyOrImplicitGetter(PseudoOp);
5264 }
5265 } else if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
5266 return RewriteObjCIvarRefExpr(IvarRefExpr);
5267 }
5268
5269 SourceRange OrigStmtRange = S->getSourceRange();
5270
5271 // Perform a bottom up rewrite of all children.
5272 for (Stmt::child_range CI = S->children(); CI; ++CI)
5273 if (*CI) {
5274 Stmt *childStmt = (*CI);
5275 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(childStmt);
5276 if (newStmt) {
5277 *CI = newStmt;
5278 }
5279 }
5280
5281 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
John McCallf4b88a42012-03-10 09:33:50 +00005282 SmallVector<DeclRefExpr *, 8> InnerBlockDeclRefs;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005283 llvm::SmallPtrSet<const DeclContext *, 8> InnerContexts;
5284 InnerContexts.insert(BE->getBlockDecl());
5285 ImportedLocalExternalDecls.clear();
5286 GetInnerBlockDeclRefExprs(BE->getBody(),
5287 InnerBlockDeclRefs, InnerContexts);
5288 // Rewrite the block body in place.
5289 Stmt *SaveCurrentBody = CurrentBody;
5290 CurrentBody = BE->getBody();
5291 PropParentMap = 0;
5292 // block literal on rhs of a property-dot-sytax assignment
5293 // must be replaced by its synthesize ast so getRewrittenText
5294 // works as expected. In this case, what actually ends up on RHS
5295 // is the blockTranscribed which is the helper function for the
5296 // block literal; as in: self.c = ^() {[ace ARR];};
5297 bool saveDisableReplaceStmt = DisableReplaceStmt;
5298 DisableReplaceStmt = false;
5299 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
5300 DisableReplaceStmt = saveDisableReplaceStmt;
5301 CurrentBody = SaveCurrentBody;
5302 PropParentMap = 0;
5303 ImportedLocalExternalDecls.clear();
5304 // Now we snarf the rewritten text and stash it away for later use.
5305 std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
5306 RewrittenBlockExprs[BE] = Str;
5307
5308 Stmt *blockTranscribed = SynthBlockInitExpr(BE, InnerBlockDeclRefs);
5309
5310 //blockTranscribed->dump();
5311 ReplaceStmt(S, blockTranscribed);
5312 return blockTranscribed;
5313 }
5314 // Handle specific things.
5315 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
5316 return RewriteAtEncode(AtEncode);
5317
5318 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
5319 return RewriteAtSelector(AtSelector);
5320
5321 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
5322 return RewriteObjCStringLiteral(AtString);
Fariborz Jahanian55947042012-03-27 20:17:30 +00005323
5324 if (ObjCBoolLiteralExpr *BoolLitExpr = dyn_cast<ObjCBoolLiteralExpr>(S))
5325 return RewriteObjCBoolLiteralExpr(BoolLitExpr);
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00005326
Patrick Beardeb382ec2012-04-19 00:25:12 +00005327 if (ObjCBoxedExpr *BoxedExpr = dyn_cast<ObjCBoxedExpr>(S))
5328 return RewriteObjCBoxedExpr(BoxedExpr);
Fariborz Jahanian86cff602012-03-30 23:35:47 +00005329
5330 if (ObjCArrayLiteral *ArrayLitExpr = dyn_cast<ObjCArrayLiteral>(S))
5331 return RewriteObjCArrayLiteralExpr(ArrayLitExpr);
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00005332
5333 if (ObjCDictionaryLiteral *DictionaryLitExpr =
5334 dyn_cast<ObjCDictionaryLiteral>(S))
5335 return RewriteObjCDictionaryLiteralExpr(DictionaryLitExpr);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005336
5337 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
5338#if 0
5339 // Before we rewrite it, put the original message expression in a comment.
5340 SourceLocation startLoc = MessExpr->getLocStart();
5341 SourceLocation endLoc = MessExpr->getLocEnd();
5342
5343 const char *startBuf = SM->getCharacterData(startLoc);
5344 const char *endBuf = SM->getCharacterData(endLoc);
5345
5346 std::string messString;
5347 messString += "// ";
5348 messString.append(startBuf, endBuf-startBuf+1);
5349 messString += "\n";
5350
5351 // FIXME: Missing definition of
5352 // InsertText(clang::SourceLocation, char const*, unsigned int).
5353 // InsertText(startLoc, messString.c_str(), messString.size());
5354 // Tried this, but it didn't work either...
5355 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
5356#endif
5357 return RewriteMessageExpr(MessExpr);
5358 }
5359
5360 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
5361 return RewriteObjCTryStmt(StmtTry);
5362
5363 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
5364 return RewriteObjCSynchronizedStmt(StmtTry);
5365
5366 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
5367 return RewriteObjCThrowStmt(StmtThrow);
5368
5369 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
5370 return RewriteObjCProtocolExpr(ProtocolExp);
5371
5372 if (ObjCForCollectionStmt *StmtForCollection =
5373 dyn_cast<ObjCForCollectionStmt>(S))
5374 return RewriteObjCForCollectionStmt(StmtForCollection,
5375 OrigStmtRange.getEnd());
5376 if (BreakStmt *StmtBreakStmt =
5377 dyn_cast<BreakStmt>(S))
5378 return RewriteBreakStmt(StmtBreakStmt);
5379 if (ContinueStmt *StmtContinueStmt =
5380 dyn_cast<ContinueStmt>(S))
5381 return RewriteContinueStmt(StmtContinueStmt);
5382
5383 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
5384 // and cast exprs.
5385 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
5386 // FIXME: What we're doing here is modifying the type-specifier that
5387 // precedes the first Decl. In the future the DeclGroup should have
5388 // a separate type-specifier that we can rewrite.
5389 // NOTE: We need to avoid rewriting the DeclStmt if it is within
5390 // the context of an ObjCForCollectionStmt. For example:
5391 // NSArray *someArray;
5392 // for (id <FooProtocol> index in someArray) ;
5393 // This is because RewriteObjCForCollectionStmt() does textual rewriting
5394 // and it depends on the original text locations/positions.
5395 if (Stmts.empty() || !IsDeclStmtInForeachHeader(DS))
5396 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
5397
5398 // Blocks rewrite rules.
5399 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
5400 DI != DE; ++DI) {
5401 Decl *SD = *DI;
5402 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
5403 if (isTopLevelBlockPointerType(ND->getType()))
5404 RewriteBlockPointerDecl(ND);
5405 else if (ND->getType()->isFunctionPointerType())
5406 CheckFunctionPointerDecl(ND->getType(), ND);
5407 if (VarDecl *VD = dyn_cast<VarDecl>(SD)) {
5408 if (VD->hasAttr<BlocksAttr>()) {
5409 static unsigned uniqueByrefDeclCount = 0;
5410 assert(!BlockByRefDeclNo.count(ND) &&
5411 "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl");
5412 BlockByRefDeclNo[ND] = uniqueByrefDeclCount++;
Fariborz Jahanian4fe261c2012-04-24 19:38:45 +00005413 RewriteByRefVar(VD, (DI == DS->decl_begin()), ((DI+1) == DE));
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005414 }
5415 else
5416 RewriteTypeOfDecl(VD);
5417 }
5418 }
5419 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(SD)) {
5420 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
5421 RewriteBlockPointerDecl(TD);
5422 else if (TD->getUnderlyingType()->isFunctionPointerType())
5423 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5424 }
5425 }
5426 }
5427
5428 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
5429 RewriteObjCQualifiedInterfaceTypes(CE);
5430
5431 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
5432 isa<DoStmt>(S) || isa<ForStmt>(S)) {
5433 assert(!Stmts.empty() && "Statement stack is empty");
5434 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
5435 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
5436 && "Statement stack mismatch");
5437 Stmts.pop_back();
5438 }
5439 // Handle blocks rewriting.
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005440 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
5441 ValueDecl *VD = DRE->getDecl();
5442 if (VD->hasAttr<BlocksAttr>())
5443 return RewriteBlockDeclRefExpr(DRE);
5444 if (HasLocalVariableExternalStorage(VD))
5445 return RewriteLocalVariableExternalStorage(DRE);
5446 }
5447
5448 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
5449 if (CE->getCallee()->getType()->isBlockPointerType()) {
5450 Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
5451 ReplaceStmt(S, BlockCall);
5452 return BlockCall;
5453 }
5454 }
5455 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
5456 RewriteCastExpr(CE);
5457 }
Fariborz Jahanianf1ee6872012-04-10 00:08:18 +00005458 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
5459 RewriteImplicitCastObjCExpr(ICE);
5460 }
Fariborz Jahanian43aa1c32012-04-16 22:14:01 +00005461#if 0
Fariborz Jahanian653b7cf2012-04-13 18:00:54 +00005462
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005463 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
5464 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(),
5465 ICE->getSubExpr(),
5466 SourceLocation());
5467 // Get the new text.
5468 std::string SStr;
5469 llvm::raw_string_ostream Buf(SStr);
5470 Replacement->printPretty(Buf, *Context);
5471 const std::string &Str = Buf.str();
5472
5473 printf("CAST = %s\n", &Str[0]);
5474 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
5475 delete S;
5476 return Replacement;
5477 }
5478#endif
5479 // Return this stmt unmodified.
5480 return S;
5481}
5482
5483void RewriteModernObjC::RewriteRecordBody(RecordDecl *RD) {
5484 for (RecordDecl::field_iterator i = RD->field_begin(),
5485 e = RD->field_end(); i != e; ++i) {
David Blaikie262bc182012-04-30 02:36:29 +00005486 FieldDecl *FD = &*i;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005487 if (isTopLevelBlockPointerType(FD->getType()))
5488 RewriteBlockPointerDecl(FD);
5489 if (FD->getType()->isObjCQualifiedIdType() ||
5490 FD->getType()->isObjCQualifiedInterfaceType())
5491 RewriteObjCQualifiedInterfaceTypes(FD);
5492 }
5493}
5494
5495/// HandleDeclInMainFile - This is called for each top-level decl defined in the
5496/// main file of the input.
5497void RewriteModernObjC::HandleDeclInMainFile(Decl *D) {
5498 switch (D->getKind()) {
5499 case Decl::Function: {
5500 FunctionDecl *FD = cast<FunctionDecl>(D);
5501 if (FD->isOverloadedOperator())
5502 return;
5503
5504 // Since function prototypes don't have ParmDecl's, we check the function
5505 // prototype. This enables us to rewrite function declarations and
5506 // definitions using the same code.
5507 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
5508
Argyrios Kyrtzidis9335df32012-02-12 04:48:45 +00005509 if (!FD->isThisDeclarationADefinition())
5510 break;
5511
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005512 // FIXME: If this should support Obj-C++, support CXXTryStmt
5513 if (CompoundStmt *Body = dyn_cast_or_null<CompoundStmt>(FD->getBody())) {
5514 CurFunctionDef = FD;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005515 CurrentBody = Body;
5516 Body =
5517 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5518 FD->setBody(Body);
5519 CurrentBody = 0;
5520 if (PropParentMap) {
5521 delete PropParentMap;
5522 PropParentMap = 0;
5523 }
5524 // This synthesizes and inserts the block "impl" struct, invoke function,
5525 // and any copy/dispose helper functions.
5526 InsertBlockLiteralsWithinFunction(FD);
5527 CurFunctionDef = 0;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005528 }
5529 break;
5530 }
5531 case Decl::ObjCMethod: {
5532 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(D);
5533 if (CompoundStmt *Body = MD->getCompoundBody()) {
5534 CurMethodDef = MD;
5535 CurrentBody = Body;
5536 Body =
5537 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5538 MD->setBody(Body);
5539 CurrentBody = 0;
5540 if (PropParentMap) {
5541 delete PropParentMap;
5542 PropParentMap = 0;
5543 }
5544 InsertBlockLiteralsWithinMethod(MD);
5545 CurMethodDef = 0;
5546 }
5547 break;
5548 }
5549 case Decl::ObjCImplementation: {
5550 ObjCImplementationDecl *CI = cast<ObjCImplementationDecl>(D);
5551 ClassImplementation.push_back(CI);
5552 break;
5553 }
5554 case Decl::ObjCCategoryImpl: {
5555 ObjCCategoryImplDecl *CI = cast<ObjCCategoryImplDecl>(D);
5556 CategoryImplementation.push_back(CI);
5557 break;
5558 }
5559 case Decl::Var: {
5560 VarDecl *VD = cast<VarDecl>(D);
5561 RewriteObjCQualifiedInterfaceTypes(VD);
5562 if (isTopLevelBlockPointerType(VD->getType()))
5563 RewriteBlockPointerDecl(VD);
5564 else if (VD->getType()->isFunctionPointerType()) {
5565 CheckFunctionPointerDecl(VD->getType(), VD);
5566 if (VD->getInit()) {
5567 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
5568 RewriteCastExpr(CE);
5569 }
5570 }
5571 } else if (VD->getType()->isRecordType()) {
5572 RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
5573 if (RD->isCompleteDefinition())
5574 RewriteRecordBody(RD);
5575 }
5576 if (VD->getInit()) {
5577 GlobalVarDecl = VD;
5578 CurrentBody = VD->getInit();
5579 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
5580 CurrentBody = 0;
5581 if (PropParentMap) {
5582 delete PropParentMap;
5583 PropParentMap = 0;
5584 }
5585 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(), VD->getName());
5586 GlobalVarDecl = 0;
5587
5588 // This is needed for blocks.
5589 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
5590 RewriteCastExpr(CE);
5591 }
5592 }
5593 break;
5594 }
5595 case Decl::TypeAlias:
5596 case Decl::Typedef: {
5597 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
5598 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
5599 RewriteBlockPointerDecl(TD);
5600 else if (TD->getUnderlyingType()->isFunctionPointerType())
5601 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5602 }
5603 break;
5604 }
5605 case Decl::CXXRecord:
5606 case Decl::Record: {
5607 RecordDecl *RD = cast<RecordDecl>(D);
5608 if (RD->isCompleteDefinition())
5609 RewriteRecordBody(RD);
5610 break;
5611 }
5612 default:
5613 break;
5614 }
5615 // Nothing yet.
5616}
5617
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00005618/// Write_ProtocolExprReferencedMetadata - This routine writer out the
5619/// protocol reference symbols in the for of:
5620/// struct _protocol_t *PROTOCOL_REF = &PROTOCOL_METADATA.
5621static void Write_ProtocolExprReferencedMetadata(ASTContext *Context,
5622 ObjCProtocolDecl *PDecl,
5623 std::string &Result) {
5624 // Also output .objc_protorefs$B section and its meta-data.
5625 if (Context->getLangOpts().MicrosoftExt)
Fariborz Jahanianbd78cfa2012-04-27 21:39:49 +00005626 Result += "static ";
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00005627 Result += "struct _protocol_t *";
5628 Result += "_OBJC_PROTOCOL_REFERENCE_$_";
5629 Result += PDecl->getNameAsString();
5630 Result += " = &";
5631 Result += "_OBJC_PROTOCOL_"; Result += PDecl->getNameAsString();
5632 Result += ";\n";
5633}
5634
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005635void RewriteModernObjC::HandleTranslationUnit(ASTContext &C) {
5636 if (Diags.hasErrorOccurred())
5637 return;
5638
5639 RewriteInclude();
5640
5641 // Here's a great place to add any extra declarations that may be needed.
5642 // Write out meta data for each @protocol(<expr>).
5643 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00005644 E = ProtocolExprDecls.end(); I != E; ++I) {
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00005645 RewriteObjCProtocolMetaData(*I, Preamble);
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00005646 Write_ProtocolExprReferencedMetadata(Context, (*I), Preamble);
5647 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005648
5649 InsertText(SM->getLocForStartOfFile(MainFileID), Preamble, false);
Fariborz Jahanian57317782012-02-21 23:58:41 +00005650 for (unsigned i = 0, e = ObjCInterfacesSeen.size(); i < e; i++) {
5651 ObjCInterfaceDecl *CDecl = ObjCInterfacesSeen[i];
5652 // Write struct declaration for the class matching its ivar declarations.
5653 // Note that for modern abi, this is postponed until the end of TU
5654 // because class extensions and the implementation might declare their own
5655 // private ivars.
5656 RewriteInterfaceDecl(CDecl);
5657 }
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00005658
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005659 if (ClassImplementation.size() || CategoryImplementation.size())
5660 RewriteImplementations();
5661
5662 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
5663 // we are done.
5664 if (const RewriteBuffer *RewriteBuf =
5665 Rewrite.getRewriteBufferFor(MainFileID)) {
5666 //printf("Changed:\n");
5667 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
5668 } else {
5669 llvm::errs() << "No changes\n";
5670 }
5671
5672 if (ClassImplementation.size() || CategoryImplementation.size() ||
5673 ProtocolExprDecls.size()) {
5674 // Rewrite Objective-c meta data*
5675 std::string ResultStr;
5676 RewriteMetaDataIntoBuffer(ResultStr);
5677 // Emit metadata.
5678 *OutFile << ResultStr;
5679 }
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005680 // Emit ImageInfo;
5681 {
5682 std::string ResultStr;
5683 WriteImageInfo(ResultStr);
5684 *OutFile << ResultStr;
5685 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005686 OutFile->flush();
5687}
5688
5689void RewriteModernObjC::Initialize(ASTContext &context) {
5690 InitializeCommon(context);
5691
Fariborz Jahanian6991bc52012-03-10 17:45:38 +00005692 Preamble += "#ifndef __OBJC2__\n";
5693 Preamble += "#define __OBJC2__\n";
5694 Preamble += "#endif\n";
5695
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005696 // declaring objc_selector outside the parameter list removes a silly
5697 // scope related warning...
5698 if (IsHeader)
5699 Preamble = "#pragma once\n";
5700 Preamble += "struct objc_selector; struct objc_class;\n";
Fariborz Jahaniane2d87bc2012-04-12 23:52:52 +00005701 Preamble += "struct __rw_objc_super { \n\tstruct objc_object *object; ";
5702 Preamble += "\n\tstruct objc_object *superClass; ";
5703 // Add a constructor for creating temporary objects.
5704 Preamble += "\n\t__rw_objc_super(struct objc_object *o, struct objc_object *s) ";
5705 Preamble += ": object(o), superClass(s) {} ";
5706 Preamble += "\n};\n";
5707
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005708 if (LangOpts.MicrosoftExt) {
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00005709 // Define all sections using syntax that makes sense.
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005710 // These are currently generated.
5711 Preamble += "\n#pragma section(\".objc_classlist$B\", long, read, write)\n";
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00005712 Preamble += "#pragma section(\".objc_catlist$B\", long, read, write)\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005713 Preamble += "#pragma section(\".objc_imageinfo$B\", long, read, write)\n";
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00005714 Preamble += "#pragma section(\".objc_nlclslist$B\", long, read, write)\n";
5715 Preamble += "#pragma section(\".objc_nlcatlist$B\", long, read, write)\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005716 // These are generated but not necessary for functionality.
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005717 Preamble += "#pragma section(\".cat_cls_meth$B\", long, read, write)\n";
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00005718 Preamble += "#pragma section(\".inst_meth$B\", long, read, write)\n";
5719 Preamble += "#pragma section(\".cls_meth$B\", long, read, write)\n";
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00005720 Preamble += "#pragma section(\".objc_ivar$B\", long, read, write)\n";
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00005721
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00005722 // These need be generated for performance. Currently they are not,
5723 // using API calls instead.
5724 Preamble += "#pragma section(\".objc_selrefs$B\", long, read, write)\n";
5725 Preamble += "#pragma section(\".objc_classrefs$B\", long, read, write)\n";
5726 Preamble += "#pragma section(\".objc_superrefs$B\", long, read, write)\n";
5727
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005728 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005729 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
5730 Preamble += "typedef struct objc_object Protocol;\n";
5731 Preamble += "#define _REWRITER_typedef_Protocol\n";
5732 Preamble += "#endif\n";
5733 if (LangOpts.MicrosoftExt) {
5734 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
5735 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
Fariborz Jahanian5cf6b6c2012-03-21 23:41:04 +00005736 }
5737 else
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005738 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
Fariborz Jahanian5cf6b6c2012-03-21 23:41:04 +00005739
5740 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend(void);\n";
5741 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSendSuper(void);\n";
5742 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend_stret(void);\n";
5743 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSendSuper_stret(void);\n";
5744 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend_fpret(void);\n";
5745
Fariborz Jahanian502261a2012-05-03 20:23:37 +00005746 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *objc_getClass";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005747 Preamble += "(const char *);\n";
5748 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *class_getSuperclass";
5749 Preamble += "(struct objc_class *);\n";
Fariborz Jahanian502261a2012-05-03 20:23:37 +00005750 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *objc_getMetaClass";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005751 Preamble += "(const char *);\n";
Fariborz Jahanian55261af2012-03-19 18:11:32 +00005752 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw( struct objc_object *);\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005753 // @synchronized hooks.
Fariborz Jahanian55261af2012-03-19 18:11:32 +00005754 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_enter( struct objc_object *);\n";
5755 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_exit( struct objc_object *);\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005756 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
5757 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
5758 Preamble += "struct __objcFastEnumerationState {\n\t";
5759 Preamble += "unsigned long state;\n\t";
5760 Preamble += "void **itemsPtr;\n\t";
5761 Preamble += "unsigned long *mutationsPtr;\n\t";
5762 Preamble += "unsigned long extra[5];\n};\n";
5763 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
5764 Preamble += "#define __FASTENUMERATIONSTATE\n";
5765 Preamble += "#endif\n";
5766 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
5767 Preamble += "struct __NSConstantStringImpl {\n";
5768 Preamble += " int *isa;\n";
5769 Preamble += " int flags;\n";
5770 Preamble += " char *str;\n";
5771 Preamble += " long length;\n";
5772 Preamble += "};\n";
5773 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
5774 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
5775 Preamble += "#else\n";
5776 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
5777 Preamble += "#endif\n";
5778 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
5779 Preamble += "#endif\n";
5780 // Blocks preamble.
5781 Preamble += "#ifndef BLOCK_IMPL\n";
5782 Preamble += "#define BLOCK_IMPL\n";
5783 Preamble += "struct __block_impl {\n";
5784 Preamble += " void *isa;\n";
5785 Preamble += " int Flags;\n";
5786 Preamble += " int Reserved;\n";
5787 Preamble += " void *FuncPtr;\n";
5788 Preamble += "};\n";
5789 Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
5790 Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n";
5791 Preamble += "extern \"C\" __declspec(dllexport) "
5792 "void _Block_object_assign(void *, const void *, const int);\n";
5793 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
5794 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
5795 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
5796 Preamble += "#else\n";
5797 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n";
5798 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n";
5799 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
5800 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
5801 Preamble += "#endif\n";
5802 Preamble += "#endif\n";
5803 if (LangOpts.MicrosoftExt) {
5804 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
5805 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
5806 Preamble += "#ifndef KEEP_ATTRIBUTES\n"; // We use this for clang tests.
5807 Preamble += "#define __attribute__(X)\n";
5808 Preamble += "#endif\n";
Fariborz Jahanian5ce28272012-04-12 16:33:31 +00005809 Preamble += "#ifndef __weak\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005810 Preamble += "#define __weak\n";
Fariborz Jahanian5ce28272012-04-12 16:33:31 +00005811 Preamble += "#endif\n";
5812 Preamble += "#ifndef __block\n";
5813 Preamble += "#define __block\n";
5814 Preamble += "#endif\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005815 }
5816 else {
5817 Preamble += "#define __block\n";
5818 Preamble += "#define __weak\n";
5819 }
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00005820
5821 // Declarations required for modern objective-c array and dictionary literals.
5822 Preamble += "\n#include <stdarg.h>\n";
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00005823 Preamble += "struct __NSContainer_literal {\n";
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00005824 Preamble += " void * *arr;\n";
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00005825 Preamble += " __NSContainer_literal (unsigned int count, ...) {\n";
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00005826 Preamble += "\tva_list marker;\n";
5827 Preamble += "\tva_start(marker, count);\n";
5828 Preamble += "\tarr = new void *[count];\n";
5829 Preamble += "\tfor (unsigned i = 0; i < count; i++)\n";
5830 Preamble += "\t arr[i] = va_arg(marker, void *);\n";
5831 Preamble += "\tva_end( marker );\n";
5832 Preamble += " };\n";
Fariborz Jahanian13a9c022012-05-02 23:53:46 +00005833 Preamble += " ~__NSContainer_literal() {\n";
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00005834 Preamble += "\tdelete[] arr;\n";
5835 Preamble += " }\n";
5836 Preamble += "};\n";
5837
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005838 // NOTE! Windows uses LLP64 for 64bit mode. So, cast pointer to long long
5839 // as this avoids warning in any 64bit/32bit compilation model.
5840 Preamble += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long long) &((TYPE *)0)->MEMBER)\n";
5841}
5842
5843/// RewriteIvarOffsetComputation - This rutine synthesizes computation of
5844/// ivar offset.
5845void RewriteModernObjC::RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
5846 std::string &Result) {
5847 if (ivar->isBitField()) {
5848 // FIXME: The hack below doesn't work for bitfields. For now, we simply
5849 // place all bitfields at offset 0.
5850 Result += "0";
5851 } else {
5852 Result += "__OFFSETOFIVAR__(struct ";
5853 Result += ivar->getContainingInterface()->getNameAsString();
5854 if (LangOpts.MicrosoftExt)
5855 Result += "_IMPL";
5856 Result += ", ";
5857 Result += ivar->getNameAsString();
5858 Result += ")";
5859 }
5860}
5861
5862/// WriteModernMetadataDeclarations - Writes out metadata declarations for modern ABI.
5863/// struct _prop_t {
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00005864/// const char *name;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005865/// char *attributes;
5866/// }
5867
5868/// struct _prop_list_t {
5869/// uint32_t entsize; // sizeof(struct _prop_t)
5870/// uint32_t count_of_properties;
5871/// struct _prop_t prop_list[count_of_properties];
5872/// }
5873
5874/// struct _protocol_t;
5875
5876/// struct _protocol_list_t {
5877/// long protocol_count; // Note, this is 32/64 bit
5878/// struct _protocol_t * protocol_list[protocol_count];
5879/// }
5880
5881/// struct _objc_method {
5882/// SEL _cmd;
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005883/// const char *method_type;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005884/// char *_imp;
5885/// }
5886
5887/// struct _method_list_t {
5888/// uint32_t entsize; // sizeof(struct _objc_method)
5889/// uint32_t method_count;
5890/// struct _objc_method method_list[method_count];
5891/// }
5892
5893/// struct _protocol_t {
5894/// id isa; // NULL
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005895/// const char *protocol_name;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005896/// const struct _protocol_list_t * protocol_list; // super protocols
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005897/// const struct method_list_t *instance_methods;
5898/// const struct method_list_t *class_methods;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005899/// const struct method_list_t *optionalInstanceMethods;
5900/// const struct method_list_t *optionalClassMethods;
5901/// const struct _prop_list_t * properties;
5902/// const uint32_t size; // sizeof(struct _protocol_t)
5903/// const uint32_t flags; // = 0
5904/// const char ** extendedMethodTypes;
5905/// }
5906
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005907/// struct _ivar_t {
5908/// unsigned long int *offset; // pointer to ivar offset location
Fariborz Jahanianae932952012-02-10 20:47:10 +00005909/// const char *name;
5910/// const char *type;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005911/// uint32_t alignment;
5912/// uint32_t size;
5913/// }
5914
5915/// struct _ivar_list_t {
5916/// uint32 entsize; // sizeof(struct _ivar_t)
5917/// uint32 count;
Fariborz Jahanianae932952012-02-10 20:47:10 +00005918/// struct _ivar_t list[count];
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005919/// }
5920
5921/// struct _class_ro_t {
Fariborz Jahanian249cd102012-03-24 16:53:16 +00005922/// uint32_t flags;
5923/// uint32_t instanceStart;
5924/// uint32_t instanceSize;
5925/// uint32_t reserved; // only when building for 64bit targets
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005926/// const uint8_t *ivarLayout;
5927/// const char *name;
5928/// const struct _method_list_t *baseMethods;
5929/// const struct _protocol_list_t *baseProtocols;
5930/// const struct _ivar_list_t *ivars;
5931/// const uint8_t *weakIvarLayout;
5932/// const struct _prop_list_t *properties;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005933/// }
5934
5935/// struct _class_t {
5936/// struct _class_t *isa;
Fariborz Jahanianfd4ce2c2012-03-20 17:34:50 +00005937/// struct _class_t *superclass;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005938/// void *cache;
5939/// IMP *vtable;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005940/// struct _class_ro_t *ro;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005941/// }
5942
5943/// struct _category_t {
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005944/// const char *name;
Fariborz Jahanian4b2fe6e2012-03-20 21:41:28 +00005945/// struct _class_t *cls;
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005946/// const struct _method_list_t *instance_methods;
5947/// const struct _method_list_t *class_methods;
5948/// const struct _protocol_list_t *protocols;
5949/// const struct _prop_list_t *properties;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005950/// }
5951
5952/// MessageRefTy - LLVM for:
5953/// struct _message_ref_t {
5954/// IMP messenger;
5955/// SEL name;
5956/// };
5957
5958/// SuperMessageRefTy - LLVM for:
5959/// struct _super_message_ref_t {
5960/// SUPER_IMP messenger;
5961/// SEL name;
5962/// };
5963
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00005964static void WriteModernMetadataDeclarations(ASTContext *Context, std::string &Result) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005965 static bool meta_data_declared = false;
5966 if (meta_data_declared)
5967 return;
5968
5969 Result += "\nstruct _prop_t {\n";
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00005970 Result += "\tconst char *name;\n";
5971 Result += "\tconst char *attributes;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005972 Result += "};\n";
5973
5974 Result += "\nstruct _protocol_t;\n";
5975
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005976 Result += "\nstruct _objc_method {\n";
5977 Result += "\tstruct objc_selector * _cmd;\n";
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005978 Result += "\tconst char *method_type;\n";
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005979 Result += "\tvoid *_imp;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005980 Result += "};\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005981
5982 Result += "\nstruct _protocol_t {\n";
5983 Result += "\tvoid * isa; // NULL\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005984 Result += "\tconst char *protocol_name;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005985 Result += "\tconst struct _protocol_list_t * protocol_list; // super protocols\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005986 Result += "\tconst struct method_list_t *instance_methods;\n";
5987 Result += "\tconst struct method_list_t *class_methods;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005988 Result += "\tconst struct method_list_t *optionalInstanceMethods;\n";
5989 Result += "\tconst struct method_list_t *optionalClassMethods;\n";
5990 Result += "\tconst struct _prop_list_t * properties;\n";
5991 Result += "\tconst unsigned int size; // sizeof(struct _protocol_t)\n";
5992 Result += "\tconst unsigned int flags; // = 0\n";
5993 Result += "\tconst char ** extendedMethodTypes;\n";
5994 Result += "};\n";
5995
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005996 Result += "\nstruct _ivar_t {\n";
5997 Result += "\tunsigned long int *offset; // pointer to ivar offset location\n";
Fariborz Jahanianae932952012-02-10 20:47:10 +00005998 Result += "\tconst char *name;\n";
5999 Result += "\tconst char *type;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006000 Result += "\tunsigned int alignment;\n";
6001 Result += "\tunsigned int size;\n";
6002 Result += "};\n";
6003
6004 Result += "\nstruct _class_ro_t {\n";
Fariborz Jahanian249cd102012-03-24 16:53:16 +00006005 Result += "\tunsigned int flags;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006006 Result += "\tunsigned int instanceStart;\n";
Fariborz Jahanian249cd102012-03-24 16:53:16 +00006007 Result += "\tunsigned int instanceSize;\n";
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00006008 const llvm::Triple &Triple(Context->getTargetInfo().getTriple());
6009 if (Triple.getArch() == llvm::Triple::x86_64)
Fariborz Jahanian249cd102012-03-24 16:53:16 +00006010 Result += "\tunsigned int reserved;\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006011 Result += "\tconst unsigned char *ivarLayout;\n";
6012 Result += "\tconst char *name;\n";
6013 Result += "\tconst struct _method_list_t *baseMethods;\n";
6014 Result += "\tconst struct _objc_protocol_list *baseProtocols;\n";
6015 Result += "\tconst struct _ivar_list_t *ivars;\n";
6016 Result += "\tconst unsigned char *weakIvarLayout;\n";
6017 Result += "\tconst struct _prop_list_t *properties;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006018 Result += "};\n";
6019
6020 Result += "\nstruct _class_t {\n";
6021 Result += "\tstruct _class_t *isa;\n";
Fariborz Jahanianfd4ce2c2012-03-20 17:34:50 +00006022 Result += "\tstruct _class_t *superclass;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006023 Result += "\tvoid *cache;\n";
6024 Result += "\tvoid *vtable;\n";
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006025 Result += "\tstruct _class_ro_t *ro;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006026 Result += "};\n";
6027
6028 Result += "\nstruct _category_t {\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006029 Result += "\tconst char *name;\n";
Fariborz Jahanian4b2fe6e2012-03-20 21:41:28 +00006030 Result += "\tstruct _class_t *cls;\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006031 Result += "\tconst struct _method_list_t *instance_methods;\n";
6032 Result += "\tconst struct _method_list_t *class_methods;\n";
6033 Result += "\tconst struct _protocol_list_t *protocols;\n";
6034 Result += "\tconst struct _prop_list_t *properties;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006035 Result += "};\n";
6036
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006037 Result += "extern \"C\" __declspec(dllimport) struct objc_cache _objc_empty_cache;\n";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006038 Result += "#pragma warning(disable:4273)\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006039 meta_data_declared = true;
6040}
6041
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006042static void Write_protocol_list_t_TypeDecl(std::string &Result,
6043 long super_protocol_count) {
6044 Result += "struct /*_protocol_list_t*/"; Result += " {\n";
6045 Result += "\tlong protocol_count; // Note, this is 32/64 bit\n";
6046 Result += "\tstruct _protocol_t *super_protocols[";
6047 Result += utostr(super_protocol_count); Result += "];\n";
6048 Result += "}";
6049}
6050
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006051static void Write_method_list_t_TypeDecl(std::string &Result,
6052 unsigned int method_count) {
6053 Result += "struct /*_method_list_t*/"; Result += " {\n";
6054 Result += "\tunsigned int entsize; // sizeof(struct _objc_method)\n";
6055 Result += "\tunsigned int method_count;\n";
6056 Result += "\tstruct _objc_method method_list[";
6057 Result += utostr(method_count); Result += "];\n";
6058 Result += "}";
6059}
6060
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006061static void Write__prop_list_t_TypeDecl(std::string &Result,
6062 unsigned int property_count) {
6063 Result += "struct /*_prop_list_t*/"; Result += " {\n";
6064 Result += "\tunsigned int entsize; // sizeof(struct _prop_t)\n";
6065 Result += "\tunsigned int count_of_properties;\n";
6066 Result += "\tstruct _prop_t prop_list[";
6067 Result += utostr(property_count); Result += "];\n";
6068 Result += "}";
6069}
6070
Fariborz Jahanianae932952012-02-10 20:47:10 +00006071static void Write__ivar_list_t_TypeDecl(std::string &Result,
6072 unsigned int ivar_count) {
6073 Result += "struct /*_ivar_list_t*/"; Result += " {\n";
6074 Result += "\tunsigned int entsize; // sizeof(struct _prop_t)\n";
6075 Result += "\tunsigned int count;\n";
6076 Result += "\tstruct _ivar_t ivar_list[";
6077 Result += utostr(ivar_count); Result += "];\n";
6078 Result += "}";
6079}
6080
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006081static void Write_protocol_list_initializer(ASTContext *Context, std::string &Result,
6082 ArrayRef<ObjCProtocolDecl *> SuperProtocols,
6083 StringRef VarName,
6084 StringRef ProtocolName) {
6085 if (SuperProtocols.size() > 0) {
6086 Result += "\nstatic ";
6087 Write_protocol_list_t_TypeDecl(Result, SuperProtocols.size());
6088 Result += " "; Result += VarName;
6089 Result += ProtocolName;
6090 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6091 Result += "\t"; Result += utostr(SuperProtocols.size()); Result += ",\n";
6092 for (unsigned i = 0, e = SuperProtocols.size(); i < e; i++) {
6093 ObjCProtocolDecl *SuperPD = SuperProtocols[i];
6094 Result += "\t&"; Result += "_OBJC_PROTOCOL_";
6095 Result += SuperPD->getNameAsString();
6096 if (i == e-1)
6097 Result += "\n};\n";
6098 else
6099 Result += ",\n";
6100 }
6101 }
6102}
6103
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006104static void Write_method_list_t_initializer(RewriteModernObjC &RewriteObj,
6105 ASTContext *Context, std::string &Result,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006106 ArrayRef<ObjCMethodDecl *> Methods,
6107 StringRef VarName,
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006108 StringRef TopLevelDeclName,
6109 bool MethodImpl) {
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006110 if (Methods.size() > 0) {
6111 Result += "\nstatic ";
6112 Write_method_list_t_TypeDecl(Result, Methods.size());
6113 Result += " "; Result += VarName;
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006114 Result += TopLevelDeclName;
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006115 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6116 Result += "\t"; Result += "sizeof(_objc_method)"; Result += ",\n";
6117 Result += "\t"; Result += utostr(Methods.size()); Result += ",\n";
6118 for (unsigned i = 0, e = Methods.size(); i < e; i++) {
6119 ObjCMethodDecl *MD = Methods[i];
6120 if (i == 0)
6121 Result += "\t{{(struct objc_selector *)\"";
6122 else
6123 Result += "\t{(struct objc_selector *)\"";
6124 Result += (MD)->getSelector().getAsString(); Result += "\"";
6125 Result += ", ";
6126 std::string MethodTypeString;
6127 Context->getObjCEncodingForMethodDecl(MD, MethodTypeString);
6128 Result += "\""; Result += MethodTypeString; Result += "\"";
6129 Result += ", ";
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006130 if (!MethodImpl)
6131 Result += "0";
6132 else {
6133 Result += "(void *)";
6134 Result += RewriteObj.MethodInternalNames[MD];
6135 }
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006136 if (i == e-1)
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006137 Result += "}}\n";
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006138 else
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006139 Result += "},\n";
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006140 }
6141 Result += "};\n";
6142 }
6143}
6144
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006145static void Write_prop_list_t_initializer(RewriteModernObjC &RewriteObj,
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006146 ASTContext *Context, std::string &Result,
6147 ArrayRef<ObjCPropertyDecl *> Properties,
6148 const Decl *Container,
6149 StringRef VarName,
6150 StringRef ProtocolName) {
6151 if (Properties.size() > 0) {
6152 Result += "\nstatic ";
6153 Write__prop_list_t_TypeDecl(Result, Properties.size());
6154 Result += " "; Result += VarName;
6155 Result += ProtocolName;
6156 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6157 Result += "\t"; Result += "sizeof(_prop_t)"; Result += ",\n";
6158 Result += "\t"; Result += utostr(Properties.size()); Result += ",\n";
6159 for (unsigned i = 0, e = Properties.size(); i < e; i++) {
6160 ObjCPropertyDecl *PropDecl = Properties[i];
6161 if (i == 0)
6162 Result += "\t{{\"";
6163 else
6164 Result += "\t{\"";
6165 Result += PropDecl->getName(); Result += "\",";
6166 std::string PropertyTypeString, QuotePropertyTypeString;
6167 Context->getObjCEncodingForPropertyDecl(PropDecl, Container, PropertyTypeString);
6168 RewriteObj.QuoteDoublequotes(PropertyTypeString, QuotePropertyTypeString);
6169 Result += "\""; Result += QuotePropertyTypeString; Result += "\"";
6170 if (i == e-1)
6171 Result += "}}\n";
6172 else
6173 Result += "},\n";
6174 }
6175 Result += "};\n";
6176 }
6177}
6178
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006179// Metadata flags
6180enum MetaDataDlags {
6181 CLS = 0x0,
6182 CLS_META = 0x1,
6183 CLS_ROOT = 0x2,
6184 OBJC2_CLS_HIDDEN = 0x10,
6185 CLS_EXCEPTION = 0x20,
6186
6187 /// (Obsolete) ARC-specific: this class has a .release_ivars method
6188 CLS_HAS_IVAR_RELEASER = 0x40,
6189 /// class was compiled with -fobjc-arr
6190 CLS_COMPILED_BY_ARC = 0x80 // (1<<7)
6191};
6192
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006193static void Write__class_ro_t_initializer(ASTContext *Context, std::string &Result,
6194 unsigned int flags,
6195 const std::string &InstanceStart,
6196 const std::string &InstanceSize,
6197 ArrayRef<ObjCMethodDecl *>baseMethods,
6198 ArrayRef<ObjCProtocolDecl *>baseProtocols,
6199 ArrayRef<ObjCIvarDecl *>ivars,
6200 ArrayRef<ObjCPropertyDecl *>Properties,
6201 StringRef VarName,
6202 StringRef ClassName) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006203 Result += "\nstatic struct _class_ro_t ";
6204 Result += VarName; Result += ClassName;
6205 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6206 Result += "\t";
6207 Result += llvm::utostr(flags); Result += ", ";
6208 Result += InstanceStart; Result += ", ";
6209 Result += InstanceSize; Result += ", \n";
6210 Result += "\t";
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00006211 const llvm::Triple &Triple(Context->getTargetInfo().getTriple());
6212 if (Triple.getArch() == llvm::Triple::x86_64)
6213 // uint32_t const reserved; // only when building for 64bit targets
6214 Result += "(unsigned int)0, \n\t";
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006215 // const uint8_t * const ivarLayout;
6216 Result += "0, \n\t";
6217 Result += "\""; Result += ClassName; Result += "\",\n\t";
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006218 bool metaclass = ((flags & CLS_META) != 0);
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006219 if (baseMethods.size() > 0) {
6220 Result += "(const struct _method_list_t *)&";
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006221 if (metaclass)
6222 Result += "_OBJC_$_CLASS_METHODS_";
6223 else
6224 Result += "_OBJC_$_INSTANCE_METHODS_";
6225 Result += ClassName;
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006226 Result += ",\n\t";
6227 }
6228 else
6229 Result += "0, \n\t";
6230
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006231 if (!metaclass && baseProtocols.size() > 0) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006232 Result += "(const struct _objc_protocol_list *)&";
6233 Result += "_OBJC_CLASS_PROTOCOLS_$_"; Result += ClassName;
6234 Result += ",\n\t";
6235 }
6236 else
6237 Result += "0, \n\t";
6238
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006239 if (!metaclass && ivars.size() > 0) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006240 Result += "(const struct _ivar_list_t *)&";
6241 Result += "_OBJC_$_INSTANCE_VARIABLES_"; Result += ClassName;
6242 Result += ",\n\t";
6243 }
6244 else
6245 Result += "0, \n\t";
6246
6247 // weakIvarLayout
6248 Result += "0, \n\t";
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006249 if (!metaclass && Properties.size() > 0) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006250 Result += "(const struct _prop_list_t *)&";
Fariborz Jahanianeeabf382012-02-16 21:57:59 +00006251 Result += "_OBJC_$_PROP_LIST_"; Result += ClassName;
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006252 Result += ",\n";
6253 }
6254 else
6255 Result += "0, \n";
6256
6257 Result += "};\n";
6258}
6259
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006260static void Write_class_t(ASTContext *Context, std::string &Result,
6261 StringRef VarName,
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006262 const ObjCInterfaceDecl *CDecl, bool metaclass) {
6263 bool rootClass = (!CDecl->getSuperClass());
6264 const ObjCInterfaceDecl *RootClass = CDecl;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006265
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006266 if (!rootClass) {
6267 // Find the Root class
6268 RootClass = CDecl->getSuperClass();
6269 while (RootClass->getSuperClass()) {
6270 RootClass = RootClass->getSuperClass();
6271 }
6272 }
6273
6274 if (metaclass && rootClass) {
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006275 // Need to handle a case of use of forward declaration.
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00006276 Result += "\n";
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006277 Result += "extern \"C\" ";
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00006278 if (CDecl->getImplementation())
6279 Result += "__declspec(dllexport) ";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006280 else
6281 Result += "__declspec(dllimport) ";
6282
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006283 Result += "struct _class_t OBJC_CLASS_$_";
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006284 Result += CDecl->getNameAsString();
6285 Result += ";\n";
6286 }
6287 // Also, for possibility of 'super' metadata class not having been defined yet.
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006288 if (!rootClass) {
Fariborz Jahanian868e9852012-03-29 19:04:10 +00006289 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00006290 Result += "\n";
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006291 Result += "extern \"C\" ";
Fariborz Jahanian868e9852012-03-29 19:04:10 +00006292 if (SuperClass->getImplementation())
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00006293 Result += "__declspec(dllexport) ";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006294 else
6295 Result += "__declspec(dllimport) ";
6296
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006297 Result += "struct _class_t ";
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00006298 Result += VarName;
Fariborz Jahanian868e9852012-03-29 19:04:10 +00006299 Result += SuperClass->getNameAsString();
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006300 Result += ";\n";
Fariborz Jahanian452eac12012-03-20 21:09:58 +00006301
Fariborz Jahanian868e9852012-03-29 19:04:10 +00006302 if (metaclass && RootClass != SuperClass) {
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006303 Result += "extern \"C\" ";
Fariborz Jahanian452eac12012-03-20 21:09:58 +00006304 if (RootClass->getImplementation())
6305 Result += "__declspec(dllexport) ";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006306 else
6307 Result += "__declspec(dllimport) ";
6308
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006309 Result += "struct _class_t ";
Fariborz Jahanian452eac12012-03-20 21:09:58 +00006310 Result += VarName;
6311 Result += RootClass->getNameAsString();
6312 Result += ";\n";
6313 }
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006314 }
6315
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006316 Result += "\nextern \"C\" __declspec(dllexport) struct _class_t ";
6317 Result += VarName; Result += CDecl->getNameAsString();
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006318 Result += " __attribute__ ((used, section (\"__DATA,__objc_data\"))) = {\n";
6319 Result += "\t";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006320 if (metaclass) {
6321 if (!rootClass) {
6322 Result += "0, // &"; Result += VarName;
6323 Result += RootClass->getNameAsString();
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006324 Result += ",\n\t";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006325 Result += "0, // &"; Result += VarName;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006326 Result += CDecl->getSuperClass()->getNameAsString();
6327 Result += ",\n\t";
6328 }
6329 else {
Fariborz Jahanian452eac12012-03-20 21:09:58 +00006330 Result += "0, // &"; Result += VarName;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006331 Result += CDecl->getNameAsString();
6332 Result += ",\n\t";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006333 Result += "0, // &OBJC_CLASS_$_"; Result += CDecl->getNameAsString();
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006334 Result += ",\n\t";
6335 }
6336 }
6337 else {
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006338 Result += "0, // &OBJC_METACLASS_$_";
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006339 Result += CDecl->getNameAsString();
6340 Result += ",\n\t";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006341 if (!rootClass) {
6342 Result += "0, // &"; Result += VarName;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006343 Result += CDecl->getSuperClass()->getNameAsString();
6344 Result += ",\n\t";
6345 }
6346 else
6347 Result += "0,\n\t";
6348 }
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006349 Result += "0, // (void *)&_objc_empty_cache,\n\t";
6350 Result += "0, // unused, was (void *)&_objc_empty_vtable,\n\t";
6351 if (metaclass)
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006352 Result += "&_OBJC_METACLASS_RO_$_";
6353 else
6354 Result += "&_OBJC_CLASS_RO_$_";
6355 Result += CDecl->getNameAsString();
6356 Result += ",\n};\n";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006357
6358 // Add static function to initialize some of the meta-data fields.
6359 // avoid doing it twice.
6360 if (metaclass)
6361 return;
6362
6363 const ObjCInterfaceDecl *SuperClass =
6364 rootClass ? CDecl : CDecl->getSuperClass();
6365
6366 Result += "static void OBJC_CLASS_SETUP_$_";
6367 Result += CDecl->getNameAsString();
6368 Result += "(void ) {\n";
6369 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
6370 Result += ".isa = "; Result += "&OBJC_METACLASS_$_";
Fariborz Jahanian452eac12012-03-20 21:09:58 +00006371 Result += RootClass->getNameAsString(); Result += ";\n";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006372
6373 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
Fariborz Jahanian452eac12012-03-20 21:09:58 +00006374 Result += ".superclass = ";
6375 if (rootClass)
6376 Result += "&OBJC_CLASS_$_";
6377 else
6378 Result += "&OBJC_METACLASS_$_";
6379
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006380 Result += SuperClass->getNameAsString(); Result += ";\n";
6381
6382 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
6383 Result += ".cache = "; Result += "&_objc_empty_cache"; Result += ";\n";
6384
6385 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6386 Result += ".isa = "; Result += "&OBJC_METACLASS_$_";
6387 Result += CDecl->getNameAsString(); Result += ";\n";
6388
6389 if (!rootClass) {
6390 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6391 Result += ".superclass = "; Result += "&OBJC_CLASS_$_";
6392 Result += SuperClass->getNameAsString(); Result += ";\n";
6393 }
6394
6395 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6396 Result += ".cache = "; Result += "&_objc_empty_cache"; Result += ";\n";
6397 Result += "}\n";
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006398}
6399
Fariborz Jahanian61186122012-02-17 18:40:41 +00006400static void Write_category_t(RewriteModernObjC &RewriteObj, ASTContext *Context,
6401 std::string &Result,
Fariborz Jahaniane0335782012-03-27 18:41:05 +00006402 ObjCCategoryDecl *CatDecl,
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006403 ObjCInterfaceDecl *ClassDecl,
Fariborz Jahanian61186122012-02-17 18:40:41 +00006404 ArrayRef<ObjCMethodDecl *> InstanceMethods,
6405 ArrayRef<ObjCMethodDecl *> ClassMethods,
6406 ArrayRef<ObjCProtocolDecl *> RefedProtocols,
6407 ArrayRef<ObjCPropertyDecl *> ClassProperties) {
Fariborz Jahaniane0335782012-03-27 18:41:05 +00006408 StringRef CatName = CatDecl->getName();
NAKAMURA Takumi20f89392012-03-21 03:21:46 +00006409 StringRef ClassName = ClassDecl->getName();
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00006410 // must declare an extern class object in case this class is not implemented
6411 // in this TU.
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006412 Result += "\n";
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006413 Result += "extern \"C\" ";
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006414 if (ClassDecl->getImplementation())
6415 Result += "__declspec(dllexport) ";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006416 else
6417 Result += "__declspec(dllimport) ";
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006418
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006419 Result += "struct _class_t ";
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00006420 Result += "OBJC_CLASS_$_"; Result += ClassName;
6421 Result += ";\n";
6422
Fariborz Jahanian61186122012-02-17 18:40:41 +00006423 Result += "\nstatic struct _category_t ";
6424 Result += "_OBJC_$_CATEGORY_";
6425 Result += ClassName; Result += "_$_"; Result += CatName;
6426 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = \n";
6427 Result += "{\n";
6428 Result += "\t\""; Result += ClassName; Result += "\",\n";
Fariborz Jahanian4b2fe6e2012-03-20 21:41:28 +00006429 Result += "\t0, // &"; Result += "OBJC_CLASS_$_"; Result += ClassName;
Fariborz Jahanian61186122012-02-17 18:40:41 +00006430 Result += ",\n";
6431 if (InstanceMethods.size() > 0) {
6432 Result += "\t(const struct _method_list_t *)&";
6433 Result += "_OBJC_$_CATEGORY_INSTANCE_METHODS_";
6434 Result += ClassName; Result += "_$_"; Result += CatName;
6435 Result += ",\n";
6436 }
6437 else
6438 Result += "\t0,\n";
6439
6440 if (ClassMethods.size() > 0) {
6441 Result += "\t(const struct _method_list_t *)&";
6442 Result += "_OBJC_$_CATEGORY_CLASS_METHODS_";
6443 Result += ClassName; Result += "_$_"; Result += CatName;
6444 Result += ",\n";
6445 }
6446 else
6447 Result += "\t0,\n";
6448
6449 if (RefedProtocols.size() > 0) {
6450 Result += "\t(const struct _protocol_list_t *)&";
6451 Result += "_OBJC_CATEGORY_PROTOCOLS_$_";
6452 Result += ClassName; Result += "_$_"; Result += CatName;
6453 Result += ",\n";
6454 }
6455 else
6456 Result += "\t0,\n";
6457
6458 if (ClassProperties.size() > 0) {
6459 Result += "\t(const struct _prop_list_t *)&"; Result += "_OBJC_$_PROP_LIST_";
6460 Result += ClassName; Result += "_$_"; Result += CatName;
6461 Result += ",\n";
6462 }
6463 else
6464 Result += "\t0,\n";
6465
6466 Result += "};\n";
Fariborz Jahanian4b2fe6e2012-03-20 21:41:28 +00006467
6468 // Add static function to initialize the class pointer in the category structure.
6469 Result += "static void OBJC_CATEGORY_SETUP_$_";
6470 Result += ClassDecl->getNameAsString();
6471 Result += "_$_";
6472 Result += CatName;
6473 Result += "(void ) {\n";
6474 Result += "\t_OBJC_$_CATEGORY_";
6475 Result += ClassDecl->getNameAsString();
6476 Result += "_$_";
6477 Result += CatName;
6478 Result += ".cls = "; Result += "&OBJC_CLASS_$_"; Result += ClassName;
6479 Result += ";\n}\n";
Fariborz Jahanian61186122012-02-17 18:40:41 +00006480}
6481
Fariborz Jahaniane0adbd82012-02-08 22:23:26 +00006482static void Write__extendedMethodTypes_initializer(RewriteModernObjC &RewriteObj,
6483 ASTContext *Context, std::string &Result,
6484 ArrayRef<ObjCMethodDecl *> Methods,
6485 StringRef VarName,
6486 StringRef ProtocolName) {
6487 if (Methods.size() == 0)
6488 return;
6489
6490 Result += "\nstatic const char *";
6491 Result += VarName; Result += ProtocolName;
6492 Result += " [] __attribute__ ((used, section (\"__DATA,__objc_const\"))) = \n";
6493 Result += "{\n";
6494 for (unsigned i = 0, e = Methods.size(); i < e; i++) {
6495 ObjCMethodDecl *MD = Methods[i];
6496 std::string MethodTypeString, QuoteMethodTypeString;
6497 Context->getObjCEncodingForMethodDecl(MD, MethodTypeString, true);
6498 RewriteObj.QuoteDoublequotes(MethodTypeString, QuoteMethodTypeString);
6499 Result += "\t\""; Result += QuoteMethodTypeString; Result += "\"";
6500 if (i == e-1)
6501 Result += "\n};\n";
6502 else {
6503 Result += ",\n";
6504 }
6505 }
6506}
6507
Fariborz Jahanianacee1c92012-04-11 21:12:36 +00006508static void Write_IvarOffsetVar(RewriteModernObjC &RewriteObj,
6509 ASTContext *Context,
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00006510 std::string &Result,
Fariborz Jahaniandb649232012-02-13 20:59:02 +00006511 ArrayRef<ObjCIvarDecl *> Ivars,
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006512 ObjCInterfaceDecl *CDecl) {
Fariborz Jahaniandb649232012-02-13 20:59:02 +00006513 // FIXME. visibilty of offset symbols may have to be set; for Darwin
6514 // this is what happens:
6515 /**
6516 if (Ivar->getAccessControl() == ObjCIvarDecl::Private ||
6517 Ivar->getAccessControl() == ObjCIvarDecl::Package ||
6518 Class->getVisibility() == HiddenVisibility)
6519 Visibility shoud be: HiddenVisibility;
6520 else
6521 Visibility shoud be: DefaultVisibility;
6522 */
6523
Fariborz Jahanian07e52882012-02-13 21:34:45 +00006524 Result += "\n";
6525 for (unsigned i =0, e = Ivars.size(); i < e; i++) {
6526 ObjCIvarDecl *IvarDecl = Ivars[i];
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00006527 if (Context->getLangOpts().MicrosoftExt)
6528 Result += "__declspec(allocate(\".objc_ivar$B\")) ";
6529
6530 if (!Context->getLangOpts().MicrosoftExt ||
6531 IvarDecl->getAccessControl() == ObjCIvarDecl::Private ||
Fariborz Jahanian117591f2012-03-10 01:34:42 +00006532 IvarDecl->getAccessControl() == ObjCIvarDecl::Package)
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006533 Result += "extern \"C\" unsigned long int ";
Fariborz Jahaniand1c84d32012-03-10 00:53:02 +00006534 else
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006535 Result += "extern \"C\" __declspec(dllexport) unsigned long int ";
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006536 WriteInternalIvarName(CDecl, IvarDecl, Result);
Fariborz Jahanian07e52882012-02-13 21:34:45 +00006537 Result += " __attribute__ ((used, section (\"__DATA,__objc_ivar\")))";
6538 Result += " = ";
Fariborz Jahanianacee1c92012-04-11 21:12:36 +00006539 RewriteObj.RewriteIvarOffsetComputation(IvarDecl, Result);
6540 Result += ";\n";
Fariborz Jahaniandb649232012-02-13 20:59:02 +00006541 }
6542}
6543
Fariborz Jahanianae932952012-02-10 20:47:10 +00006544static void Write__ivar_list_t_initializer(RewriteModernObjC &RewriteObj,
6545 ASTContext *Context, std::string &Result,
6546 ArrayRef<ObjCIvarDecl *> Ivars,
6547 StringRef VarName,
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006548 ObjCInterfaceDecl *CDecl) {
Fariborz Jahanianae932952012-02-10 20:47:10 +00006549 if (Ivars.size() > 0) {
Fariborz Jahanianacee1c92012-04-11 21:12:36 +00006550 Write_IvarOffsetVar(RewriteObj, Context, Result, Ivars, CDecl);
Fariborz Jahanian07e52882012-02-13 21:34:45 +00006551
Fariborz Jahanianae932952012-02-10 20:47:10 +00006552 Result += "\nstatic ";
6553 Write__ivar_list_t_TypeDecl(Result, Ivars.size());
6554 Result += " "; Result += VarName;
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006555 Result += CDecl->getNameAsString();
Fariborz Jahanianae932952012-02-10 20:47:10 +00006556 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6557 Result += "\t"; Result += "sizeof(_ivar_t)"; Result += ",\n";
6558 Result += "\t"; Result += utostr(Ivars.size()); Result += ",\n";
6559 for (unsigned i =0, e = Ivars.size(); i < e; i++) {
6560 ObjCIvarDecl *IvarDecl = Ivars[i];
6561 if (i == 0)
6562 Result += "\t{{";
6563 else
6564 Result += "\t {";
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006565 Result += "(unsigned long int *)&";
6566 WriteInternalIvarName(CDecl, IvarDecl, Result);
Fariborz Jahaniandb649232012-02-13 20:59:02 +00006567 Result += ", ";
Fariborz Jahanianae932952012-02-10 20:47:10 +00006568
6569 Result += "\""; Result += IvarDecl->getName(); Result += "\", ";
6570 std::string IvarTypeString, QuoteIvarTypeString;
6571 Context->getObjCEncodingForType(IvarDecl->getType(), IvarTypeString,
6572 IvarDecl);
6573 RewriteObj.QuoteDoublequotes(IvarTypeString, QuoteIvarTypeString);
6574 Result += "\""; Result += QuoteIvarTypeString; Result += "\", ";
6575
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00006576 // FIXME. this alignment represents the host alignment and need be changed to
6577 // represent the target alignment.
6578 unsigned Align = Context->getTypeAlign(IvarDecl->getType())/8;
6579 Align = llvm::Log2_32(Align);
Fariborz Jahanianae932952012-02-10 20:47:10 +00006580 Result += llvm::utostr(Align); Result += ", ";
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00006581 CharUnits Size = Context->getTypeSizeInChars(IvarDecl->getType());
6582 Result += llvm::utostr(Size.getQuantity());
Fariborz Jahanianae932952012-02-10 20:47:10 +00006583 if (i == e-1)
6584 Result += "}}\n";
6585 else
6586 Result += "},\n";
6587 }
6588 Result += "};\n";
6589 }
6590}
6591
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006592/// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006593void RewriteModernObjC::RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl,
6594 std::string &Result) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006595
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006596 // Do not synthesize the protocol more than once.
6597 if (ObjCSynthesizedProtocols.count(PDecl->getCanonicalDecl()))
6598 return;
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00006599 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006600
6601 if (ObjCProtocolDecl *Def = PDecl->getDefinition())
6602 PDecl = Def;
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006603 // Must write out all protocol definitions in current qualifier list,
6604 // and in their nested qualifiers before writing out current definition.
6605 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
6606 E = PDecl->protocol_end(); I != E; ++I)
6607 RewriteObjCProtocolMetaData(*I, Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006608
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006609 // Construct method lists.
6610 std::vector<ObjCMethodDecl *> InstanceMethods, ClassMethods;
6611 std::vector<ObjCMethodDecl *> OptInstanceMethods, OptClassMethods;
6612 for (ObjCProtocolDecl::instmeth_iterator
6613 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
6614 I != E; ++I) {
6615 ObjCMethodDecl *MD = *I;
6616 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
6617 OptInstanceMethods.push_back(MD);
6618 } else {
6619 InstanceMethods.push_back(MD);
6620 }
6621 }
6622
6623 for (ObjCProtocolDecl::classmeth_iterator
6624 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
6625 I != E; ++I) {
6626 ObjCMethodDecl *MD = *I;
6627 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
6628 OptClassMethods.push_back(MD);
6629 } else {
6630 ClassMethods.push_back(MD);
6631 }
6632 }
Fariborz Jahaniane0adbd82012-02-08 22:23:26 +00006633 std::vector<ObjCMethodDecl *> AllMethods;
6634 for (unsigned i = 0, e = InstanceMethods.size(); i < e; i++)
6635 AllMethods.push_back(InstanceMethods[i]);
6636 for (unsigned i = 0, e = ClassMethods.size(); i < e; i++)
6637 AllMethods.push_back(ClassMethods[i]);
6638 for (unsigned i = 0, e = OptInstanceMethods.size(); i < e; i++)
6639 AllMethods.push_back(OptInstanceMethods[i]);
6640 for (unsigned i = 0, e = OptClassMethods.size(); i < e; i++)
6641 AllMethods.push_back(OptClassMethods[i]);
6642
6643 Write__extendedMethodTypes_initializer(*this, Context, Result,
6644 AllMethods,
6645 "_OBJC_PROTOCOL_METHOD_TYPES_",
6646 PDecl->getNameAsString());
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006647 // Protocol's super protocol list
6648 std::vector<ObjCProtocolDecl *> SuperProtocols;
6649 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
6650 E = PDecl->protocol_end(); I != E; ++I)
6651 SuperProtocols.push_back(*I);
6652
6653 Write_protocol_list_initializer(Context, Result, SuperProtocols,
6654 "_OBJC_PROTOCOL_REFS_",
6655 PDecl->getNameAsString());
6656
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006657 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006658 "_OBJC_PROTOCOL_INSTANCE_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006659 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006660
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006661 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006662 "_OBJC_PROTOCOL_CLASS_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006663 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006664
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006665 Write_method_list_t_initializer(*this, Context, Result, OptInstanceMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006666 "_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006667 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006668
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006669 Write_method_list_t_initializer(*this, Context, Result, OptClassMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006670 "_OBJC_PROTOCOL_OPT_CLASS_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006671 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006672
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006673 // Protocol's property metadata.
6674 std::vector<ObjCPropertyDecl *> ProtocolProperties;
6675 for (ObjCContainerDecl::prop_iterator I = PDecl->prop_begin(),
6676 E = PDecl->prop_end(); I != E; ++I)
David Blaikie262bc182012-04-30 02:36:29 +00006677 ProtocolProperties.push_back(&*I);
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006678
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006679 Write_prop_list_t_initializer(*this, Context, Result, ProtocolProperties,
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006680 /* Container */0,
6681 "_OBJC_PROTOCOL_PROPERTIES_",
6682 PDecl->getNameAsString());
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006683
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006684 // Writer out root metadata for current protocol: struct _protocol_t
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00006685 Result += "\n";
6686 if (LangOpts.MicrosoftExt)
Fariborz Jahanian8590d862012-04-14 17:13:08 +00006687 Result += "static ";
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00006688 Result += "struct _protocol_t _OBJC_PROTOCOL_";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006689 Result += PDecl->getNameAsString();
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006690 Result += " __attribute__ ((used, section (\"__DATA,__datacoal_nt,coalesced\"))) = {\n";
6691 Result += "\t0,\n"; // id is; is null
6692 Result += "\t\""; Result += PDecl->getNameAsString(); Result += "\",\n";
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006693 if (SuperProtocols.size() > 0) {
6694 Result += "\t(const struct _protocol_list_t *)&"; Result += "_OBJC_PROTOCOL_REFS_";
6695 Result += PDecl->getNameAsString(); Result += ",\n";
6696 }
6697 else
6698 Result += "\t0,\n";
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006699 if (InstanceMethods.size() > 0) {
6700 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
6701 Result += PDecl->getNameAsString(); Result += ",\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006702 }
6703 else
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006704 Result += "\t0,\n";
6705
6706 if (ClassMethods.size() > 0) {
6707 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_CLASS_METHODS_";
6708 Result += PDecl->getNameAsString(); Result += ",\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006709 }
6710 else
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006711 Result += "\t0,\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006712
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006713 if (OptInstanceMethods.size() > 0) {
6714 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_";
6715 Result += PDecl->getNameAsString(); Result += ",\n";
6716 }
6717 else
6718 Result += "\t0,\n";
6719
6720 if (OptClassMethods.size() > 0) {
6721 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_CLASS_METHODS_";
6722 Result += PDecl->getNameAsString(); Result += ",\n";
6723 }
6724 else
6725 Result += "\t0,\n";
6726
6727 if (ProtocolProperties.size() > 0) {
6728 Result += "\t(const struct _prop_list_t *)&_OBJC_PROTOCOL_PROPERTIES_";
6729 Result += PDecl->getNameAsString(); Result += ",\n";
6730 }
6731 else
6732 Result += "\t0,\n";
6733
6734 Result += "\t"; Result += "sizeof(_protocol_t)"; Result += ",\n";
6735 Result += "\t0,\n";
6736
Fariborz Jahaniane0adbd82012-02-08 22:23:26 +00006737 if (AllMethods.size() > 0) {
6738 Result += "\t(const char **)&"; Result += "_OBJC_PROTOCOL_METHOD_TYPES_";
6739 Result += PDecl->getNameAsString();
6740 Result += "\n};\n";
6741 }
6742 else
6743 Result += "\t0\n};\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00006744
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00006745 if (LangOpts.MicrosoftExt)
Fariborz Jahanian8590d862012-04-14 17:13:08 +00006746 Result += "static ";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00006747 Result += "struct _protocol_t *";
6748 Result += "_OBJC_LABEL_PROTOCOL_$_"; Result += PDecl->getNameAsString();
6749 Result += " = &_OBJC_PROTOCOL_"; Result += PDecl->getNameAsString();
6750 Result += ";\n";
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006751
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006752 // Mark this protocol as having been generated.
6753 if (!ObjCSynthesizedProtocols.insert(PDecl->getCanonicalDecl()))
6754 llvm_unreachable("protocol already synthesized");
6755
6756}
6757
6758void RewriteModernObjC::RewriteObjCProtocolListMetaData(
6759 const ObjCList<ObjCProtocolDecl> &Protocols,
6760 StringRef prefix, StringRef ClassName,
6761 std::string &Result) {
6762 if (Protocols.empty()) return;
6763
6764 for (unsigned i = 0; i != Protocols.size(); i++)
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006765 RewriteObjCProtocolMetaData(Protocols[i], Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006766
6767 // Output the top lovel protocol meta-data for the class.
6768 /* struct _objc_protocol_list {
6769 struct _objc_protocol_list *next;
6770 int protocol_count;
6771 struct _objc_protocol *class_protocols[];
6772 }
6773 */
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00006774 Result += "\n";
6775 if (LangOpts.MicrosoftExt)
6776 Result += "__declspec(allocate(\".cat_cls_meth$B\")) ";
6777 Result += "static struct {\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006778 Result += "\tstruct _objc_protocol_list *next;\n";
6779 Result += "\tint protocol_count;\n";
6780 Result += "\tstruct _objc_protocol *class_protocols[";
6781 Result += utostr(Protocols.size());
6782 Result += "];\n} _OBJC_";
6783 Result += prefix;
6784 Result += "_PROTOCOLS_";
6785 Result += ClassName;
6786 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
6787 "{\n\t0, ";
6788 Result += utostr(Protocols.size());
6789 Result += "\n";
6790
6791 Result += "\t,{&_OBJC_PROTOCOL_";
6792 Result += Protocols[0]->getNameAsString();
6793 Result += " \n";
6794
6795 for (unsigned i = 1; i != Protocols.size(); i++) {
6796 Result += "\t ,&_OBJC_PROTOCOL_";
6797 Result += Protocols[i]->getNameAsString();
6798 Result += "\n";
6799 }
6800 Result += "\t }\n};\n";
6801}
6802
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006803/// hasObjCExceptionAttribute - Return true if this class or any super
6804/// class has the __objc_exception__ attribute.
6805/// FIXME. Move this to ASTContext.cpp as it is also used for IRGen.
6806static bool hasObjCExceptionAttribute(ASTContext &Context,
6807 const ObjCInterfaceDecl *OID) {
6808 if (OID->hasAttr<ObjCExceptionAttr>())
6809 return true;
6810 if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
6811 return hasObjCExceptionAttribute(Context, Super);
6812 return false;
6813}
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006814
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006815void RewriteModernObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
6816 std::string &Result) {
6817 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
6818
6819 // Explicitly declared @interface's are already synthesized.
Fariborz Jahanianae932952012-02-10 20:47:10 +00006820 if (CDecl->isImplicitInterfaceDecl())
6821 assert(false &&
6822 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00006823
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00006824 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanianae932952012-02-10 20:47:10 +00006825 SmallVector<ObjCIvarDecl *, 8> IVars;
6826
6827 for (ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
6828 IVD; IVD = IVD->getNextIvar()) {
6829 // Ignore unnamed bit-fields.
6830 if (!IVD->getDeclName())
6831 continue;
6832 IVars.push_back(IVD);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006833 }
6834
Fariborz Jahanianae932952012-02-10 20:47:10 +00006835 Write__ivar_list_t_initializer(*this, Context, Result, IVars,
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006836 "_OBJC_$_INSTANCE_VARIABLES_",
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006837 CDecl);
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006838
6839 // Build _objc_method_list for class's instance methods if needed
6840 SmallVector<ObjCMethodDecl *, 32>
6841 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
6842
6843 // If any of our property implementations have associated getters or
6844 // setters, produce metadata for them as well.
6845 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
6846 PropEnd = IDecl->propimpl_end();
6847 Prop != PropEnd; ++Prop) {
David Blaikie262bc182012-04-30 02:36:29 +00006848 if (Prop->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006849 continue;
David Blaikie262bc182012-04-30 02:36:29 +00006850 if (!Prop->getPropertyIvarDecl())
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006851 continue;
David Blaikie262bc182012-04-30 02:36:29 +00006852 ObjCPropertyDecl *PD = Prop->getPropertyDecl();
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006853 if (!PD)
6854 continue;
6855 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
Fariborz Jahanian301e2e42012-05-03 22:52:13 +00006856 if (mustSynthesizeSetterGetterMethod(IDecl, PD, true /*getter*/))
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006857 InstanceMethods.push_back(Getter);
6858 if (PD->isReadOnly())
6859 continue;
6860 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
Fariborz Jahanian301e2e42012-05-03 22:52:13 +00006861 if (mustSynthesizeSetterGetterMethod(IDecl, PD, false /*setter*/))
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006862 InstanceMethods.push_back(Setter);
6863 }
6864
6865 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
6866 "_OBJC_$_INSTANCE_METHODS_",
6867 IDecl->getNameAsString(), true);
6868
6869 SmallVector<ObjCMethodDecl *, 32>
6870 ClassMethods(IDecl->classmeth_begin(), IDecl->classmeth_end());
6871
6872 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
6873 "_OBJC_$_CLASS_METHODS_",
6874 IDecl->getNameAsString(), true);
Fariborz Jahanian0a525342012-02-14 19:31:35 +00006875
6876 // Protocols referenced in class declaration?
6877 // Protocol's super protocol list
6878 std::vector<ObjCProtocolDecl *> RefedProtocols;
6879 const ObjCList<ObjCProtocolDecl> &Protocols = CDecl->getReferencedProtocols();
6880 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
6881 E = Protocols.end();
6882 I != E; ++I) {
6883 RefedProtocols.push_back(*I);
6884 // Must write out all protocol definitions in current qualifier list,
6885 // and in their nested qualifiers before writing out current definition.
6886 RewriteObjCProtocolMetaData(*I, Result);
6887 }
6888
6889 Write_protocol_list_initializer(Context, Result,
6890 RefedProtocols,
6891 "_OBJC_CLASS_PROTOCOLS_$_",
6892 IDecl->getNameAsString());
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006893
6894 // Protocol's property metadata.
6895 std::vector<ObjCPropertyDecl *> ClassProperties;
6896 for (ObjCContainerDecl::prop_iterator I = CDecl->prop_begin(),
6897 E = CDecl->prop_end(); I != E; ++I)
David Blaikie262bc182012-04-30 02:36:29 +00006898 ClassProperties.push_back(&*I);
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006899
6900 Write_prop_list_t_initializer(*this, Context, Result, ClassProperties,
Fariborz Jahanian2df089d2012-03-22 17:39:35 +00006901 /* Container */IDecl,
Fariborz Jahanianeeabf382012-02-16 21:57:59 +00006902 "_OBJC_$_PROP_LIST_",
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006903 CDecl->getNameAsString());
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006904
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006905
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006906 // Data for initializing _class_ro_t metaclass meta-data
6907 uint32_t flags = CLS_META;
6908 std::string InstanceSize;
6909 std::string InstanceStart;
6910
6911
6912 bool classIsHidden = CDecl->getVisibility() == HiddenVisibility;
6913 if (classIsHidden)
6914 flags |= OBJC2_CLS_HIDDEN;
6915
6916 if (!CDecl->getSuperClass())
6917 // class is root
6918 flags |= CLS_ROOT;
6919 InstanceSize = "sizeof(struct _class_t)";
6920 InstanceStart = InstanceSize;
6921 Write__class_ro_t_initializer(Context, Result, flags,
6922 InstanceStart, InstanceSize,
6923 ClassMethods,
6924 0,
6925 0,
6926 0,
6927 "_OBJC_METACLASS_RO_$_",
6928 CDecl->getNameAsString());
6929
6930
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006931 // Data for initializing _class_ro_t meta-data
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006932 flags = CLS;
6933 if (classIsHidden)
6934 flags |= OBJC2_CLS_HIDDEN;
6935
6936 if (hasObjCExceptionAttribute(*Context, CDecl))
6937 flags |= CLS_EXCEPTION;
6938
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006939 if (!CDecl->getSuperClass())
6940 // class is root
6941 flags |= CLS_ROOT;
6942
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006943 InstanceSize.clear();
6944 InstanceStart.clear();
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006945 if (!ObjCSynthesizedStructs.count(CDecl)) {
6946 InstanceSize = "0";
6947 InstanceStart = "0";
6948 }
6949 else {
6950 InstanceSize = "sizeof(struct ";
6951 InstanceSize += CDecl->getNameAsString();
6952 InstanceSize += "_IMPL)";
6953
6954 ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
6955 if (IVD) {
Fariborz Jahanianacee1c92012-04-11 21:12:36 +00006956 RewriteIvarOffsetComputation(IVD, InstanceStart);
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006957 }
6958 else
6959 InstanceStart = InstanceSize;
6960 }
6961 Write__class_ro_t_initializer(Context, Result, flags,
6962 InstanceStart, InstanceSize,
6963 InstanceMethods,
6964 RefedProtocols,
6965 IVars,
6966 ClassProperties,
6967 "_OBJC_CLASS_RO_$_",
6968 CDecl->getNameAsString());
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006969
6970 Write_class_t(Context, Result,
6971 "OBJC_METACLASS_$_",
6972 CDecl, /*metaclass*/true);
6973
6974 Write_class_t(Context, Result,
6975 "OBJC_CLASS_$_",
6976 CDecl, /*metaclass*/false);
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006977
6978 if (ImplementationIsNonLazy(IDecl))
6979 DefinedNonLazyClasses.push_back(CDecl);
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006980
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006981}
6982
Fariborz Jahaniane0335782012-03-27 18:41:05 +00006983void RewriteModernObjC::RewriteClassSetupInitHook(std::string &Result) {
6984 int ClsDefCount = ClassImplementation.size();
6985 if (!ClsDefCount)
6986 return;
6987 Result += "#pragma section(\".objc_inithooks$B\", long, read, write)\n";
6988 Result += "__declspec(allocate(\".objc_inithooks$B\")) ";
6989 Result += "static void *OBJC_CLASS_SETUP[] = {\n";
6990 for (int i = 0; i < ClsDefCount; i++) {
6991 ObjCImplementationDecl *IDecl = ClassImplementation[i];
6992 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
6993 Result += "\t(void *)&OBJC_CLASS_SETUP_$_";
6994 Result += CDecl->getName(); Result += ",\n";
6995 }
6996 Result += "};\n";
6997}
6998
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006999void RewriteModernObjC::RewriteMetaDataIntoBuffer(std::string &Result) {
7000 int ClsDefCount = ClassImplementation.size();
7001 int CatDefCount = CategoryImplementation.size();
7002
7003 // For each implemented class, write out all its meta data.
7004 for (int i = 0; i < ClsDefCount; i++)
7005 RewriteObjCClassMetaData(ClassImplementation[i], Result);
7006
Fariborz Jahaniane0335782012-03-27 18:41:05 +00007007 RewriteClassSetupInitHook(Result);
7008
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007009 // For each implemented category, write out all its meta data.
7010 for (int i = 0; i < CatDefCount; i++)
7011 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
7012
Fariborz Jahaniane0335782012-03-27 18:41:05 +00007013 RewriteCategorySetupInitHook(Result);
7014
Fariborz Jahaniandf795672012-02-17 00:06:14 +00007015 if (ClsDefCount > 0) {
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00007016 if (LangOpts.MicrosoftExt)
7017 Result += "__declspec(allocate(\".objc_classlist$B\")) ";
Fariborz Jahaniandf795672012-02-17 00:06:14 +00007018 Result += "static struct _class_t *L_OBJC_LABEL_CLASS_$ [";
7019 Result += llvm::utostr(ClsDefCount); Result += "]";
7020 Result +=
7021 " __attribute__((used, section (\"__DATA, __objc_classlist,"
7022 "regular,no_dead_strip\")))= {\n";
7023 for (int i = 0; i < ClsDefCount; i++) {
7024 Result += "\t&OBJC_CLASS_$_";
7025 Result += ClassImplementation[i]->getNameAsString();
7026 Result += ",\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007027 }
Fariborz Jahaniandf795672012-02-17 00:06:14 +00007028 Result += "};\n";
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00007029
7030 if (!DefinedNonLazyClasses.empty()) {
7031 if (LangOpts.MicrosoftExt)
7032 Result += "__declspec(allocate(\".objc_nlclslist$B\")) \n";
7033 Result += "static struct _class_t *_OBJC_LABEL_NONLAZY_CLASS_$[] = {\n\t";
7034 for (unsigned i = 0, e = DefinedNonLazyClasses.size(); i < e; i++) {
7035 Result += "\t&OBJC_CLASS_$_"; Result += DefinedNonLazyClasses[i]->getNameAsString();
7036 Result += ",\n";
7037 }
7038 Result += "};\n";
7039 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007040 }
Fariborz Jahanian61186122012-02-17 18:40:41 +00007041
7042 if (CatDefCount > 0) {
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00007043 if (LangOpts.MicrosoftExt)
7044 Result += "__declspec(allocate(\".objc_catlist$B\")) ";
Fariborz Jahanian61186122012-02-17 18:40:41 +00007045 Result += "static struct _category_t *L_OBJC_LABEL_CATEGORY_$ [";
7046 Result += llvm::utostr(CatDefCount); Result += "]";
7047 Result +=
7048 " __attribute__((used, section (\"__DATA, __objc_catlist,"
7049 "regular,no_dead_strip\")))= {\n";
7050 for (int i = 0; i < CatDefCount; i++) {
7051 Result += "\t&_OBJC_$_CATEGORY_";
7052 Result +=
7053 CategoryImplementation[i]->getClassInterface()->getNameAsString();
7054 Result += "_$_";
7055 Result += CategoryImplementation[i]->getNameAsString();
7056 Result += ",\n";
7057 }
7058 Result += "};\n";
7059 }
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00007060
7061 if (!DefinedNonLazyCategories.empty()) {
7062 if (LangOpts.MicrosoftExt)
7063 Result += "__declspec(allocate(\".objc_nlcatlist$B\")) \n";
7064 Result += "static struct _category_t *_OBJC_LABEL_NONLAZY_CATEGORY_$[] = {\n\t";
7065 for (unsigned i = 0, e = DefinedNonLazyCategories.size(); i < e; i++) {
7066 Result += "\t&_OBJC_$_CATEGORY_";
7067 Result +=
7068 DefinedNonLazyCategories[i]->getClassInterface()->getNameAsString();
7069 Result += "_$_";
7070 Result += DefinedNonLazyCategories[i]->getNameAsString();
7071 Result += ",\n";
7072 }
7073 Result += "};\n";
7074 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007075}
7076
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00007077void RewriteModernObjC::WriteImageInfo(std::string &Result) {
7078 if (LangOpts.MicrosoftExt)
7079 Result += "__declspec(allocate(\".objc_imageinfo$B\")) \n";
7080
7081 Result += "static struct IMAGE_INFO { unsigned version; unsigned flag; } ";
7082 // version 0, ObjCABI is 2
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00007083 Result += "_OBJC_IMAGE_INFO = { 0, 2 };\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00007084}
7085
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007086/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
7087/// implementation.
7088void RewriteModernObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
7089 std::string &Result) {
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00007090 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007091 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
7092 // Find category declaration for this implementation.
Fariborz Jahanian61186122012-02-17 18:40:41 +00007093 ObjCCategoryDecl *CDecl=0;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007094 for (CDecl = ClassDecl->getCategoryList(); CDecl;
7095 CDecl = CDecl->getNextClassCategory())
7096 if (CDecl->getIdentifier() == IDecl->getIdentifier())
7097 break;
7098
7099 std::string FullCategoryName = ClassDecl->getNameAsString();
Fariborz Jahanian61186122012-02-17 18:40:41 +00007100 FullCategoryName += "_$_";
7101 FullCategoryName += CDecl->getNameAsString();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007102
7103 // Build _objc_method_list for class's instance methods if needed
7104 SmallVector<ObjCMethodDecl *, 32>
7105 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
7106
7107 // If any of our property implementations have associated getters or
7108 // setters, produce metadata for them as well.
7109 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
7110 PropEnd = IDecl->propimpl_end();
7111 Prop != PropEnd; ++Prop) {
David Blaikie262bc182012-04-30 02:36:29 +00007112 if (Prop->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007113 continue;
David Blaikie262bc182012-04-30 02:36:29 +00007114 if (!Prop->getPropertyIvarDecl())
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007115 continue;
David Blaikie262bc182012-04-30 02:36:29 +00007116 ObjCPropertyDecl *PD = Prop->getPropertyDecl();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007117 if (!PD)
7118 continue;
7119 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
7120 InstanceMethods.push_back(Getter);
7121 if (PD->isReadOnly())
7122 continue;
7123 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
7124 InstanceMethods.push_back(Setter);
7125 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007126
Fariborz Jahanian61186122012-02-17 18:40:41 +00007127 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
7128 "_OBJC_$_CATEGORY_INSTANCE_METHODS_",
7129 FullCategoryName, true);
7130
7131 SmallVector<ObjCMethodDecl *, 32>
7132 ClassMethods(IDecl->classmeth_begin(), IDecl->classmeth_end());
7133
7134 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
7135 "_OBJC_$_CATEGORY_CLASS_METHODS_",
7136 FullCategoryName, true);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007137
7138 // Protocols referenced in class declaration?
Fariborz Jahanian61186122012-02-17 18:40:41 +00007139 // Protocol's super protocol list
7140 std::vector<ObjCProtocolDecl *> RefedProtocols;
Argyrios Kyrtzidisa5f44412012-03-13 01:09:41 +00007141 for (ObjCInterfaceDecl::protocol_iterator I = CDecl->protocol_begin(),
7142 E = CDecl->protocol_end();
7143
7144 I != E; ++I) {
Fariborz Jahanian61186122012-02-17 18:40:41 +00007145 RefedProtocols.push_back(*I);
7146 // Must write out all protocol definitions in current qualifier list,
7147 // and in their nested qualifiers before writing out current definition.
7148 RewriteObjCProtocolMetaData(*I, Result);
7149 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007150
Fariborz Jahanian61186122012-02-17 18:40:41 +00007151 Write_protocol_list_initializer(Context, Result,
7152 RefedProtocols,
7153 "_OBJC_CATEGORY_PROTOCOLS_$_",
7154 FullCategoryName);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007155
Fariborz Jahanian61186122012-02-17 18:40:41 +00007156 // Protocol's property metadata.
7157 std::vector<ObjCPropertyDecl *> ClassProperties;
7158 for (ObjCContainerDecl::prop_iterator I = CDecl->prop_begin(),
7159 E = CDecl->prop_end(); I != E; ++I)
David Blaikie262bc182012-04-30 02:36:29 +00007160 ClassProperties.push_back(&*I);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007161
Fariborz Jahanian61186122012-02-17 18:40:41 +00007162 Write_prop_list_t_initializer(*this, Context, Result, ClassProperties,
7163 /* Container */0,
7164 "_OBJC_$_PROP_LIST_",
7165 FullCategoryName);
7166
7167 Write_category_t(*this, Context, Result,
Fariborz Jahaniane0335782012-03-27 18:41:05 +00007168 CDecl,
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00007169 ClassDecl,
Fariborz Jahanian61186122012-02-17 18:40:41 +00007170 InstanceMethods,
7171 ClassMethods,
7172 RefedProtocols,
7173 ClassProperties);
7174
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00007175 // Determine if this category is also "non-lazy".
7176 if (ImplementationIsNonLazy(IDecl))
7177 DefinedNonLazyCategories.push_back(CDecl);
Fariborz Jahaniane0335782012-03-27 18:41:05 +00007178
7179}
7180
7181void RewriteModernObjC::RewriteCategorySetupInitHook(std::string &Result) {
7182 int CatDefCount = CategoryImplementation.size();
7183 if (!CatDefCount)
7184 return;
7185 Result += "#pragma section(\".objc_inithooks$B\", long, read, write)\n";
7186 Result += "__declspec(allocate(\".objc_inithooks$B\")) ";
7187 Result += "static void *OBJC_CATEGORY_SETUP[] = {\n";
7188 for (int i = 0; i < CatDefCount; i++) {
7189 ObjCCategoryImplDecl *IDecl = CategoryImplementation[i];
7190 ObjCCategoryDecl *CatDecl= IDecl->getCategoryDecl();
7191 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
7192 Result += "\t(void *)&OBJC_CATEGORY_SETUP_$_";
7193 Result += ClassDecl->getName();
7194 Result += "_$_";
7195 Result += CatDecl->getName();
7196 Result += ",\n";
7197 }
7198 Result += "};\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007199}
7200
7201// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
7202/// class methods.
7203template<typename MethodIterator>
7204void RewriteModernObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
7205 MethodIterator MethodEnd,
7206 bool IsInstanceMethod,
7207 StringRef prefix,
7208 StringRef ClassName,
7209 std::string &Result) {
7210 if (MethodBegin == MethodEnd) return;
7211
7212 if (!objc_impl_method) {
7213 /* struct _objc_method {
7214 SEL _cmd;
7215 char *method_types;
7216 void *_imp;
7217 }
7218 */
7219 Result += "\nstruct _objc_method {\n";
7220 Result += "\tSEL _cmd;\n";
7221 Result += "\tchar *method_types;\n";
7222 Result += "\tvoid *_imp;\n";
7223 Result += "};\n";
7224
7225 objc_impl_method = true;
7226 }
7227
7228 // Build _objc_method_list for class's methods if needed
7229
7230 /* struct {
7231 struct _objc_method_list *next_method;
7232 int method_count;
7233 struct _objc_method method_list[];
7234 }
7235 */
7236 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00007237 Result += "\n";
7238 if (LangOpts.MicrosoftExt) {
7239 if (IsInstanceMethod)
7240 Result += "__declspec(allocate(\".inst_meth$B\")) ";
7241 else
7242 Result += "__declspec(allocate(\".cls_meth$B\")) ";
7243 }
7244 Result += "static struct {\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007245 Result += "\tstruct _objc_method_list *next_method;\n";
7246 Result += "\tint method_count;\n";
7247 Result += "\tstruct _objc_method method_list[";
7248 Result += utostr(NumMethods);
7249 Result += "];\n} _OBJC_";
7250 Result += prefix;
7251 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
7252 Result += "_METHODS_";
7253 Result += ClassName;
7254 Result += " __attribute__ ((used, section (\"__OBJC, __";
7255 Result += IsInstanceMethod ? "inst" : "cls";
7256 Result += "_meth\")))= ";
7257 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
7258
7259 Result += "\t,{{(SEL)\"";
7260 Result += (*MethodBegin)->getSelector().getAsString().c_str();
7261 std::string MethodTypeString;
7262 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
7263 Result += "\", \"";
7264 Result += MethodTypeString;
7265 Result += "\", (void *)";
7266 Result += MethodInternalNames[*MethodBegin];
7267 Result += "}\n";
7268 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
7269 Result += "\t ,{(SEL)\"";
7270 Result += (*MethodBegin)->getSelector().getAsString().c_str();
7271 std::string MethodTypeString;
7272 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
7273 Result += "\", \"";
7274 Result += MethodTypeString;
7275 Result += "\", (void *)";
7276 Result += MethodInternalNames[*MethodBegin];
7277 Result += "}\n";
7278 }
7279 Result += "\t }\n};\n";
7280}
7281
7282Stmt *RewriteModernObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) {
7283 SourceRange OldRange = IV->getSourceRange();
7284 Expr *BaseExpr = IV->getBase();
7285
7286 // Rewrite the base, but without actually doing replaces.
7287 {
7288 DisableReplaceStmtScope S(*this);
7289 BaseExpr = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(BaseExpr));
7290 IV->setBase(BaseExpr);
7291 }
7292
7293 ObjCIvarDecl *D = IV->getDecl();
7294
7295 Expr *Replacement = IV;
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007296
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007297 if (BaseExpr->getType()->isObjCObjectPointerType()) {
7298 const ObjCInterfaceType *iFaceDecl =
7299 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
7300 assert(iFaceDecl && "RewriteObjCIvarRefExpr - iFaceDecl is null");
7301 // lookup which class implements the instance variable.
7302 ObjCInterfaceDecl *clsDeclared = 0;
7303 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
7304 clsDeclared);
7305 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
7306
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007307 // Build name of symbol holding ivar offset.
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00007308 std::string IvarOffsetName;
7309 WriteInternalIvarName(clsDeclared, D, IvarOffsetName);
7310
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00007311 ReferencedIvars[clsDeclared].insert(D);
7312
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007313 // cast offset to "char *".
7314 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context,
7315 Context->getPointerType(Context->CharTy),
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007316 CK_BitCast,
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007317 BaseExpr);
7318 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
7319 SourceLocation(), &Context->Idents.get(IvarOffsetName),
7320 Context->UnsignedLongTy, 0, SC_Extern, SC_None);
John McCallf4b88a42012-03-10 09:33:50 +00007321 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, false,
7322 Context->UnsignedLongTy, VK_LValue,
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007323 SourceLocation());
7324 BinaryOperator *addExpr =
7325 new (Context) BinaryOperator(castExpr, DRE, BO_Add,
7326 Context->getPointerType(Context->CharTy),
7327 VK_RValue, OK_Ordinary, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007328 // Don't forget the parens to enforce the proper binding.
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007329 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(),
7330 SourceLocation(),
7331 addExpr);
Fariborz Jahanian0d6e22a2012-02-24 17:35:35 +00007332 QualType IvarT = D->getType();
Fariborz Jahanian27fc81b2012-04-27 22:48:54 +00007333
Fariborz Jahanianf5eac482012-05-02 17:34:59 +00007334 if (!isa<TypedefType>(IvarT) && IvarT->isRecordType()) {
Fariborz Jahanian27fc81b2012-04-27 22:48:54 +00007335 RecordDecl *RD = IvarT->getAs<RecordType>()->getDecl();
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00007336 RD = RD->getDefinition();
7337 if (RD && !RD->getDeclName().getAsIdentifierInfo()) {
Fariborz Jahanian27fc81b2012-04-27 22:48:54 +00007338 // decltype(((Foo_IMPL*)0)->bar) *
Fariborz Jahanianf5eac482012-05-02 17:34:59 +00007339 ObjCContainerDecl *CDecl =
7340 dyn_cast<ObjCContainerDecl>(D->getDeclContext());
7341 // ivar in class extensions requires special treatment.
7342 if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(CDecl))
7343 CDecl = CatDecl->getClassInterface();
7344 std::string RecName = CDecl->getName();
Fariborz Jahanian27fc81b2012-04-27 22:48:54 +00007345 RecName += "_IMPL";
7346 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
7347 SourceLocation(), SourceLocation(),
7348 &Context->Idents.get(RecName.c_str()));
7349 QualType PtrStructIMPL = Context->getPointerType(Context->getTagDeclType(RD));
7350 unsigned UnsignedIntSize =
7351 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
7352 Expr *Zero = IntegerLiteral::Create(*Context,
7353 llvm::APInt(UnsignedIntSize, 0),
7354 Context->UnsignedIntTy, SourceLocation());
7355 Zero = NoTypeInfoCStyleCastExpr(Context, PtrStructIMPL, CK_BitCast, Zero);
7356 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
7357 Zero);
7358 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
7359 SourceLocation(),
7360 &Context->Idents.get(D->getNameAsString()),
7361 IvarT, 0,
7362 /*BitWidth=*/0, /*Mutable=*/true,
7363 /*HasInit=*/false);
7364 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
7365 FD->getType(), VK_LValue,
7366 OK_Ordinary);
7367 IvarT = Context->getDecltypeType(ME, ME->getType());
7368 }
7369 }
Fariborz Jahanian8e0913d2012-02-29 00:26:20 +00007370 convertObjCTypeToCStyleType(IvarT);
Fariborz Jahanian0d6e22a2012-02-24 17:35:35 +00007371 QualType castT = Context->getPointerType(IvarT);
Fariborz Jahanian27fc81b2012-04-27 22:48:54 +00007372
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007373 castExpr = NoTypeInfoCStyleCastExpr(Context,
7374 castT,
7375 CK_BitCast,
7376 PE);
Fariborz Jahanian27fc81b2012-04-27 22:48:54 +00007377
7378
Fariborz Jahanian8e0913d2012-02-29 00:26:20 +00007379 Expr *Exp = new (Context) UnaryOperator(castExpr, UO_Deref, IvarT,
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007380 VK_LValue, OK_Ordinary,
7381 SourceLocation());
7382 PE = new (Context) ParenExpr(OldRange.getBegin(),
7383 OldRange.getEnd(),
7384 Exp);
7385
7386 Replacement = PE;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007387 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007388
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007389 ReplaceStmtWithRange(IV, Replacement, OldRange);
7390 return Replacement;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007391}