blob: 66069766bb5ff9edbec22019f04ffb7737c79c16 [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
784void RewriteModernObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
785 ObjCImplementationDecl *IMD,
786 ObjCCategoryImplDecl *CID) {
787 static bool objcGetPropertyDefined = false;
788 static bool objcSetPropertyDefined = false;
789 SourceLocation startLoc = PID->getLocStart();
790 InsertText(startLoc, "// ");
791 const char *startBuf = SM->getCharacterData(startLoc);
792 assert((*startBuf == '@') && "bogus @synthesize location");
793 const char *semiBuf = strchr(startBuf, ';');
794 assert((*semiBuf == ';') && "@synthesize: can't find ';'");
795 SourceLocation onePastSemiLoc =
796 startLoc.getLocWithOffset(semiBuf-startBuf+1);
797
798 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
799 return; // FIXME: is this correct?
800
801 // Generate the 'getter' function.
802 ObjCPropertyDecl *PD = PID->getPropertyDecl();
803 ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
804
805 if (!OID)
806 return;
807 unsigned Attributes = PD->getPropertyAttributes();
808 if (!PD->getGetterMethodDecl()->isDefined()) {
809 bool GenGetProperty = !(Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic) &&
810 (Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
811 ObjCPropertyDecl::OBJC_PR_copy));
812 std::string Getr;
813 if (GenGetProperty && !objcGetPropertyDefined) {
814 objcGetPropertyDefined = true;
815 // FIXME. Is this attribute correct in all cases?
816 Getr = "\nextern \"C\" __declspec(dllimport) "
817 "id objc_getProperty(id, SEL, long, bool);\n";
818 }
819 RewriteObjCMethodDecl(OID->getContainingInterface(),
820 PD->getGetterMethodDecl(), Getr);
821 Getr += "{ ";
822 // Synthesize an explicit cast to gain access to the ivar.
823 // See objc-act.c:objc_synthesize_new_getter() for details.
824 if (GenGetProperty) {
825 // return objc_getProperty(self, _cmd, offsetof(ClassDecl, OID), 1)
826 Getr += "typedef ";
827 const FunctionType *FPRetType = 0;
828 RewriteTypeIntoString(PD->getGetterMethodDecl()->getResultType(), Getr,
829 FPRetType);
830 Getr += " _TYPE";
831 if (FPRetType) {
832 Getr += ")"; // close the precedence "scope" for "*".
833
834 // Now, emit the argument types (if any).
835 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)){
836 Getr += "(";
837 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
838 if (i) Getr += ", ";
839 std::string ParamStr = FT->getArgType(i).getAsString(
840 Context->getPrintingPolicy());
841 Getr += ParamStr;
842 }
843 if (FT->isVariadic()) {
844 if (FT->getNumArgs()) Getr += ", ";
845 Getr += "...";
846 }
847 Getr += ")";
848 } else
849 Getr += "()";
850 }
851 Getr += ";\n";
852 Getr += "return (_TYPE)";
853 Getr += "objc_getProperty(self, _cmd, ";
854 RewriteIvarOffsetComputation(OID, Getr);
855 Getr += ", 1)";
856 }
857 else
858 Getr += "return " + getIvarAccessString(OID);
859 Getr += "; }";
860 InsertText(onePastSemiLoc, Getr);
861 }
862
863 if (PD->isReadOnly() || PD->getSetterMethodDecl()->isDefined())
864 return;
865
866 // Generate the 'setter' function.
867 std::string Setr;
868 bool GenSetProperty = Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
869 ObjCPropertyDecl::OBJC_PR_copy);
870 if (GenSetProperty && !objcSetPropertyDefined) {
871 objcSetPropertyDefined = true;
872 // FIXME. Is this attribute correct in all cases?
873 Setr = "\nextern \"C\" __declspec(dllimport) "
874 "void objc_setProperty (id, SEL, long, id, bool, bool);\n";
875 }
876
877 RewriteObjCMethodDecl(OID->getContainingInterface(),
878 PD->getSetterMethodDecl(), Setr);
879 Setr += "{ ";
880 // Synthesize an explicit cast to initialize the ivar.
881 // See objc-act.c:objc_synthesize_new_setter() for details.
882 if (GenSetProperty) {
883 Setr += "objc_setProperty (self, _cmd, ";
884 RewriteIvarOffsetComputation(OID, Setr);
885 Setr += ", (id)";
886 Setr += PD->getName();
887 Setr += ", ";
888 if (Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic)
889 Setr += "0, ";
890 else
891 Setr += "1, ";
892 if (Attributes & ObjCPropertyDecl::OBJC_PR_copy)
893 Setr += "1)";
894 else
895 Setr += "0)";
896 }
897 else {
898 Setr += getIvarAccessString(OID) + " = ";
899 Setr += PD->getName();
900 }
901 Setr += "; }";
902 InsertText(onePastSemiLoc, Setr);
903}
904
905static void RewriteOneForwardClassDecl(ObjCInterfaceDecl *ForwardDecl,
906 std::string &typedefString) {
907 typedefString += "#ifndef _REWRITER_typedef_";
908 typedefString += ForwardDecl->getNameAsString();
909 typedefString += "\n";
910 typedefString += "#define _REWRITER_typedef_";
911 typedefString += ForwardDecl->getNameAsString();
912 typedefString += "\n";
913 typedefString += "typedef struct objc_object ";
914 typedefString += ForwardDecl->getNameAsString();
Fariborz Jahanianc38503b2012-03-12 23:58:28 +0000915 // typedef struct { } _objc_exc_Classname;
916 typedefString += ";\ntypedef struct {} _objc_exc_";
917 typedefString += ForwardDecl->getNameAsString();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000918 typedefString += ";\n#endif\n";
919}
920
921void RewriteModernObjC::RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
922 const std::string &typedefString) {
923 SourceLocation startLoc = ClassDecl->getLocStart();
924 const char *startBuf = SM->getCharacterData(startLoc);
925 const char *semiPtr = strchr(startBuf, ';');
926 // Replace the @class with typedefs corresponding to the classes.
927 ReplaceText(startLoc, semiPtr-startBuf+1, typedefString);
928}
929
930void RewriteModernObjC::RewriteForwardClassDecl(DeclGroupRef D) {
931 std::string typedefString;
932 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
933 ObjCInterfaceDecl *ForwardDecl = cast<ObjCInterfaceDecl>(*I);
934 if (I == D.begin()) {
935 // Translate to typedef's that forward reference structs with the same name
936 // as the class. As a convenience, we include the original declaration
937 // as a comment.
938 typedefString += "// @class ";
939 typedefString += ForwardDecl->getNameAsString();
940 typedefString += ";\n";
941 }
942 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
943 }
944 DeclGroupRef::iterator I = D.begin();
945 RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(*I), typedefString);
946}
947
948void RewriteModernObjC::RewriteForwardClassDecl(
949 const llvm::SmallVector<Decl*, 8> &D) {
950 std::string typedefString;
951 for (unsigned i = 0; i < D.size(); i++) {
952 ObjCInterfaceDecl *ForwardDecl = cast<ObjCInterfaceDecl>(D[i]);
953 if (i == 0) {
954 typedefString += "// @class ";
955 typedefString += ForwardDecl->getNameAsString();
956 typedefString += ";\n";
957 }
958 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
959 }
960 RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(D[0]), typedefString);
961}
962
963void RewriteModernObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
964 // When method is a synthesized one, such as a getter/setter there is
965 // nothing to rewrite.
966 if (Method->isImplicit())
967 return;
968 SourceLocation LocStart = Method->getLocStart();
969 SourceLocation LocEnd = Method->getLocEnd();
970
971 if (SM->getExpansionLineNumber(LocEnd) >
972 SM->getExpansionLineNumber(LocStart)) {
973 InsertText(LocStart, "#if 0\n");
974 ReplaceText(LocEnd, 1, ";\n#endif\n");
975 } else {
976 InsertText(LocStart, "// ");
977 }
978}
979
980void RewriteModernObjC::RewriteProperty(ObjCPropertyDecl *prop) {
981 SourceLocation Loc = prop->getAtLoc();
982
983 ReplaceText(Loc, 0, "// ");
984 // FIXME: handle properties that are declared across multiple lines.
985}
986
987void RewriteModernObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
988 SourceLocation LocStart = CatDecl->getLocStart();
989
990 // FIXME: handle category headers that are declared across multiple lines.
Fariborz Jahanianb68258f2012-05-01 17:46:45 +0000991 if (CatDecl->getIvarRBraceLoc().isValid()) {
992 ReplaceText(LocStart, 1, "/** ");
993 ReplaceText(CatDecl->getIvarRBraceLoc(), 1, "**/ ");
994 }
995 else {
Fariborz Jahaniand2aea122012-02-19 19:00:05 +0000996 ReplaceText(LocStart, 0, "// ");
Fariborz Jahanianb68258f2012-05-01 17:46:45 +0000997 }
Fariborz Jahanianaf300292012-02-20 20:09:20 +0000998
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000999 for (ObjCCategoryDecl::prop_iterator I = CatDecl->prop_begin(),
1000 E = CatDecl->prop_end(); I != E; ++I)
David Blaikie262bc182012-04-30 02:36:29 +00001001 RewriteProperty(&*I);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001002
1003 for (ObjCCategoryDecl::instmeth_iterator
1004 I = CatDecl->instmeth_begin(), E = CatDecl->instmeth_end();
1005 I != E; ++I)
1006 RewriteMethodDeclaration(*I);
1007 for (ObjCCategoryDecl::classmeth_iterator
1008 I = CatDecl->classmeth_begin(), E = CatDecl->classmeth_end();
1009 I != E; ++I)
1010 RewriteMethodDeclaration(*I);
1011
1012 // Lastly, comment out the @end.
1013 ReplaceText(CatDecl->getAtEndRange().getBegin(),
1014 strlen("@end"), "/* @end */");
1015}
1016
1017void RewriteModernObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
1018 SourceLocation LocStart = PDecl->getLocStart();
1019 assert(PDecl->isThisDeclarationADefinition());
1020
1021 // FIXME: handle protocol headers that are declared across multiple lines.
1022 ReplaceText(LocStart, 0, "// ");
1023
1024 for (ObjCProtocolDecl::instmeth_iterator
1025 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
1026 I != E; ++I)
1027 RewriteMethodDeclaration(*I);
1028 for (ObjCProtocolDecl::classmeth_iterator
1029 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
1030 I != E; ++I)
1031 RewriteMethodDeclaration(*I);
1032
1033 for (ObjCInterfaceDecl::prop_iterator I = PDecl->prop_begin(),
1034 E = PDecl->prop_end(); I != E; ++I)
David Blaikie262bc182012-04-30 02:36:29 +00001035 RewriteProperty(&*I);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001036
1037 // Lastly, comment out the @end.
1038 SourceLocation LocEnd = PDecl->getAtEndRange().getBegin();
1039 ReplaceText(LocEnd, strlen("@end"), "/* @end */");
1040
1041 // Must comment out @optional/@required
1042 const char *startBuf = SM->getCharacterData(LocStart);
1043 const char *endBuf = SM->getCharacterData(LocEnd);
1044 for (const char *p = startBuf; p < endBuf; p++) {
1045 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
1046 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
1047 ReplaceText(OptionalLoc, strlen("@optional"), "/* @optional */");
1048
1049 }
1050 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
1051 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
1052 ReplaceText(OptionalLoc, strlen("@required"), "/* @required */");
1053
1054 }
1055 }
1056}
1057
1058void RewriteModernObjC::RewriteForwardProtocolDecl(DeclGroupRef D) {
1059 SourceLocation LocStart = (*D.begin())->getLocStart();
1060 if (LocStart.isInvalid())
1061 llvm_unreachable("Invalid SourceLocation");
1062 // FIXME: handle forward protocol that are declared across multiple lines.
1063 ReplaceText(LocStart, 0, "// ");
1064}
1065
1066void
1067RewriteModernObjC::RewriteForwardProtocolDecl(const llvm::SmallVector<Decl*, 8> &DG) {
1068 SourceLocation LocStart = DG[0]->getLocStart();
1069 if (LocStart.isInvalid())
1070 llvm_unreachable("Invalid SourceLocation");
1071 // FIXME: handle forward protocol that are declared across multiple lines.
1072 ReplaceText(LocStart, 0, "// ");
1073}
1074
Fariborz Jahanianb3f904f2012-04-03 17:35:38 +00001075void
1076RewriteModernObjC::RewriteLinkageSpec(LinkageSpecDecl *LSD) {
1077 SourceLocation LocStart = LSD->getExternLoc();
1078 if (LocStart.isInvalid())
1079 llvm_unreachable("Invalid extern SourceLocation");
1080
1081 ReplaceText(LocStart, 0, "// ");
1082 if (!LSD->hasBraces())
1083 return;
1084 // FIXME. We don't rewrite well if '{' is not on same line as 'extern'.
1085 SourceLocation LocRBrace = LSD->getRBraceLoc();
1086 if (LocRBrace.isInvalid())
1087 llvm_unreachable("Invalid rbrace SourceLocation");
1088 ReplaceText(LocRBrace, 0, "// ");
1089}
1090
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001091void RewriteModernObjC::RewriteTypeIntoString(QualType T, std::string &ResultStr,
1092 const FunctionType *&FPRetType) {
1093 if (T->isObjCQualifiedIdType())
1094 ResultStr += "id";
1095 else if (T->isFunctionPointerType() ||
1096 T->isBlockPointerType()) {
1097 // needs special handling, since pointer-to-functions have special
1098 // syntax (where a decaration models use).
1099 QualType retType = T;
1100 QualType PointeeTy;
1101 if (const PointerType* PT = retType->getAs<PointerType>())
1102 PointeeTy = PT->getPointeeType();
1103 else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>())
1104 PointeeTy = BPT->getPointeeType();
1105 if ((FPRetType = PointeeTy->getAs<FunctionType>())) {
1106 ResultStr += FPRetType->getResultType().getAsString(
1107 Context->getPrintingPolicy());
1108 ResultStr += "(*";
1109 }
1110 } else
1111 ResultStr += T.getAsString(Context->getPrintingPolicy());
1112}
1113
1114void RewriteModernObjC::RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
1115 ObjCMethodDecl *OMD,
1116 std::string &ResultStr) {
1117 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
1118 const FunctionType *FPRetType = 0;
1119 ResultStr += "\nstatic ";
1120 RewriteTypeIntoString(OMD->getResultType(), ResultStr, FPRetType);
1121 ResultStr += " ";
1122
1123 // Unique method name
1124 std::string NameStr;
1125
1126 if (OMD->isInstanceMethod())
1127 NameStr += "_I_";
1128 else
1129 NameStr += "_C_";
1130
1131 NameStr += IDecl->getNameAsString();
1132 NameStr += "_";
1133
1134 if (ObjCCategoryImplDecl *CID =
1135 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
1136 NameStr += CID->getNameAsString();
1137 NameStr += "_";
1138 }
1139 // Append selector names, replacing ':' with '_'
1140 {
1141 std::string selString = OMD->getSelector().getAsString();
1142 int len = selString.size();
1143 for (int i = 0; i < len; i++)
1144 if (selString[i] == ':')
1145 selString[i] = '_';
1146 NameStr += selString;
1147 }
1148 // Remember this name for metadata emission
1149 MethodInternalNames[OMD] = NameStr;
1150 ResultStr += NameStr;
1151
1152 // Rewrite arguments
1153 ResultStr += "(";
1154
1155 // invisible arguments
1156 if (OMD->isInstanceMethod()) {
1157 QualType selfTy = Context->getObjCInterfaceType(IDecl);
1158 selfTy = Context->getPointerType(selfTy);
1159 if (!LangOpts.MicrosoftExt) {
1160 if (ObjCSynthesizedStructs.count(const_cast<ObjCInterfaceDecl*>(IDecl)))
1161 ResultStr += "struct ";
1162 }
1163 // When rewriting for Microsoft, explicitly omit the structure name.
1164 ResultStr += IDecl->getNameAsString();
1165 ResultStr += " *";
1166 }
1167 else
1168 ResultStr += Context->getObjCClassType().getAsString(
1169 Context->getPrintingPolicy());
1170
1171 ResultStr += " self, ";
1172 ResultStr += Context->getObjCSelType().getAsString(Context->getPrintingPolicy());
1173 ResultStr += " _cmd";
1174
1175 // Method arguments.
1176 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
1177 E = OMD->param_end(); PI != E; ++PI) {
1178 ParmVarDecl *PDecl = *PI;
1179 ResultStr += ", ";
1180 if (PDecl->getType()->isObjCQualifiedIdType()) {
1181 ResultStr += "id ";
1182 ResultStr += PDecl->getNameAsString();
1183 } else {
1184 std::string Name = PDecl->getNameAsString();
1185 QualType QT = PDecl->getType();
1186 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian2610f902012-03-27 16:42:20 +00001187 (void)convertBlockPointerToFunctionPointer(QT);
1188 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001189 ResultStr += Name;
1190 }
1191 }
1192 if (OMD->isVariadic())
1193 ResultStr += ", ...";
1194 ResultStr += ") ";
1195
1196 if (FPRetType) {
1197 ResultStr += ")"; // close the precedence "scope" for "*".
1198
1199 // Now, emit the argument types (if any).
1200 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
1201 ResultStr += "(";
1202 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
1203 if (i) ResultStr += ", ";
1204 std::string ParamStr = FT->getArgType(i).getAsString(
1205 Context->getPrintingPolicy());
1206 ResultStr += ParamStr;
1207 }
1208 if (FT->isVariadic()) {
1209 if (FT->getNumArgs()) ResultStr += ", ";
1210 ResultStr += "...";
1211 }
1212 ResultStr += ")";
1213 } else {
1214 ResultStr += "()";
1215 }
1216 }
1217}
1218void RewriteModernObjC::RewriteImplementationDecl(Decl *OID) {
1219 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
1220 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
1221
Fariborz Jahaniand2aea122012-02-19 19:00:05 +00001222 if (IMD) {
Fariborz Jahanianb68258f2012-05-01 17:46:45 +00001223 if (IMD->getIvarRBraceLoc().isValid()) {
1224 ReplaceText(IMD->getLocStart(), 1, "/** ");
1225 ReplaceText(IMD->getIvarRBraceLoc(), 1, "**/ ");
Fariborz Jahaniand2aea122012-02-19 19:00:05 +00001226 }
Fariborz Jahanianb68258f2012-05-01 17:46:45 +00001227 else {
1228 InsertText(IMD->getLocStart(), "// ");
1229 }
Fariborz Jahaniand2aea122012-02-19 19:00:05 +00001230 }
1231 else
1232 InsertText(CID->getLocStart(), "// ");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001233
1234 for (ObjCCategoryImplDecl::instmeth_iterator
1235 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
1236 E = IMD ? IMD->instmeth_end() : CID->instmeth_end();
1237 I != E; ++I) {
1238 std::string ResultStr;
1239 ObjCMethodDecl *OMD = *I;
1240 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
1241 SourceLocation LocStart = OMD->getLocStart();
1242 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
1243
1244 const char *startBuf = SM->getCharacterData(LocStart);
1245 const char *endBuf = SM->getCharacterData(LocEnd);
1246 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
1247 }
1248
1249 for (ObjCCategoryImplDecl::classmeth_iterator
1250 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
1251 E = IMD ? IMD->classmeth_end() : CID->classmeth_end();
1252 I != E; ++I) {
1253 std::string ResultStr;
1254 ObjCMethodDecl *OMD = *I;
1255 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
1256 SourceLocation LocStart = OMD->getLocStart();
1257 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
1258
1259 const char *startBuf = SM->getCharacterData(LocStart);
1260 const char *endBuf = SM->getCharacterData(LocEnd);
1261 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
1262 }
1263 for (ObjCCategoryImplDecl::propimpl_iterator
1264 I = IMD ? IMD->propimpl_begin() : CID->propimpl_begin(),
1265 E = IMD ? IMD->propimpl_end() : CID->propimpl_end();
1266 I != E; ++I) {
David Blaikie262bc182012-04-30 02:36:29 +00001267 RewritePropertyImplDecl(&*I, IMD, CID);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001268 }
1269
1270 InsertText(IMD ? IMD->getLocEnd() : CID->getLocEnd(), "// ");
1271}
1272
1273void RewriteModernObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00001274 // Do not synthesize more than once.
1275 if (ObjCSynthesizedStructs.count(ClassDecl))
1276 return;
1277 // Make sure super class's are written before current class is written.
1278 ObjCInterfaceDecl *SuperClass = ClassDecl->getSuperClass();
1279 while (SuperClass) {
1280 RewriteInterfaceDecl(SuperClass);
1281 SuperClass = SuperClass->getSuperClass();
1282 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001283 std::string ResultStr;
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +00001284 if (!ObjCWrittenInterfaces.count(ClassDecl->getCanonicalDecl())) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001285 // we haven't seen a forward decl - generate a typedef.
Fariborz Jahanianc38503b2012-03-12 23:58:28 +00001286 RewriteOneForwardClassDecl(ClassDecl, ResultStr);
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00001287 RewriteIvarOffsetSymbols(ClassDecl, ResultStr);
1288
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001289 RewriteObjCInternalStruct(ClassDecl, ResultStr);
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +00001290 // Mark this typedef as having been written into its c++ equivalent.
1291 ObjCWrittenInterfaces.insert(ClassDecl->getCanonicalDecl());
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001292
1293 for (ObjCInterfaceDecl::prop_iterator I = ClassDecl->prop_begin(),
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001294 E = ClassDecl->prop_end(); I != E; ++I)
David Blaikie262bc182012-04-30 02:36:29 +00001295 RewriteProperty(&*I);
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001296 for (ObjCInterfaceDecl::instmeth_iterator
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001297 I = ClassDecl->instmeth_begin(), E = ClassDecl->instmeth_end();
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001298 I != E; ++I)
1299 RewriteMethodDeclaration(*I);
1300 for (ObjCInterfaceDecl::classmeth_iterator
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001301 I = ClassDecl->classmeth_begin(), E = ClassDecl->classmeth_end();
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001302 I != E; ++I)
1303 RewriteMethodDeclaration(*I);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001304
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001305 // Lastly, comment out the @end.
1306 ReplaceText(ClassDecl->getAtEndRange().getBegin(), strlen("@end"),
1307 "/* @end */");
1308 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001309}
1310
1311Stmt *RewriteModernObjC::RewritePropertyOrImplicitSetter(PseudoObjectExpr *PseudoOp) {
1312 SourceRange OldRange = PseudoOp->getSourceRange();
1313
1314 // We just magically know some things about the structure of this
1315 // expression.
1316 ObjCMessageExpr *OldMsg =
1317 cast<ObjCMessageExpr>(PseudoOp->getSemanticExpr(
1318 PseudoOp->getNumSemanticExprs() - 1));
1319
1320 // Because the rewriter doesn't allow us to rewrite rewritten code,
1321 // we need to suppress rewriting the sub-statements.
Fariborz Jahanian88ec6102012-04-10 22:06:54 +00001322 Expr *Base;
1323 SmallVector<Expr*, 2> Args;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001324 {
1325 DisableReplaceStmtScope S(*this);
1326
1327 // Rebuild the base expression if we have one.
1328 Base = 0;
1329 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1330 Base = OldMsg->getInstanceReceiver();
1331 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1332 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1333 }
Fariborz Jahanian88ec6102012-04-10 22:06:54 +00001334
1335 unsigned numArgs = OldMsg->getNumArgs();
1336 for (unsigned i = 0; i < numArgs; i++) {
1337 Expr *Arg = OldMsg->getArg(i);
1338 if (isa<OpaqueValueExpr>(Arg))
1339 Arg = cast<OpaqueValueExpr>(Arg)->getSourceExpr();
1340 Arg = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Arg));
1341 Args.push_back(Arg);
1342 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001343 }
1344
1345 // TODO: avoid this copy.
1346 SmallVector<SourceLocation, 1> SelLocs;
1347 OldMsg->getSelectorLocs(SelLocs);
1348
1349 ObjCMessageExpr *NewMsg = 0;
1350 switch (OldMsg->getReceiverKind()) {
1351 case ObjCMessageExpr::Class:
1352 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1353 OldMsg->getValueKind(),
1354 OldMsg->getLeftLoc(),
1355 OldMsg->getClassReceiverTypeInfo(),
1356 OldMsg->getSelector(),
1357 SelLocs,
1358 OldMsg->getMethodDecl(),
Fariborz Jahanian88ec6102012-04-10 22:06:54 +00001359 Args,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001360 OldMsg->getRightLoc(),
1361 OldMsg->isImplicit());
1362 break;
1363
1364 case ObjCMessageExpr::Instance:
1365 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1366 OldMsg->getValueKind(),
1367 OldMsg->getLeftLoc(),
1368 Base,
1369 OldMsg->getSelector(),
1370 SelLocs,
1371 OldMsg->getMethodDecl(),
Fariborz Jahanian88ec6102012-04-10 22:06:54 +00001372 Args,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001373 OldMsg->getRightLoc(),
1374 OldMsg->isImplicit());
1375 break;
1376
1377 case ObjCMessageExpr::SuperClass:
1378 case ObjCMessageExpr::SuperInstance:
1379 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1380 OldMsg->getValueKind(),
1381 OldMsg->getLeftLoc(),
1382 OldMsg->getSuperLoc(),
1383 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1384 OldMsg->getSuperType(),
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
1394 Stmt *Replacement = SynthMessageExpr(NewMsg);
1395 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1396 return Replacement;
1397}
1398
1399Stmt *RewriteModernObjC::RewritePropertyOrImplicitGetter(PseudoObjectExpr *PseudoOp) {
1400 SourceRange OldRange = PseudoOp->getSourceRange();
1401
1402 // We just magically know some things about the structure of this
1403 // expression.
1404 ObjCMessageExpr *OldMsg =
1405 cast<ObjCMessageExpr>(PseudoOp->getResultExpr()->IgnoreImplicit());
1406
1407 // Because the rewriter doesn't allow us to rewrite rewritten code,
1408 // we need to suppress rewriting the sub-statements.
1409 Expr *Base = 0;
Fariborz Jahanian88ec6102012-04-10 22:06:54 +00001410 SmallVector<Expr*, 1> Args;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001411 {
1412 DisableReplaceStmtScope S(*this);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001413 // Rebuild the base expression if we have one.
1414 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1415 Base = OldMsg->getInstanceReceiver();
1416 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1417 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1418 }
Fariborz Jahanian88ec6102012-04-10 22:06:54 +00001419 unsigned numArgs = OldMsg->getNumArgs();
1420 for (unsigned i = 0; i < numArgs; i++) {
1421 Expr *Arg = OldMsg->getArg(i);
1422 if (isa<OpaqueValueExpr>(Arg))
1423 Arg = cast<OpaqueValueExpr>(Arg)->getSourceExpr();
1424 Arg = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Arg));
1425 Args.push_back(Arg);
1426 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001427 }
1428
1429 // Intentionally empty.
1430 SmallVector<SourceLocation, 1> SelLocs;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001431
1432 ObjCMessageExpr *NewMsg = 0;
1433 switch (OldMsg->getReceiverKind()) {
1434 case ObjCMessageExpr::Class:
1435 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1436 OldMsg->getValueKind(),
1437 OldMsg->getLeftLoc(),
1438 OldMsg->getClassReceiverTypeInfo(),
1439 OldMsg->getSelector(),
1440 SelLocs,
1441 OldMsg->getMethodDecl(),
1442 Args,
1443 OldMsg->getRightLoc(),
1444 OldMsg->isImplicit());
1445 break;
1446
1447 case ObjCMessageExpr::Instance:
1448 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1449 OldMsg->getValueKind(),
1450 OldMsg->getLeftLoc(),
1451 Base,
1452 OldMsg->getSelector(),
1453 SelLocs,
1454 OldMsg->getMethodDecl(),
1455 Args,
1456 OldMsg->getRightLoc(),
1457 OldMsg->isImplicit());
1458 break;
1459
1460 case ObjCMessageExpr::SuperClass:
1461 case ObjCMessageExpr::SuperInstance:
1462 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1463 OldMsg->getValueKind(),
1464 OldMsg->getLeftLoc(),
1465 OldMsg->getSuperLoc(),
1466 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1467 OldMsg->getSuperType(),
1468 OldMsg->getSelector(),
1469 SelLocs,
1470 OldMsg->getMethodDecl(),
1471 Args,
1472 OldMsg->getRightLoc(),
1473 OldMsg->isImplicit());
1474 break;
1475 }
1476
1477 Stmt *Replacement = SynthMessageExpr(NewMsg);
1478 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1479 return Replacement;
1480}
1481
1482/// SynthCountByEnumWithState - To print:
1483/// ((unsigned int (*)
1484/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1485/// (void *)objc_msgSend)((id)l_collection,
1486/// sel_registerName(
1487/// "countByEnumeratingWithState:objects:count:"),
1488/// &enumState,
1489/// (id *)__rw_items, (unsigned int)16)
1490///
1491void RewriteModernObjC::SynthCountByEnumWithState(std::string &buf) {
1492 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1493 "id *, unsigned int))(void *)objc_msgSend)";
1494 buf += "\n\t\t";
1495 buf += "((id)l_collection,\n\t\t";
1496 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1497 buf += "\n\t\t";
1498 buf += "&enumState, "
1499 "(id *)__rw_items, (unsigned int)16)";
1500}
1501
1502/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1503/// statement to exit to its outer synthesized loop.
1504///
1505Stmt *RewriteModernObjC::RewriteBreakStmt(BreakStmt *S) {
1506 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1507 return S;
1508 // replace break with goto __break_label
1509 std::string buf;
1510
1511 SourceLocation startLoc = S->getLocStart();
1512 buf = "goto __break_label_";
1513 buf += utostr(ObjCBcLabelNo.back());
1514 ReplaceText(startLoc, strlen("break"), buf);
1515
1516 return 0;
1517}
1518
1519/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1520/// statement to continue with its inner synthesized loop.
1521///
1522Stmt *RewriteModernObjC::RewriteContinueStmt(ContinueStmt *S) {
1523 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1524 return S;
1525 // replace continue with goto __continue_label
1526 std::string buf;
1527
1528 SourceLocation startLoc = S->getLocStart();
1529 buf = "goto __continue_label_";
1530 buf += utostr(ObjCBcLabelNo.back());
1531 ReplaceText(startLoc, strlen("continue"), buf);
1532
1533 return 0;
1534}
1535
1536/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
1537/// It rewrites:
1538/// for ( type elem in collection) { stmts; }
1539
1540/// Into:
1541/// {
1542/// type elem;
1543/// struct __objcFastEnumerationState enumState = { 0 };
1544/// id __rw_items[16];
1545/// id l_collection = (id)collection;
1546/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1547/// objects:__rw_items count:16];
1548/// if (limit) {
1549/// unsigned long startMutations = *enumState.mutationsPtr;
1550/// do {
1551/// unsigned long counter = 0;
1552/// do {
1553/// if (startMutations != *enumState.mutationsPtr)
1554/// objc_enumerationMutation(l_collection);
1555/// elem = (type)enumState.itemsPtr[counter++];
1556/// stmts;
1557/// __continue_label: ;
1558/// } while (counter < limit);
1559/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1560/// objects:__rw_items count:16]);
1561/// elem = nil;
1562/// __break_label: ;
1563/// }
1564/// else
1565/// elem = nil;
1566/// }
1567///
1568Stmt *RewriteModernObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
1569 SourceLocation OrigEnd) {
1570 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
1571 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
1572 "ObjCForCollectionStmt Statement stack mismatch");
1573 assert(!ObjCBcLabelNo.empty() &&
1574 "ObjCForCollectionStmt - Label No stack empty");
1575
1576 SourceLocation startLoc = S->getLocStart();
1577 const char *startBuf = SM->getCharacterData(startLoc);
1578 StringRef elementName;
1579 std::string elementTypeAsString;
1580 std::string buf;
1581 buf = "\n{\n\t";
1582 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1583 // type elem;
1584 NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
1585 QualType ElementType = cast<ValueDecl>(D)->getType();
1586 if (ElementType->isObjCQualifiedIdType() ||
1587 ElementType->isObjCQualifiedInterfaceType())
1588 // Simply use 'id' for all qualified types.
1589 elementTypeAsString = "id";
1590 else
1591 elementTypeAsString = ElementType.getAsString(Context->getPrintingPolicy());
1592 buf += elementTypeAsString;
1593 buf += " ";
1594 elementName = D->getName();
1595 buf += elementName;
1596 buf += ";\n\t";
1597 }
1598 else {
1599 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
1600 elementName = DR->getDecl()->getName();
1601 ValueDecl *VD = cast<ValueDecl>(DR->getDecl());
1602 if (VD->getType()->isObjCQualifiedIdType() ||
1603 VD->getType()->isObjCQualifiedInterfaceType())
1604 // Simply use 'id' for all qualified types.
1605 elementTypeAsString = "id";
1606 else
1607 elementTypeAsString = VD->getType().getAsString(Context->getPrintingPolicy());
1608 }
1609
1610 // struct __objcFastEnumerationState enumState = { 0 };
1611 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1612 // id __rw_items[16];
1613 buf += "id __rw_items[16];\n\t";
1614 // id l_collection = (id)
1615 buf += "id l_collection = (id)";
1616 // Find start location of 'collection' the hard way!
1617 const char *startCollectionBuf = startBuf;
1618 startCollectionBuf += 3; // skip 'for'
1619 startCollectionBuf = strchr(startCollectionBuf, '(');
1620 startCollectionBuf++; // skip '('
1621 // find 'in' and skip it.
1622 while (*startCollectionBuf != ' ' ||
1623 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1624 (*(startCollectionBuf+3) != ' ' &&
1625 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1626 startCollectionBuf++;
1627 startCollectionBuf += 3;
1628
1629 // Replace: "for (type element in" with string constructed thus far.
1630 ReplaceText(startLoc, startCollectionBuf - startBuf, buf);
1631 // Replace ')' in for '(' type elem in collection ')' with ';'
1632 SourceLocation rightParenLoc = S->getRParenLoc();
1633 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1634 SourceLocation lparenLoc = startLoc.getLocWithOffset(rparenBuf-startBuf);
1635 buf = ";\n\t";
1636
1637 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1638 // objects:__rw_items count:16];
1639 // which is synthesized into:
1640 // unsigned int limit =
1641 // ((unsigned int (*)
1642 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1643 // (void *)objc_msgSend)((id)l_collection,
1644 // sel_registerName(
1645 // "countByEnumeratingWithState:objects:count:"),
1646 // (struct __objcFastEnumerationState *)&state,
1647 // (id *)__rw_items, (unsigned int)16);
1648 buf += "unsigned long limit =\n\t\t";
1649 SynthCountByEnumWithState(buf);
1650 buf += ";\n\t";
1651 /// if (limit) {
1652 /// unsigned long startMutations = *enumState.mutationsPtr;
1653 /// do {
1654 /// unsigned long counter = 0;
1655 /// do {
1656 /// if (startMutations != *enumState.mutationsPtr)
1657 /// objc_enumerationMutation(l_collection);
1658 /// elem = (type)enumState.itemsPtr[counter++];
1659 buf += "if (limit) {\n\t";
1660 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1661 buf += "do {\n\t\t";
1662 buf += "unsigned long counter = 0;\n\t\t";
1663 buf += "do {\n\t\t\t";
1664 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1665 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1666 buf += elementName;
1667 buf += " = (";
1668 buf += elementTypeAsString;
1669 buf += ")enumState.itemsPtr[counter++];";
1670 // Replace ')' in for '(' type elem in collection ')' with all of these.
1671 ReplaceText(lparenLoc, 1, buf);
1672
1673 /// __continue_label: ;
1674 /// } while (counter < limit);
1675 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1676 /// objects:__rw_items count:16]);
1677 /// elem = nil;
1678 /// __break_label: ;
1679 /// }
1680 /// else
1681 /// elem = nil;
1682 /// }
1683 ///
1684 buf = ";\n\t";
1685 buf += "__continue_label_";
1686 buf += utostr(ObjCBcLabelNo.back());
1687 buf += ": ;";
1688 buf += "\n\t\t";
1689 buf += "} while (counter < limit);\n\t";
1690 buf += "} while (limit = ";
1691 SynthCountByEnumWithState(buf);
1692 buf += ");\n\t";
1693 buf += elementName;
1694 buf += " = ((";
1695 buf += elementTypeAsString;
1696 buf += ")0);\n\t";
1697 buf += "__break_label_";
1698 buf += utostr(ObjCBcLabelNo.back());
1699 buf += ": ;\n\t";
1700 buf += "}\n\t";
1701 buf += "else\n\t\t";
1702 buf += elementName;
1703 buf += " = ((";
1704 buf += elementTypeAsString;
1705 buf += ")0);\n\t";
1706 buf += "}\n";
1707
1708 // Insert all these *after* the statement body.
1709 // FIXME: If this should support Obj-C++, support CXXTryStmt
1710 if (isa<CompoundStmt>(S->getBody())) {
1711 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(1);
1712 InsertText(endBodyLoc, buf);
1713 } else {
1714 /* Need to treat single statements specially. For example:
1715 *
1716 * for (A *a in b) if (stuff()) break;
1717 * for (A *a in b) xxxyy;
1718 *
1719 * The following code simply scans ahead to the semi to find the actual end.
1720 */
1721 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1722 const char *semiBuf = strchr(stmtBuf, ';');
1723 assert(semiBuf && "Can't find ';'");
1724 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(semiBuf-stmtBuf+1);
1725 InsertText(endBodyLoc, buf);
1726 }
1727 Stmts.pop_back();
1728 ObjCBcLabelNo.pop_back();
1729 return 0;
1730}
1731
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001732static void Write_RethrowObject(std::string &buf) {
1733 buf += "{ struct _FIN { _FIN(id reth) : rethrow(reth) {}\n";
1734 buf += "\t~_FIN() { if (rethrow) objc_exception_throw(rethrow); }\n";
1735 buf += "\tid rethrow;\n";
1736 buf += "\t} _fin_force_rethow(_rethrow);";
1737}
1738
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001739/// RewriteObjCSynchronizedStmt -
1740/// This routine rewrites @synchronized(expr) stmt;
1741/// into:
1742/// objc_sync_enter(expr);
1743/// @try stmt @finally { objc_sync_exit(expr); }
1744///
1745Stmt *RewriteModernObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
1746 // Get the start location and compute the semi location.
1747 SourceLocation startLoc = S->getLocStart();
1748 const char *startBuf = SM->getCharacterData(startLoc);
1749
1750 assert((*startBuf == '@') && "bogus @synchronized location");
1751
1752 std::string buf;
Fariborz Jahanian22e2f852012-03-17 17:46:02 +00001753 buf = "{ id _rethrow = 0; id _sync_obj = ";
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001754
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001755 const char *lparenBuf = startBuf;
1756 while (*lparenBuf != '(') lparenBuf++;
1757 ReplaceText(startLoc, lparenBuf-startBuf+1, buf);
Fariborz Jahanian22e2f852012-03-17 17:46:02 +00001758
1759 buf = "; objc_sync_enter(_sync_obj);\n";
1760 buf += "try {\n\tstruct _SYNC_EXIT { _SYNC_EXIT(id arg) : sync_exit(arg) {}";
1761 buf += "\n\t~_SYNC_EXIT() {objc_sync_exit(sync_exit);}";
1762 buf += "\n\tid sync_exit;";
1763 buf += "\n\t} _sync_exit(_sync_obj);\n";
1764
1765 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1766 // the sync expression is typically a message expression that's already
1767 // been rewritten! (which implies the SourceLocation's are invalid).
1768 SourceLocation RParenExprLoc = S->getSynchBody()->getLocStart();
1769 const char *RParenExprLocBuf = SM->getCharacterData(RParenExprLoc);
1770 while (*RParenExprLocBuf != ')') RParenExprLocBuf--;
1771 RParenExprLoc = startLoc.getLocWithOffset(RParenExprLocBuf-startBuf);
1772
1773 SourceLocation LBranceLoc = S->getSynchBody()->getLocStart();
1774 const char *LBraceLocBuf = SM->getCharacterData(LBranceLoc);
1775 assert (*LBraceLocBuf == '{');
1776 ReplaceText(RParenExprLoc, (LBraceLocBuf - SM->getCharacterData(RParenExprLoc) + 1), buf);
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001777
Fariborz Jahanianb655bf02012-03-16 21:43:45 +00001778 SourceLocation startRBraceLoc = S->getSynchBody()->getLocEnd();
Matt Beaumont-Gay9ab511c2012-03-16 22:20:39 +00001779 assert((*SM->getCharacterData(startRBraceLoc) == '}') &&
1780 "bogus @synchronized block");
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001781
1782 buf = "} catch (id e) {_rethrow = e;}\n";
1783 Write_RethrowObject(buf);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001784 buf += "}\n";
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001785 buf += "}\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001786
Fariborz Jahanianb655bf02012-03-16 21:43:45 +00001787 ReplaceText(startRBraceLoc, 1, buf);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001788
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001789 return 0;
1790}
1791
1792void RewriteModernObjC::WarnAboutReturnGotoStmts(Stmt *S)
1793{
1794 // Perform a bottom up traversal of all children.
1795 for (Stmt::child_range CI = S->children(); CI; ++CI)
1796 if (*CI)
1797 WarnAboutReturnGotoStmts(*CI);
1798
1799 if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
1800 Diags.Report(Context->getFullLoc(S->getLocStart()),
1801 TryFinallyContainsReturnDiag);
1802 }
1803 return;
1804}
1805
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001806Stmt *RewriteModernObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Fariborz Jahanianb1228182012-03-15 22:42:15 +00001807 ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt();
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001808 bool noCatch = S->getNumCatchStmts() == 0;
Fariborz Jahanianb1228182012-03-15 22:42:15 +00001809 std::string buf;
1810
1811 if (finalStmt) {
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001812 if (noCatch)
1813 buf = "{ id volatile _rethrow = 0;\n";
1814 else {
1815 buf = "{ id volatile _rethrow = 0;\ntry {\n";
1816 }
Fariborz Jahanianb1228182012-03-15 22:42:15 +00001817 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001818 // Get the start location and compute the semi location.
1819 SourceLocation startLoc = S->getLocStart();
1820 const char *startBuf = SM->getCharacterData(startLoc);
1821
1822 assert((*startBuf == '@') && "bogus @try location");
Fariborz Jahanianb1228182012-03-15 22:42:15 +00001823 if (finalStmt)
1824 ReplaceText(startLoc, 1, buf);
1825 else
1826 // @try -> try
1827 ReplaceText(startLoc, 1, "");
1828
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001829 for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I) {
1830 ObjCAtCatchStmt *Catch = S->getCatchStmt(I);
Fariborz Jahanian4c148812012-03-15 20:11:10 +00001831 VarDecl *catchDecl = Catch->getCatchParamDecl();
Fariborz Jahanianc38503b2012-03-12 23:58:28 +00001832
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001833 startLoc = Catch->getLocStart();
Fariborz Jahanian4c148812012-03-15 20:11:10 +00001834 bool AtRemoved = false;
1835 if (catchDecl) {
1836 QualType t = catchDecl->getType();
1837 if (const ObjCObjectPointerType *Ptr = t->getAs<ObjCObjectPointerType>()) {
1838 // Should be a pointer to a class.
1839 ObjCInterfaceDecl *IDecl = Ptr->getObjectType()->getInterface();
1840 if (IDecl) {
1841 std::string Result;
1842 startBuf = SM->getCharacterData(startLoc);
1843 assert((*startBuf == '@') && "bogus @catch location");
1844 SourceLocation rParenLoc = Catch->getRParenLoc();
1845 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1846
1847 // _objc_exc_Foo *_e as argument to catch.
1848 Result = "catch (_objc_exc_"; Result += IDecl->getNameAsString();
1849 Result += " *_"; Result += catchDecl->getNameAsString();
1850 Result += ")";
1851 ReplaceText(startLoc, rParenBuf-startBuf+1, Result);
1852 // Foo *e = (Foo *)_e;
1853 Result.clear();
1854 Result = "{ ";
1855 Result += IDecl->getNameAsString();
1856 Result += " *"; Result += catchDecl->getNameAsString();
1857 Result += " = ("; Result += IDecl->getNameAsString(); Result += "*)";
1858 Result += "_"; Result += catchDecl->getNameAsString();
1859
1860 Result += "; ";
1861 SourceLocation lBraceLoc = Catch->getCatchBody()->getLocStart();
1862 ReplaceText(lBraceLoc, 1, Result);
1863 AtRemoved = true;
1864 }
1865 }
1866 }
1867 if (!AtRemoved)
1868 // @catch -> catch
1869 ReplaceText(startLoc, 1, "");
Fariborz Jahanianc38503b2012-03-12 23:58:28 +00001870
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001871 }
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001872 if (finalStmt) {
1873 buf.clear();
1874 if (noCatch)
1875 buf = "catch (id e) {_rethrow = e;}\n";
1876 else
1877 buf = "}\ncatch (id e) {_rethrow = e;}\n";
1878
1879 SourceLocation startFinalLoc = finalStmt->getLocStart();
1880 ReplaceText(startFinalLoc, 8, buf);
1881 Stmt *body = finalStmt->getFinallyBody();
1882 SourceLocation startFinalBodyLoc = body->getLocStart();
1883 buf.clear();
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001884 Write_RethrowObject(buf);
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001885 ReplaceText(startFinalBodyLoc, 1, buf);
1886
1887 SourceLocation endFinalBodyLoc = body->getLocEnd();
1888 ReplaceText(endFinalBodyLoc, 1, "}\n}");
Fariborz Jahanian22e2f852012-03-17 17:46:02 +00001889 // Now check for any return/continue/go statements within the @try.
1890 WarnAboutReturnGotoStmts(S->getTryBody());
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001891 }
1892
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001893 return 0;
1894}
1895
1896// This can't be done with ReplaceStmt(S, ThrowExpr), since
1897// the throw expression is typically a message expression that's already
1898// been rewritten! (which implies the SourceLocation's are invalid).
1899Stmt *RewriteModernObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
1900 // Get the start location and compute the semi location.
1901 SourceLocation startLoc = S->getLocStart();
1902 const char *startBuf = SM->getCharacterData(startLoc);
1903
1904 assert((*startBuf == '@') && "bogus @throw location");
1905
1906 std::string buf;
1907 /* void objc_exception_throw(id) __attribute__((noreturn)); */
1908 if (S->getThrowExpr())
1909 buf = "objc_exception_throw(";
Fariborz Jahanian40539462012-03-16 16:52:06 +00001910 else
1911 buf = "throw";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001912
1913 // handle "@ throw" correctly.
1914 const char *wBuf = strchr(startBuf, 'w');
1915 assert((*wBuf == 'w') && "@throw: can't find 'w'");
1916 ReplaceText(startLoc, wBuf-startBuf+1, buf);
1917
1918 const char *semiBuf = strchr(startBuf, ';');
1919 assert((*semiBuf == ';') && "@throw: can't find ';'");
1920 SourceLocation semiLoc = startLoc.getLocWithOffset(semiBuf-startBuf);
Fariborz Jahanian40539462012-03-16 16:52:06 +00001921 if (S->getThrowExpr())
1922 ReplaceText(semiLoc, 1, ");");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001923 return 0;
1924}
1925
1926Stmt *RewriteModernObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
1927 // Create a new string expression.
1928 QualType StrType = Context->getPointerType(Context->CharTy);
1929 std::string StrEncoding;
1930 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
1931 Expr *Replacement = StringLiteral::Create(*Context, StrEncoding,
1932 StringLiteral::Ascii, false,
1933 StrType, SourceLocation());
1934 ReplaceStmt(Exp, Replacement);
1935
1936 // Replace this subexpr in the parent.
1937 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
1938 return Replacement;
1939}
1940
1941Stmt *RewriteModernObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
1942 if (!SelGetUidFunctionDecl)
1943 SynthSelGetUidFunctionDecl();
1944 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
1945 // Create a call to sel_registerName("selName").
1946 SmallVector<Expr*, 8> SelExprs;
1947 QualType argType = Context->getPointerType(Context->CharTy);
1948 SelExprs.push_back(StringLiteral::Create(*Context,
1949 Exp->getSelector().getAsString(),
1950 StringLiteral::Ascii, false,
1951 argType, SourceLocation()));
1952 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1953 &SelExprs[0], SelExprs.size());
1954 ReplaceStmt(Exp, SelExp);
1955 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
1956 return SelExp;
1957}
1958
1959CallExpr *RewriteModernObjC::SynthesizeCallToFunctionDecl(
1960 FunctionDecl *FD, Expr **args, unsigned nargs, SourceLocation StartLoc,
1961 SourceLocation EndLoc) {
1962 // Get the type, we will need to reference it in a couple spots.
1963 QualType msgSendType = FD->getType();
1964
1965 // Create a reference to the objc_msgSend() declaration.
1966 DeclRefExpr *DRE =
John McCallf4b88a42012-03-10 09:33:50 +00001967 new (Context) DeclRefExpr(FD, false, msgSendType, VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001968
1969 // Now, we cast the reference to a pointer to the objc_msgSend type.
1970 QualType pToFunc = Context->getPointerType(msgSendType);
1971 ImplicitCastExpr *ICE =
1972 ImplicitCastExpr::Create(*Context, pToFunc, CK_FunctionToPointerDecay,
1973 DRE, 0, VK_RValue);
1974
1975 const FunctionType *FT = msgSendType->getAs<FunctionType>();
1976
1977 CallExpr *Exp =
1978 new (Context) CallExpr(*Context, ICE, args, nargs,
1979 FT->getCallResultType(*Context),
1980 VK_RValue, EndLoc);
1981 return Exp;
1982}
1983
1984static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
1985 const char *&startRef, const char *&endRef) {
1986 while (startBuf < endBuf) {
1987 if (*startBuf == '<')
1988 startRef = startBuf; // mark the start.
1989 if (*startBuf == '>') {
1990 if (startRef && *startRef == '<') {
1991 endRef = startBuf; // mark the end.
1992 return true;
1993 }
1994 return false;
1995 }
1996 startBuf++;
1997 }
1998 return false;
1999}
2000
2001static void scanToNextArgument(const char *&argRef) {
2002 int angle = 0;
2003 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
2004 if (*argRef == '<')
2005 angle++;
2006 else if (*argRef == '>')
2007 angle--;
2008 argRef++;
2009 }
2010 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
2011}
2012
2013bool RewriteModernObjC::needToScanForQualifiers(QualType T) {
2014 if (T->isObjCQualifiedIdType())
2015 return true;
2016 if (const PointerType *PT = T->getAs<PointerType>()) {
2017 if (PT->getPointeeType()->isObjCQualifiedIdType())
2018 return true;
2019 }
2020 if (T->isObjCObjectPointerType()) {
2021 T = T->getPointeeType();
2022 return T->isObjCQualifiedInterfaceType();
2023 }
2024 if (T->isArrayType()) {
2025 QualType ElemTy = Context->getBaseElementType(T);
2026 return needToScanForQualifiers(ElemTy);
2027 }
2028 return false;
2029}
2030
2031void RewriteModernObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
2032 QualType Type = E->getType();
2033 if (needToScanForQualifiers(Type)) {
2034 SourceLocation Loc, EndLoc;
2035
2036 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
2037 Loc = ECE->getLParenLoc();
2038 EndLoc = ECE->getRParenLoc();
2039 } else {
2040 Loc = E->getLocStart();
2041 EndLoc = E->getLocEnd();
2042 }
2043 // This will defend against trying to rewrite synthesized expressions.
2044 if (Loc.isInvalid() || EndLoc.isInvalid())
2045 return;
2046
2047 const char *startBuf = SM->getCharacterData(Loc);
2048 const char *endBuf = SM->getCharacterData(EndLoc);
2049 const char *startRef = 0, *endRef = 0;
2050 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2051 // Get the locations of the startRef, endRef.
2052 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-startBuf);
2053 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-startBuf+1);
2054 // Comment out the protocol references.
2055 InsertText(LessLoc, "/*");
2056 InsertText(GreaterLoc, "*/");
2057 }
2058 }
2059}
2060
2061void RewriteModernObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
2062 SourceLocation Loc;
2063 QualType Type;
2064 const FunctionProtoType *proto = 0;
2065 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
2066 Loc = VD->getLocation();
2067 Type = VD->getType();
2068 }
2069 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
2070 Loc = FD->getLocation();
2071 // Check for ObjC 'id' and class types that have been adorned with protocol
2072 // information (id<p>, C<p>*). The protocol references need to be rewritten!
2073 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2074 assert(funcType && "missing function type");
2075 proto = dyn_cast<FunctionProtoType>(funcType);
2076 if (!proto)
2077 return;
2078 Type = proto->getResultType();
2079 }
2080 else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
2081 Loc = FD->getLocation();
2082 Type = FD->getType();
2083 }
2084 else
2085 return;
2086
2087 if (needToScanForQualifiers(Type)) {
2088 // Since types are unique, we need to scan the buffer.
2089
2090 const char *endBuf = SM->getCharacterData(Loc);
2091 const char *startBuf = endBuf;
2092 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
2093 startBuf--; // scan backward (from the decl location) for return type.
2094 const char *startRef = 0, *endRef = 0;
2095 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2096 // Get the locations of the startRef, endRef.
2097 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-endBuf);
2098 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-endBuf+1);
2099 // Comment out the protocol references.
2100 InsertText(LessLoc, "/*");
2101 InsertText(GreaterLoc, "*/");
2102 }
2103 }
2104 if (!proto)
2105 return; // most likely, was a variable
2106 // Now check arguments.
2107 const char *startBuf = SM->getCharacterData(Loc);
2108 const char *startFuncBuf = startBuf;
2109 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
2110 if (needToScanForQualifiers(proto->getArgType(i))) {
2111 // Since types are unique, we need to scan the buffer.
2112
2113 const char *endBuf = startBuf;
2114 // scan forward (from the decl location) for argument types.
2115 scanToNextArgument(endBuf);
2116 const char *startRef = 0, *endRef = 0;
2117 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2118 // Get the locations of the startRef, endRef.
2119 SourceLocation LessLoc =
2120 Loc.getLocWithOffset(startRef-startFuncBuf);
2121 SourceLocation GreaterLoc =
2122 Loc.getLocWithOffset(endRef-startFuncBuf+1);
2123 // Comment out the protocol references.
2124 InsertText(LessLoc, "/*");
2125 InsertText(GreaterLoc, "*/");
2126 }
2127 startBuf = ++endBuf;
2128 }
2129 else {
2130 // If the function name is derived from a macro expansion, then the
2131 // argument buffer will not follow the name. Need to speak with Chris.
2132 while (*startBuf && *startBuf != ')' && *startBuf != ',')
2133 startBuf++; // scan forward (from the decl location) for argument types.
2134 startBuf++;
2135 }
2136 }
2137}
2138
2139void RewriteModernObjC::RewriteTypeOfDecl(VarDecl *ND) {
2140 QualType QT = ND->getType();
2141 const Type* TypePtr = QT->getAs<Type>();
2142 if (!isa<TypeOfExprType>(TypePtr))
2143 return;
2144 while (isa<TypeOfExprType>(TypePtr)) {
2145 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
2146 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
2147 TypePtr = QT->getAs<Type>();
2148 }
2149 // FIXME. This will not work for multiple declarators; as in:
2150 // __typeof__(a) b,c,d;
2151 std::string TypeAsString(QT.getAsString(Context->getPrintingPolicy()));
2152 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
2153 const char *startBuf = SM->getCharacterData(DeclLoc);
2154 if (ND->getInit()) {
2155 std::string Name(ND->getNameAsString());
2156 TypeAsString += " " + Name + " = ";
2157 Expr *E = ND->getInit();
2158 SourceLocation startLoc;
2159 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
2160 startLoc = ECE->getLParenLoc();
2161 else
2162 startLoc = E->getLocStart();
2163 startLoc = SM->getExpansionLoc(startLoc);
2164 const char *endBuf = SM->getCharacterData(startLoc);
2165 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
2166 }
2167 else {
2168 SourceLocation X = ND->getLocEnd();
2169 X = SM->getExpansionLoc(X);
2170 const char *endBuf = SM->getCharacterData(X);
2171 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
2172 }
2173}
2174
2175// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
2176void RewriteModernObjC::SynthSelGetUidFunctionDecl() {
2177 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
2178 SmallVector<QualType, 16> ArgTys;
2179 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2180 QualType getFuncType =
2181 getSimpleFunctionType(Context->getObjCSelType(), &ArgTys[0], ArgTys.size());
2182 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2183 SourceLocation(),
2184 SourceLocation(),
2185 SelGetUidIdent, getFuncType, 0,
2186 SC_Extern,
2187 SC_None, false);
2188}
2189
2190void RewriteModernObjC::RewriteFunctionDecl(FunctionDecl *FD) {
2191 // declared in <objc/objc.h>
2192 if (FD->getIdentifier() &&
2193 FD->getName() == "sel_registerName") {
2194 SelGetUidFunctionDecl = FD;
2195 return;
2196 }
2197 RewriteObjCQualifiedInterfaceTypes(FD);
2198}
2199
2200void RewriteModernObjC::RewriteBlockPointerType(std::string& Str, QualType Type) {
2201 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
2202 const char *argPtr = TypeString.c_str();
2203 if (!strchr(argPtr, '^')) {
2204 Str += TypeString;
2205 return;
2206 }
2207 while (*argPtr) {
2208 Str += (*argPtr == '^' ? '*' : *argPtr);
2209 argPtr++;
2210 }
2211}
2212
2213// FIXME. Consolidate this routine with RewriteBlockPointerType.
2214void RewriteModernObjC::RewriteBlockPointerTypeVariable(std::string& Str,
2215 ValueDecl *VD) {
2216 QualType Type = VD->getType();
2217 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
2218 const char *argPtr = TypeString.c_str();
2219 int paren = 0;
2220 while (*argPtr) {
2221 switch (*argPtr) {
2222 case '(':
2223 Str += *argPtr;
2224 paren++;
2225 break;
2226 case ')':
2227 Str += *argPtr;
2228 paren--;
2229 break;
2230 case '^':
2231 Str += '*';
2232 if (paren == 1)
2233 Str += VD->getNameAsString();
2234 break;
2235 default:
2236 Str += *argPtr;
2237 break;
2238 }
2239 argPtr++;
2240 }
2241}
2242
Fariborz Jahanianb75f8de2012-04-19 00:50:01 +00002243void RewriteModernObjC::RewriteBlockLiteralFunctionDecl(FunctionDecl *FD) {
2244 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
2245 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2246 const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(funcType);
2247 if (!proto)
2248 return;
2249 QualType Type = proto->getResultType();
2250 std::string FdStr = Type.getAsString(Context->getPrintingPolicy());
2251 FdStr += " ";
2252 FdStr += FD->getName();
2253 FdStr += "(";
2254 unsigned numArgs = proto->getNumArgs();
2255 for (unsigned i = 0; i < numArgs; i++) {
2256 QualType ArgType = proto->getArgType(i);
2257 RewriteBlockPointerType(FdStr, ArgType);
2258 if (i+1 < numArgs)
2259 FdStr += ", ";
2260 }
Fariborz Jahanianb5863da2012-04-19 16:30:28 +00002261 if (FD->isVariadic()) {
2262 FdStr += (numArgs > 0) ? ", ...);\n" : "...);\n";
2263 }
2264 else
2265 FdStr += ");\n";
Fariborz Jahanianb75f8de2012-04-19 00:50:01 +00002266 InsertText(FunLocStart, FdStr);
2267}
2268
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002269// SynthSuperContructorFunctionDecl - id __rw_objc_super(id obj, id super);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002270void RewriteModernObjC::SynthSuperContructorFunctionDecl() {
2271 if (SuperContructorFunctionDecl)
2272 return;
2273 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
2274 SmallVector<QualType, 16> ArgTys;
2275 QualType argT = Context->getObjCIdType();
2276 assert(!argT.isNull() && "Can't find 'id' type");
2277 ArgTys.push_back(argT);
2278 ArgTys.push_back(argT);
2279 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2280 &ArgTys[0], ArgTys.size());
2281 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2282 SourceLocation(),
2283 SourceLocation(),
2284 msgSendIdent, msgSendType, 0,
2285 SC_Extern,
2286 SC_None, false);
2287}
2288
2289// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
2290void RewriteModernObjC::SynthMsgSendFunctionDecl() {
2291 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
2292 SmallVector<QualType, 16> ArgTys;
2293 QualType argT = Context->getObjCIdType();
2294 assert(!argT.isNull() && "Can't find 'id' type");
2295 ArgTys.push_back(argT);
2296 argT = Context->getObjCSelType();
2297 assert(!argT.isNull() && "Can't find 'SEL' type");
2298 ArgTys.push_back(argT);
2299 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2300 &ArgTys[0], ArgTys.size(),
2301 true /*isVariadic*/);
2302 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2303 SourceLocation(),
2304 SourceLocation(),
2305 msgSendIdent, msgSendType, 0,
2306 SC_Extern,
2307 SC_None, false);
2308}
2309
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002310// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(void);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002311void RewriteModernObjC::SynthMsgSendSuperFunctionDecl() {
2312 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002313 SmallVector<QualType, 2> ArgTys;
2314 ArgTys.push_back(Context->VoidTy);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002315 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002316 &ArgTys[0], 1,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002317 true /*isVariadic*/);
2318 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2319 SourceLocation(),
2320 SourceLocation(),
2321 msgSendIdent, msgSendType, 0,
2322 SC_Extern,
2323 SC_None, false);
2324}
2325
2326// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
2327void RewriteModernObjC::SynthMsgSendStretFunctionDecl() {
2328 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
2329 SmallVector<QualType, 16> ArgTys;
2330 QualType argT = Context->getObjCIdType();
2331 assert(!argT.isNull() && "Can't find 'id' type");
2332 ArgTys.push_back(argT);
2333 argT = Context->getObjCSelType();
2334 assert(!argT.isNull() && "Can't find 'SEL' type");
2335 ArgTys.push_back(argT);
2336 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2337 &ArgTys[0], ArgTys.size(),
2338 true /*isVariadic*/);
2339 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2340 SourceLocation(),
2341 SourceLocation(),
2342 msgSendIdent, msgSendType, 0,
2343 SC_Extern,
2344 SC_None, false);
2345}
2346
2347// SynthMsgSendSuperStretFunctionDecl -
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002348// id objc_msgSendSuper_stret(void);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002349void RewriteModernObjC::SynthMsgSendSuperStretFunctionDecl() {
2350 IdentifierInfo *msgSendIdent =
2351 &Context->Idents.get("objc_msgSendSuper_stret");
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002352 SmallVector<QualType, 2> ArgTys;
2353 ArgTys.push_back(Context->VoidTy);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002354 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002355 &ArgTys[0], 1,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002356 true /*isVariadic*/);
2357 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2358 SourceLocation(),
2359 SourceLocation(),
2360 msgSendIdent, msgSendType, 0,
2361 SC_Extern,
2362 SC_None, false);
2363}
2364
2365// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
2366void RewriteModernObjC::SynthMsgSendFpretFunctionDecl() {
2367 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
2368 SmallVector<QualType, 16> ArgTys;
2369 QualType argT = Context->getObjCIdType();
2370 assert(!argT.isNull() && "Can't find 'id' type");
2371 ArgTys.push_back(argT);
2372 argT = Context->getObjCSelType();
2373 assert(!argT.isNull() && "Can't find 'SEL' type");
2374 ArgTys.push_back(argT);
2375 QualType msgSendType = getSimpleFunctionType(Context->DoubleTy,
2376 &ArgTys[0], ArgTys.size(),
2377 true /*isVariadic*/);
2378 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2379 SourceLocation(),
2380 SourceLocation(),
2381 msgSendIdent, msgSendType, 0,
2382 SC_Extern,
2383 SC_None, false);
2384}
2385
2386// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
2387void RewriteModernObjC::SynthGetClassFunctionDecl() {
2388 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
2389 SmallVector<QualType, 16> ArgTys;
2390 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2391 QualType getClassType = getSimpleFunctionType(Context->getObjCIdType(),
2392 &ArgTys[0], ArgTys.size());
2393 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2394 SourceLocation(),
2395 SourceLocation(),
2396 getClassIdent, getClassType, 0,
2397 SC_Extern,
2398 SC_None, false);
2399}
2400
2401// SynthGetSuperClassFunctionDecl - Class class_getSuperclass(Class cls);
2402void RewriteModernObjC::SynthGetSuperClassFunctionDecl() {
2403 IdentifierInfo *getSuperClassIdent =
2404 &Context->Idents.get("class_getSuperclass");
2405 SmallVector<QualType, 16> ArgTys;
2406 ArgTys.push_back(Context->getObjCClassType());
2407 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
2408 &ArgTys[0], ArgTys.size());
2409 GetSuperClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2410 SourceLocation(),
2411 SourceLocation(),
2412 getSuperClassIdent,
2413 getClassType, 0,
2414 SC_Extern,
2415 SC_None,
2416 false);
2417}
2418
2419// SynthGetMetaClassFunctionDecl - id objc_getMetaClass(const char *name);
2420void RewriteModernObjC::SynthGetMetaClassFunctionDecl() {
2421 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
2422 SmallVector<QualType, 16> ArgTys;
2423 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2424 QualType getClassType = getSimpleFunctionType(Context->getObjCIdType(),
2425 &ArgTys[0], ArgTys.size());
2426 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2427 SourceLocation(),
2428 SourceLocation(),
2429 getClassIdent, getClassType, 0,
2430 SC_Extern,
2431 SC_None, false);
2432}
2433
2434Stmt *RewriteModernObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
2435 QualType strType = getConstantStringStructType();
2436
2437 std::string S = "__NSConstantStringImpl_";
2438
2439 std::string tmpName = InFileName;
2440 unsigned i;
2441 for (i=0; i < tmpName.length(); i++) {
2442 char c = tmpName.at(i);
2443 // replace any non alphanumeric characters with '_'.
2444 if (!isalpha(c) && (c < '0' || c > '9'))
2445 tmpName[i] = '_';
2446 }
2447 S += tmpName;
2448 S += "_";
2449 S += utostr(NumObjCStringLiterals++);
2450
2451 Preamble += "static __NSConstantStringImpl " + S;
2452 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2453 Preamble += "0x000007c8,"; // utf8_str
2454 // The pretty printer for StringLiteral handles escape characters properly.
2455 std::string prettyBufS;
2456 llvm::raw_string_ostream prettyBuf(prettyBufS);
2457 Exp->getString()->printPretty(prettyBuf, *Context, 0,
2458 PrintingPolicy(LangOpts));
2459 Preamble += prettyBuf.str();
2460 Preamble += ",";
2461 Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
2462
2463 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
2464 SourceLocation(), &Context->Idents.get(S),
2465 strType, 0, SC_Static, SC_None);
John McCallf4b88a42012-03-10 09:33:50 +00002466 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, false, strType, VK_LValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002467 SourceLocation());
2468 Expr *Unop = new (Context) UnaryOperator(DRE, UO_AddrOf,
2469 Context->getPointerType(DRE->getType()),
2470 VK_RValue, OK_Ordinary,
2471 SourceLocation());
2472 // cast to NSConstantString *
2473 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Exp->getType(),
2474 CK_CPointerToObjCPointerCast, Unop);
2475 ReplaceStmt(Exp, cast);
2476 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2477 return cast;
2478}
2479
Fariborz Jahanian55947042012-03-27 20:17:30 +00002480Stmt *RewriteModernObjC::RewriteObjCBoolLiteralExpr(ObjCBoolLiteralExpr *Exp) {
2481 unsigned IntSize =
2482 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
2483
2484 Expr *FlagExp = IntegerLiteral::Create(*Context,
2485 llvm::APInt(IntSize, Exp->getValue()),
2486 Context->IntTy, Exp->getLocation());
2487 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Context->ObjCBuiltinBoolTy,
2488 CK_BitCast, FlagExp);
2489 ParenExpr *PE = new (Context) ParenExpr(Exp->getLocation(), Exp->getExprLoc(),
2490 cast);
2491 ReplaceStmt(Exp, PE);
2492 return PE;
2493}
2494
Patrick Beardeb382ec2012-04-19 00:25:12 +00002495Stmt *RewriteModernObjC::RewriteObjCBoxedExpr(ObjCBoxedExpr *Exp) {
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002496 // synthesize declaration of helper functions needed in this routine.
2497 if (!SelGetUidFunctionDecl)
2498 SynthSelGetUidFunctionDecl();
2499 // use objc_msgSend() for all.
2500 if (!MsgSendFunctionDecl)
2501 SynthMsgSendFunctionDecl();
2502 if (!GetClassFunctionDecl)
2503 SynthGetClassFunctionDecl();
2504
2505 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2506 SourceLocation StartLoc = Exp->getLocStart();
2507 SourceLocation EndLoc = Exp->getLocEnd();
2508
2509 // Synthesize a call to objc_msgSend().
2510 SmallVector<Expr*, 4> MsgExprs;
2511 SmallVector<Expr*, 4> ClsExprs;
2512 QualType argType = Context->getPointerType(Context->CharTy);
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002513
Patrick Beardeb382ec2012-04-19 00:25:12 +00002514 // Create a call to objc_getClass("<BoxingClass>"). It will be the 1st argument.
2515 ObjCMethodDecl *BoxingMethod = Exp->getBoxingMethod();
2516 ObjCInterfaceDecl *BoxingClass = BoxingMethod->getClassInterface();
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002517
Patrick Beardeb382ec2012-04-19 00:25:12 +00002518 IdentifierInfo *clsName = BoxingClass->getIdentifier();
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002519 ClsExprs.push_back(StringLiteral::Create(*Context,
2520 clsName->getName(),
2521 StringLiteral::Ascii, false,
2522 argType, SourceLocation()));
2523 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2524 &ClsExprs[0],
2525 ClsExprs.size(),
2526 StartLoc, EndLoc);
2527 MsgExprs.push_back(Cls);
2528
Patrick Beardeb382ec2012-04-19 00:25:12 +00002529 // Create a call to sel_registerName("<BoxingMethod>:"), etc.
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002530 // it will be the 2nd argument.
2531 SmallVector<Expr*, 4> SelExprs;
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002532 SelExprs.push_back(StringLiteral::Create(*Context,
Patrick Beardeb382ec2012-04-19 00:25:12 +00002533 BoxingMethod->getSelector().getAsString(),
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002534 StringLiteral::Ascii, false,
2535 argType, SourceLocation()));
2536 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2537 &SelExprs[0], SelExprs.size(),
2538 StartLoc, EndLoc);
2539 MsgExprs.push_back(SelExp);
2540
Patrick Beardeb382ec2012-04-19 00:25:12 +00002541 // User provided sub-expression is the 3rd, and last, argument.
2542 Expr *subExpr = Exp->getSubExpr();
2543 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(subExpr)) {
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002544 QualType type = ICE->getType();
2545 const Expr *SubExpr = ICE->IgnoreParenImpCasts();
2546 CastKind CK = CK_BitCast;
2547 if (SubExpr->getType()->isIntegralType(*Context) && type->isBooleanType())
2548 CK = CK_IntegralToBoolean;
Patrick Beardeb382ec2012-04-19 00:25:12 +00002549 subExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, subExpr);
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002550 }
Patrick Beardeb382ec2012-04-19 00:25:12 +00002551 MsgExprs.push_back(subExpr);
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002552
2553 SmallVector<QualType, 4> ArgTypes;
2554 ArgTypes.push_back(Context->getObjCIdType());
2555 ArgTypes.push_back(Context->getObjCSelType());
Patrick Beardeb382ec2012-04-19 00:25:12 +00002556 for (ObjCMethodDecl::param_iterator PI = BoxingMethod->param_begin(),
2557 E = BoxingMethod->param_end(); PI != E; ++PI)
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002558 ArgTypes.push_back((*PI)->getType());
Patrick Beardeb382ec2012-04-19 00:25:12 +00002559
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002560 QualType returnType = Exp->getType();
2561 // Get the type, we will need to reference it in a couple spots.
2562 QualType msgSendType = MsgSendFlavor->getType();
2563
2564 // Create a reference to the objc_msgSend() declaration.
2565 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
2566 VK_LValue, SourceLocation());
2567
2568 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
Patrick Beardeb382ec2012-04-19 00:25:12 +00002569 Context->getPointerType(Context->VoidTy),
2570 CK_BitCast, DRE);
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002571
2572 // Now do the "normal" pointer to function cast.
2573 QualType castType =
Patrick Beardeb382ec2012-04-19 00:25:12 +00002574 getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
2575 BoxingMethod->isVariadic());
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002576 castType = Context->getPointerType(castType);
2577 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2578 cast);
2579
2580 // Don't forget the parens to enforce the proper binding.
2581 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
2582
2583 const FunctionType *FT = msgSendType->getAs<FunctionType>();
2584 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
2585 MsgExprs.size(),
2586 FT->getResultType(), VK_RValue,
2587 EndLoc);
2588 ReplaceStmt(Exp, CE);
2589 return CE;
2590}
2591
Fariborz Jahanian86cff602012-03-30 23:35:47 +00002592Stmt *RewriteModernObjC::RewriteObjCArrayLiteralExpr(ObjCArrayLiteral *Exp) {
2593 // synthesize declaration of helper functions needed in this routine.
2594 if (!SelGetUidFunctionDecl)
2595 SynthSelGetUidFunctionDecl();
2596 // use objc_msgSend() for all.
2597 if (!MsgSendFunctionDecl)
2598 SynthMsgSendFunctionDecl();
2599 if (!GetClassFunctionDecl)
2600 SynthGetClassFunctionDecl();
2601
2602 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2603 SourceLocation StartLoc = Exp->getLocStart();
2604 SourceLocation EndLoc = Exp->getLocEnd();
2605
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00002606 // Build the expression: __NSContainer_literal(int, ...).arr
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00002607 QualType IntQT = Context->IntTy;
2608 QualType NSArrayFType =
2609 getSimpleFunctionType(Context->VoidTy, &IntQT, 1, true);
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00002610 std::string NSArrayFName("__NSContainer_literal");
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00002611 FunctionDecl *NSArrayFD = SynthBlockInitFunctionDecl(NSArrayFName);
2612 DeclRefExpr *NSArrayDRE =
2613 new (Context) DeclRefExpr(NSArrayFD, false, NSArrayFType, VK_RValue,
2614 SourceLocation());
2615
2616 SmallVector<Expr*, 16> InitExprs;
2617 unsigned NumElements = Exp->getNumElements();
2618 unsigned UnsignedIntSize =
2619 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
2620 Expr *count = IntegerLiteral::Create(*Context,
2621 llvm::APInt(UnsignedIntSize, NumElements),
2622 Context->UnsignedIntTy, SourceLocation());
2623 InitExprs.push_back(count);
2624 for (unsigned i = 0; i < NumElements; i++)
2625 InitExprs.push_back(Exp->getElement(i));
2626 Expr *NSArrayCallExpr =
2627 new (Context) CallExpr(*Context, NSArrayDRE, &InitExprs[0], InitExprs.size(),
2628 NSArrayFType, VK_LValue, SourceLocation());
2629
2630 FieldDecl *ARRFD = FieldDecl::Create(*Context, 0, SourceLocation(),
2631 SourceLocation(),
2632 &Context->Idents.get("arr"),
2633 Context->getPointerType(Context->VoidPtrTy), 0,
2634 /*BitWidth=*/0, /*Mutable=*/true,
2635 /*HasInit=*/false);
2636 MemberExpr *ArrayLiteralME =
2637 new (Context) MemberExpr(NSArrayCallExpr, false, ARRFD,
2638 SourceLocation(),
2639 ARRFD->getType(), VK_LValue,
2640 OK_Ordinary);
2641 QualType ConstIdT = Context->getObjCIdType().withConst();
2642 CStyleCastExpr * ArrayLiteralObjects =
2643 NoTypeInfoCStyleCastExpr(Context,
2644 Context->getPointerType(ConstIdT),
2645 CK_BitCast,
2646 ArrayLiteralME);
2647
Fariborz Jahanian86cff602012-03-30 23:35:47 +00002648 // Synthesize a call to objc_msgSend().
2649 SmallVector<Expr*, 32> MsgExprs;
2650 SmallVector<Expr*, 4> ClsExprs;
2651 QualType argType = Context->getPointerType(Context->CharTy);
2652 QualType expType = Exp->getType();
2653
2654 // Create a call to objc_getClass("NSArray"). It will be th 1st argument.
2655 ObjCInterfaceDecl *Class =
2656 expType->getPointeeType()->getAs<ObjCObjectType>()->getInterface();
2657
2658 IdentifierInfo *clsName = Class->getIdentifier();
2659 ClsExprs.push_back(StringLiteral::Create(*Context,
2660 clsName->getName(),
2661 StringLiteral::Ascii, false,
2662 argType, SourceLocation()));
2663 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2664 &ClsExprs[0],
2665 ClsExprs.size(),
2666 StartLoc, EndLoc);
2667 MsgExprs.push_back(Cls);
2668
2669 // Create a call to sel_registerName("arrayWithObjects:count:").
2670 // it will be the 2nd argument.
2671 SmallVector<Expr*, 4> SelExprs;
2672 ObjCMethodDecl *ArrayMethod = Exp->getArrayWithObjectsMethod();
2673 SelExprs.push_back(StringLiteral::Create(*Context,
2674 ArrayMethod->getSelector().getAsString(),
2675 StringLiteral::Ascii, false,
2676 argType, SourceLocation()));
2677 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2678 &SelExprs[0], SelExprs.size(),
2679 StartLoc, EndLoc);
2680 MsgExprs.push_back(SelExp);
2681
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00002682 // (const id [])objects
2683 MsgExprs.push_back(ArrayLiteralObjects);
Fariborz Jahanian86cff602012-03-30 23:35:47 +00002684
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00002685 // (NSUInteger)cnt
2686 Expr *cnt = IntegerLiteral::Create(*Context,
2687 llvm::APInt(UnsignedIntSize, NumElements),
2688 Context->UnsignedIntTy, SourceLocation());
2689 MsgExprs.push_back(cnt);
Fariborz Jahanian86cff602012-03-30 23:35:47 +00002690
2691
2692 SmallVector<QualType, 4> ArgTypes;
2693 ArgTypes.push_back(Context->getObjCIdType());
2694 ArgTypes.push_back(Context->getObjCSelType());
2695 for (ObjCMethodDecl::param_iterator PI = ArrayMethod->param_begin(),
2696 E = ArrayMethod->param_end(); PI != E; ++PI)
2697 ArgTypes.push_back((*PI)->getType());
2698
2699 QualType returnType = Exp->getType();
2700 // Get the type, we will need to reference it in a couple spots.
2701 QualType msgSendType = MsgSendFlavor->getType();
2702
2703 // Create a reference to the objc_msgSend() declaration.
2704 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
2705 VK_LValue, SourceLocation());
2706
2707 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
2708 Context->getPointerType(Context->VoidTy),
2709 CK_BitCast, DRE);
2710
2711 // Now do the "normal" pointer to function cast.
2712 QualType castType =
2713 getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
2714 ArrayMethod->isVariadic());
2715 castType = Context->getPointerType(castType);
2716 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2717 cast);
2718
2719 // Don't forget the parens to enforce the proper binding.
2720 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
2721
2722 const FunctionType *FT = msgSendType->getAs<FunctionType>();
2723 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
2724 MsgExprs.size(),
2725 FT->getResultType(), VK_RValue,
2726 EndLoc);
2727 ReplaceStmt(Exp, CE);
2728 return CE;
2729}
2730
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00002731Stmt *RewriteModernObjC::RewriteObjCDictionaryLiteralExpr(ObjCDictionaryLiteral *Exp) {
2732 // synthesize declaration of helper functions needed in this routine.
2733 if (!SelGetUidFunctionDecl)
2734 SynthSelGetUidFunctionDecl();
2735 // use objc_msgSend() for all.
2736 if (!MsgSendFunctionDecl)
2737 SynthMsgSendFunctionDecl();
2738 if (!GetClassFunctionDecl)
2739 SynthGetClassFunctionDecl();
2740
2741 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2742 SourceLocation StartLoc = Exp->getLocStart();
2743 SourceLocation EndLoc = Exp->getLocEnd();
2744
2745 // Build the expression: __NSContainer_literal(int, ...).arr
2746 QualType IntQT = Context->IntTy;
2747 QualType NSDictFType =
2748 getSimpleFunctionType(Context->VoidTy, &IntQT, 1, true);
2749 std::string NSDictFName("__NSContainer_literal");
2750 FunctionDecl *NSDictFD = SynthBlockInitFunctionDecl(NSDictFName);
2751 DeclRefExpr *NSDictDRE =
2752 new (Context) DeclRefExpr(NSDictFD, false, NSDictFType, VK_RValue,
2753 SourceLocation());
2754
2755 SmallVector<Expr*, 16> KeyExprs;
2756 SmallVector<Expr*, 16> ValueExprs;
2757
2758 unsigned NumElements = Exp->getNumElements();
2759 unsigned UnsignedIntSize =
2760 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
2761 Expr *count = IntegerLiteral::Create(*Context,
2762 llvm::APInt(UnsignedIntSize, NumElements),
2763 Context->UnsignedIntTy, SourceLocation());
2764 KeyExprs.push_back(count);
2765 ValueExprs.push_back(count);
2766 for (unsigned i = 0; i < NumElements; i++) {
2767 ObjCDictionaryElement Element = Exp->getKeyValueElement(i);
2768 KeyExprs.push_back(Element.Key);
2769 ValueExprs.push_back(Element.Value);
2770 }
2771
2772 // (const id [])objects
2773 Expr *NSValueCallExpr =
2774 new (Context) CallExpr(*Context, NSDictDRE, &ValueExprs[0], ValueExprs.size(),
2775 NSDictFType, VK_LValue, SourceLocation());
2776
2777 FieldDecl *ARRFD = FieldDecl::Create(*Context, 0, SourceLocation(),
2778 SourceLocation(),
2779 &Context->Idents.get("arr"),
2780 Context->getPointerType(Context->VoidPtrTy), 0,
2781 /*BitWidth=*/0, /*Mutable=*/true,
2782 /*HasInit=*/false);
2783 MemberExpr *DictLiteralValueME =
2784 new (Context) MemberExpr(NSValueCallExpr, false, ARRFD,
2785 SourceLocation(),
2786 ARRFD->getType(), VK_LValue,
2787 OK_Ordinary);
2788 QualType ConstIdT = Context->getObjCIdType().withConst();
2789 CStyleCastExpr * DictValueObjects =
2790 NoTypeInfoCStyleCastExpr(Context,
2791 Context->getPointerType(ConstIdT),
2792 CK_BitCast,
2793 DictLiteralValueME);
2794 // (const id <NSCopying> [])keys
2795 Expr *NSKeyCallExpr =
2796 new (Context) CallExpr(*Context, NSDictDRE, &KeyExprs[0], KeyExprs.size(),
2797 NSDictFType, VK_LValue, SourceLocation());
2798
2799 MemberExpr *DictLiteralKeyME =
2800 new (Context) MemberExpr(NSKeyCallExpr, false, ARRFD,
2801 SourceLocation(),
2802 ARRFD->getType(), VK_LValue,
2803 OK_Ordinary);
2804
2805 CStyleCastExpr * DictKeyObjects =
2806 NoTypeInfoCStyleCastExpr(Context,
2807 Context->getPointerType(ConstIdT),
2808 CK_BitCast,
2809 DictLiteralKeyME);
2810
2811
2812
2813 // Synthesize a call to objc_msgSend().
2814 SmallVector<Expr*, 32> MsgExprs;
2815 SmallVector<Expr*, 4> ClsExprs;
2816 QualType argType = Context->getPointerType(Context->CharTy);
2817 QualType expType = Exp->getType();
2818
2819 // Create a call to objc_getClass("NSArray"). It will be th 1st argument.
2820 ObjCInterfaceDecl *Class =
2821 expType->getPointeeType()->getAs<ObjCObjectType>()->getInterface();
2822
2823 IdentifierInfo *clsName = Class->getIdentifier();
2824 ClsExprs.push_back(StringLiteral::Create(*Context,
2825 clsName->getName(),
2826 StringLiteral::Ascii, false,
2827 argType, SourceLocation()));
2828 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2829 &ClsExprs[0],
2830 ClsExprs.size(),
2831 StartLoc, EndLoc);
2832 MsgExprs.push_back(Cls);
2833
2834 // Create a call to sel_registerName("arrayWithObjects:count:").
2835 // it will be the 2nd argument.
2836 SmallVector<Expr*, 4> SelExprs;
2837 ObjCMethodDecl *DictMethod = Exp->getDictWithObjectsMethod();
2838 SelExprs.push_back(StringLiteral::Create(*Context,
2839 DictMethod->getSelector().getAsString(),
2840 StringLiteral::Ascii, false,
2841 argType, SourceLocation()));
2842 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2843 &SelExprs[0], SelExprs.size(),
2844 StartLoc, EndLoc);
2845 MsgExprs.push_back(SelExp);
2846
2847 // (const id [])objects
2848 MsgExprs.push_back(DictValueObjects);
2849
2850 // (const id <NSCopying> [])keys
2851 MsgExprs.push_back(DictKeyObjects);
2852
2853 // (NSUInteger)cnt
2854 Expr *cnt = IntegerLiteral::Create(*Context,
2855 llvm::APInt(UnsignedIntSize, NumElements),
2856 Context->UnsignedIntTy, SourceLocation());
2857 MsgExprs.push_back(cnt);
2858
2859
2860 SmallVector<QualType, 8> ArgTypes;
2861 ArgTypes.push_back(Context->getObjCIdType());
2862 ArgTypes.push_back(Context->getObjCSelType());
2863 for (ObjCMethodDecl::param_iterator PI = DictMethod->param_begin(),
2864 E = DictMethod->param_end(); PI != E; ++PI) {
2865 QualType T = (*PI)->getType();
2866 if (const PointerType* PT = T->getAs<PointerType>()) {
2867 QualType PointeeTy = PT->getPointeeType();
2868 convertToUnqualifiedObjCType(PointeeTy);
2869 T = Context->getPointerType(PointeeTy);
2870 }
2871 ArgTypes.push_back(T);
2872 }
2873
2874 QualType returnType = Exp->getType();
2875 // Get the type, we will need to reference it in a couple spots.
2876 QualType msgSendType = MsgSendFlavor->getType();
2877
2878 // Create a reference to the objc_msgSend() declaration.
2879 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
2880 VK_LValue, SourceLocation());
2881
2882 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
2883 Context->getPointerType(Context->VoidTy),
2884 CK_BitCast, DRE);
2885
2886 // Now do the "normal" pointer to function cast.
2887 QualType castType =
2888 getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
2889 DictMethod->isVariadic());
2890 castType = Context->getPointerType(castType);
2891 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2892 cast);
2893
2894 // Don't forget the parens to enforce the proper binding.
2895 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
2896
2897 const FunctionType *FT = msgSendType->getAs<FunctionType>();
2898 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
2899 MsgExprs.size(),
2900 FT->getResultType(), VK_RValue,
2901 EndLoc);
2902 ReplaceStmt(Exp, CE);
2903 return CE;
2904}
2905
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002906// struct __rw_objc_super {
2907// struct objc_object *object; struct objc_object *superClass;
2908// };
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002909QualType RewriteModernObjC::getSuperStructType() {
2910 if (!SuperStructDecl) {
2911 SuperStructDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
2912 SourceLocation(), SourceLocation(),
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002913 &Context->Idents.get("__rw_objc_super"));
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002914 QualType FieldTypes[2];
2915
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002916 // struct objc_object *object;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002917 FieldTypes[0] = Context->getObjCIdType();
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002918 // struct objc_object *superClass;
2919 FieldTypes[1] = Context->getObjCIdType();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002920
2921 // Create fields
2922 for (unsigned i = 0; i < 2; ++i) {
2923 SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
2924 SourceLocation(),
2925 SourceLocation(), 0,
2926 FieldTypes[i], 0,
2927 /*BitWidth=*/0,
2928 /*Mutable=*/false,
2929 /*HasInit=*/false));
2930 }
2931
2932 SuperStructDecl->completeDefinition();
2933 }
2934 return Context->getTagDeclType(SuperStructDecl);
2935}
2936
2937QualType RewriteModernObjC::getConstantStringStructType() {
2938 if (!ConstantStringDecl) {
2939 ConstantStringDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
2940 SourceLocation(), SourceLocation(),
2941 &Context->Idents.get("__NSConstantStringImpl"));
2942 QualType FieldTypes[4];
2943
2944 // struct objc_object *receiver;
2945 FieldTypes[0] = Context->getObjCIdType();
2946 // int flags;
2947 FieldTypes[1] = Context->IntTy;
2948 // char *str;
2949 FieldTypes[2] = Context->getPointerType(Context->CharTy);
2950 // long length;
2951 FieldTypes[3] = Context->LongTy;
2952
2953 // Create fields
2954 for (unsigned i = 0; i < 4; ++i) {
2955 ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
2956 ConstantStringDecl,
2957 SourceLocation(),
2958 SourceLocation(), 0,
2959 FieldTypes[i], 0,
2960 /*BitWidth=*/0,
2961 /*Mutable=*/true,
2962 /*HasInit=*/false));
2963 }
2964
2965 ConstantStringDecl->completeDefinition();
2966 }
2967 return Context->getTagDeclType(ConstantStringDecl);
2968}
2969
2970Stmt *RewriteModernObjC::SynthMessageExpr(ObjCMessageExpr *Exp,
2971 SourceLocation StartLoc,
2972 SourceLocation EndLoc) {
2973 if (!SelGetUidFunctionDecl)
2974 SynthSelGetUidFunctionDecl();
2975 if (!MsgSendFunctionDecl)
2976 SynthMsgSendFunctionDecl();
2977 if (!MsgSendSuperFunctionDecl)
2978 SynthMsgSendSuperFunctionDecl();
2979 if (!MsgSendStretFunctionDecl)
2980 SynthMsgSendStretFunctionDecl();
2981 if (!MsgSendSuperStretFunctionDecl)
2982 SynthMsgSendSuperStretFunctionDecl();
2983 if (!MsgSendFpretFunctionDecl)
2984 SynthMsgSendFpretFunctionDecl();
2985 if (!GetClassFunctionDecl)
2986 SynthGetClassFunctionDecl();
2987 if (!GetSuperClassFunctionDecl)
2988 SynthGetSuperClassFunctionDecl();
2989 if (!GetMetaClassFunctionDecl)
2990 SynthGetMetaClassFunctionDecl();
2991
2992 // default to objc_msgSend().
2993 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2994 // May need to use objc_msgSend_stret() as well.
2995 FunctionDecl *MsgSendStretFlavor = 0;
2996 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
2997 QualType resultType = mDecl->getResultType();
2998 if (resultType->isRecordType())
2999 MsgSendStretFlavor = MsgSendStretFunctionDecl;
3000 else if (resultType->isRealFloatingType())
3001 MsgSendFlavor = MsgSendFpretFunctionDecl;
3002 }
3003
3004 // Synthesize a call to objc_msgSend().
3005 SmallVector<Expr*, 8> MsgExprs;
3006 switch (Exp->getReceiverKind()) {
3007 case ObjCMessageExpr::SuperClass: {
3008 MsgSendFlavor = MsgSendSuperFunctionDecl;
3009 if (MsgSendStretFlavor)
3010 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
3011 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
3012
3013 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
3014
3015 SmallVector<Expr*, 4> InitExprs;
3016
3017 // set the receiver to self, the first argument to all methods.
3018 InitExprs.push_back(
3019 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3020 CK_BitCast,
3021 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCallf4b88a42012-03-10 09:33:50 +00003022 false,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003023 Context->getObjCIdType(),
3024 VK_RValue,
3025 SourceLocation()))
3026 ); // set the 'receiver'.
3027
3028 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3029 SmallVector<Expr*, 8> ClsExprs;
3030 QualType argType = Context->getPointerType(Context->CharTy);
3031 ClsExprs.push_back(StringLiteral::Create(*Context,
3032 ClassDecl->getIdentifier()->getName(),
3033 StringLiteral::Ascii, false,
3034 argType, SourceLocation()));
3035 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
3036 &ClsExprs[0],
3037 ClsExprs.size(),
3038 StartLoc,
3039 EndLoc);
3040 // (Class)objc_getClass("CurrentClass")
3041 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
3042 Context->getObjCClassType(),
3043 CK_BitCast, Cls);
3044 ClsExprs.clear();
3045 ClsExprs.push_back(ArgExpr);
3046 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
3047 &ClsExprs[0], ClsExprs.size(),
3048 StartLoc, EndLoc);
3049
3050 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3051 // To turn off a warning, type-cast to 'id'
3052 InitExprs.push_back( // set 'super class', using class_getSuperclass().
3053 NoTypeInfoCStyleCastExpr(Context,
3054 Context->getObjCIdType(),
3055 CK_BitCast, Cls));
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003056 // struct __rw_objc_super
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003057 QualType superType = getSuperStructType();
3058 Expr *SuperRep;
3059
3060 if (LangOpts.MicrosoftExt) {
3061 SynthSuperContructorFunctionDecl();
3062 // Simulate a contructor call...
3063 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
John McCallf4b88a42012-03-10 09:33:50 +00003064 false, superType, VK_LValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003065 SourceLocation());
3066 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
3067 InitExprs.size(),
3068 superType, VK_LValue,
3069 SourceLocation());
3070 // The code for super is a little tricky to prevent collision with
3071 // the structure definition in the header. The rewriter has it's own
3072 // internal definition (__rw_objc_super) that is uses. This is why
3073 // we need the cast below. For example:
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003074 // (struct __rw_objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003075 //
3076 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
3077 Context->getPointerType(SuperRep->getType()),
3078 VK_RValue, OK_Ordinary,
3079 SourceLocation());
3080 SuperRep = NoTypeInfoCStyleCastExpr(Context,
3081 Context->getPointerType(superType),
3082 CK_BitCast, SuperRep);
3083 } else {
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003084 // (struct __rw_objc_super) { <exprs from above> }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003085 InitListExpr *ILE =
3086 new (Context) InitListExpr(*Context, SourceLocation(),
3087 &InitExprs[0], InitExprs.size(),
3088 SourceLocation());
3089 TypeSourceInfo *superTInfo
3090 = Context->getTrivialTypeSourceInfo(superType);
3091 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
3092 superType, VK_LValue,
3093 ILE, false);
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003094 // struct __rw_objc_super *
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003095 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
3096 Context->getPointerType(SuperRep->getType()),
3097 VK_RValue, OK_Ordinary,
3098 SourceLocation());
3099 }
3100 MsgExprs.push_back(SuperRep);
3101 break;
3102 }
3103
3104 case ObjCMessageExpr::Class: {
3105 SmallVector<Expr*, 8> ClsExprs;
3106 QualType argType = Context->getPointerType(Context->CharTy);
3107 ObjCInterfaceDecl *Class
3108 = Exp->getClassReceiver()->getAs<ObjCObjectType>()->getInterface();
3109 IdentifierInfo *clsName = Class->getIdentifier();
3110 ClsExprs.push_back(StringLiteral::Create(*Context,
3111 clsName->getName(),
3112 StringLiteral::Ascii, false,
3113 argType, SourceLocation()));
3114 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
3115 &ClsExprs[0],
3116 ClsExprs.size(),
3117 StartLoc, EndLoc);
3118 MsgExprs.push_back(Cls);
3119 break;
3120 }
3121
3122 case ObjCMessageExpr::SuperInstance:{
3123 MsgSendFlavor = MsgSendSuperFunctionDecl;
3124 if (MsgSendStretFlavor)
3125 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
3126 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
3127 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
3128 SmallVector<Expr*, 4> InitExprs;
3129
3130 InitExprs.push_back(
3131 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3132 CK_BitCast,
3133 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCallf4b88a42012-03-10 09:33:50 +00003134 false,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003135 Context->getObjCIdType(),
3136 VK_RValue, SourceLocation()))
3137 ); // set the 'receiver'.
3138
3139 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3140 SmallVector<Expr*, 8> ClsExprs;
3141 QualType argType = Context->getPointerType(Context->CharTy);
3142 ClsExprs.push_back(StringLiteral::Create(*Context,
3143 ClassDecl->getIdentifier()->getName(),
3144 StringLiteral::Ascii, false, argType,
3145 SourceLocation()));
3146 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
3147 &ClsExprs[0],
3148 ClsExprs.size(),
3149 StartLoc, EndLoc);
3150 // (Class)objc_getClass("CurrentClass")
3151 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
3152 Context->getObjCClassType(),
3153 CK_BitCast, Cls);
3154 ClsExprs.clear();
3155 ClsExprs.push_back(ArgExpr);
3156 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
3157 &ClsExprs[0], ClsExprs.size(),
3158 StartLoc, EndLoc);
3159
3160 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3161 // To turn off a warning, type-cast to 'id'
3162 InitExprs.push_back(
3163 // set 'super class', using class_getSuperclass().
3164 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3165 CK_BitCast, Cls));
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003166 // struct __rw_objc_super
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003167 QualType superType = getSuperStructType();
3168 Expr *SuperRep;
3169
3170 if (LangOpts.MicrosoftExt) {
3171 SynthSuperContructorFunctionDecl();
3172 // Simulate a contructor call...
3173 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
John McCallf4b88a42012-03-10 09:33:50 +00003174 false, superType, VK_LValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003175 SourceLocation());
3176 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
3177 InitExprs.size(),
3178 superType, VK_LValue, SourceLocation());
3179 // The code for super is a little tricky to prevent collision with
3180 // the structure definition in the header. The rewriter has it's own
3181 // internal definition (__rw_objc_super) that is uses. This is why
3182 // we need the cast below. For example:
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003183 // (struct __rw_objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003184 //
3185 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
3186 Context->getPointerType(SuperRep->getType()),
3187 VK_RValue, OK_Ordinary,
3188 SourceLocation());
3189 SuperRep = NoTypeInfoCStyleCastExpr(Context,
3190 Context->getPointerType(superType),
3191 CK_BitCast, SuperRep);
3192 } else {
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003193 // (struct __rw_objc_super) { <exprs from above> }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003194 InitListExpr *ILE =
3195 new (Context) InitListExpr(*Context, SourceLocation(),
3196 &InitExprs[0], InitExprs.size(),
3197 SourceLocation());
3198 TypeSourceInfo *superTInfo
3199 = Context->getTrivialTypeSourceInfo(superType);
3200 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
3201 superType, VK_RValue, ILE,
3202 false);
3203 }
3204 MsgExprs.push_back(SuperRep);
3205 break;
3206 }
3207
3208 case ObjCMessageExpr::Instance: {
3209 // Remove all type-casts because it may contain objc-style types; e.g.
3210 // Foo<Proto> *.
3211 Expr *recExpr = Exp->getInstanceReceiver();
3212 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
3213 recExpr = CE->getSubExpr();
3214 CastKind CK = recExpr->getType()->isObjCObjectPointerType()
3215 ? CK_BitCast : recExpr->getType()->isBlockPointerType()
3216 ? CK_BlockPointerToObjCPointerCast
3217 : CK_CPointerToObjCPointerCast;
3218
3219 recExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3220 CK, recExpr);
3221 MsgExprs.push_back(recExpr);
3222 break;
3223 }
3224 }
3225
3226 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
3227 SmallVector<Expr*, 8> SelExprs;
3228 QualType argType = Context->getPointerType(Context->CharTy);
3229 SelExprs.push_back(StringLiteral::Create(*Context,
3230 Exp->getSelector().getAsString(),
3231 StringLiteral::Ascii, false,
3232 argType, SourceLocation()));
3233 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
3234 &SelExprs[0], SelExprs.size(),
3235 StartLoc,
3236 EndLoc);
3237 MsgExprs.push_back(SelExp);
3238
3239 // Now push any user supplied arguments.
3240 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
3241 Expr *userExpr = Exp->getArg(i);
3242 // Make all implicit casts explicit...ICE comes in handy:-)
3243 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
3244 // Reuse the ICE type, it is exactly what the doctor ordered.
3245 QualType type = ICE->getType();
3246 if (needToScanForQualifiers(type))
3247 type = Context->getObjCIdType();
3248 // Make sure we convert "type (^)(...)" to "type (*)(...)".
3249 (void)convertBlockPointerToFunctionPointer(type);
3250 const Expr *SubExpr = ICE->IgnoreParenImpCasts();
3251 CastKind CK;
3252 if (SubExpr->getType()->isIntegralType(*Context) &&
3253 type->isBooleanType()) {
3254 CK = CK_IntegralToBoolean;
3255 } else if (type->isObjCObjectPointerType()) {
3256 if (SubExpr->getType()->isBlockPointerType()) {
3257 CK = CK_BlockPointerToObjCPointerCast;
3258 } else if (SubExpr->getType()->isPointerType()) {
3259 CK = CK_CPointerToObjCPointerCast;
3260 } else {
3261 CK = CK_BitCast;
3262 }
3263 } else {
3264 CK = CK_BitCast;
3265 }
3266
3267 userExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, userExpr);
3268 }
3269 // Make id<P...> cast into an 'id' cast.
3270 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
3271 if (CE->getType()->isObjCQualifiedIdType()) {
3272 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
3273 userExpr = CE->getSubExpr();
3274 CastKind CK;
3275 if (userExpr->getType()->isIntegralType(*Context)) {
3276 CK = CK_IntegralToPointer;
3277 } else if (userExpr->getType()->isBlockPointerType()) {
3278 CK = CK_BlockPointerToObjCPointerCast;
3279 } else if (userExpr->getType()->isPointerType()) {
3280 CK = CK_CPointerToObjCPointerCast;
3281 } else {
3282 CK = CK_BitCast;
3283 }
3284 userExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3285 CK, userExpr);
3286 }
3287 }
3288 MsgExprs.push_back(userExpr);
3289 // We've transferred the ownership to MsgExprs. For now, we *don't* null
3290 // out the argument in the original expression (since we aren't deleting
3291 // the ObjCMessageExpr). See RewritePropertyOrImplicitSetter() usage for more info.
3292 //Exp->setArg(i, 0);
3293 }
3294 // Generate the funky cast.
3295 CastExpr *cast;
3296 SmallVector<QualType, 8> ArgTypes;
3297 QualType returnType;
3298
3299 // Push 'id' and 'SEL', the 2 implicit arguments.
3300 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
3301 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
3302 else
3303 ArgTypes.push_back(Context->getObjCIdType());
3304 ArgTypes.push_back(Context->getObjCSelType());
3305 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
3306 // Push any user argument types.
3307 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
3308 E = OMD->param_end(); PI != E; ++PI) {
3309 QualType t = (*PI)->getType()->isObjCQualifiedIdType()
3310 ? Context->getObjCIdType()
3311 : (*PI)->getType();
3312 // Make sure we convert "t (^)(...)" to "t (*)(...)".
3313 (void)convertBlockPointerToFunctionPointer(t);
3314 ArgTypes.push_back(t);
3315 }
3316 returnType = Exp->getType();
3317 convertToUnqualifiedObjCType(returnType);
3318 (void)convertBlockPointerToFunctionPointer(returnType);
3319 } else {
3320 returnType = Context->getObjCIdType();
3321 }
3322 // Get the type, we will need to reference it in a couple spots.
3323 QualType msgSendType = MsgSendFlavor->getType();
3324
3325 // Create a reference to the objc_msgSend() declaration.
John McCallf4b88a42012-03-10 09:33:50 +00003326 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003327 VK_LValue, SourceLocation());
3328
3329 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
3330 // If we don't do this cast, we get the following bizarre warning/note:
3331 // xx.m:13: warning: function called through a non-compatible type
3332 // xx.m:13: note: if this code is reached, the program will abort
3333 cast = NoTypeInfoCStyleCastExpr(Context,
3334 Context->getPointerType(Context->VoidTy),
3335 CK_BitCast, DRE);
3336
3337 // Now do the "normal" pointer to function cast.
3338 QualType castType =
3339 getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
3340 // If we don't have a method decl, force a variadic cast.
3341 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true);
3342 castType = Context->getPointerType(castType);
3343 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
3344 cast);
3345
3346 // Don't forget the parens to enforce the proper binding.
3347 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
3348
3349 const FunctionType *FT = msgSendType->getAs<FunctionType>();
3350 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
3351 MsgExprs.size(),
3352 FT->getResultType(), VK_RValue,
3353 EndLoc);
3354 Stmt *ReplacingStmt = CE;
3355 if (MsgSendStretFlavor) {
3356 // We have the method which returns a struct/union. Must also generate
3357 // call to objc_msgSend_stret and hang both varieties on a conditional
3358 // expression which dictate which one to envoke depending on size of
3359 // method's return type.
3360
3361 // Create a reference to the objc_msgSend_stret() declaration.
John McCallf4b88a42012-03-10 09:33:50 +00003362 DeclRefExpr *STDRE = new (Context) DeclRefExpr(MsgSendStretFlavor,
3363 false, msgSendType,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003364 VK_LValue, SourceLocation());
3365 // Need to cast objc_msgSend_stret to "void *" (see above comment).
3366 cast = NoTypeInfoCStyleCastExpr(Context,
3367 Context->getPointerType(Context->VoidTy),
3368 CK_BitCast, STDRE);
3369 // Now do the "normal" pointer to function cast.
3370 castType = getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
3371 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false);
3372 castType = Context->getPointerType(castType);
3373 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
3374 cast);
3375
3376 // Don't forget the parens to enforce the proper binding.
3377 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
3378
3379 FT = msgSendType->getAs<FunctionType>();
3380 CallExpr *STCE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
3381 MsgExprs.size(),
3382 FT->getResultType(), VK_RValue,
3383 SourceLocation());
3384
3385 // Build sizeof(returnType)
3386 UnaryExprOrTypeTraitExpr *sizeofExpr =
3387 new (Context) UnaryExprOrTypeTraitExpr(UETT_SizeOf,
3388 Context->getTrivialTypeSourceInfo(returnType),
3389 Context->getSizeType(), SourceLocation(),
3390 SourceLocation());
3391 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
3392 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
3393 // For X86 it is more complicated and some kind of target specific routine
3394 // is needed to decide what to do.
3395 unsigned IntSize =
3396 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
3397 IntegerLiteral *limit = IntegerLiteral::Create(*Context,
3398 llvm::APInt(IntSize, 8),
3399 Context->IntTy,
3400 SourceLocation());
3401 BinaryOperator *lessThanExpr =
3402 new (Context) BinaryOperator(sizeofExpr, limit, BO_LE, Context->IntTy,
3403 VK_RValue, OK_Ordinary, SourceLocation());
3404 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
3405 ConditionalOperator *CondExpr =
3406 new (Context) ConditionalOperator(lessThanExpr,
3407 SourceLocation(), CE,
3408 SourceLocation(), STCE,
3409 returnType, VK_RValue, OK_Ordinary);
3410 ReplacingStmt = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3411 CondExpr);
3412 }
3413 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3414 return ReplacingStmt;
3415}
3416
3417Stmt *RewriteModernObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
3418 Stmt *ReplacingStmt = SynthMessageExpr(Exp, Exp->getLocStart(),
3419 Exp->getLocEnd());
3420
3421 // Now do the actual rewrite.
3422 ReplaceStmt(Exp, ReplacingStmt);
3423
3424 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3425 return ReplacingStmt;
3426}
3427
3428// typedef struct objc_object Protocol;
3429QualType RewriteModernObjC::getProtocolType() {
3430 if (!ProtocolTypeDecl) {
3431 TypeSourceInfo *TInfo
3432 = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
3433 ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
3434 SourceLocation(), SourceLocation(),
3435 &Context->Idents.get("Protocol"),
3436 TInfo);
3437 }
3438 return Context->getTypeDeclType(ProtocolTypeDecl);
3439}
3440
3441/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
3442/// a synthesized/forward data reference (to the protocol's metadata).
3443/// The forward references (and metadata) are generated in
3444/// RewriteModernObjC::HandleTranslationUnit().
3445Stmt *RewriteModernObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00003446 std::string Name = "_OBJC_PROTOCOL_REFERENCE_$_" +
3447 Exp->getProtocol()->getNameAsString();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003448 IdentifierInfo *ID = &Context->Idents.get(Name);
3449 VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
3450 SourceLocation(), ID, getProtocolType(), 0,
3451 SC_Extern, SC_None);
John McCallf4b88a42012-03-10 09:33:50 +00003452 DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, false, getProtocolType(),
3453 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003454 Expr *DerefExpr = new (Context) UnaryOperator(DRE, UO_AddrOf,
3455 Context->getPointerType(DRE->getType()),
3456 VK_RValue, OK_Ordinary, SourceLocation());
3457 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, DerefExpr->getType(),
3458 CK_BitCast,
3459 DerefExpr);
3460 ReplaceStmt(Exp, castExpr);
3461 ProtocolExprDecls.insert(Exp->getProtocol()->getCanonicalDecl());
3462 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3463 return castExpr;
3464
3465}
3466
3467bool RewriteModernObjC::BufferContainsPPDirectives(const char *startBuf,
3468 const char *endBuf) {
3469 while (startBuf < endBuf) {
3470 if (*startBuf == '#') {
3471 // Skip whitespace.
3472 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
3473 ;
3474 if (!strncmp(startBuf, "if", strlen("if")) ||
3475 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
3476 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
3477 !strncmp(startBuf, "define", strlen("define")) ||
3478 !strncmp(startBuf, "undef", strlen("undef")) ||
3479 !strncmp(startBuf, "else", strlen("else")) ||
3480 !strncmp(startBuf, "elif", strlen("elif")) ||
3481 !strncmp(startBuf, "endif", strlen("endif")) ||
3482 !strncmp(startBuf, "pragma", strlen("pragma")) ||
3483 !strncmp(startBuf, "include", strlen("include")) ||
3484 !strncmp(startBuf, "import", strlen("import")) ||
3485 !strncmp(startBuf, "include_next", strlen("include_next")))
3486 return true;
3487 }
3488 startBuf++;
3489 }
3490 return false;
3491}
3492
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003493/// IsTagDefinedInsideClass - This routine checks that a named tagged type
3494/// is defined inside an objective-c class. If so, it returns true.
Fariborz Jahanianb68258f2012-05-01 17:46:45 +00003495bool RewriteModernObjC::IsTagDefinedInsideClass(ObjCContainerDecl *IDecl,
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003496 TagDecl *Tag,
3497 bool &IsNamedDefinition) {
Fariborz Jahanian89585e802012-04-30 19:46:53 +00003498 if (!IDecl)
3499 return false;
3500 SourceLocation TagLocation;
3501 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) {
3502 RD = RD->getDefinition();
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003503 if (!RD || !RD->getDeclName().getAsIdentifierInfo())
Fariborz Jahanian89585e802012-04-30 19:46:53 +00003504 return false;
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003505 IsNamedDefinition = true;
Fariborz Jahanian89585e802012-04-30 19:46:53 +00003506 TagLocation = RD->getLocation();
3507 return Context->getSourceManager().isBeforeInTranslationUnit(
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003508 IDecl->getLocation(), TagLocation);
3509 }
3510 if (EnumDecl *ED = dyn_cast<EnumDecl>(Tag)) {
3511 if (!ED || !ED->getDeclName().getAsIdentifierInfo())
3512 return false;
3513 IsNamedDefinition = true;
3514 TagLocation = ED->getLocation();
3515 return Context->getSourceManager().isBeforeInTranslationUnit(
3516 IDecl->getLocation(), TagLocation);
3517
Fariborz Jahanian89585e802012-04-30 19:46:53 +00003518 }
3519 return false;
3520}
3521
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003522/// RewriteObjCFieldDeclType - This routine rewrites a type into the buffer.
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003523/// It handles elaborated types, as well as enum types in the process.
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003524bool RewriteModernObjC::RewriteObjCFieldDeclType(QualType &Type,
3525 std::string &Result) {
3526 if (Type->isArrayType()) {
3527 QualType ElemTy = Context->getBaseElementType(Type);
3528 return RewriteObjCFieldDeclType(ElemTy, Result);
3529 }
3530 else if (Type->isRecordType()) {
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003531 RecordDecl *RD = Type->getAs<RecordType>()->getDecl();
3532 if (RD->isCompleteDefinition()) {
3533 if (RD->isStruct())
3534 Result += "\n\tstruct ";
3535 else if (RD->isUnion())
3536 Result += "\n\tunion ";
3537 else
3538 assert(false && "class not allowed as an ivar type");
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003539
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003540 Result += RD->getName();
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003541 if (GlobalDefinedTags.count(RD)) {
3542 // struct/union is defined globally, use it.
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003543 Result += " ";
3544 return true;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003545 }
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003546 Result += " {\n";
3547 for (RecordDecl::field_iterator i = RD->field_begin(),
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003548 e = RD->field_end(); i != e; ++i) {
David Blaikie262bc182012-04-30 02:36:29 +00003549 FieldDecl *FD = &*i;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003550 RewriteObjCFieldDecl(FD, Result);
3551 }
3552 Result += "\t} ";
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003553 return true;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003554 }
3555 }
3556 else if (Type->isEnumeralType()) {
3557 EnumDecl *ED = Type->getAs<EnumType>()->getDecl();
3558 if (ED->isCompleteDefinition()) {
3559 Result += "\n\tenum ";
3560 Result += ED->getName();
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003561 if (GlobalDefinedTags.count(ED)) {
3562 // Enum is globall defined, use it.
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003563 Result += " ";
3564 return true;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003565 }
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003566
3567 Result += " {\n";
3568 for (EnumDecl::enumerator_iterator EC = ED->enumerator_begin(),
3569 ECEnd = ED->enumerator_end(); EC != ECEnd; ++EC) {
3570 Result += "\t"; Result += EC->getName(); Result += " = ";
3571 llvm::APSInt Val = EC->getInitVal();
3572 Result += Val.toString(10);
3573 Result += ",\n";
3574 }
3575 Result += "\t} ";
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003576 return true;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003577 }
3578 }
3579
3580 Result += "\t";
3581 convertObjCTypeToCStyleType(Type);
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003582 return false;
3583}
3584
3585
3586/// RewriteObjCFieldDecl - This routine rewrites a field into the buffer.
3587/// It handles elaborated types, as well as enum types in the process.
3588void RewriteModernObjC::RewriteObjCFieldDecl(FieldDecl *fieldDecl,
3589 std::string &Result) {
3590 QualType Type = fieldDecl->getType();
3591 std::string Name = fieldDecl->getNameAsString();
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003592
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003593 bool EleboratedType = RewriteObjCFieldDeclType(Type, Result);
3594 if (!EleboratedType)
3595 Type.getAsStringInternal(Name, Context->getPrintingPolicy());
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003596 Result += Name;
3597 if (fieldDecl->isBitField()) {
3598 Result += " : "; Result += utostr(fieldDecl->getBitWidthValue(*Context));
3599 }
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003600 else if (EleboratedType && Type->isArrayType()) {
3601 CanQualType CType = Context->getCanonicalType(Type);
3602 while (isa<ArrayType>(CType)) {
3603 if (const ConstantArrayType *CAT = Context->getAsConstantArrayType(CType)) {
3604 Result += "[";
3605 llvm::APInt Dim = CAT->getSize();
3606 Result += utostr(Dim.getZExtValue());
3607 Result += "]";
3608 }
3609 CType = CType->getAs<ArrayType>()->getElementType();
3610 }
3611 }
3612
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003613 Result += ";\n";
3614}
3615
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003616/// RewriteLocallyDefinedNamedAggregates - This routine rewrites locally defined
3617/// named aggregate types into the input buffer.
3618void RewriteModernObjC::RewriteLocallyDefinedNamedAggregates(FieldDecl *fieldDecl,
3619 std::string &Result) {
3620 QualType Type = fieldDecl->getType();
3621 if (Type->isArrayType())
3622 Type = Context->getBaseElementType(Type);
Fariborz Jahanianb68258f2012-05-01 17:46:45 +00003623 ObjCContainerDecl *IDecl =
3624 dyn_cast<ObjCContainerDecl>(fieldDecl->getDeclContext());
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003625
3626 TagDecl *TD = 0;
3627 if (Type->isRecordType()) {
3628 TD = Type->getAs<RecordType>()->getDecl();
3629 }
3630 else if (Type->isEnumeralType()) {
3631 TD = Type->getAs<EnumType>()->getDecl();
3632 }
3633
3634 if (TD) {
3635 if (GlobalDefinedTags.count(TD))
3636 return;
3637
3638 bool IsNamedDefinition = false;
3639 if (IsTagDefinedInsideClass(IDecl, TD, IsNamedDefinition)) {
3640 RewriteObjCFieldDeclType(Type, Result);
3641 Result += ";";
3642 }
3643 if (IsNamedDefinition)
3644 GlobalDefinedTags.insert(TD);
3645 }
3646
3647}
3648
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003649/// RewriteObjCInternalStruct - Rewrite one internal struct corresponding to
3650/// an objective-c class with ivars.
3651void RewriteModernObjC::RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
3652 std::string &Result) {
3653 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
3654 assert(CDecl->getName() != "" &&
3655 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003656 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003657 SmallVector<ObjCIvarDecl *, 8> IVars;
3658 for (ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
Fariborz Jahanian9a2105b2012-03-06 17:16:27 +00003659 IVD; IVD = IVD->getNextIvar())
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003660 IVars.push_back(IVD);
Fariborz Jahanian9a2105b2012-03-06 17:16:27 +00003661
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003662 SourceLocation LocStart = CDecl->getLocStart();
3663 SourceLocation LocEnd = CDecl->getEndOfDefinitionLoc();
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003664
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003665 const char *startBuf = SM->getCharacterData(LocStart);
3666 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003667
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003668 // If no ivars and no root or if its root, directly or indirectly,
3669 // have no ivars (thus not synthesized) then no need to synthesize this class.
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003670 if ((!CDecl->isThisDeclarationADefinition() || IVars.size() == 0) &&
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003671 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
3672 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
3673 ReplaceText(LocStart, endBuf-startBuf, Result);
3674 return;
3675 }
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003676
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003677 // Insert named struct/union definitions inside class to
3678 // outer scope. This follows semantics of locally defined
3679 // struct/unions in objective-c classes.
3680 for (unsigned i = 0, e = IVars.size(); i < e; i++)
3681 RewriteLocallyDefinedNamedAggregates(IVars[i], Result);
3682
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003683 Result += "\nstruct ";
3684 Result += CDecl->getNameAsString();
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003685 Result += "_IMPL {\n";
3686
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00003687 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003688 Result += "\tstruct "; Result += RCDecl->getNameAsString();
3689 Result += "_IMPL "; Result += RCDecl->getNameAsString();
3690 Result += "_IVARS;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003691 }
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003692
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003693 for (unsigned i = 0, e = IVars.size(); i < e; i++)
3694 RewriteObjCFieldDecl(IVars[i], Result);
Fariborz Jahanian0b17b9a2012-02-12 21:36:23 +00003695
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003696 Result += "};\n";
3697 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
3698 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00003699 // Mark this struct as having been generated.
3700 if (!ObjCSynthesizedStructs.insert(CDecl))
3701 llvm_unreachable("struct already synthesize- RewriteObjCInternalStruct");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003702}
3703
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00003704static void WriteInternalIvarName(ObjCInterfaceDecl *IDecl,
3705 ObjCIvarDecl *IvarDecl, std::string &Result) {
3706 Result += "OBJC_IVAR_$_";
3707 Result += IDecl->getName();
3708 Result += "$";
3709 Result += IvarDecl->getName();
3710}
3711
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00003712/// RewriteIvarOffsetSymbols - Rewrite ivar offset symbols of those ivars which
3713/// have been referenced in an ivar access expression.
3714void RewriteModernObjC::RewriteIvarOffsetSymbols(ObjCInterfaceDecl *CDecl,
3715 std::string &Result) {
3716 // write out ivar offset symbols which have been referenced in an ivar
3717 // access expression.
3718 llvm::SmallPtrSet<ObjCIvarDecl *, 8> Ivars = ReferencedIvars[CDecl];
3719 if (Ivars.empty())
3720 return;
3721 for (llvm::SmallPtrSet<ObjCIvarDecl *, 8>::iterator i = Ivars.begin(),
3722 e = Ivars.end(); i != e; i++) {
3723 ObjCIvarDecl *IvarDecl = (*i);
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00003724 Result += "\n";
3725 if (LangOpts.MicrosoftExt)
3726 Result += "__declspec(allocate(\".objc_ivar$B\")) ";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00003727 Result += "extern \"C\" ";
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00003728 if (LangOpts.MicrosoftExt &&
3729 IvarDecl->getAccessControl() != ObjCIvarDecl::Private &&
Fariborz Jahanian297976d2012-03-29 17:51:09 +00003730 IvarDecl->getAccessControl() != ObjCIvarDecl::Package)
3731 Result += "__declspec(dllimport) ";
3732
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00003733 Result += "unsigned long ";
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00003734 WriteInternalIvarName(CDecl, IvarDecl, Result);
3735 Result += ";";
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00003736 }
3737}
3738
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003739//===----------------------------------------------------------------------===//
3740// Meta Data Emission
3741//===----------------------------------------------------------------------===//
3742
3743
3744/// RewriteImplementations - This routine rewrites all method implementations
3745/// and emits meta-data.
3746
3747void RewriteModernObjC::RewriteImplementations() {
3748 int ClsDefCount = ClassImplementation.size();
3749 int CatDefCount = CategoryImplementation.size();
3750
3751 // Rewrite implemented methods
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00003752 for (int i = 0; i < ClsDefCount; i++) {
3753 ObjCImplementationDecl *OIMP = ClassImplementation[i];
3754 ObjCInterfaceDecl *CDecl = OIMP->getClassInterface();
3755 if (CDecl->isImplicitInterfaceDecl())
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +00003756 assert(false &&
3757 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00003758 RewriteImplementationDecl(OIMP);
3759 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003760
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00003761 for (int i = 0; i < CatDefCount; i++) {
3762 ObjCCategoryImplDecl *CIMP = CategoryImplementation[i];
3763 ObjCInterfaceDecl *CDecl = CIMP->getClassInterface();
3764 if (CDecl->isImplicitInterfaceDecl())
3765 assert(false &&
3766 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00003767 RewriteImplementationDecl(CIMP);
3768 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003769}
3770
3771void RewriteModernObjC::RewriteByRefString(std::string &ResultStr,
3772 const std::string &Name,
3773 ValueDecl *VD, bool def) {
3774 assert(BlockByRefDeclNo.count(VD) &&
3775 "RewriteByRefString: ByRef decl missing");
3776 if (def)
3777 ResultStr += "struct ";
3778 ResultStr += "__Block_byref_" + Name +
3779 "_" + utostr(BlockByRefDeclNo[VD]) ;
3780}
3781
3782static bool HasLocalVariableExternalStorage(ValueDecl *VD) {
3783 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
3784 return (Var->isFunctionOrMethodVarDecl() && !Var->hasLocalStorage());
3785 return false;
3786}
3787
3788std::string RewriteModernObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
3789 StringRef funcName,
3790 std::string Tag) {
3791 const FunctionType *AFT = CE->getFunctionType();
3792 QualType RT = AFT->getResultType();
3793 std::string StructRef = "struct " + Tag;
3794 std::string S = "static " + RT.getAsString(Context->getPrintingPolicy()) + " __" +
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00003795 funcName.str() + "_block_func_" + utostr(i);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003796
3797 BlockDecl *BD = CE->getBlockDecl();
3798
3799 if (isa<FunctionNoProtoType>(AFT)) {
3800 // No user-supplied arguments. Still need to pass in a pointer to the
3801 // block (to reference imported block decl refs).
3802 S += "(" + StructRef + " *__cself)";
3803 } else if (BD->param_empty()) {
3804 S += "(" + StructRef + " *__cself)";
3805 } else {
3806 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
3807 assert(FT && "SynthesizeBlockFunc: No function proto");
3808 S += '(';
3809 // first add the implicit argument.
3810 S += StructRef + " *__cself, ";
3811 std::string ParamStr;
3812 for (BlockDecl::param_iterator AI = BD->param_begin(),
3813 E = BD->param_end(); AI != E; ++AI) {
3814 if (AI != BD->param_begin()) S += ", ";
3815 ParamStr = (*AI)->getNameAsString();
3816 QualType QT = (*AI)->getType();
Fariborz Jahanian2610f902012-03-27 16:42:20 +00003817 (void)convertBlockPointerToFunctionPointer(QT);
3818 QT.getAsStringInternal(ParamStr, Context->getPrintingPolicy());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003819 S += ParamStr;
3820 }
3821 if (FT->isVariadic()) {
3822 if (!BD->param_empty()) S += ", ";
3823 S += "...";
3824 }
3825 S += ')';
3826 }
3827 S += " {\n";
3828
3829 // Create local declarations to avoid rewriting all closure decl ref exprs.
3830 // First, emit a declaration for all "by ref" decls.
3831 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3832 E = BlockByRefDecls.end(); I != E; ++I) {
3833 S += " ";
3834 std::string Name = (*I)->getNameAsString();
3835 std::string TypeString;
3836 RewriteByRefString(TypeString, Name, (*I));
3837 TypeString += " *";
3838 Name = TypeString + Name;
3839 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
3840 }
3841 // Next, emit a declaration for all "by copy" declarations.
3842 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3843 E = BlockByCopyDecls.end(); I != E; ++I) {
3844 S += " ";
3845 // Handle nested closure invocation. For example:
3846 //
3847 // void (^myImportedClosure)(void);
3848 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
3849 //
3850 // void (^anotherClosure)(void);
3851 // anotherClosure = ^(void) {
3852 // myImportedClosure(); // import and invoke the closure
3853 // };
3854 //
3855 if (isTopLevelBlockPointerType((*I)->getType())) {
3856 RewriteBlockPointerTypeVariable(S, (*I));
3857 S += " = (";
3858 RewriteBlockPointerType(S, (*I)->getType());
3859 S += ")";
3860 S += "__cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
3861 }
3862 else {
3863 std::string Name = (*I)->getNameAsString();
3864 QualType QT = (*I)->getType();
3865 if (HasLocalVariableExternalStorage(*I))
3866 QT = Context->getPointerType(QT);
3867 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
3868 S += Name + " = __cself->" +
3869 (*I)->getNameAsString() + "; // bound by copy\n";
3870 }
3871 }
3872 std::string RewrittenStr = RewrittenBlockExprs[CE];
3873 const char *cstr = RewrittenStr.c_str();
3874 while (*cstr++ != '{') ;
3875 S += cstr;
3876 S += "\n";
3877 return S;
3878}
3879
3880std::string RewriteModernObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
3881 StringRef funcName,
3882 std::string Tag) {
3883 std::string StructRef = "struct " + Tag;
3884 std::string S = "static void __";
3885
3886 S += funcName;
3887 S += "_block_copy_" + utostr(i);
3888 S += "(" + StructRef;
3889 S += "*dst, " + StructRef;
3890 S += "*src) {";
3891 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
3892 E = ImportedBlockDecls.end(); I != E; ++I) {
3893 ValueDecl *VD = (*I);
3894 S += "_Block_object_assign((void*)&dst->";
3895 S += (*I)->getNameAsString();
3896 S += ", (void*)src->";
3897 S += (*I)->getNameAsString();
3898 if (BlockByRefDeclsPtrSet.count((*I)))
3899 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
3900 else if (VD->getType()->isBlockPointerType())
3901 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
3902 else
3903 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
3904 }
3905 S += "}\n";
3906
3907 S += "\nstatic void __";
3908 S += funcName;
3909 S += "_block_dispose_" + utostr(i);
3910 S += "(" + StructRef;
3911 S += "*src) {";
3912 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
3913 E = ImportedBlockDecls.end(); I != E; ++I) {
3914 ValueDecl *VD = (*I);
3915 S += "_Block_object_dispose((void*)src->";
3916 S += (*I)->getNameAsString();
3917 if (BlockByRefDeclsPtrSet.count((*I)))
3918 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
3919 else if (VD->getType()->isBlockPointerType())
3920 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
3921 else
3922 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
3923 }
3924 S += "}\n";
3925 return S;
3926}
3927
3928std::string RewriteModernObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
3929 std::string Desc) {
3930 std::string S = "\nstruct " + Tag;
3931 std::string Constructor = " " + Tag;
3932
3933 S += " {\n struct __block_impl impl;\n";
3934 S += " struct " + Desc;
3935 S += "* Desc;\n";
3936
3937 Constructor += "(void *fp, "; // Invoke function pointer.
3938 Constructor += "struct " + Desc; // Descriptor pointer.
3939 Constructor += " *desc";
3940
3941 if (BlockDeclRefs.size()) {
3942 // Output all "by copy" declarations.
3943 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3944 E = BlockByCopyDecls.end(); I != E; ++I) {
3945 S += " ";
3946 std::string FieldName = (*I)->getNameAsString();
3947 std::string ArgName = "_" + FieldName;
3948 // Handle nested closure invocation. For example:
3949 //
3950 // void (^myImportedBlock)(void);
3951 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
3952 //
3953 // void (^anotherBlock)(void);
3954 // anotherBlock = ^(void) {
3955 // myImportedBlock(); // import and invoke the closure
3956 // };
3957 //
3958 if (isTopLevelBlockPointerType((*I)->getType())) {
3959 S += "struct __block_impl *";
3960 Constructor += ", void *" + ArgName;
3961 } else {
3962 QualType QT = (*I)->getType();
3963 if (HasLocalVariableExternalStorage(*I))
3964 QT = Context->getPointerType(QT);
3965 QT.getAsStringInternal(FieldName, Context->getPrintingPolicy());
3966 QT.getAsStringInternal(ArgName, Context->getPrintingPolicy());
3967 Constructor += ", " + ArgName;
3968 }
3969 S += FieldName + ";\n";
3970 }
3971 // Output all "by ref" declarations.
3972 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3973 E = BlockByRefDecls.end(); I != E; ++I) {
3974 S += " ";
3975 std::string FieldName = (*I)->getNameAsString();
3976 std::string ArgName = "_" + FieldName;
3977 {
3978 std::string TypeString;
3979 RewriteByRefString(TypeString, FieldName, (*I));
3980 TypeString += " *";
3981 FieldName = TypeString + FieldName;
3982 ArgName = TypeString + ArgName;
3983 Constructor += ", " + ArgName;
3984 }
3985 S += FieldName + "; // by ref\n";
3986 }
3987 // Finish writing the constructor.
3988 Constructor += ", int flags=0)";
3989 // Initialize all "by copy" arguments.
3990 bool firsTime = true;
3991 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3992 E = BlockByCopyDecls.end(); I != E; ++I) {
3993 std::string Name = (*I)->getNameAsString();
3994 if (firsTime) {
3995 Constructor += " : ";
3996 firsTime = false;
3997 }
3998 else
3999 Constructor += ", ";
4000 if (isTopLevelBlockPointerType((*I)->getType()))
4001 Constructor += Name + "((struct __block_impl *)_" + Name + ")";
4002 else
4003 Constructor += Name + "(_" + Name + ")";
4004 }
4005 // Initialize all "by ref" arguments.
4006 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
4007 E = BlockByRefDecls.end(); I != E; ++I) {
4008 std::string Name = (*I)->getNameAsString();
4009 if (firsTime) {
4010 Constructor += " : ";
4011 firsTime = false;
4012 }
4013 else
4014 Constructor += ", ";
4015 Constructor += Name + "(_" + Name + "->__forwarding)";
4016 }
4017
4018 Constructor += " {\n";
4019 if (GlobalVarDecl)
4020 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4021 else
4022 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
4023 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
4024
4025 Constructor += " Desc = desc;\n";
4026 } else {
4027 // Finish writing the constructor.
4028 Constructor += ", int flags=0) {\n";
4029 if (GlobalVarDecl)
4030 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4031 else
4032 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
4033 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
4034 Constructor += " Desc = desc;\n";
4035 }
4036 Constructor += " ";
4037 Constructor += "}\n";
4038 S += Constructor;
4039 S += "};\n";
4040 return S;
4041}
4042
4043std::string RewriteModernObjC::SynthesizeBlockDescriptor(std::string DescTag,
4044 std::string ImplTag, int i,
4045 StringRef FunName,
4046 unsigned hasCopy) {
4047 std::string S = "\nstatic struct " + DescTag;
4048
4049 S += " {\n unsigned long reserved;\n";
4050 S += " unsigned long Block_size;\n";
4051 if (hasCopy) {
4052 S += " void (*copy)(struct ";
4053 S += ImplTag; S += "*, struct ";
4054 S += ImplTag; S += "*);\n";
4055
4056 S += " void (*dispose)(struct ";
4057 S += ImplTag; S += "*);\n";
4058 }
4059 S += "} ";
4060
4061 S += DescTag + "_DATA = { 0, sizeof(struct ";
4062 S += ImplTag + ")";
4063 if (hasCopy) {
4064 S += ", __" + FunName.str() + "_block_copy_" + utostr(i);
4065 S += ", __" + FunName.str() + "_block_dispose_" + utostr(i);
4066 }
4067 S += "};\n";
4068 return S;
4069}
4070
Fariborz Jahanian76a98be2012-04-17 18:40:53 +00004071/// getFunctionSourceLocation - returns start location of a function
4072/// definition. Complication arises when function has declared as
4073/// extern "C" or extern "C" {...}
Fariborz Jahanianb75f8de2012-04-19 00:50:01 +00004074static SourceLocation getFunctionSourceLocation (RewriteModernObjC &R,
4075 FunctionDecl *FD) {
Fariborz Jahanianb5863da2012-04-19 16:30:28 +00004076 if (FD->isExternC() && !FD->isMain()) {
4077 const DeclContext *DC = FD->getDeclContext();
4078 if (const LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(DC))
4079 // if it is extern "C" {...}, return function decl's own location.
4080 if (!LSD->getRBraceLoc().isValid())
4081 return LSD->getExternLoc();
Fariborz Jahanianb75f8de2012-04-19 00:50:01 +00004082 }
Fariborz Jahanianb5863da2012-04-19 16:30:28 +00004083 if (FD->getStorageClassAsWritten() != SC_None)
4084 R.RewriteBlockLiteralFunctionDecl(FD);
Fariborz Jahanian76a98be2012-04-17 18:40:53 +00004085 return FD->getTypeSpecStartLoc();
4086}
4087
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004088void RewriteModernObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
4089 StringRef FunName) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004090 bool RewriteSC = (GlobalVarDecl &&
4091 !Blocks.empty() &&
4092 GlobalVarDecl->getStorageClass() == SC_Static &&
4093 GlobalVarDecl->getType().getCVRQualifiers());
4094 if (RewriteSC) {
4095 std::string SC(" void __");
4096 SC += GlobalVarDecl->getNameAsString();
4097 SC += "() {}";
4098 InsertText(FunLocStart, SC);
4099 }
4100
4101 // Insert closures that were part of the function.
4102 for (unsigned i = 0, count=0; i < Blocks.size(); i++) {
4103 CollectBlockDeclRefInfo(Blocks[i]);
4104 // Need to copy-in the inner copied-in variables not actually used in this
4105 // block.
4106 for (int j = 0; j < InnerDeclRefsCount[i]; j++) {
John McCallf4b88a42012-03-10 09:33:50 +00004107 DeclRefExpr *Exp = InnerDeclRefs[count++];
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004108 ValueDecl *VD = Exp->getDecl();
4109 BlockDeclRefs.push_back(Exp);
John McCallf4b88a42012-03-10 09:33:50 +00004110 if (!VD->hasAttr<BlocksAttr>()) {
4111 if (!BlockByCopyDeclsPtrSet.count(VD)) {
4112 BlockByCopyDeclsPtrSet.insert(VD);
4113 BlockByCopyDecls.push_back(VD);
4114 }
4115 continue;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004116 }
John McCallf4b88a42012-03-10 09:33:50 +00004117
4118 if (!BlockByRefDeclsPtrSet.count(VD)) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004119 BlockByRefDeclsPtrSet.insert(VD);
4120 BlockByRefDecls.push_back(VD);
4121 }
John McCallf4b88a42012-03-10 09:33:50 +00004122
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004123 // imported objects in the inner blocks not used in the outer
4124 // blocks must be copied/disposed in the outer block as well.
John McCallf4b88a42012-03-10 09:33:50 +00004125 if (VD->getType()->isObjCObjectPointerType() ||
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004126 VD->getType()->isBlockPointerType())
4127 ImportedBlockDecls.insert(VD);
4128 }
4129
4130 std::string ImplTag = "__" + FunName.str() + "_block_impl_" + utostr(i);
4131 std::string DescTag = "__" + FunName.str() + "_block_desc_" + utostr(i);
4132
4133 std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
4134
4135 InsertText(FunLocStart, CI);
4136
4137 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
4138
4139 InsertText(FunLocStart, CF);
4140
4141 if (ImportedBlockDecls.size()) {
4142 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
4143 InsertText(FunLocStart, HF);
4144 }
4145 std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
4146 ImportedBlockDecls.size() > 0);
4147 InsertText(FunLocStart, BD);
4148
4149 BlockDeclRefs.clear();
4150 BlockByRefDecls.clear();
4151 BlockByRefDeclsPtrSet.clear();
4152 BlockByCopyDecls.clear();
4153 BlockByCopyDeclsPtrSet.clear();
4154 ImportedBlockDecls.clear();
4155 }
4156 if (RewriteSC) {
4157 // Must insert any 'const/volatile/static here. Since it has been
4158 // removed as result of rewriting of block literals.
4159 std::string SC;
4160 if (GlobalVarDecl->getStorageClass() == SC_Static)
4161 SC = "static ";
4162 if (GlobalVarDecl->getType().isConstQualified())
4163 SC += "const ";
4164 if (GlobalVarDecl->getType().isVolatileQualified())
4165 SC += "volatile ";
4166 if (GlobalVarDecl->getType().isRestrictQualified())
4167 SC += "restrict ";
4168 InsertText(FunLocStart, SC);
4169 }
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00004170 if (GlobalConstructionExp) {
4171 // extra fancy dance for global literal expression.
4172
4173 // Always the latest block expression on the block stack.
4174 std::string Tag = "__";
4175 Tag += FunName;
4176 Tag += "_block_impl_";
4177 Tag += utostr(Blocks.size()-1);
4178 std::string globalBuf = "static ";
4179 globalBuf += Tag; globalBuf += " ";
4180 std::string SStr;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004181
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00004182 llvm::raw_string_ostream constructorExprBuf(SStr);
4183 GlobalConstructionExp->printPretty(constructorExprBuf, *Context, 0,
4184 PrintingPolicy(LangOpts));
4185 globalBuf += constructorExprBuf.str();
4186 globalBuf += ";\n";
4187 InsertText(FunLocStart, globalBuf);
4188 GlobalConstructionExp = 0;
4189 }
4190
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004191 Blocks.clear();
4192 InnerDeclRefsCount.clear();
4193 InnerDeclRefs.clear();
4194 RewrittenBlockExprs.clear();
4195}
4196
4197void RewriteModernObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
Fariborz Jahanian04189532012-04-25 17:56:48 +00004198 SourceLocation FunLocStart =
4199 (!Blocks.empty()) ? getFunctionSourceLocation(*this, FD)
4200 : FD->getTypeSpecStartLoc();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004201 StringRef FuncName = FD->getName();
4202
4203 SynthesizeBlockLiterals(FunLocStart, FuncName);
4204}
4205
4206static void BuildUniqueMethodName(std::string &Name,
4207 ObjCMethodDecl *MD) {
4208 ObjCInterfaceDecl *IFace = MD->getClassInterface();
4209 Name = IFace->getName();
4210 Name += "__" + MD->getSelector().getAsString();
4211 // Convert colons to underscores.
4212 std::string::size_type loc = 0;
4213 while ((loc = Name.find(":", loc)) != std::string::npos)
4214 Name.replace(loc, 1, "_");
4215}
4216
4217void RewriteModernObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
4218 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
4219 //SourceLocation FunLocStart = MD->getLocStart();
4220 SourceLocation FunLocStart = MD->getLocStart();
4221 std::string FuncName;
4222 BuildUniqueMethodName(FuncName, MD);
4223 SynthesizeBlockLiterals(FunLocStart, FuncName);
4224}
4225
4226void RewriteModernObjC::GetBlockDeclRefExprs(Stmt *S) {
4227 for (Stmt::child_range CI = S->children(); CI; ++CI)
4228 if (*CI) {
4229 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
4230 GetBlockDeclRefExprs(CBE->getBody());
4231 else
4232 GetBlockDeclRefExprs(*CI);
4233 }
4234 // Handle specific things.
Fariborz Jahanian0e976812012-04-16 23:00:57 +00004235 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4236 if (DRE->refersToEnclosingLocal()) {
4237 // FIXME: Handle enums.
4238 if (!isa<FunctionDecl>(DRE->getDecl()))
4239 BlockDeclRefs.push_back(DRE);
4240 if (HasLocalVariableExternalStorage(DRE->getDecl()))
4241 BlockDeclRefs.push_back(DRE);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004242 }
Fariborz Jahanian0e976812012-04-16 23:00:57 +00004243 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004244
4245 return;
4246}
4247
4248void RewriteModernObjC::GetInnerBlockDeclRefExprs(Stmt *S,
John McCallf4b88a42012-03-10 09:33:50 +00004249 SmallVector<DeclRefExpr *, 8> &InnerBlockDeclRefs,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004250 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts) {
4251 for (Stmt::child_range CI = S->children(); CI; ++CI)
4252 if (*CI) {
4253 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI)) {
4254 InnerContexts.insert(cast<DeclContext>(CBE->getBlockDecl()));
4255 GetInnerBlockDeclRefExprs(CBE->getBody(),
4256 InnerBlockDeclRefs,
4257 InnerContexts);
4258 }
4259 else
4260 GetInnerBlockDeclRefExprs(*CI,
4261 InnerBlockDeclRefs,
4262 InnerContexts);
4263
4264 }
4265 // Handle specific things.
John McCallf4b88a42012-03-10 09:33:50 +00004266 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4267 if (DRE->refersToEnclosingLocal()) {
4268 if (!isa<FunctionDecl>(DRE->getDecl()) &&
4269 !InnerContexts.count(DRE->getDecl()->getDeclContext()))
4270 InnerBlockDeclRefs.push_back(DRE);
4271 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl()))
4272 if (Var->isFunctionOrMethodVarDecl())
4273 ImportedLocalExternalDecls.insert(Var);
4274 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004275 }
4276
4277 return;
4278}
4279
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00004280/// convertObjCTypeToCStyleType - This routine converts such objc types
4281/// as qualified objects, and blocks to their closest c/c++ types that
4282/// it can. It returns true if input type was modified.
4283bool RewriteModernObjC::convertObjCTypeToCStyleType(QualType &T) {
4284 QualType oldT = T;
4285 convertBlockPointerToFunctionPointer(T);
4286 if (T->isFunctionPointerType()) {
4287 QualType PointeeTy;
4288 if (const PointerType* PT = T->getAs<PointerType>()) {
4289 PointeeTy = PT->getPointeeType();
4290 if (const FunctionType *FT = PointeeTy->getAs<FunctionType>()) {
4291 T = convertFunctionTypeOfBlocks(FT);
4292 T = Context->getPointerType(T);
4293 }
4294 }
4295 }
4296
4297 convertToUnqualifiedObjCType(T);
4298 return T != oldT;
4299}
4300
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004301/// convertFunctionTypeOfBlocks - This routine converts a function type
4302/// whose result type may be a block pointer or whose argument type(s)
4303/// might be block pointers to an equivalent function type replacing
4304/// all block pointers to function pointers.
4305QualType RewriteModernObjC::convertFunctionTypeOfBlocks(const FunctionType *FT) {
4306 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
4307 // FTP will be null for closures that don't take arguments.
4308 // Generate a funky cast.
4309 SmallVector<QualType, 8> ArgTypes;
4310 QualType Res = FT->getResultType();
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00004311 bool modified = convertObjCTypeToCStyleType(Res);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004312
4313 if (FTP) {
4314 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4315 E = FTP->arg_type_end(); I && (I != E); ++I) {
4316 QualType t = *I;
4317 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00004318 if (convertObjCTypeToCStyleType(t))
4319 modified = true;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004320 ArgTypes.push_back(t);
4321 }
4322 }
4323 QualType FuncType;
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00004324 if (modified)
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004325 FuncType = getSimpleFunctionType(Res, &ArgTypes[0], ArgTypes.size());
4326 else FuncType = QualType(FT, 0);
4327 return FuncType;
4328}
4329
4330Stmt *RewriteModernObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
4331 // Navigate to relevant type information.
4332 const BlockPointerType *CPT = 0;
4333
4334 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
4335 CPT = DRE->getType()->getAs<BlockPointerType>();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004336 } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
4337 CPT = MExpr->getType()->getAs<BlockPointerType>();
4338 }
4339 else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
4340 return SynthesizeBlockCall(Exp, PRE->getSubExpr());
4341 }
4342 else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
4343 CPT = IEXPR->getType()->getAs<BlockPointerType>();
4344 else if (const ConditionalOperator *CEXPR =
4345 dyn_cast<ConditionalOperator>(BlockExp)) {
4346 Expr *LHSExp = CEXPR->getLHS();
4347 Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
4348 Expr *RHSExp = CEXPR->getRHS();
4349 Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
4350 Expr *CONDExp = CEXPR->getCond();
4351 ConditionalOperator *CondExpr =
4352 new (Context) ConditionalOperator(CONDExp,
4353 SourceLocation(), cast<Expr>(LHSStmt),
4354 SourceLocation(), cast<Expr>(RHSStmt),
4355 Exp->getType(), VK_RValue, OK_Ordinary);
4356 return CondExpr;
4357 } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
4358 CPT = IRE->getType()->getAs<BlockPointerType>();
4359 } else if (const PseudoObjectExpr *POE
4360 = dyn_cast<PseudoObjectExpr>(BlockExp)) {
4361 CPT = POE->getType()->castAs<BlockPointerType>();
4362 } else {
4363 assert(1 && "RewriteBlockClass: Bad type");
4364 }
4365 assert(CPT && "RewriteBlockClass: Bad type");
4366 const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
4367 assert(FT && "RewriteBlockClass: Bad type");
4368 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
4369 // FTP will be null for closures that don't take arguments.
4370
4371 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
4372 SourceLocation(), SourceLocation(),
4373 &Context->Idents.get("__block_impl"));
4374 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
4375
4376 // Generate a funky cast.
4377 SmallVector<QualType, 8> ArgTypes;
4378
4379 // Push the block argument type.
4380 ArgTypes.push_back(PtrBlock);
4381 if (FTP) {
4382 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4383 E = FTP->arg_type_end(); I && (I != E); ++I) {
4384 QualType t = *I;
4385 // Make sure we convert "t (^)(...)" to "t (*)(...)".
4386 if (!convertBlockPointerToFunctionPointer(t))
4387 convertToUnqualifiedObjCType(t);
4388 ArgTypes.push_back(t);
4389 }
4390 }
4391 // Now do the pointer to function cast.
4392 QualType PtrToFuncCastType
4393 = getSimpleFunctionType(Exp->getType(), &ArgTypes[0], ArgTypes.size());
4394
4395 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
4396
4397 CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock,
4398 CK_BitCast,
4399 const_cast<Expr*>(BlockExp));
4400 // Don't forget the parens to enforce the proper binding.
4401 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4402 BlkCast);
4403 //PE->dump();
4404
4405 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4406 SourceLocation(),
4407 &Context->Idents.get("FuncPtr"),
4408 Context->VoidPtrTy, 0,
4409 /*BitWidth=*/0, /*Mutable=*/true,
4410 /*HasInit=*/false);
4411 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
4412 FD->getType(), VK_LValue,
4413 OK_Ordinary);
4414
4415
4416 CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType,
4417 CK_BitCast, ME);
4418 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
4419
4420 SmallVector<Expr*, 8> BlkExprs;
4421 // Add the implicit argument.
4422 BlkExprs.push_back(BlkCast);
4423 // Add the user arguments.
4424 for (CallExpr::arg_iterator I = Exp->arg_begin(),
4425 E = Exp->arg_end(); I != E; ++I) {
4426 BlkExprs.push_back(*I);
4427 }
4428 CallExpr *CE = new (Context) CallExpr(*Context, PE, &BlkExprs[0],
4429 BlkExprs.size(),
4430 Exp->getType(), VK_RValue,
4431 SourceLocation());
4432 return CE;
4433}
4434
4435// We need to return the rewritten expression to handle cases where the
John McCallf4b88a42012-03-10 09:33:50 +00004436// DeclRefExpr is embedded in another expression being rewritten.
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004437// For example:
4438//
4439// int main() {
4440// __block Foo *f;
4441// __block int i;
4442//
4443// void (^myblock)() = ^() {
John McCallf4b88a42012-03-10 09:33:50 +00004444// [f test]; // f is a DeclRefExpr embedded in a message (which is being rewritten).
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004445// i = 77;
4446// };
4447//}
John McCallf4b88a42012-03-10 09:33:50 +00004448Stmt *RewriteModernObjC::RewriteBlockDeclRefExpr(DeclRefExpr *DeclRefExp) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004449 // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
4450 // for each DeclRefExp where BYREFVAR is name of the variable.
John McCallf4b88a42012-03-10 09:33:50 +00004451 ValueDecl *VD = DeclRefExp->getDecl();
4452 bool isArrow = DeclRefExp->refersToEnclosingLocal();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004453
4454 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4455 SourceLocation(),
4456 &Context->Idents.get("__forwarding"),
4457 Context->VoidPtrTy, 0,
4458 /*BitWidth=*/0, /*Mutable=*/true,
4459 /*HasInit=*/false);
4460 MemberExpr *ME = new (Context) MemberExpr(DeclRefExp, isArrow,
4461 FD, SourceLocation(),
4462 FD->getType(), VK_LValue,
4463 OK_Ordinary);
4464
4465 StringRef Name = VD->getName();
4466 FD = FieldDecl::Create(*Context, 0, SourceLocation(), SourceLocation(),
4467 &Context->Idents.get(Name),
4468 Context->VoidPtrTy, 0,
4469 /*BitWidth=*/0, /*Mutable=*/true,
4470 /*HasInit=*/false);
4471 ME = new (Context) MemberExpr(ME, true, FD, SourceLocation(),
4472 DeclRefExp->getType(), VK_LValue, OK_Ordinary);
4473
4474
4475
4476 // Need parens to enforce precedence.
4477 ParenExpr *PE = new (Context) ParenExpr(DeclRefExp->getExprLoc(),
4478 DeclRefExp->getExprLoc(),
4479 ME);
4480 ReplaceStmt(DeclRefExp, PE);
4481 return PE;
4482}
4483
4484// Rewrites the imported local variable V with external storage
4485// (static, extern, etc.) as *V
4486//
4487Stmt *RewriteModernObjC::RewriteLocalVariableExternalStorage(DeclRefExpr *DRE) {
4488 ValueDecl *VD = DRE->getDecl();
4489 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4490 if (!ImportedLocalExternalDecls.count(Var))
4491 return DRE;
4492 Expr *Exp = new (Context) UnaryOperator(DRE, UO_Deref, DRE->getType(),
4493 VK_LValue, OK_Ordinary,
4494 DRE->getLocation());
4495 // Need parens to enforce precedence.
4496 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4497 Exp);
4498 ReplaceStmt(DRE, PE);
4499 return PE;
4500}
4501
4502void RewriteModernObjC::RewriteCastExpr(CStyleCastExpr *CE) {
4503 SourceLocation LocStart = CE->getLParenLoc();
4504 SourceLocation LocEnd = CE->getRParenLoc();
4505
4506 // Need to avoid trying to rewrite synthesized casts.
4507 if (LocStart.isInvalid())
4508 return;
4509 // Need to avoid trying to rewrite casts contained in macros.
4510 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
4511 return;
4512
4513 const char *startBuf = SM->getCharacterData(LocStart);
4514 const char *endBuf = SM->getCharacterData(LocEnd);
4515 QualType QT = CE->getType();
4516 const Type* TypePtr = QT->getAs<Type>();
4517 if (isa<TypeOfExprType>(TypePtr)) {
4518 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
4519 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
4520 std::string TypeAsString = "(";
4521 RewriteBlockPointerType(TypeAsString, QT);
4522 TypeAsString += ")";
4523 ReplaceText(LocStart, endBuf-startBuf+1, TypeAsString);
4524 return;
4525 }
4526 // advance the location to startArgList.
4527 const char *argPtr = startBuf;
4528
4529 while (*argPtr++ && (argPtr < endBuf)) {
4530 switch (*argPtr) {
4531 case '^':
4532 // Replace the '^' with '*'.
4533 LocStart = LocStart.getLocWithOffset(argPtr-startBuf);
4534 ReplaceText(LocStart, 1, "*");
4535 break;
4536 }
4537 }
4538 return;
4539}
4540
Fariborz Jahanianf1ee6872012-04-10 00:08:18 +00004541void RewriteModernObjC::RewriteImplicitCastObjCExpr(CastExpr *IC) {
4542 CastKind CastKind = IC->getCastKind();
Fariborz Jahanian43aa1c32012-04-16 22:14:01 +00004543 if (CastKind != CK_BlockPointerToObjCPointerCast &&
4544 CastKind != CK_AnyPointerToBlockPointerCast)
4545 return;
Fariborz Jahanianf1ee6872012-04-10 00:08:18 +00004546
Fariborz Jahanian43aa1c32012-04-16 22:14:01 +00004547 QualType QT = IC->getType();
4548 (void)convertBlockPointerToFunctionPointer(QT);
4549 std::string TypeString(QT.getAsString(Context->getPrintingPolicy()));
4550 std::string Str = "(";
4551 Str += TypeString;
4552 Str += ")";
4553 InsertText(IC->getSubExpr()->getLocStart(), &Str[0], Str.size());
4554
Fariborz Jahanianf1ee6872012-04-10 00:08:18 +00004555 return;
4556}
4557
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004558void RewriteModernObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
4559 SourceLocation DeclLoc = FD->getLocation();
4560 unsigned parenCount = 0;
4561
4562 // We have 1 or more arguments that have closure pointers.
4563 const char *startBuf = SM->getCharacterData(DeclLoc);
4564 const char *startArgList = strchr(startBuf, '(');
4565
4566 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
4567
4568 parenCount++;
4569 // advance the location to startArgList.
4570 DeclLoc = DeclLoc.getLocWithOffset(startArgList-startBuf);
4571 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
4572
4573 const char *argPtr = startArgList;
4574
4575 while (*argPtr++ && parenCount) {
4576 switch (*argPtr) {
4577 case '^':
4578 // Replace the '^' with '*'.
4579 DeclLoc = DeclLoc.getLocWithOffset(argPtr-startArgList);
4580 ReplaceText(DeclLoc, 1, "*");
4581 break;
4582 case '(':
4583 parenCount++;
4584 break;
4585 case ')':
4586 parenCount--;
4587 break;
4588 }
4589 }
4590 return;
4591}
4592
4593bool RewriteModernObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
4594 const FunctionProtoType *FTP;
4595 const PointerType *PT = QT->getAs<PointerType>();
4596 if (PT) {
4597 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4598 } else {
4599 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4600 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4601 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4602 }
4603 if (FTP) {
4604 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4605 E = FTP->arg_type_end(); I != E; ++I)
4606 if (isTopLevelBlockPointerType(*I))
4607 return true;
4608 }
4609 return false;
4610}
4611
4612bool RewriteModernObjC::PointerTypeTakesAnyObjCQualifiedType(QualType QT) {
4613 const FunctionProtoType *FTP;
4614 const PointerType *PT = QT->getAs<PointerType>();
4615 if (PT) {
4616 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4617 } else {
4618 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4619 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4620 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4621 }
4622 if (FTP) {
4623 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4624 E = FTP->arg_type_end(); I != E; ++I) {
4625 if ((*I)->isObjCQualifiedIdType())
4626 return true;
4627 if ((*I)->isObjCObjectPointerType() &&
4628 (*I)->getPointeeType()->isObjCQualifiedInterfaceType())
4629 return true;
4630 }
4631
4632 }
4633 return false;
4634}
4635
4636void RewriteModernObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
4637 const char *&RParen) {
4638 const char *argPtr = strchr(Name, '(');
4639 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
4640
4641 LParen = argPtr; // output the start.
4642 argPtr++; // skip past the left paren.
4643 unsigned parenCount = 1;
4644
4645 while (*argPtr && parenCount) {
4646 switch (*argPtr) {
4647 case '(': parenCount++; break;
4648 case ')': parenCount--; break;
4649 default: break;
4650 }
4651 if (parenCount) argPtr++;
4652 }
4653 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
4654 RParen = argPtr; // output the end
4655}
4656
4657void RewriteModernObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
4658 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4659 RewriteBlockPointerFunctionArgs(FD);
4660 return;
4661 }
4662 // Handle Variables and Typedefs.
4663 SourceLocation DeclLoc = ND->getLocation();
4664 QualType DeclT;
4665 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
4666 DeclT = VD->getType();
4667 else if (TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(ND))
4668 DeclT = TDD->getUnderlyingType();
4669 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
4670 DeclT = FD->getType();
4671 else
4672 llvm_unreachable("RewriteBlockPointerDecl(): Decl type not yet handled");
4673
4674 const char *startBuf = SM->getCharacterData(DeclLoc);
4675 const char *endBuf = startBuf;
4676 // scan backward (from the decl location) for the end of the previous decl.
4677 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
4678 startBuf--;
4679 SourceLocation Start = DeclLoc.getLocWithOffset(startBuf-endBuf);
4680 std::string buf;
4681 unsigned OrigLength=0;
4682 // *startBuf != '^' if we are dealing with a pointer to function that
4683 // may take block argument types (which will be handled below).
4684 if (*startBuf == '^') {
4685 // Replace the '^' with '*', computing a negative offset.
4686 buf = '*';
4687 startBuf++;
4688 OrigLength++;
4689 }
4690 while (*startBuf != ')') {
4691 buf += *startBuf;
4692 startBuf++;
4693 OrigLength++;
4694 }
4695 buf += ')';
4696 OrigLength++;
4697
4698 if (PointerTypeTakesAnyBlockArguments(DeclT) ||
4699 PointerTypeTakesAnyObjCQualifiedType(DeclT)) {
4700 // Replace the '^' with '*' for arguments.
4701 // Replace id<P> with id/*<>*/
4702 DeclLoc = ND->getLocation();
4703 startBuf = SM->getCharacterData(DeclLoc);
4704 const char *argListBegin, *argListEnd;
4705 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
4706 while (argListBegin < argListEnd) {
4707 if (*argListBegin == '^')
4708 buf += '*';
4709 else if (*argListBegin == '<') {
4710 buf += "/*";
4711 buf += *argListBegin++;
4712 OrigLength++;;
4713 while (*argListBegin != '>') {
4714 buf += *argListBegin++;
4715 OrigLength++;
4716 }
4717 buf += *argListBegin;
4718 buf += "*/";
4719 }
4720 else
4721 buf += *argListBegin;
4722 argListBegin++;
4723 OrigLength++;
4724 }
4725 buf += ')';
4726 OrigLength++;
4727 }
4728 ReplaceText(Start, OrigLength, buf);
4729
4730 return;
4731}
4732
4733
4734/// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
4735/// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
4736/// struct Block_byref_id_object *src) {
4737/// _Block_object_assign (&_dest->object, _src->object,
4738/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4739/// [|BLOCK_FIELD_IS_WEAK]) // object
4740/// _Block_object_assign(&_dest->object, _src->object,
4741/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4742/// [|BLOCK_FIELD_IS_WEAK]) // block
4743/// }
4744/// And:
4745/// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
4746/// _Block_object_dispose(_src->object,
4747/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4748/// [|BLOCK_FIELD_IS_WEAK]) // object
4749/// _Block_object_dispose(_src->object,
4750/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4751/// [|BLOCK_FIELD_IS_WEAK]) // block
4752/// }
4753
4754std::string RewriteModernObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
4755 int flag) {
4756 std::string S;
4757 if (CopyDestroyCache.count(flag))
4758 return S;
4759 CopyDestroyCache.insert(flag);
4760 S = "static void __Block_byref_id_object_copy_";
4761 S += utostr(flag);
4762 S += "(void *dst, void *src) {\n";
4763
4764 // offset into the object pointer is computed as:
4765 // void * + void* + int + int + void* + void *
4766 unsigned IntSize =
4767 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
4768 unsigned VoidPtrSize =
4769 static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
4770
4771 unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/Context->getCharWidth();
4772 S += " _Block_object_assign((char*)dst + ";
4773 S += utostr(offset);
4774 S += ", *(void * *) ((char*)src + ";
4775 S += utostr(offset);
4776 S += "), ";
4777 S += utostr(flag);
4778 S += ");\n}\n";
4779
4780 S += "static void __Block_byref_id_object_dispose_";
4781 S += utostr(flag);
4782 S += "(void *src) {\n";
4783 S += " _Block_object_dispose(*(void * *) ((char*)src + ";
4784 S += utostr(offset);
4785 S += "), ";
4786 S += utostr(flag);
4787 S += ");\n}\n";
4788 return S;
4789}
4790
4791/// RewriteByRefVar - For each __block typex ND variable this routine transforms
4792/// the declaration into:
4793/// struct __Block_byref_ND {
4794/// void *__isa; // NULL for everything except __weak pointers
4795/// struct __Block_byref_ND *__forwarding;
4796/// int32_t __flags;
4797/// int32_t __size;
4798/// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
4799/// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
4800/// typex ND;
4801/// };
4802///
4803/// It then replaces declaration of ND variable with:
4804/// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
4805/// __size=sizeof(struct __Block_byref_ND),
4806/// ND=initializer-if-any};
4807///
4808///
Fariborz Jahanian4fe261c2012-04-24 19:38:45 +00004809void RewriteModernObjC::RewriteByRefVar(VarDecl *ND, bool firstDecl,
4810 bool lastDecl) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004811 int flag = 0;
4812 int isa = 0;
4813 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
4814 if (DeclLoc.isInvalid())
4815 // If type location is missing, it is because of missing type (a warning).
4816 // Use variable's location which is good for this case.
4817 DeclLoc = ND->getLocation();
4818 const char *startBuf = SM->getCharacterData(DeclLoc);
4819 SourceLocation X = ND->getLocEnd();
4820 X = SM->getExpansionLoc(X);
4821 const char *endBuf = SM->getCharacterData(X);
4822 std::string Name(ND->getNameAsString());
4823 std::string ByrefType;
4824 RewriteByRefString(ByrefType, Name, ND, true);
4825 ByrefType += " {\n";
4826 ByrefType += " void *__isa;\n";
4827 RewriteByRefString(ByrefType, Name, ND);
4828 ByrefType += " *__forwarding;\n";
4829 ByrefType += " int __flags;\n";
4830 ByrefType += " int __size;\n";
4831 // Add void *__Block_byref_id_object_copy;
4832 // void *__Block_byref_id_object_dispose; if needed.
4833 QualType Ty = ND->getType();
4834 bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty);
4835 if (HasCopyAndDispose) {
4836 ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
4837 ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
4838 }
4839
4840 QualType T = Ty;
4841 (void)convertBlockPointerToFunctionPointer(T);
4842 T.getAsStringInternal(Name, Context->getPrintingPolicy());
4843
4844 ByrefType += " " + Name + ";\n";
4845 ByrefType += "};\n";
4846 // Insert this type in global scope. It is needed by helper function.
4847 SourceLocation FunLocStart;
4848 if (CurFunctionDef)
Fariborz Jahanianb75f8de2012-04-19 00:50:01 +00004849 FunLocStart = getFunctionSourceLocation(*this, CurFunctionDef);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004850 else {
4851 assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null");
4852 FunLocStart = CurMethodDef->getLocStart();
4853 }
4854 InsertText(FunLocStart, ByrefType);
Fariborz Jahanian8247c4e2012-04-24 16:45:27 +00004855
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004856 if (Ty.isObjCGCWeak()) {
4857 flag |= BLOCK_FIELD_IS_WEAK;
4858 isa = 1;
4859 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004860 if (HasCopyAndDispose) {
4861 flag = BLOCK_BYREF_CALLER;
4862 QualType Ty = ND->getType();
4863 // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
4864 if (Ty->isBlockPointerType())
4865 flag |= BLOCK_FIELD_IS_BLOCK;
4866 else
4867 flag |= BLOCK_FIELD_IS_OBJECT;
4868 std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
4869 if (!HF.empty())
4870 InsertText(FunLocStart, HF);
4871 }
4872
4873 // struct __Block_byref_ND ND =
4874 // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
4875 // initializer-if-any};
4876 bool hasInit = (ND->getInit() != 0);
Fariborz Jahanian104dbf92012-04-11 23:57:12 +00004877 // FIXME. rewriter does not support __block c++ objects which
4878 // require construction.
Fariborz Jahanian65a7c682012-04-26 23:20:25 +00004879 if (hasInit)
4880 if (CXXConstructExpr *CExp = dyn_cast<CXXConstructExpr>(ND->getInit())) {
4881 CXXConstructorDecl *CXXDecl = CExp->getConstructor();
4882 if (CXXDecl && CXXDecl->isDefaultConstructor())
4883 hasInit = false;
4884 }
4885
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004886 unsigned flags = 0;
4887 if (HasCopyAndDispose)
4888 flags |= BLOCK_HAS_COPY_DISPOSE;
4889 Name = ND->getNameAsString();
4890 ByrefType.clear();
4891 RewriteByRefString(ByrefType, Name, ND);
4892 std::string ForwardingCastType("(");
4893 ForwardingCastType += ByrefType + " *)";
Fariborz Jahanian8247c4e2012-04-24 16:45:27 +00004894 ByrefType += " " + Name + " = {(void*)";
4895 ByrefType += utostr(isa);
4896 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
4897 ByrefType += utostr(flags);
4898 ByrefType += ", ";
4899 ByrefType += "sizeof(";
4900 RewriteByRefString(ByrefType, Name, ND);
4901 ByrefType += ")";
4902 if (HasCopyAndDispose) {
4903 ByrefType += ", __Block_byref_id_object_copy_";
4904 ByrefType += utostr(flag);
4905 ByrefType += ", __Block_byref_id_object_dispose_";
4906 ByrefType += utostr(flag);
4907 }
4908
Fariborz Jahanian4fe261c2012-04-24 19:38:45 +00004909 if (!firstDecl) {
4910 // In multiple __block declarations, and for all but 1st declaration,
4911 // find location of the separating comma. This would be start location
4912 // where new text is to be inserted.
4913 DeclLoc = ND->getLocation();
4914 const char *startDeclBuf = SM->getCharacterData(DeclLoc);
4915 const char *commaBuf = startDeclBuf;
4916 while (*commaBuf != ',')
4917 commaBuf--;
4918 assert((*commaBuf == ',') && "RewriteByRefVar: can't find ','");
4919 DeclLoc = DeclLoc.getLocWithOffset(commaBuf - startDeclBuf);
4920 startBuf = commaBuf;
4921 }
4922
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004923 if (!hasInit) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004924 ByrefType += "};\n";
4925 unsigned nameSize = Name.size();
4926 // for block or function pointer declaration. Name is aleady
4927 // part of the declaration.
4928 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType())
4929 nameSize = 1;
4930 ReplaceText(DeclLoc, endBuf-startBuf+nameSize, ByrefType);
4931 }
4932 else {
Fariborz Jahanian8247c4e2012-04-24 16:45:27 +00004933 ByrefType += ", ";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004934 SourceLocation startLoc;
4935 Expr *E = ND->getInit();
4936 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
4937 startLoc = ECE->getLParenLoc();
4938 else
4939 startLoc = E->getLocStart();
4940 startLoc = SM->getExpansionLoc(startLoc);
4941 endBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004942 ReplaceText(DeclLoc, endBuf-startBuf, ByrefType);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004943
Fariborz Jahanian4fe261c2012-04-24 19:38:45 +00004944 const char separator = lastDecl ? ';' : ',';
4945 const char *startInitializerBuf = SM->getCharacterData(startLoc);
4946 const char *separatorBuf = strchr(startInitializerBuf, separator);
4947 assert((*separatorBuf == separator) &&
4948 "RewriteByRefVar: can't find ';' or ','");
4949 SourceLocation separatorLoc =
4950 startLoc.getLocWithOffset(separatorBuf-startInitializerBuf);
4951
4952 InsertText(separatorLoc, lastDecl ? "}" : "};\n");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004953 }
4954 return;
4955}
4956
4957void RewriteModernObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
4958 // Add initializers for any closure decl refs.
4959 GetBlockDeclRefExprs(Exp->getBody());
4960 if (BlockDeclRefs.size()) {
4961 // Unique all "by copy" declarations.
4962 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00004963 if (!BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004964 if (!BlockByCopyDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
4965 BlockByCopyDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
4966 BlockByCopyDecls.push_back(BlockDeclRefs[i]->getDecl());
4967 }
4968 }
4969 // Unique all "by ref" declarations.
4970 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00004971 if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004972 if (!BlockByRefDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
4973 BlockByRefDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
4974 BlockByRefDecls.push_back(BlockDeclRefs[i]->getDecl());
4975 }
4976 }
4977 // Find any imported blocks...they will need special attention.
4978 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00004979 if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004980 BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
4981 BlockDeclRefs[i]->getType()->isBlockPointerType())
4982 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
4983 }
4984}
4985
4986FunctionDecl *RewriteModernObjC::SynthBlockInitFunctionDecl(StringRef name) {
4987 IdentifierInfo *ID = &Context->Idents.get(name);
4988 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
4989 return FunctionDecl::Create(*Context, TUDecl, SourceLocation(),
4990 SourceLocation(), ID, FType, 0, SC_Extern,
4991 SC_None, false, false);
4992}
4993
4994Stmt *RewriteModernObjC::SynthBlockInitExpr(BlockExpr *Exp,
John McCallf4b88a42012-03-10 09:33:50 +00004995 const SmallVector<DeclRefExpr *, 8> &InnerBlockDeclRefs) {
Fariborz Jahaniand13c2c22012-03-22 19:54:39 +00004996
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004997 const BlockDecl *block = Exp->getBlockDecl();
Fariborz Jahaniand13c2c22012-03-22 19:54:39 +00004998
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004999 Blocks.push_back(Exp);
5000
5001 CollectBlockDeclRefInfo(Exp);
5002
5003 // Add inner imported variables now used in current block.
5004 int countOfInnerDecls = 0;
5005 if (!InnerBlockDeclRefs.empty()) {
5006 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++) {
John McCallf4b88a42012-03-10 09:33:50 +00005007 DeclRefExpr *Exp = InnerBlockDeclRefs[i];
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005008 ValueDecl *VD = Exp->getDecl();
John McCallf4b88a42012-03-10 09:33:50 +00005009 if (!VD->hasAttr<BlocksAttr>() && !BlockByCopyDeclsPtrSet.count(VD)) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005010 // We need to save the copied-in variables in nested
5011 // blocks because it is needed at the end for some of the API generations.
5012 // See SynthesizeBlockLiterals routine.
5013 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5014 BlockDeclRefs.push_back(Exp);
5015 BlockByCopyDeclsPtrSet.insert(VD);
5016 BlockByCopyDecls.push_back(VD);
5017 }
John McCallf4b88a42012-03-10 09:33:50 +00005018 if (VD->hasAttr<BlocksAttr>() && !BlockByRefDeclsPtrSet.count(VD)) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005019 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5020 BlockDeclRefs.push_back(Exp);
5021 BlockByRefDeclsPtrSet.insert(VD);
5022 BlockByRefDecls.push_back(VD);
5023 }
5024 }
5025 // Find any imported blocks...they will need special attention.
5026 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00005027 if (InnerBlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005028 InnerBlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
5029 InnerBlockDeclRefs[i]->getType()->isBlockPointerType())
5030 ImportedBlockDecls.insert(InnerBlockDeclRefs[i]->getDecl());
5031 }
5032 InnerDeclRefsCount.push_back(countOfInnerDecls);
5033
5034 std::string FuncName;
5035
5036 if (CurFunctionDef)
5037 FuncName = CurFunctionDef->getNameAsString();
5038 else if (CurMethodDef)
5039 BuildUniqueMethodName(FuncName, CurMethodDef);
5040 else if (GlobalVarDecl)
5041 FuncName = std::string(GlobalVarDecl->getNameAsString());
5042
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00005043 bool GlobalBlockExpr =
5044 block->getDeclContext()->getRedeclContext()->isFileContext();
5045
5046 if (GlobalBlockExpr && !GlobalVarDecl) {
5047 Diags.Report(block->getLocation(), GlobalBlockRewriteFailedDiag);
5048 GlobalBlockExpr = false;
5049 }
5050
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005051 std::string BlockNumber = utostr(Blocks.size()-1);
5052
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005053 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
5054
5055 // Get a pointer to the function type so we can cast appropriately.
5056 QualType BFT = convertFunctionTypeOfBlocks(Exp->getFunctionType());
5057 QualType FType = Context->getPointerType(BFT);
5058
5059 FunctionDecl *FD;
5060 Expr *NewRep;
5061
5062 // Simulate a contructor call...
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00005063 std::string Tag;
5064
5065 if (GlobalBlockExpr)
5066 Tag = "__global_";
5067 else
5068 Tag = "__";
5069 Tag += FuncName + "_block_impl_" + BlockNumber;
5070
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005071 FD = SynthBlockInitFunctionDecl(Tag);
John McCallf4b88a42012-03-10 09:33:50 +00005072 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, false, FType, VK_RValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005073 SourceLocation());
5074
5075 SmallVector<Expr*, 4> InitExprs;
5076
5077 // Initialize the block function.
5078 FD = SynthBlockInitFunctionDecl(Func);
John McCallf4b88a42012-03-10 09:33:50 +00005079 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, false, FD->getType(),
5080 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005081 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
5082 CK_BitCast, Arg);
5083 InitExprs.push_back(castExpr);
5084
5085 // Initialize the block descriptor.
5086 std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
5087
5088 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl,
5089 SourceLocation(), SourceLocation(),
5090 &Context->Idents.get(DescData.c_str()),
5091 Context->VoidPtrTy, 0,
5092 SC_Static, SC_None);
5093 UnaryOperator *DescRefExpr =
John McCallf4b88a42012-03-10 09:33:50 +00005094 new (Context) UnaryOperator(new (Context) DeclRefExpr(NewVD, false,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005095 Context->VoidPtrTy,
5096 VK_LValue,
5097 SourceLocation()),
5098 UO_AddrOf,
5099 Context->getPointerType(Context->VoidPtrTy),
5100 VK_RValue, OK_Ordinary,
5101 SourceLocation());
5102 InitExprs.push_back(DescRefExpr);
5103
5104 // Add initializers for any closure decl refs.
5105 if (BlockDeclRefs.size()) {
5106 Expr *Exp;
5107 // Output all "by copy" declarations.
5108 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
5109 E = BlockByCopyDecls.end(); I != E; ++I) {
5110 if (isObjCType((*I)->getType())) {
5111 // FIXME: Conform to ABI ([[obj retain] autorelease]).
5112 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00005113 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(),
5114 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005115 if (HasLocalVariableExternalStorage(*I)) {
5116 QualType QT = (*I)->getType();
5117 QT = Context->getPointerType(QT);
5118 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
5119 OK_Ordinary, SourceLocation());
5120 }
5121 } else if (isTopLevelBlockPointerType((*I)->getType())) {
5122 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00005123 Arg = new (Context) DeclRefExpr(FD, false, FD->getType(),
5124 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005125 Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
5126 CK_BitCast, Arg);
5127 } else {
5128 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00005129 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(),
5130 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005131 if (HasLocalVariableExternalStorage(*I)) {
5132 QualType QT = (*I)->getType();
5133 QT = Context->getPointerType(QT);
5134 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
5135 OK_Ordinary, SourceLocation());
5136 }
5137
5138 }
5139 InitExprs.push_back(Exp);
5140 }
5141 // Output all "by ref" declarations.
5142 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
5143 E = BlockByRefDecls.end(); I != E; ++I) {
5144 ValueDecl *ND = (*I);
5145 std::string Name(ND->getNameAsString());
5146 std::string RecName;
5147 RewriteByRefString(RecName, Name, ND, true);
5148 IdentifierInfo *II = &Context->Idents.get(RecName.c_str()
5149 + sizeof("struct"));
5150 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
5151 SourceLocation(), SourceLocation(),
5152 II);
5153 assert(RD && "SynthBlockInitExpr(): Can't find RecordDecl");
5154 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
5155
5156 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00005157 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(), VK_LValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005158 SourceLocation());
5159 bool isNestedCapturedVar = false;
5160 if (block)
5161 for (BlockDecl::capture_const_iterator ci = block->capture_begin(),
5162 ce = block->capture_end(); ci != ce; ++ci) {
5163 const VarDecl *variable = ci->getVariable();
5164 if (variable == ND && ci->isNested()) {
5165 assert (ci->isByRef() &&
5166 "SynthBlockInitExpr - captured block variable is not byref");
5167 isNestedCapturedVar = true;
5168 break;
5169 }
5170 }
5171 // captured nested byref variable has its address passed. Do not take
5172 // its address again.
5173 if (!isNestedCapturedVar)
5174 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf,
5175 Context->getPointerType(Exp->getType()),
5176 VK_RValue, OK_Ordinary, SourceLocation());
5177 Exp = NoTypeInfoCStyleCastExpr(Context, castT, CK_BitCast, Exp);
5178 InitExprs.push_back(Exp);
5179 }
5180 }
5181 if (ImportedBlockDecls.size()) {
5182 // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
5183 int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
5184 unsigned IntSize =
5185 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
5186 Expr *FlagExp = IntegerLiteral::Create(*Context, llvm::APInt(IntSize, flag),
5187 Context->IntTy, SourceLocation());
5188 InitExprs.push_back(FlagExp);
5189 }
5190 NewRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0], InitExprs.size(),
5191 FType, VK_LValue, SourceLocation());
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00005192
5193 if (GlobalBlockExpr) {
5194 assert (GlobalConstructionExp == 0 &&
5195 "SynthBlockInitExpr - GlobalConstructionExp must be null");
5196 GlobalConstructionExp = NewRep;
5197 NewRep = DRE;
5198 }
5199
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005200 NewRep = new (Context) UnaryOperator(NewRep, UO_AddrOf,
5201 Context->getPointerType(NewRep->getType()),
5202 VK_RValue, OK_Ordinary, SourceLocation());
5203 NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CK_BitCast,
5204 NewRep);
5205 BlockDeclRefs.clear();
5206 BlockByRefDecls.clear();
5207 BlockByRefDeclsPtrSet.clear();
5208 BlockByCopyDecls.clear();
5209 BlockByCopyDeclsPtrSet.clear();
5210 ImportedBlockDecls.clear();
5211 return NewRep;
5212}
5213
5214bool RewriteModernObjC::IsDeclStmtInForeachHeader(DeclStmt *DS) {
5215 if (const ObjCForCollectionStmt * CS =
5216 dyn_cast<ObjCForCollectionStmt>(Stmts.back()))
5217 return CS->getElement() == DS;
5218 return false;
5219}
5220
5221//===----------------------------------------------------------------------===//
5222// Function Body / Expression rewriting
5223//===----------------------------------------------------------------------===//
5224
5225Stmt *RewriteModernObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
5226 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
5227 isa<DoStmt>(S) || isa<ForStmt>(S))
5228 Stmts.push_back(S);
5229 else if (isa<ObjCForCollectionStmt>(S)) {
5230 Stmts.push_back(S);
5231 ObjCBcLabelNo.push_back(++BcLabelCount);
5232 }
5233
5234 // Pseudo-object operations and ivar references need special
5235 // treatment because we're going to recursively rewrite them.
5236 if (PseudoObjectExpr *PseudoOp = dyn_cast<PseudoObjectExpr>(S)) {
5237 if (isa<BinaryOperator>(PseudoOp->getSyntacticForm())) {
5238 return RewritePropertyOrImplicitSetter(PseudoOp);
5239 } else {
5240 return RewritePropertyOrImplicitGetter(PseudoOp);
5241 }
5242 } else if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
5243 return RewriteObjCIvarRefExpr(IvarRefExpr);
5244 }
5245
5246 SourceRange OrigStmtRange = S->getSourceRange();
5247
5248 // Perform a bottom up rewrite of all children.
5249 for (Stmt::child_range CI = S->children(); CI; ++CI)
5250 if (*CI) {
5251 Stmt *childStmt = (*CI);
5252 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(childStmt);
5253 if (newStmt) {
5254 *CI = newStmt;
5255 }
5256 }
5257
5258 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
John McCallf4b88a42012-03-10 09:33:50 +00005259 SmallVector<DeclRefExpr *, 8> InnerBlockDeclRefs;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005260 llvm::SmallPtrSet<const DeclContext *, 8> InnerContexts;
5261 InnerContexts.insert(BE->getBlockDecl());
5262 ImportedLocalExternalDecls.clear();
5263 GetInnerBlockDeclRefExprs(BE->getBody(),
5264 InnerBlockDeclRefs, InnerContexts);
5265 // Rewrite the block body in place.
5266 Stmt *SaveCurrentBody = CurrentBody;
5267 CurrentBody = BE->getBody();
5268 PropParentMap = 0;
5269 // block literal on rhs of a property-dot-sytax assignment
5270 // must be replaced by its synthesize ast so getRewrittenText
5271 // works as expected. In this case, what actually ends up on RHS
5272 // is the blockTranscribed which is the helper function for the
5273 // block literal; as in: self.c = ^() {[ace ARR];};
5274 bool saveDisableReplaceStmt = DisableReplaceStmt;
5275 DisableReplaceStmt = false;
5276 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
5277 DisableReplaceStmt = saveDisableReplaceStmt;
5278 CurrentBody = SaveCurrentBody;
5279 PropParentMap = 0;
5280 ImportedLocalExternalDecls.clear();
5281 // Now we snarf the rewritten text and stash it away for later use.
5282 std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
5283 RewrittenBlockExprs[BE] = Str;
5284
5285 Stmt *blockTranscribed = SynthBlockInitExpr(BE, InnerBlockDeclRefs);
5286
5287 //blockTranscribed->dump();
5288 ReplaceStmt(S, blockTranscribed);
5289 return blockTranscribed;
5290 }
5291 // Handle specific things.
5292 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
5293 return RewriteAtEncode(AtEncode);
5294
5295 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
5296 return RewriteAtSelector(AtSelector);
5297
5298 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
5299 return RewriteObjCStringLiteral(AtString);
Fariborz Jahanian55947042012-03-27 20:17:30 +00005300
5301 if (ObjCBoolLiteralExpr *BoolLitExpr = dyn_cast<ObjCBoolLiteralExpr>(S))
5302 return RewriteObjCBoolLiteralExpr(BoolLitExpr);
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00005303
Patrick Beardeb382ec2012-04-19 00:25:12 +00005304 if (ObjCBoxedExpr *BoxedExpr = dyn_cast<ObjCBoxedExpr>(S))
5305 return RewriteObjCBoxedExpr(BoxedExpr);
Fariborz Jahanian86cff602012-03-30 23:35:47 +00005306
5307 if (ObjCArrayLiteral *ArrayLitExpr = dyn_cast<ObjCArrayLiteral>(S))
5308 return RewriteObjCArrayLiteralExpr(ArrayLitExpr);
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00005309
5310 if (ObjCDictionaryLiteral *DictionaryLitExpr =
5311 dyn_cast<ObjCDictionaryLiteral>(S))
5312 return RewriteObjCDictionaryLiteralExpr(DictionaryLitExpr);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005313
5314 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
5315#if 0
5316 // Before we rewrite it, put the original message expression in a comment.
5317 SourceLocation startLoc = MessExpr->getLocStart();
5318 SourceLocation endLoc = MessExpr->getLocEnd();
5319
5320 const char *startBuf = SM->getCharacterData(startLoc);
5321 const char *endBuf = SM->getCharacterData(endLoc);
5322
5323 std::string messString;
5324 messString += "// ";
5325 messString.append(startBuf, endBuf-startBuf+1);
5326 messString += "\n";
5327
5328 // FIXME: Missing definition of
5329 // InsertText(clang::SourceLocation, char const*, unsigned int).
5330 // InsertText(startLoc, messString.c_str(), messString.size());
5331 // Tried this, but it didn't work either...
5332 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
5333#endif
5334 return RewriteMessageExpr(MessExpr);
5335 }
5336
5337 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
5338 return RewriteObjCTryStmt(StmtTry);
5339
5340 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
5341 return RewriteObjCSynchronizedStmt(StmtTry);
5342
5343 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
5344 return RewriteObjCThrowStmt(StmtThrow);
5345
5346 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
5347 return RewriteObjCProtocolExpr(ProtocolExp);
5348
5349 if (ObjCForCollectionStmt *StmtForCollection =
5350 dyn_cast<ObjCForCollectionStmt>(S))
5351 return RewriteObjCForCollectionStmt(StmtForCollection,
5352 OrigStmtRange.getEnd());
5353 if (BreakStmt *StmtBreakStmt =
5354 dyn_cast<BreakStmt>(S))
5355 return RewriteBreakStmt(StmtBreakStmt);
5356 if (ContinueStmt *StmtContinueStmt =
5357 dyn_cast<ContinueStmt>(S))
5358 return RewriteContinueStmt(StmtContinueStmt);
5359
5360 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
5361 // and cast exprs.
5362 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
5363 // FIXME: What we're doing here is modifying the type-specifier that
5364 // precedes the first Decl. In the future the DeclGroup should have
5365 // a separate type-specifier that we can rewrite.
5366 // NOTE: We need to avoid rewriting the DeclStmt if it is within
5367 // the context of an ObjCForCollectionStmt. For example:
5368 // NSArray *someArray;
5369 // for (id <FooProtocol> index in someArray) ;
5370 // This is because RewriteObjCForCollectionStmt() does textual rewriting
5371 // and it depends on the original text locations/positions.
5372 if (Stmts.empty() || !IsDeclStmtInForeachHeader(DS))
5373 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
5374
5375 // Blocks rewrite rules.
5376 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
5377 DI != DE; ++DI) {
5378 Decl *SD = *DI;
5379 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
5380 if (isTopLevelBlockPointerType(ND->getType()))
5381 RewriteBlockPointerDecl(ND);
5382 else if (ND->getType()->isFunctionPointerType())
5383 CheckFunctionPointerDecl(ND->getType(), ND);
5384 if (VarDecl *VD = dyn_cast<VarDecl>(SD)) {
5385 if (VD->hasAttr<BlocksAttr>()) {
5386 static unsigned uniqueByrefDeclCount = 0;
5387 assert(!BlockByRefDeclNo.count(ND) &&
5388 "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl");
5389 BlockByRefDeclNo[ND] = uniqueByrefDeclCount++;
Fariborz Jahanian4fe261c2012-04-24 19:38:45 +00005390 RewriteByRefVar(VD, (DI == DS->decl_begin()), ((DI+1) == DE));
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005391 }
5392 else
5393 RewriteTypeOfDecl(VD);
5394 }
5395 }
5396 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(SD)) {
5397 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
5398 RewriteBlockPointerDecl(TD);
5399 else if (TD->getUnderlyingType()->isFunctionPointerType())
5400 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5401 }
5402 }
5403 }
5404
5405 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
5406 RewriteObjCQualifiedInterfaceTypes(CE);
5407
5408 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
5409 isa<DoStmt>(S) || isa<ForStmt>(S)) {
5410 assert(!Stmts.empty() && "Statement stack is empty");
5411 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
5412 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
5413 && "Statement stack mismatch");
5414 Stmts.pop_back();
5415 }
5416 // Handle blocks rewriting.
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005417 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
5418 ValueDecl *VD = DRE->getDecl();
5419 if (VD->hasAttr<BlocksAttr>())
5420 return RewriteBlockDeclRefExpr(DRE);
5421 if (HasLocalVariableExternalStorage(VD))
5422 return RewriteLocalVariableExternalStorage(DRE);
5423 }
5424
5425 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
5426 if (CE->getCallee()->getType()->isBlockPointerType()) {
5427 Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
5428 ReplaceStmt(S, BlockCall);
5429 return BlockCall;
5430 }
5431 }
5432 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
5433 RewriteCastExpr(CE);
5434 }
Fariborz Jahanianf1ee6872012-04-10 00:08:18 +00005435 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
5436 RewriteImplicitCastObjCExpr(ICE);
5437 }
Fariborz Jahanian43aa1c32012-04-16 22:14:01 +00005438#if 0
Fariborz Jahanian653b7cf2012-04-13 18:00:54 +00005439
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005440 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
5441 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(),
5442 ICE->getSubExpr(),
5443 SourceLocation());
5444 // Get the new text.
5445 std::string SStr;
5446 llvm::raw_string_ostream Buf(SStr);
5447 Replacement->printPretty(Buf, *Context);
5448 const std::string &Str = Buf.str();
5449
5450 printf("CAST = %s\n", &Str[0]);
5451 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
5452 delete S;
5453 return Replacement;
5454 }
5455#endif
5456 // Return this stmt unmodified.
5457 return S;
5458}
5459
5460void RewriteModernObjC::RewriteRecordBody(RecordDecl *RD) {
5461 for (RecordDecl::field_iterator i = RD->field_begin(),
5462 e = RD->field_end(); i != e; ++i) {
David Blaikie262bc182012-04-30 02:36:29 +00005463 FieldDecl *FD = &*i;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005464 if (isTopLevelBlockPointerType(FD->getType()))
5465 RewriteBlockPointerDecl(FD);
5466 if (FD->getType()->isObjCQualifiedIdType() ||
5467 FD->getType()->isObjCQualifiedInterfaceType())
5468 RewriteObjCQualifiedInterfaceTypes(FD);
5469 }
5470}
5471
5472/// HandleDeclInMainFile - This is called for each top-level decl defined in the
5473/// main file of the input.
5474void RewriteModernObjC::HandleDeclInMainFile(Decl *D) {
5475 switch (D->getKind()) {
5476 case Decl::Function: {
5477 FunctionDecl *FD = cast<FunctionDecl>(D);
5478 if (FD->isOverloadedOperator())
5479 return;
5480
5481 // Since function prototypes don't have ParmDecl's, we check the function
5482 // prototype. This enables us to rewrite function declarations and
5483 // definitions using the same code.
5484 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
5485
Argyrios Kyrtzidis9335df32012-02-12 04:48:45 +00005486 if (!FD->isThisDeclarationADefinition())
5487 break;
5488
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005489 // FIXME: If this should support Obj-C++, support CXXTryStmt
5490 if (CompoundStmt *Body = dyn_cast_or_null<CompoundStmt>(FD->getBody())) {
5491 CurFunctionDef = FD;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005492 CurrentBody = Body;
5493 Body =
5494 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5495 FD->setBody(Body);
5496 CurrentBody = 0;
5497 if (PropParentMap) {
5498 delete PropParentMap;
5499 PropParentMap = 0;
5500 }
5501 // This synthesizes and inserts the block "impl" struct, invoke function,
5502 // and any copy/dispose helper functions.
5503 InsertBlockLiteralsWithinFunction(FD);
5504 CurFunctionDef = 0;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005505 }
5506 break;
5507 }
5508 case Decl::ObjCMethod: {
5509 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(D);
5510 if (CompoundStmt *Body = MD->getCompoundBody()) {
5511 CurMethodDef = MD;
5512 CurrentBody = Body;
5513 Body =
5514 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5515 MD->setBody(Body);
5516 CurrentBody = 0;
5517 if (PropParentMap) {
5518 delete PropParentMap;
5519 PropParentMap = 0;
5520 }
5521 InsertBlockLiteralsWithinMethod(MD);
5522 CurMethodDef = 0;
5523 }
5524 break;
5525 }
5526 case Decl::ObjCImplementation: {
5527 ObjCImplementationDecl *CI = cast<ObjCImplementationDecl>(D);
5528 ClassImplementation.push_back(CI);
5529 break;
5530 }
5531 case Decl::ObjCCategoryImpl: {
5532 ObjCCategoryImplDecl *CI = cast<ObjCCategoryImplDecl>(D);
5533 CategoryImplementation.push_back(CI);
5534 break;
5535 }
5536 case Decl::Var: {
5537 VarDecl *VD = cast<VarDecl>(D);
5538 RewriteObjCQualifiedInterfaceTypes(VD);
5539 if (isTopLevelBlockPointerType(VD->getType()))
5540 RewriteBlockPointerDecl(VD);
5541 else if (VD->getType()->isFunctionPointerType()) {
5542 CheckFunctionPointerDecl(VD->getType(), VD);
5543 if (VD->getInit()) {
5544 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
5545 RewriteCastExpr(CE);
5546 }
5547 }
5548 } else if (VD->getType()->isRecordType()) {
5549 RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
5550 if (RD->isCompleteDefinition())
5551 RewriteRecordBody(RD);
5552 }
5553 if (VD->getInit()) {
5554 GlobalVarDecl = VD;
5555 CurrentBody = VD->getInit();
5556 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
5557 CurrentBody = 0;
5558 if (PropParentMap) {
5559 delete PropParentMap;
5560 PropParentMap = 0;
5561 }
5562 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(), VD->getName());
5563 GlobalVarDecl = 0;
5564
5565 // This is needed for blocks.
5566 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
5567 RewriteCastExpr(CE);
5568 }
5569 }
5570 break;
5571 }
5572 case Decl::TypeAlias:
5573 case Decl::Typedef: {
5574 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
5575 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
5576 RewriteBlockPointerDecl(TD);
5577 else if (TD->getUnderlyingType()->isFunctionPointerType())
5578 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5579 }
5580 break;
5581 }
5582 case Decl::CXXRecord:
5583 case Decl::Record: {
5584 RecordDecl *RD = cast<RecordDecl>(D);
5585 if (RD->isCompleteDefinition())
5586 RewriteRecordBody(RD);
5587 break;
5588 }
5589 default:
5590 break;
5591 }
5592 // Nothing yet.
5593}
5594
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00005595/// Write_ProtocolExprReferencedMetadata - This routine writer out the
5596/// protocol reference symbols in the for of:
5597/// struct _protocol_t *PROTOCOL_REF = &PROTOCOL_METADATA.
5598static void Write_ProtocolExprReferencedMetadata(ASTContext *Context,
5599 ObjCProtocolDecl *PDecl,
5600 std::string &Result) {
5601 // Also output .objc_protorefs$B section and its meta-data.
5602 if (Context->getLangOpts().MicrosoftExt)
Fariborz Jahanianbd78cfa2012-04-27 21:39:49 +00005603 Result += "static ";
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00005604 Result += "struct _protocol_t *";
5605 Result += "_OBJC_PROTOCOL_REFERENCE_$_";
5606 Result += PDecl->getNameAsString();
5607 Result += " = &";
5608 Result += "_OBJC_PROTOCOL_"; Result += PDecl->getNameAsString();
5609 Result += ";\n";
5610}
5611
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005612void RewriteModernObjC::HandleTranslationUnit(ASTContext &C) {
5613 if (Diags.hasErrorOccurred())
5614 return;
5615
5616 RewriteInclude();
5617
5618 // Here's a great place to add any extra declarations that may be needed.
5619 // Write out meta data for each @protocol(<expr>).
5620 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00005621 E = ProtocolExprDecls.end(); I != E; ++I) {
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00005622 RewriteObjCProtocolMetaData(*I, Preamble);
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00005623 Write_ProtocolExprReferencedMetadata(Context, (*I), Preamble);
5624 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005625
5626 InsertText(SM->getLocForStartOfFile(MainFileID), Preamble, false);
Fariborz Jahanian57317782012-02-21 23:58:41 +00005627 for (unsigned i = 0, e = ObjCInterfacesSeen.size(); i < e; i++) {
5628 ObjCInterfaceDecl *CDecl = ObjCInterfacesSeen[i];
5629 // Write struct declaration for the class matching its ivar declarations.
5630 // Note that for modern abi, this is postponed until the end of TU
5631 // because class extensions and the implementation might declare their own
5632 // private ivars.
5633 RewriteInterfaceDecl(CDecl);
5634 }
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00005635
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005636 if (ClassImplementation.size() || CategoryImplementation.size())
5637 RewriteImplementations();
5638
5639 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
5640 // we are done.
5641 if (const RewriteBuffer *RewriteBuf =
5642 Rewrite.getRewriteBufferFor(MainFileID)) {
5643 //printf("Changed:\n");
5644 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
5645 } else {
5646 llvm::errs() << "No changes\n";
5647 }
5648
5649 if (ClassImplementation.size() || CategoryImplementation.size() ||
5650 ProtocolExprDecls.size()) {
5651 // Rewrite Objective-c meta data*
5652 std::string ResultStr;
5653 RewriteMetaDataIntoBuffer(ResultStr);
5654 // Emit metadata.
5655 *OutFile << ResultStr;
5656 }
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005657 // Emit ImageInfo;
5658 {
5659 std::string ResultStr;
5660 WriteImageInfo(ResultStr);
5661 *OutFile << ResultStr;
5662 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005663 OutFile->flush();
5664}
5665
5666void RewriteModernObjC::Initialize(ASTContext &context) {
5667 InitializeCommon(context);
5668
Fariborz Jahanian6991bc52012-03-10 17:45:38 +00005669 Preamble += "#ifndef __OBJC2__\n";
5670 Preamble += "#define __OBJC2__\n";
5671 Preamble += "#endif\n";
5672
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005673 // declaring objc_selector outside the parameter list removes a silly
5674 // scope related warning...
5675 if (IsHeader)
5676 Preamble = "#pragma once\n";
5677 Preamble += "struct objc_selector; struct objc_class;\n";
Fariborz Jahaniane2d87bc2012-04-12 23:52:52 +00005678 Preamble += "struct __rw_objc_super { \n\tstruct objc_object *object; ";
5679 Preamble += "\n\tstruct objc_object *superClass; ";
5680 // Add a constructor for creating temporary objects.
5681 Preamble += "\n\t__rw_objc_super(struct objc_object *o, struct objc_object *s) ";
5682 Preamble += ": object(o), superClass(s) {} ";
5683 Preamble += "\n};\n";
5684
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005685 if (LangOpts.MicrosoftExt) {
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00005686 // Define all sections using syntax that makes sense.
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005687 // These are currently generated.
5688 Preamble += "\n#pragma section(\".objc_classlist$B\", long, read, write)\n";
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00005689 Preamble += "#pragma section(\".objc_catlist$B\", long, read, write)\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005690 Preamble += "#pragma section(\".objc_imageinfo$B\", long, read, write)\n";
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00005691 Preamble += "#pragma section(\".objc_nlclslist$B\", long, read, write)\n";
5692 Preamble += "#pragma section(\".objc_nlcatlist$B\", long, read, write)\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005693 // These are generated but not necessary for functionality.
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005694 Preamble += "#pragma section(\".cat_cls_meth$B\", long, read, write)\n";
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00005695 Preamble += "#pragma section(\".inst_meth$B\", long, read, write)\n";
5696 Preamble += "#pragma section(\".cls_meth$B\", long, read, write)\n";
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00005697 Preamble += "#pragma section(\".objc_ivar$B\", long, read, write)\n";
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00005698
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00005699 // These need be generated for performance. Currently they are not,
5700 // using API calls instead.
5701 Preamble += "#pragma section(\".objc_selrefs$B\", long, read, write)\n";
5702 Preamble += "#pragma section(\".objc_classrefs$B\", long, read, write)\n";
5703 Preamble += "#pragma section(\".objc_superrefs$B\", long, read, write)\n";
5704
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005705 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005706 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
5707 Preamble += "typedef struct objc_object Protocol;\n";
5708 Preamble += "#define _REWRITER_typedef_Protocol\n";
5709 Preamble += "#endif\n";
5710 if (LangOpts.MicrosoftExt) {
5711 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
5712 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
Fariborz Jahanian5cf6b6c2012-03-21 23:41:04 +00005713 }
5714 else
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005715 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
Fariborz Jahanian5cf6b6c2012-03-21 23:41:04 +00005716
5717 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend(void);\n";
5718 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSendSuper(void);\n";
5719 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend_stret(void);\n";
5720 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSendSuper_stret(void);\n";
5721 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend_fpret(void);\n";
5722
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005723 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getClass";
5724 Preamble += "(const char *);\n";
5725 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *class_getSuperclass";
5726 Preamble += "(struct objc_class *);\n";
5727 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getMetaClass";
5728 Preamble += "(const char *);\n";
Fariborz Jahanian55261af2012-03-19 18:11:32 +00005729 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw( struct objc_object *);\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005730 // @synchronized hooks.
Fariborz Jahanian55261af2012-03-19 18:11:32 +00005731 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_enter( struct objc_object *);\n";
5732 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_exit( struct objc_object *);\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005733 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
5734 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
5735 Preamble += "struct __objcFastEnumerationState {\n\t";
5736 Preamble += "unsigned long state;\n\t";
5737 Preamble += "void **itemsPtr;\n\t";
5738 Preamble += "unsigned long *mutationsPtr;\n\t";
5739 Preamble += "unsigned long extra[5];\n};\n";
5740 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
5741 Preamble += "#define __FASTENUMERATIONSTATE\n";
5742 Preamble += "#endif\n";
5743 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
5744 Preamble += "struct __NSConstantStringImpl {\n";
5745 Preamble += " int *isa;\n";
5746 Preamble += " int flags;\n";
5747 Preamble += " char *str;\n";
5748 Preamble += " long length;\n";
5749 Preamble += "};\n";
5750 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
5751 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
5752 Preamble += "#else\n";
5753 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
5754 Preamble += "#endif\n";
5755 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
5756 Preamble += "#endif\n";
5757 // Blocks preamble.
5758 Preamble += "#ifndef BLOCK_IMPL\n";
5759 Preamble += "#define BLOCK_IMPL\n";
5760 Preamble += "struct __block_impl {\n";
5761 Preamble += " void *isa;\n";
5762 Preamble += " int Flags;\n";
5763 Preamble += " int Reserved;\n";
5764 Preamble += " void *FuncPtr;\n";
5765 Preamble += "};\n";
5766 Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
5767 Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n";
5768 Preamble += "extern \"C\" __declspec(dllexport) "
5769 "void _Block_object_assign(void *, const void *, const int);\n";
5770 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
5771 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
5772 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
5773 Preamble += "#else\n";
5774 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n";
5775 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n";
5776 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
5777 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
5778 Preamble += "#endif\n";
5779 Preamble += "#endif\n";
5780 if (LangOpts.MicrosoftExt) {
5781 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
5782 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
5783 Preamble += "#ifndef KEEP_ATTRIBUTES\n"; // We use this for clang tests.
5784 Preamble += "#define __attribute__(X)\n";
5785 Preamble += "#endif\n";
Fariborz Jahanian5ce28272012-04-12 16:33:31 +00005786 Preamble += "#ifndef __weak\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005787 Preamble += "#define __weak\n";
Fariborz Jahanian5ce28272012-04-12 16:33:31 +00005788 Preamble += "#endif\n";
5789 Preamble += "#ifndef __block\n";
5790 Preamble += "#define __block\n";
5791 Preamble += "#endif\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005792 }
5793 else {
5794 Preamble += "#define __block\n";
5795 Preamble += "#define __weak\n";
5796 }
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00005797
5798 // Declarations required for modern objective-c array and dictionary literals.
5799 Preamble += "\n#include <stdarg.h>\n";
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00005800 Preamble += "struct __NSContainer_literal {\n";
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00005801 Preamble += " void * *arr;\n";
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00005802 Preamble += " __NSContainer_literal (unsigned int count, ...) {\n";
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00005803 Preamble += "\tva_list marker;\n";
5804 Preamble += "\tva_start(marker, count);\n";
5805 Preamble += "\tarr = new void *[count];\n";
5806 Preamble += "\tfor (unsigned i = 0; i < count; i++)\n";
5807 Preamble += "\t arr[i] = va_arg(marker, void *);\n";
5808 Preamble += "\tva_end( marker );\n";
5809 Preamble += " };\n";
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00005810 Preamble += " __NSContainer_literal() {\n";
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00005811 Preamble += "\tdelete[] arr;\n";
5812 Preamble += " }\n";
5813 Preamble += "};\n";
5814
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005815 // NOTE! Windows uses LLP64 for 64bit mode. So, cast pointer to long long
5816 // as this avoids warning in any 64bit/32bit compilation model.
5817 Preamble += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long long) &((TYPE *)0)->MEMBER)\n";
5818}
5819
5820/// RewriteIvarOffsetComputation - This rutine synthesizes computation of
5821/// ivar offset.
5822void RewriteModernObjC::RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
5823 std::string &Result) {
5824 if (ivar->isBitField()) {
5825 // FIXME: The hack below doesn't work for bitfields. For now, we simply
5826 // place all bitfields at offset 0.
5827 Result += "0";
5828 } else {
5829 Result += "__OFFSETOFIVAR__(struct ";
5830 Result += ivar->getContainingInterface()->getNameAsString();
5831 if (LangOpts.MicrosoftExt)
5832 Result += "_IMPL";
5833 Result += ", ";
5834 Result += ivar->getNameAsString();
5835 Result += ")";
5836 }
5837}
5838
5839/// WriteModernMetadataDeclarations - Writes out metadata declarations for modern ABI.
5840/// struct _prop_t {
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00005841/// const char *name;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005842/// char *attributes;
5843/// }
5844
5845/// struct _prop_list_t {
5846/// uint32_t entsize; // sizeof(struct _prop_t)
5847/// uint32_t count_of_properties;
5848/// struct _prop_t prop_list[count_of_properties];
5849/// }
5850
5851/// struct _protocol_t;
5852
5853/// struct _protocol_list_t {
5854/// long protocol_count; // Note, this is 32/64 bit
5855/// struct _protocol_t * protocol_list[protocol_count];
5856/// }
5857
5858/// struct _objc_method {
5859/// SEL _cmd;
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005860/// const char *method_type;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005861/// char *_imp;
5862/// }
5863
5864/// struct _method_list_t {
5865/// uint32_t entsize; // sizeof(struct _objc_method)
5866/// uint32_t method_count;
5867/// struct _objc_method method_list[method_count];
5868/// }
5869
5870/// struct _protocol_t {
5871/// id isa; // NULL
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005872/// const char *protocol_name;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005873/// const struct _protocol_list_t * protocol_list; // super protocols
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005874/// const struct method_list_t *instance_methods;
5875/// const struct method_list_t *class_methods;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005876/// const struct method_list_t *optionalInstanceMethods;
5877/// const struct method_list_t *optionalClassMethods;
5878/// const struct _prop_list_t * properties;
5879/// const uint32_t size; // sizeof(struct _protocol_t)
5880/// const uint32_t flags; // = 0
5881/// const char ** extendedMethodTypes;
5882/// }
5883
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005884/// struct _ivar_t {
5885/// unsigned long int *offset; // pointer to ivar offset location
Fariborz Jahanianae932952012-02-10 20:47:10 +00005886/// const char *name;
5887/// const char *type;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005888/// uint32_t alignment;
5889/// uint32_t size;
5890/// }
5891
5892/// struct _ivar_list_t {
5893/// uint32 entsize; // sizeof(struct _ivar_t)
5894/// uint32 count;
Fariborz Jahanianae932952012-02-10 20:47:10 +00005895/// struct _ivar_t list[count];
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005896/// }
5897
5898/// struct _class_ro_t {
Fariborz Jahanian249cd102012-03-24 16:53:16 +00005899/// uint32_t flags;
5900/// uint32_t instanceStart;
5901/// uint32_t instanceSize;
5902/// uint32_t reserved; // only when building for 64bit targets
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005903/// const uint8_t *ivarLayout;
5904/// const char *name;
5905/// const struct _method_list_t *baseMethods;
5906/// const struct _protocol_list_t *baseProtocols;
5907/// const struct _ivar_list_t *ivars;
5908/// const uint8_t *weakIvarLayout;
5909/// const struct _prop_list_t *properties;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005910/// }
5911
5912/// struct _class_t {
5913/// struct _class_t *isa;
Fariborz Jahanianfd4ce2c2012-03-20 17:34:50 +00005914/// struct _class_t *superclass;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005915/// void *cache;
5916/// IMP *vtable;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005917/// struct _class_ro_t *ro;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005918/// }
5919
5920/// struct _category_t {
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005921/// const char *name;
Fariborz Jahanian4b2fe6e2012-03-20 21:41:28 +00005922/// struct _class_t *cls;
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005923/// const struct _method_list_t *instance_methods;
5924/// const struct _method_list_t *class_methods;
5925/// const struct _protocol_list_t *protocols;
5926/// const struct _prop_list_t *properties;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005927/// }
5928
5929/// MessageRefTy - LLVM for:
5930/// struct _message_ref_t {
5931/// IMP messenger;
5932/// SEL name;
5933/// };
5934
5935/// SuperMessageRefTy - LLVM for:
5936/// struct _super_message_ref_t {
5937/// SUPER_IMP messenger;
5938/// SEL name;
5939/// };
5940
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00005941static void WriteModernMetadataDeclarations(ASTContext *Context, std::string &Result) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005942 static bool meta_data_declared = false;
5943 if (meta_data_declared)
5944 return;
5945
5946 Result += "\nstruct _prop_t {\n";
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00005947 Result += "\tconst char *name;\n";
5948 Result += "\tconst char *attributes;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005949 Result += "};\n";
5950
5951 Result += "\nstruct _protocol_t;\n";
5952
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005953 Result += "\nstruct _objc_method {\n";
5954 Result += "\tstruct objc_selector * _cmd;\n";
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005955 Result += "\tconst char *method_type;\n";
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005956 Result += "\tvoid *_imp;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005957 Result += "};\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005958
5959 Result += "\nstruct _protocol_t {\n";
5960 Result += "\tvoid * isa; // NULL\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005961 Result += "\tconst char *protocol_name;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005962 Result += "\tconst struct _protocol_list_t * protocol_list; // super protocols\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005963 Result += "\tconst struct method_list_t *instance_methods;\n";
5964 Result += "\tconst struct method_list_t *class_methods;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005965 Result += "\tconst struct method_list_t *optionalInstanceMethods;\n";
5966 Result += "\tconst struct method_list_t *optionalClassMethods;\n";
5967 Result += "\tconst struct _prop_list_t * properties;\n";
5968 Result += "\tconst unsigned int size; // sizeof(struct _protocol_t)\n";
5969 Result += "\tconst unsigned int flags; // = 0\n";
5970 Result += "\tconst char ** extendedMethodTypes;\n";
5971 Result += "};\n";
5972
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005973 Result += "\nstruct _ivar_t {\n";
5974 Result += "\tunsigned long int *offset; // pointer to ivar offset location\n";
Fariborz Jahanianae932952012-02-10 20:47:10 +00005975 Result += "\tconst char *name;\n";
5976 Result += "\tconst char *type;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005977 Result += "\tunsigned int alignment;\n";
5978 Result += "\tunsigned int size;\n";
5979 Result += "};\n";
5980
5981 Result += "\nstruct _class_ro_t {\n";
Fariborz Jahanian249cd102012-03-24 16:53:16 +00005982 Result += "\tunsigned int flags;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005983 Result += "\tunsigned int instanceStart;\n";
Fariborz Jahanian249cd102012-03-24 16:53:16 +00005984 Result += "\tunsigned int instanceSize;\n";
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00005985 const llvm::Triple &Triple(Context->getTargetInfo().getTriple());
5986 if (Triple.getArch() == llvm::Triple::x86_64)
Fariborz Jahanian249cd102012-03-24 16:53:16 +00005987 Result += "\tunsigned int reserved;\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005988 Result += "\tconst unsigned char *ivarLayout;\n";
5989 Result += "\tconst char *name;\n";
5990 Result += "\tconst struct _method_list_t *baseMethods;\n";
5991 Result += "\tconst struct _objc_protocol_list *baseProtocols;\n";
5992 Result += "\tconst struct _ivar_list_t *ivars;\n";
5993 Result += "\tconst unsigned char *weakIvarLayout;\n";
5994 Result += "\tconst struct _prop_list_t *properties;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005995 Result += "};\n";
5996
5997 Result += "\nstruct _class_t {\n";
5998 Result += "\tstruct _class_t *isa;\n";
Fariborz Jahanianfd4ce2c2012-03-20 17:34:50 +00005999 Result += "\tstruct _class_t *superclass;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006000 Result += "\tvoid *cache;\n";
6001 Result += "\tvoid *vtable;\n";
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006002 Result += "\tstruct _class_ro_t *ro;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006003 Result += "};\n";
6004
6005 Result += "\nstruct _category_t {\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006006 Result += "\tconst char *name;\n";
Fariborz Jahanian4b2fe6e2012-03-20 21:41:28 +00006007 Result += "\tstruct _class_t *cls;\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006008 Result += "\tconst struct _method_list_t *instance_methods;\n";
6009 Result += "\tconst struct _method_list_t *class_methods;\n";
6010 Result += "\tconst struct _protocol_list_t *protocols;\n";
6011 Result += "\tconst struct _prop_list_t *properties;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006012 Result += "};\n";
6013
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006014 Result += "extern \"C\" __declspec(dllimport) struct objc_cache _objc_empty_cache;\n";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006015 Result += "#pragma warning(disable:4273)\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006016 meta_data_declared = true;
6017}
6018
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006019static void Write_protocol_list_t_TypeDecl(std::string &Result,
6020 long super_protocol_count) {
6021 Result += "struct /*_protocol_list_t*/"; Result += " {\n";
6022 Result += "\tlong protocol_count; // Note, this is 32/64 bit\n";
6023 Result += "\tstruct _protocol_t *super_protocols[";
6024 Result += utostr(super_protocol_count); Result += "];\n";
6025 Result += "}";
6026}
6027
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006028static void Write_method_list_t_TypeDecl(std::string &Result,
6029 unsigned int method_count) {
6030 Result += "struct /*_method_list_t*/"; Result += " {\n";
6031 Result += "\tunsigned int entsize; // sizeof(struct _objc_method)\n";
6032 Result += "\tunsigned int method_count;\n";
6033 Result += "\tstruct _objc_method method_list[";
6034 Result += utostr(method_count); Result += "];\n";
6035 Result += "}";
6036}
6037
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006038static void Write__prop_list_t_TypeDecl(std::string &Result,
6039 unsigned int property_count) {
6040 Result += "struct /*_prop_list_t*/"; Result += " {\n";
6041 Result += "\tunsigned int entsize; // sizeof(struct _prop_t)\n";
6042 Result += "\tunsigned int count_of_properties;\n";
6043 Result += "\tstruct _prop_t prop_list[";
6044 Result += utostr(property_count); Result += "];\n";
6045 Result += "}";
6046}
6047
Fariborz Jahanianae932952012-02-10 20:47:10 +00006048static void Write__ivar_list_t_TypeDecl(std::string &Result,
6049 unsigned int ivar_count) {
6050 Result += "struct /*_ivar_list_t*/"; Result += " {\n";
6051 Result += "\tunsigned int entsize; // sizeof(struct _prop_t)\n";
6052 Result += "\tunsigned int count;\n";
6053 Result += "\tstruct _ivar_t ivar_list[";
6054 Result += utostr(ivar_count); Result += "];\n";
6055 Result += "}";
6056}
6057
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006058static void Write_protocol_list_initializer(ASTContext *Context, std::string &Result,
6059 ArrayRef<ObjCProtocolDecl *> SuperProtocols,
6060 StringRef VarName,
6061 StringRef ProtocolName) {
6062 if (SuperProtocols.size() > 0) {
6063 Result += "\nstatic ";
6064 Write_protocol_list_t_TypeDecl(Result, SuperProtocols.size());
6065 Result += " "; Result += VarName;
6066 Result += ProtocolName;
6067 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6068 Result += "\t"; Result += utostr(SuperProtocols.size()); Result += ",\n";
6069 for (unsigned i = 0, e = SuperProtocols.size(); i < e; i++) {
6070 ObjCProtocolDecl *SuperPD = SuperProtocols[i];
6071 Result += "\t&"; Result += "_OBJC_PROTOCOL_";
6072 Result += SuperPD->getNameAsString();
6073 if (i == e-1)
6074 Result += "\n};\n";
6075 else
6076 Result += ",\n";
6077 }
6078 }
6079}
6080
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006081static void Write_method_list_t_initializer(RewriteModernObjC &RewriteObj,
6082 ASTContext *Context, std::string &Result,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006083 ArrayRef<ObjCMethodDecl *> Methods,
6084 StringRef VarName,
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006085 StringRef TopLevelDeclName,
6086 bool MethodImpl) {
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006087 if (Methods.size() > 0) {
6088 Result += "\nstatic ";
6089 Write_method_list_t_TypeDecl(Result, Methods.size());
6090 Result += " "; Result += VarName;
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006091 Result += TopLevelDeclName;
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006092 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6093 Result += "\t"; Result += "sizeof(_objc_method)"; Result += ",\n";
6094 Result += "\t"; Result += utostr(Methods.size()); Result += ",\n";
6095 for (unsigned i = 0, e = Methods.size(); i < e; i++) {
6096 ObjCMethodDecl *MD = Methods[i];
6097 if (i == 0)
6098 Result += "\t{{(struct objc_selector *)\"";
6099 else
6100 Result += "\t{(struct objc_selector *)\"";
6101 Result += (MD)->getSelector().getAsString(); Result += "\"";
6102 Result += ", ";
6103 std::string MethodTypeString;
6104 Context->getObjCEncodingForMethodDecl(MD, MethodTypeString);
6105 Result += "\""; Result += MethodTypeString; Result += "\"";
6106 Result += ", ";
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006107 if (!MethodImpl)
6108 Result += "0";
6109 else {
6110 Result += "(void *)";
6111 Result += RewriteObj.MethodInternalNames[MD];
6112 }
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006113 if (i == e-1)
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006114 Result += "}}\n";
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006115 else
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006116 Result += "},\n";
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006117 }
6118 Result += "};\n";
6119 }
6120}
6121
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006122static void Write_prop_list_t_initializer(RewriteModernObjC &RewriteObj,
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006123 ASTContext *Context, std::string &Result,
6124 ArrayRef<ObjCPropertyDecl *> Properties,
6125 const Decl *Container,
6126 StringRef VarName,
6127 StringRef ProtocolName) {
6128 if (Properties.size() > 0) {
6129 Result += "\nstatic ";
6130 Write__prop_list_t_TypeDecl(Result, Properties.size());
6131 Result += " "; Result += VarName;
6132 Result += ProtocolName;
6133 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6134 Result += "\t"; Result += "sizeof(_prop_t)"; Result += ",\n";
6135 Result += "\t"; Result += utostr(Properties.size()); Result += ",\n";
6136 for (unsigned i = 0, e = Properties.size(); i < e; i++) {
6137 ObjCPropertyDecl *PropDecl = Properties[i];
6138 if (i == 0)
6139 Result += "\t{{\"";
6140 else
6141 Result += "\t{\"";
6142 Result += PropDecl->getName(); Result += "\",";
6143 std::string PropertyTypeString, QuotePropertyTypeString;
6144 Context->getObjCEncodingForPropertyDecl(PropDecl, Container, PropertyTypeString);
6145 RewriteObj.QuoteDoublequotes(PropertyTypeString, QuotePropertyTypeString);
6146 Result += "\""; Result += QuotePropertyTypeString; Result += "\"";
6147 if (i == e-1)
6148 Result += "}}\n";
6149 else
6150 Result += "},\n";
6151 }
6152 Result += "};\n";
6153 }
6154}
6155
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006156// Metadata flags
6157enum MetaDataDlags {
6158 CLS = 0x0,
6159 CLS_META = 0x1,
6160 CLS_ROOT = 0x2,
6161 OBJC2_CLS_HIDDEN = 0x10,
6162 CLS_EXCEPTION = 0x20,
6163
6164 /// (Obsolete) ARC-specific: this class has a .release_ivars method
6165 CLS_HAS_IVAR_RELEASER = 0x40,
6166 /// class was compiled with -fobjc-arr
6167 CLS_COMPILED_BY_ARC = 0x80 // (1<<7)
6168};
6169
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006170static void Write__class_ro_t_initializer(ASTContext *Context, std::string &Result,
6171 unsigned int flags,
6172 const std::string &InstanceStart,
6173 const std::string &InstanceSize,
6174 ArrayRef<ObjCMethodDecl *>baseMethods,
6175 ArrayRef<ObjCProtocolDecl *>baseProtocols,
6176 ArrayRef<ObjCIvarDecl *>ivars,
6177 ArrayRef<ObjCPropertyDecl *>Properties,
6178 StringRef VarName,
6179 StringRef ClassName) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006180 Result += "\nstatic struct _class_ro_t ";
6181 Result += VarName; Result += ClassName;
6182 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6183 Result += "\t";
6184 Result += llvm::utostr(flags); Result += ", ";
6185 Result += InstanceStart; Result += ", ";
6186 Result += InstanceSize; Result += ", \n";
6187 Result += "\t";
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00006188 const llvm::Triple &Triple(Context->getTargetInfo().getTriple());
6189 if (Triple.getArch() == llvm::Triple::x86_64)
6190 // uint32_t const reserved; // only when building for 64bit targets
6191 Result += "(unsigned int)0, \n\t";
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006192 // const uint8_t * const ivarLayout;
6193 Result += "0, \n\t";
6194 Result += "\""; Result += ClassName; Result += "\",\n\t";
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006195 bool metaclass = ((flags & CLS_META) != 0);
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006196 if (baseMethods.size() > 0) {
6197 Result += "(const struct _method_list_t *)&";
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006198 if (metaclass)
6199 Result += "_OBJC_$_CLASS_METHODS_";
6200 else
6201 Result += "_OBJC_$_INSTANCE_METHODS_";
6202 Result += ClassName;
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006203 Result += ",\n\t";
6204 }
6205 else
6206 Result += "0, \n\t";
6207
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006208 if (!metaclass && baseProtocols.size() > 0) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006209 Result += "(const struct _objc_protocol_list *)&";
6210 Result += "_OBJC_CLASS_PROTOCOLS_$_"; Result += ClassName;
6211 Result += ",\n\t";
6212 }
6213 else
6214 Result += "0, \n\t";
6215
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006216 if (!metaclass && ivars.size() > 0) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006217 Result += "(const struct _ivar_list_t *)&";
6218 Result += "_OBJC_$_INSTANCE_VARIABLES_"; Result += ClassName;
6219 Result += ",\n\t";
6220 }
6221 else
6222 Result += "0, \n\t";
6223
6224 // weakIvarLayout
6225 Result += "0, \n\t";
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006226 if (!metaclass && Properties.size() > 0) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006227 Result += "(const struct _prop_list_t *)&";
Fariborz Jahanianeeabf382012-02-16 21:57:59 +00006228 Result += "_OBJC_$_PROP_LIST_"; Result += ClassName;
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006229 Result += ",\n";
6230 }
6231 else
6232 Result += "0, \n";
6233
6234 Result += "};\n";
6235}
6236
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006237static void Write_class_t(ASTContext *Context, std::string &Result,
6238 StringRef VarName,
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006239 const ObjCInterfaceDecl *CDecl, bool metaclass) {
6240 bool rootClass = (!CDecl->getSuperClass());
6241 const ObjCInterfaceDecl *RootClass = CDecl;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006242
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006243 if (!rootClass) {
6244 // Find the Root class
6245 RootClass = CDecl->getSuperClass();
6246 while (RootClass->getSuperClass()) {
6247 RootClass = RootClass->getSuperClass();
6248 }
6249 }
6250
6251 if (metaclass && rootClass) {
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006252 // Need to handle a case of use of forward declaration.
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00006253 Result += "\n";
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006254 Result += "extern \"C\" ";
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00006255 if (CDecl->getImplementation())
6256 Result += "__declspec(dllexport) ";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006257 else
6258 Result += "__declspec(dllimport) ";
6259
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006260 Result += "struct _class_t OBJC_CLASS_$_";
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006261 Result += CDecl->getNameAsString();
6262 Result += ";\n";
6263 }
6264 // Also, for possibility of 'super' metadata class not having been defined yet.
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006265 if (!rootClass) {
Fariborz Jahanian868e9852012-03-29 19:04:10 +00006266 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00006267 Result += "\n";
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006268 Result += "extern \"C\" ";
Fariborz Jahanian868e9852012-03-29 19:04:10 +00006269 if (SuperClass->getImplementation())
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00006270 Result += "__declspec(dllexport) ";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006271 else
6272 Result += "__declspec(dllimport) ";
6273
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006274 Result += "struct _class_t ";
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00006275 Result += VarName;
Fariborz Jahanian868e9852012-03-29 19:04:10 +00006276 Result += SuperClass->getNameAsString();
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006277 Result += ";\n";
Fariborz Jahanian452eac12012-03-20 21:09:58 +00006278
Fariborz Jahanian868e9852012-03-29 19:04:10 +00006279 if (metaclass && RootClass != SuperClass) {
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006280 Result += "extern \"C\" ";
Fariborz Jahanian452eac12012-03-20 21:09:58 +00006281 if (RootClass->getImplementation())
6282 Result += "__declspec(dllexport) ";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006283 else
6284 Result += "__declspec(dllimport) ";
6285
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006286 Result += "struct _class_t ";
Fariborz Jahanian452eac12012-03-20 21:09:58 +00006287 Result += VarName;
6288 Result += RootClass->getNameAsString();
6289 Result += ";\n";
6290 }
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006291 }
6292
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006293 Result += "\nextern \"C\" __declspec(dllexport) struct _class_t ";
6294 Result += VarName; Result += CDecl->getNameAsString();
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006295 Result += " __attribute__ ((used, section (\"__DATA,__objc_data\"))) = {\n";
6296 Result += "\t";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006297 if (metaclass) {
6298 if (!rootClass) {
6299 Result += "0, // &"; Result += VarName;
6300 Result += RootClass->getNameAsString();
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006301 Result += ",\n\t";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006302 Result += "0, // &"; Result += VarName;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006303 Result += CDecl->getSuperClass()->getNameAsString();
6304 Result += ",\n\t";
6305 }
6306 else {
Fariborz Jahanian452eac12012-03-20 21:09:58 +00006307 Result += "0, // &"; Result += VarName;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006308 Result += CDecl->getNameAsString();
6309 Result += ",\n\t";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006310 Result += "0, // &OBJC_CLASS_$_"; Result += CDecl->getNameAsString();
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006311 Result += ",\n\t";
6312 }
6313 }
6314 else {
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006315 Result += "0, // &OBJC_METACLASS_$_";
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006316 Result += CDecl->getNameAsString();
6317 Result += ",\n\t";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006318 if (!rootClass) {
6319 Result += "0, // &"; Result += VarName;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006320 Result += CDecl->getSuperClass()->getNameAsString();
6321 Result += ",\n\t";
6322 }
6323 else
6324 Result += "0,\n\t";
6325 }
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006326 Result += "0, // (void *)&_objc_empty_cache,\n\t";
6327 Result += "0, // unused, was (void *)&_objc_empty_vtable,\n\t";
6328 if (metaclass)
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006329 Result += "&_OBJC_METACLASS_RO_$_";
6330 else
6331 Result += "&_OBJC_CLASS_RO_$_";
6332 Result += CDecl->getNameAsString();
6333 Result += ",\n};\n";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006334
6335 // Add static function to initialize some of the meta-data fields.
6336 // avoid doing it twice.
6337 if (metaclass)
6338 return;
6339
6340 const ObjCInterfaceDecl *SuperClass =
6341 rootClass ? CDecl : CDecl->getSuperClass();
6342
6343 Result += "static void OBJC_CLASS_SETUP_$_";
6344 Result += CDecl->getNameAsString();
6345 Result += "(void ) {\n";
6346 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
6347 Result += ".isa = "; Result += "&OBJC_METACLASS_$_";
Fariborz Jahanian452eac12012-03-20 21:09:58 +00006348 Result += RootClass->getNameAsString(); Result += ";\n";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006349
6350 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
Fariborz Jahanian452eac12012-03-20 21:09:58 +00006351 Result += ".superclass = ";
6352 if (rootClass)
6353 Result += "&OBJC_CLASS_$_";
6354 else
6355 Result += "&OBJC_METACLASS_$_";
6356
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006357 Result += SuperClass->getNameAsString(); Result += ";\n";
6358
6359 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
6360 Result += ".cache = "; Result += "&_objc_empty_cache"; Result += ";\n";
6361
6362 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6363 Result += ".isa = "; Result += "&OBJC_METACLASS_$_";
6364 Result += CDecl->getNameAsString(); Result += ";\n";
6365
6366 if (!rootClass) {
6367 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6368 Result += ".superclass = "; Result += "&OBJC_CLASS_$_";
6369 Result += SuperClass->getNameAsString(); Result += ";\n";
6370 }
6371
6372 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6373 Result += ".cache = "; Result += "&_objc_empty_cache"; Result += ";\n";
6374 Result += "}\n";
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006375}
6376
Fariborz Jahanian61186122012-02-17 18:40:41 +00006377static void Write_category_t(RewriteModernObjC &RewriteObj, ASTContext *Context,
6378 std::string &Result,
Fariborz Jahaniane0335782012-03-27 18:41:05 +00006379 ObjCCategoryDecl *CatDecl,
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006380 ObjCInterfaceDecl *ClassDecl,
Fariborz Jahanian61186122012-02-17 18:40:41 +00006381 ArrayRef<ObjCMethodDecl *> InstanceMethods,
6382 ArrayRef<ObjCMethodDecl *> ClassMethods,
6383 ArrayRef<ObjCProtocolDecl *> RefedProtocols,
6384 ArrayRef<ObjCPropertyDecl *> ClassProperties) {
Fariborz Jahaniane0335782012-03-27 18:41:05 +00006385 StringRef CatName = CatDecl->getName();
NAKAMURA Takumi20f89392012-03-21 03:21:46 +00006386 StringRef ClassName = ClassDecl->getName();
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00006387 // must declare an extern class object in case this class is not implemented
6388 // in this TU.
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006389 Result += "\n";
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006390 Result += "extern \"C\" ";
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006391 if (ClassDecl->getImplementation())
6392 Result += "__declspec(dllexport) ";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006393 else
6394 Result += "__declspec(dllimport) ";
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006395
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006396 Result += "struct _class_t ";
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00006397 Result += "OBJC_CLASS_$_"; Result += ClassName;
6398 Result += ";\n";
6399
Fariborz Jahanian61186122012-02-17 18:40:41 +00006400 Result += "\nstatic struct _category_t ";
6401 Result += "_OBJC_$_CATEGORY_";
6402 Result += ClassName; Result += "_$_"; Result += CatName;
6403 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = \n";
6404 Result += "{\n";
6405 Result += "\t\""; Result += ClassName; Result += "\",\n";
Fariborz Jahanian4b2fe6e2012-03-20 21:41:28 +00006406 Result += "\t0, // &"; Result += "OBJC_CLASS_$_"; Result += ClassName;
Fariborz Jahanian61186122012-02-17 18:40:41 +00006407 Result += ",\n";
6408 if (InstanceMethods.size() > 0) {
6409 Result += "\t(const struct _method_list_t *)&";
6410 Result += "_OBJC_$_CATEGORY_INSTANCE_METHODS_";
6411 Result += ClassName; Result += "_$_"; Result += CatName;
6412 Result += ",\n";
6413 }
6414 else
6415 Result += "\t0,\n";
6416
6417 if (ClassMethods.size() > 0) {
6418 Result += "\t(const struct _method_list_t *)&";
6419 Result += "_OBJC_$_CATEGORY_CLASS_METHODS_";
6420 Result += ClassName; Result += "_$_"; Result += CatName;
6421 Result += ",\n";
6422 }
6423 else
6424 Result += "\t0,\n";
6425
6426 if (RefedProtocols.size() > 0) {
6427 Result += "\t(const struct _protocol_list_t *)&";
6428 Result += "_OBJC_CATEGORY_PROTOCOLS_$_";
6429 Result += ClassName; Result += "_$_"; Result += CatName;
6430 Result += ",\n";
6431 }
6432 else
6433 Result += "\t0,\n";
6434
6435 if (ClassProperties.size() > 0) {
6436 Result += "\t(const struct _prop_list_t *)&"; Result += "_OBJC_$_PROP_LIST_";
6437 Result += ClassName; Result += "_$_"; Result += CatName;
6438 Result += ",\n";
6439 }
6440 else
6441 Result += "\t0,\n";
6442
6443 Result += "};\n";
Fariborz Jahanian4b2fe6e2012-03-20 21:41:28 +00006444
6445 // Add static function to initialize the class pointer in the category structure.
6446 Result += "static void OBJC_CATEGORY_SETUP_$_";
6447 Result += ClassDecl->getNameAsString();
6448 Result += "_$_";
6449 Result += CatName;
6450 Result += "(void ) {\n";
6451 Result += "\t_OBJC_$_CATEGORY_";
6452 Result += ClassDecl->getNameAsString();
6453 Result += "_$_";
6454 Result += CatName;
6455 Result += ".cls = "; Result += "&OBJC_CLASS_$_"; Result += ClassName;
6456 Result += ";\n}\n";
Fariborz Jahanian61186122012-02-17 18:40:41 +00006457}
6458
Fariborz Jahaniane0adbd82012-02-08 22:23:26 +00006459static void Write__extendedMethodTypes_initializer(RewriteModernObjC &RewriteObj,
6460 ASTContext *Context, std::string &Result,
6461 ArrayRef<ObjCMethodDecl *> Methods,
6462 StringRef VarName,
6463 StringRef ProtocolName) {
6464 if (Methods.size() == 0)
6465 return;
6466
6467 Result += "\nstatic const char *";
6468 Result += VarName; Result += ProtocolName;
6469 Result += " [] __attribute__ ((used, section (\"__DATA,__objc_const\"))) = \n";
6470 Result += "{\n";
6471 for (unsigned i = 0, e = Methods.size(); i < e; i++) {
6472 ObjCMethodDecl *MD = Methods[i];
6473 std::string MethodTypeString, QuoteMethodTypeString;
6474 Context->getObjCEncodingForMethodDecl(MD, MethodTypeString, true);
6475 RewriteObj.QuoteDoublequotes(MethodTypeString, QuoteMethodTypeString);
6476 Result += "\t\""; Result += QuoteMethodTypeString; Result += "\"";
6477 if (i == e-1)
6478 Result += "\n};\n";
6479 else {
6480 Result += ",\n";
6481 }
6482 }
6483}
6484
Fariborz Jahanianacee1c92012-04-11 21:12:36 +00006485static void Write_IvarOffsetVar(RewriteModernObjC &RewriteObj,
6486 ASTContext *Context,
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00006487 std::string &Result,
Fariborz Jahaniandb649232012-02-13 20:59:02 +00006488 ArrayRef<ObjCIvarDecl *> Ivars,
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006489 ObjCInterfaceDecl *CDecl) {
Fariborz Jahaniandb649232012-02-13 20:59:02 +00006490 // FIXME. visibilty of offset symbols may have to be set; for Darwin
6491 // this is what happens:
6492 /**
6493 if (Ivar->getAccessControl() == ObjCIvarDecl::Private ||
6494 Ivar->getAccessControl() == ObjCIvarDecl::Package ||
6495 Class->getVisibility() == HiddenVisibility)
6496 Visibility shoud be: HiddenVisibility;
6497 else
6498 Visibility shoud be: DefaultVisibility;
6499 */
6500
Fariborz Jahanian07e52882012-02-13 21:34:45 +00006501 Result += "\n";
6502 for (unsigned i =0, e = Ivars.size(); i < e; i++) {
6503 ObjCIvarDecl *IvarDecl = Ivars[i];
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00006504 if (Context->getLangOpts().MicrosoftExt)
6505 Result += "__declspec(allocate(\".objc_ivar$B\")) ";
6506
6507 if (!Context->getLangOpts().MicrosoftExt ||
6508 IvarDecl->getAccessControl() == ObjCIvarDecl::Private ||
Fariborz Jahanian117591f2012-03-10 01:34:42 +00006509 IvarDecl->getAccessControl() == ObjCIvarDecl::Package)
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006510 Result += "extern \"C\" unsigned long int ";
Fariborz Jahaniand1c84d32012-03-10 00:53:02 +00006511 else
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006512 Result += "extern \"C\" __declspec(dllexport) unsigned long int ";
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006513 WriteInternalIvarName(CDecl, IvarDecl, Result);
Fariborz Jahanian07e52882012-02-13 21:34:45 +00006514 Result += " __attribute__ ((used, section (\"__DATA,__objc_ivar\")))";
6515 Result += " = ";
Fariborz Jahanianacee1c92012-04-11 21:12:36 +00006516 RewriteObj.RewriteIvarOffsetComputation(IvarDecl, Result);
6517 Result += ";\n";
Fariborz Jahaniandb649232012-02-13 20:59:02 +00006518 }
6519}
6520
Fariborz Jahanianae932952012-02-10 20:47:10 +00006521static void Write__ivar_list_t_initializer(RewriteModernObjC &RewriteObj,
6522 ASTContext *Context, std::string &Result,
6523 ArrayRef<ObjCIvarDecl *> Ivars,
6524 StringRef VarName,
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006525 ObjCInterfaceDecl *CDecl) {
Fariborz Jahanianae932952012-02-10 20:47:10 +00006526 if (Ivars.size() > 0) {
Fariborz Jahanianacee1c92012-04-11 21:12:36 +00006527 Write_IvarOffsetVar(RewriteObj, Context, Result, Ivars, CDecl);
Fariborz Jahanian07e52882012-02-13 21:34:45 +00006528
Fariborz Jahanianae932952012-02-10 20:47:10 +00006529 Result += "\nstatic ";
6530 Write__ivar_list_t_TypeDecl(Result, Ivars.size());
6531 Result += " "; Result += VarName;
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006532 Result += CDecl->getNameAsString();
Fariborz Jahanianae932952012-02-10 20:47:10 +00006533 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6534 Result += "\t"; Result += "sizeof(_ivar_t)"; Result += ",\n";
6535 Result += "\t"; Result += utostr(Ivars.size()); Result += ",\n";
6536 for (unsigned i =0, e = Ivars.size(); i < e; i++) {
6537 ObjCIvarDecl *IvarDecl = Ivars[i];
6538 if (i == 0)
6539 Result += "\t{{";
6540 else
6541 Result += "\t {";
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006542 Result += "(unsigned long int *)&";
6543 WriteInternalIvarName(CDecl, IvarDecl, Result);
Fariborz Jahaniandb649232012-02-13 20:59:02 +00006544 Result += ", ";
Fariborz Jahanianae932952012-02-10 20:47:10 +00006545
6546 Result += "\""; Result += IvarDecl->getName(); Result += "\", ";
6547 std::string IvarTypeString, QuoteIvarTypeString;
6548 Context->getObjCEncodingForType(IvarDecl->getType(), IvarTypeString,
6549 IvarDecl);
6550 RewriteObj.QuoteDoublequotes(IvarTypeString, QuoteIvarTypeString);
6551 Result += "\""; Result += QuoteIvarTypeString; Result += "\", ";
6552
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00006553 // FIXME. this alignment represents the host alignment and need be changed to
6554 // represent the target alignment.
6555 unsigned Align = Context->getTypeAlign(IvarDecl->getType())/8;
6556 Align = llvm::Log2_32(Align);
Fariborz Jahanianae932952012-02-10 20:47:10 +00006557 Result += llvm::utostr(Align); Result += ", ";
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00006558 CharUnits Size = Context->getTypeSizeInChars(IvarDecl->getType());
6559 Result += llvm::utostr(Size.getQuantity());
Fariborz Jahanianae932952012-02-10 20:47:10 +00006560 if (i == e-1)
6561 Result += "}}\n";
6562 else
6563 Result += "},\n";
6564 }
6565 Result += "};\n";
6566 }
6567}
6568
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006569/// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006570void RewriteModernObjC::RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl,
6571 std::string &Result) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006572
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006573 // Do not synthesize the protocol more than once.
6574 if (ObjCSynthesizedProtocols.count(PDecl->getCanonicalDecl()))
6575 return;
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00006576 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006577
6578 if (ObjCProtocolDecl *Def = PDecl->getDefinition())
6579 PDecl = Def;
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006580 // Must write out all protocol definitions in current qualifier list,
6581 // and in their nested qualifiers before writing out current definition.
6582 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
6583 E = PDecl->protocol_end(); I != E; ++I)
6584 RewriteObjCProtocolMetaData(*I, Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006585
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006586 // Construct method lists.
6587 std::vector<ObjCMethodDecl *> InstanceMethods, ClassMethods;
6588 std::vector<ObjCMethodDecl *> OptInstanceMethods, OptClassMethods;
6589 for (ObjCProtocolDecl::instmeth_iterator
6590 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
6591 I != E; ++I) {
6592 ObjCMethodDecl *MD = *I;
6593 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
6594 OptInstanceMethods.push_back(MD);
6595 } else {
6596 InstanceMethods.push_back(MD);
6597 }
6598 }
6599
6600 for (ObjCProtocolDecl::classmeth_iterator
6601 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
6602 I != E; ++I) {
6603 ObjCMethodDecl *MD = *I;
6604 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
6605 OptClassMethods.push_back(MD);
6606 } else {
6607 ClassMethods.push_back(MD);
6608 }
6609 }
Fariborz Jahaniane0adbd82012-02-08 22:23:26 +00006610 std::vector<ObjCMethodDecl *> AllMethods;
6611 for (unsigned i = 0, e = InstanceMethods.size(); i < e; i++)
6612 AllMethods.push_back(InstanceMethods[i]);
6613 for (unsigned i = 0, e = ClassMethods.size(); i < e; i++)
6614 AllMethods.push_back(ClassMethods[i]);
6615 for (unsigned i = 0, e = OptInstanceMethods.size(); i < e; i++)
6616 AllMethods.push_back(OptInstanceMethods[i]);
6617 for (unsigned i = 0, e = OptClassMethods.size(); i < e; i++)
6618 AllMethods.push_back(OptClassMethods[i]);
6619
6620 Write__extendedMethodTypes_initializer(*this, Context, Result,
6621 AllMethods,
6622 "_OBJC_PROTOCOL_METHOD_TYPES_",
6623 PDecl->getNameAsString());
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006624 // Protocol's super protocol list
6625 std::vector<ObjCProtocolDecl *> SuperProtocols;
6626 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
6627 E = PDecl->protocol_end(); I != E; ++I)
6628 SuperProtocols.push_back(*I);
6629
6630 Write_protocol_list_initializer(Context, Result, SuperProtocols,
6631 "_OBJC_PROTOCOL_REFS_",
6632 PDecl->getNameAsString());
6633
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006634 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006635 "_OBJC_PROTOCOL_INSTANCE_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006636 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006637
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006638 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006639 "_OBJC_PROTOCOL_CLASS_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006640 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006641
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006642 Write_method_list_t_initializer(*this, Context, Result, OptInstanceMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006643 "_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006644 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006645
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006646 Write_method_list_t_initializer(*this, Context, Result, OptClassMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006647 "_OBJC_PROTOCOL_OPT_CLASS_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006648 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006649
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006650 // Protocol's property metadata.
6651 std::vector<ObjCPropertyDecl *> ProtocolProperties;
6652 for (ObjCContainerDecl::prop_iterator I = PDecl->prop_begin(),
6653 E = PDecl->prop_end(); I != E; ++I)
David Blaikie262bc182012-04-30 02:36:29 +00006654 ProtocolProperties.push_back(&*I);
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006655
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006656 Write_prop_list_t_initializer(*this, Context, Result, ProtocolProperties,
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006657 /* Container */0,
6658 "_OBJC_PROTOCOL_PROPERTIES_",
6659 PDecl->getNameAsString());
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006660
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006661 // Writer out root metadata for current protocol: struct _protocol_t
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00006662 Result += "\n";
6663 if (LangOpts.MicrosoftExt)
Fariborz Jahanian8590d862012-04-14 17:13:08 +00006664 Result += "static ";
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00006665 Result += "struct _protocol_t _OBJC_PROTOCOL_";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006666 Result += PDecl->getNameAsString();
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006667 Result += " __attribute__ ((used, section (\"__DATA,__datacoal_nt,coalesced\"))) = {\n";
6668 Result += "\t0,\n"; // id is; is null
6669 Result += "\t\""; Result += PDecl->getNameAsString(); Result += "\",\n";
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006670 if (SuperProtocols.size() > 0) {
6671 Result += "\t(const struct _protocol_list_t *)&"; Result += "_OBJC_PROTOCOL_REFS_";
6672 Result += PDecl->getNameAsString(); Result += ",\n";
6673 }
6674 else
6675 Result += "\t0,\n";
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006676 if (InstanceMethods.size() > 0) {
6677 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
6678 Result += PDecl->getNameAsString(); Result += ",\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006679 }
6680 else
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006681 Result += "\t0,\n";
6682
6683 if (ClassMethods.size() > 0) {
6684 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_CLASS_METHODS_";
6685 Result += PDecl->getNameAsString(); Result += ",\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006686 }
6687 else
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006688 Result += "\t0,\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006689
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006690 if (OptInstanceMethods.size() > 0) {
6691 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_";
6692 Result += PDecl->getNameAsString(); Result += ",\n";
6693 }
6694 else
6695 Result += "\t0,\n";
6696
6697 if (OptClassMethods.size() > 0) {
6698 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_CLASS_METHODS_";
6699 Result += PDecl->getNameAsString(); Result += ",\n";
6700 }
6701 else
6702 Result += "\t0,\n";
6703
6704 if (ProtocolProperties.size() > 0) {
6705 Result += "\t(const struct _prop_list_t *)&_OBJC_PROTOCOL_PROPERTIES_";
6706 Result += PDecl->getNameAsString(); Result += ",\n";
6707 }
6708 else
6709 Result += "\t0,\n";
6710
6711 Result += "\t"; Result += "sizeof(_protocol_t)"; Result += ",\n";
6712 Result += "\t0,\n";
6713
Fariborz Jahaniane0adbd82012-02-08 22:23:26 +00006714 if (AllMethods.size() > 0) {
6715 Result += "\t(const char **)&"; Result += "_OBJC_PROTOCOL_METHOD_TYPES_";
6716 Result += PDecl->getNameAsString();
6717 Result += "\n};\n";
6718 }
6719 else
6720 Result += "\t0\n};\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00006721
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00006722 if (LangOpts.MicrosoftExt)
Fariborz Jahanian8590d862012-04-14 17:13:08 +00006723 Result += "static ";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00006724 Result += "struct _protocol_t *";
6725 Result += "_OBJC_LABEL_PROTOCOL_$_"; Result += PDecl->getNameAsString();
6726 Result += " = &_OBJC_PROTOCOL_"; Result += PDecl->getNameAsString();
6727 Result += ";\n";
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006728
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006729 // Mark this protocol as having been generated.
6730 if (!ObjCSynthesizedProtocols.insert(PDecl->getCanonicalDecl()))
6731 llvm_unreachable("protocol already synthesized");
6732
6733}
6734
6735void RewriteModernObjC::RewriteObjCProtocolListMetaData(
6736 const ObjCList<ObjCProtocolDecl> &Protocols,
6737 StringRef prefix, StringRef ClassName,
6738 std::string &Result) {
6739 if (Protocols.empty()) return;
6740
6741 for (unsigned i = 0; i != Protocols.size(); i++)
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006742 RewriteObjCProtocolMetaData(Protocols[i], Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006743
6744 // Output the top lovel protocol meta-data for the class.
6745 /* struct _objc_protocol_list {
6746 struct _objc_protocol_list *next;
6747 int protocol_count;
6748 struct _objc_protocol *class_protocols[];
6749 }
6750 */
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00006751 Result += "\n";
6752 if (LangOpts.MicrosoftExt)
6753 Result += "__declspec(allocate(\".cat_cls_meth$B\")) ";
6754 Result += "static struct {\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006755 Result += "\tstruct _objc_protocol_list *next;\n";
6756 Result += "\tint protocol_count;\n";
6757 Result += "\tstruct _objc_protocol *class_protocols[";
6758 Result += utostr(Protocols.size());
6759 Result += "];\n} _OBJC_";
6760 Result += prefix;
6761 Result += "_PROTOCOLS_";
6762 Result += ClassName;
6763 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
6764 "{\n\t0, ";
6765 Result += utostr(Protocols.size());
6766 Result += "\n";
6767
6768 Result += "\t,{&_OBJC_PROTOCOL_";
6769 Result += Protocols[0]->getNameAsString();
6770 Result += " \n";
6771
6772 for (unsigned i = 1; i != Protocols.size(); i++) {
6773 Result += "\t ,&_OBJC_PROTOCOL_";
6774 Result += Protocols[i]->getNameAsString();
6775 Result += "\n";
6776 }
6777 Result += "\t }\n};\n";
6778}
6779
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006780/// hasObjCExceptionAttribute - Return true if this class or any super
6781/// class has the __objc_exception__ attribute.
6782/// FIXME. Move this to ASTContext.cpp as it is also used for IRGen.
6783static bool hasObjCExceptionAttribute(ASTContext &Context,
6784 const ObjCInterfaceDecl *OID) {
6785 if (OID->hasAttr<ObjCExceptionAttr>())
6786 return true;
6787 if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
6788 return hasObjCExceptionAttribute(Context, Super);
6789 return false;
6790}
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006791
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006792void RewriteModernObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
6793 std::string &Result) {
6794 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
6795
6796 // Explicitly declared @interface's are already synthesized.
Fariborz Jahanianae932952012-02-10 20:47:10 +00006797 if (CDecl->isImplicitInterfaceDecl())
6798 assert(false &&
6799 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00006800
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00006801 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanianae932952012-02-10 20:47:10 +00006802 SmallVector<ObjCIvarDecl *, 8> IVars;
6803
6804 for (ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
6805 IVD; IVD = IVD->getNextIvar()) {
6806 // Ignore unnamed bit-fields.
6807 if (!IVD->getDeclName())
6808 continue;
6809 IVars.push_back(IVD);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006810 }
6811
Fariborz Jahanianae932952012-02-10 20:47:10 +00006812 Write__ivar_list_t_initializer(*this, Context, Result, IVars,
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006813 "_OBJC_$_INSTANCE_VARIABLES_",
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006814 CDecl);
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006815
6816 // Build _objc_method_list for class's instance methods if needed
6817 SmallVector<ObjCMethodDecl *, 32>
6818 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
6819
6820 // If any of our property implementations have associated getters or
6821 // setters, produce metadata for them as well.
6822 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
6823 PropEnd = IDecl->propimpl_end();
6824 Prop != PropEnd; ++Prop) {
David Blaikie262bc182012-04-30 02:36:29 +00006825 if (Prop->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006826 continue;
David Blaikie262bc182012-04-30 02:36:29 +00006827 if (!Prop->getPropertyIvarDecl())
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006828 continue;
David Blaikie262bc182012-04-30 02:36:29 +00006829 ObjCPropertyDecl *PD = Prop->getPropertyDecl();
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006830 if (!PD)
6831 continue;
6832 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
6833 if (!Getter->isDefined())
6834 InstanceMethods.push_back(Getter);
6835 if (PD->isReadOnly())
6836 continue;
6837 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
6838 if (!Setter->isDefined())
6839 InstanceMethods.push_back(Setter);
6840 }
6841
6842 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
6843 "_OBJC_$_INSTANCE_METHODS_",
6844 IDecl->getNameAsString(), true);
6845
6846 SmallVector<ObjCMethodDecl *, 32>
6847 ClassMethods(IDecl->classmeth_begin(), IDecl->classmeth_end());
6848
6849 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
6850 "_OBJC_$_CLASS_METHODS_",
6851 IDecl->getNameAsString(), true);
Fariborz Jahanian0a525342012-02-14 19:31:35 +00006852
6853 // Protocols referenced in class declaration?
6854 // Protocol's super protocol list
6855 std::vector<ObjCProtocolDecl *> RefedProtocols;
6856 const ObjCList<ObjCProtocolDecl> &Protocols = CDecl->getReferencedProtocols();
6857 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
6858 E = Protocols.end();
6859 I != E; ++I) {
6860 RefedProtocols.push_back(*I);
6861 // Must write out all protocol definitions in current qualifier list,
6862 // and in their nested qualifiers before writing out current definition.
6863 RewriteObjCProtocolMetaData(*I, Result);
6864 }
6865
6866 Write_protocol_list_initializer(Context, Result,
6867 RefedProtocols,
6868 "_OBJC_CLASS_PROTOCOLS_$_",
6869 IDecl->getNameAsString());
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006870
6871 // Protocol's property metadata.
6872 std::vector<ObjCPropertyDecl *> ClassProperties;
6873 for (ObjCContainerDecl::prop_iterator I = CDecl->prop_begin(),
6874 E = CDecl->prop_end(); I != E; ++I)
David Blaikie262bc182012-04-30 02:36:29 +00006875 ClassProperties.push_back(&*I);
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006876
6877 Write_prop_list_t_initializer(*this, Context, Result, ClassProperties,
Fariborz Jahanian2df089d2012-03-22 17:39:35 +00006878 /* Container */IDecl,
Fariborz Jahanianeeabf382012-02-16 21:57:59 +00006879 "_OBJC_$_PROP_LIST_",
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006880 CDecl->getNameAsString());
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006881
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006882
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006883 // Data for initializing _class_ro_t metaclass meta-data
6884 uint32_t flags = CLS_META;
6885 std::string InstanceSize;
6886 std::string InstanceStart;
6887
6888
6889 bool classIsHidden = CDecl->getVisibility() == HiddenVisibility;
6890 if (classIsHidden)
6891 flags |= OBJC2_CLS_HIDDEN;
6892
6893 if (!CDecl->getSuperClass())
6894 // class is root
6895 flags |= CLS_ROOT;
6896 InstanceSize = "sizeof(struct _class_t)";
6897 InstanceStart = InstanceSize;
6898 Write__class_ro_t_initializer(Context, Result, flags,
6899 InstanceStart, InstanceSize,
6900 ClassMethods,
6901 0,
6902 0,
6903 0,
6904 "_OBJC_METACLASS_RO_$_",
6905 CDecl->getNameAsString());
6906
6907
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006908 // Data for initializing _class_ro_t meta-data
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006909 flags = CLS;
6910 if (classIsHidden)
6911 flags |= OBJC2_CLS_HIDDEN;
6912
6913 if (hasObjCExceptionAttribute(*Context, CDecl))
6914 flags |= CLS_EXCEPTION;
6915
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006916 if (!CDecl->getSuperClass())
6917 // class is root
6918 flags |= CLS_ROOT;
6919
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006920 InstanceSize.clear();
6921 InstanceStart.clear();
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006922 if (!ObjCSynthesizedStructs.count(CDecl)) {
6923 InstanceSize = "0";
6924 InstanceStart = "0";
6925 }
6926 else {
6927 InstanceSize = "sizeof(struct ";
6928 InstanceSize += CDecl->getNameAsString();
6929 InstanceSize += "_IMPL)";
6930
6931 ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
6932 if (IVD) {
Fariborz Jahanianacee1c92012-04-11 21:12:36 +00006933 RewriteIvarOffsetComputation(IVD, InstanceStart);
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006934 }
6935 else
6936 InstanceStart = InstanceSize;
6937 }
6938 Write__class_ro_t_initializer(Context, Result, flags,
6939 InstanceStart, InstanceSize,
6940 InstanceMethods,
6941 RefedProtocols,
6942 IVars,
6943 ClassProperties,
6944 "_OBJC_CLASS_RO_$_",
6945 CDecl->getNameAsString());
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006946
6947 Write_class_t(Context, Result,
6948 "OBJC_METACLASS_$_",
6949 CDecl, /*metaclass*/true);
6950
6951 Write_class_t(Context, Result,
6952 "OBJC_CLASS_$_",
6953 CDecl, /*metaclass*/false);
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006954
6955 if (ImplementationIsNonLazy(IDecl))
6956 DefinedNonLazyClasses.push_back(CDecl);
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006957
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006958}
6959
Fariborz Jahaniane0335782012-03-27 18:41:05 +00006960void RewriteModernObjC::RewriteClassSetupInitHook(std::string &Result) {
6961 int ClsDefCount = ClassImplementation.size();
6962 if (!ClsDefCount)
6963 return;
6964 Result += "#pragma section(\".objc_inithooks$B\", long, read, write)\n";
6965 Result += "__declspec(allocate(\".objc_inithooks$B\")) ";
6966 Result += "static void *OBJC_CLASS_SETUP[] = {\n";
6967 for (int i = 0; i < ClsDefCount; i++) {
6968 ObjCImplementationDecl *IDecl = ClassImplementation[i];
6969 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
6970 Result += "\t(void *)&OBJC_CLASS_SETUP_$_";
6971 Result += CDecl->getName(); Result += ",\n";
6972 }
6973 Result += "};\n";
6974}
6975
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006976void RewriteModernObjC::RewriteMetaDataIntoBuffer(std::string &Result) {
6977 int ClsDefCount = ClassImplementation.size();
6978 int CatDefCount = CategoryImplementation.size();
6979
6980 // For each implemented class, write out all its meta data.
6981 for (int i = 0; i < ClsDefCount; i++)
6982 RewriteObjCClassMetaData(ClassImplementation[i], Result);
6983
Fariborz Jahaniane0335782012-03-27 18:41:05 +00006984 RewriteClassSetupInitHook(Result);
6985
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006986 // For each implemented category, write out all its meta data.
6987 for (int i = 0; i < CatDefCount; i++)
6988 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
6989
Fariborz Jahaniane0335782012-03-27 18:41:05 +00006990 RewriteCategorySetupInitHook(Result);
6991
Fariborz Jahaniandf795672012-02-17 00:06:14 +00006992 if (ClsDefCount > 0) {
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00006993 if (LangOpts.MicrosoftExt)
6994 Result += "__declspec(allocate(\".objc_classlist$B\")) ";
Fariborz Jahaniandf795672012-02-17 00:06:14 +00006995 Result += "static struct _class_t *L_OBJC_LABEL_CLASS_$ [";
6996 Result += llvm::utostr(ClsDefCount); Result += "]";
6997 Result +=
6998 " __attribute__((used, section (\"__DATA, __objc_classlist,"
6999 "regular,no_dead_strip\")))= {\n";
7000 for (int i = 0; i < ClsDefCount; i++) {
7001 Result += "\t&OBJC_CLASS_$_";
7002 Result += ClassImplementation[i]->getNameAsString();
7003 Result += ",\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007004 }
Fariborz Jahaniandf795672012-02-17 00:06:14 +00007005 Result += "};\n";
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00007006
7007 if (!DefinedNonLazyClasses.empty()) {
7008 if (LangOpts.MicrosoftExt)
7009 Result += "__declspec(allocate(\".objc_nlclslist$B\")) \n";
7010 Result += "static struct _class_t *_OBJC_LABEL_NONLAZY_CLASS_$[] = {\n\t";
7011 for (unsigned i = 0, e = DefinedNonLazyClasses.size(); i < e; i++) {
7012 Result += "\t&OBJC_CLASS_$_"; Result += DefinedNonLazyClasses[i]->getNameAsString();
7013 Result += ",\n";
7014 }
7015 Result += "};\n";
7016 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007017 }
Fariborz Jahanian61186122012-02-17 18:40:41 +00007018
7019 if (CatDefCount > 0) {
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00007020 if (LangOpts.MicrosoftExt)
7021 Result += "__declspec(allocate(\".objc_catlist$B\")) ";
Fariborz Jahanian61186122012-02-17 18:40:41 +00007022 Result += "static struct _category_t *L_OBJC_LABEL_CATEGORY_$ [";
7023 Result += llvm::utostr(CatDefCount); Result += "]";
7024 Result +=
7025 " __attribute__((used, section (\"__DATA, __objc_catlist,"
7026 "regular,no_dead_strip\")))= {\n";
7027 for (int i = 0; i < CatDefCount; i++) {
7028 Result += "\t&_OBJC_$_CATEGORY_";
7029 Result +=
7030 CategoryImplementation[i]->getClassInterface()->getNameAsString();
7031 Result += "_$_";
7032 Result += CategoryImplementation[i]->getNameAsString();
7033 Result += ",\n";
7034 }
7035 Result += "};\n";
7036 }
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00007037
7038 if (!DefinedNonLazyCategories.empty()) {
7039 if (LangOpts.MicrosoftExt)
7040 Result += "__declspec(allocate(\".objc_nlcatlist$B\")) \n";
7041 Result += "static struct _category_t *_OBJC_LABEL_NONLAZY_CATEGORY_$[] = {\n\t";
7042 for (unsigned i = 0, e = DefinedNonLazyCategories.size(); i < e; i++) {
7043 Result += "\t&_OBJC_$_CATEGORY_";
7044 Result +=
7045 DefinedNonLazyCategories[i]->getClassInterface()->getNameAsString();
7046 Result += "_$_";
7047 Result += DefinedNonLazyCategories[i]->getNameAsString();
7048 Result += ",\n";
7049 }
7050 Result += "};\n";
7051 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007052}
7053
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00007054void RewriteModernObjC::WriteImageInfo(std::string &Result) {
7055 if (LangOpts.MicrosoftExt)
7056 Result += "__declspec(allocate(\".objc_imageinfo$B\")) \n";
7057
7058 Result += "static struct IMAGE_INFO { unsigned version; unsigned flag; } ";
7059 // version 0, ObjCABI is 2
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00007060 Result += "_OBJC_IMAGE_INFO = { 0, 2 };\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00007061}
7062
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007063/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
7064/// implementation.
7065void RewriteModernObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
7066 std::string &Result) {
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00007067 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007068 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
7069 // Find category declaration for this implementation.
Fariborz Jahanian61186122012-02-17 18:40:41 +00007070 ObjCCategoryDecl *CDecl=0;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007071 for (CDecl = ClassDecl->getCategoryList(); CDecl;
7072 CDecl = CDecl->getNextClassCategory())
7073 if (CDecl->getIdentifier() == IDecl->getIdentifier())
7074 break;
7075
7076 std::string FullCategoryName = ClassDecl->getNameAsString();
Fariborz Jahanian61186122012-02-17 18:40:41 +00007077 FullCategoryName += "_$_";
7078 FullCategoryName += CDecl->getNameAsString();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007079
7080 // Build _objc_method_list for class's instance methods if needed
7081 SmallVector<ObjCMethodDecl *, 32>
7082 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
7083
7084 // If any of our property implementations have associated getters or
7085 // setters, produce metadata for them as well.
7086 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
7087 PropEnd = IDecl->propimpl_end();
7088 Prop != PropEnd; ++Prop) {
David Blaikie262bc182012-04-30 02:36:29 +00007089 if (Prop->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007090 continue;
David Blaikie262bc182012-04-30 02:36:29 +00007091 if (!Prop->getPropertyIvarDecl())
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007092 continue;
David Blaikie262bc182012-04-30 02:36:29 +00007093 ObjCPropertyDecl *PD = Prop->getPropertyDecl();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007094 if (!PD)
7095 continue;
7096 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
7097 InstanceMethods.push_back(Getter);
7098 if (PD->isReadOnly())
7099 continue;
7100 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
7101 InstanceMethods.push_back(Setter);
7102 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007103
Fariborz Jahanian61186122012-02-17 18:40:41 +00007104 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
7105 "_OBJC_$_CATEGORY_INSTANCE_METHODS_",
7106 FullCategoryName, true);
7107
7108 SmallVector<ObjCMethodDecl *, 32>
7109 ClassMethods(IDecl->classmeth_begin(), IDecl->classmeth_end());
7110
7111 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
7112 "_OBJC_$_CATEGORY_CLASS_METHODS_",
7113 FullCategoryName, true);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007114
7115 // Protocols referenced in class declaration?
Fariborz Jahanian61186122012-02-17 18:40:41 +00007116 // Protocol's super protocol list
7117 std::vector<ObjCProtocolDecl *> RefedProtocols;
Argyrios Kyrtzidisa5f44412012-03-13 01:09:41 +00007118 for (ObjCInterfaceDecl::protocol_iterator I = CDecl->protocol_begin(),
7119 E = CDecl->protocol_end();
7120
7121 I != E; ++I) {
Fariborz Jahanian61186122012-02-17 18:40:41 +00007122 RefedProtocols.push_back(*I);
7123 // Must write out all protocol definitions in current qualifier list,
7124 // and in their nested qualifiers before writing out current definition.
7125 RewriteObjCProtocolMetaData(*I, Result);
7126 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007127
Fariborz Jahanian61186122012-02-17 18:40:41 +00007128 Write_protocol_list_initializer(Context, Result,
7129 RefedProtocols,
7130 "_OBJC_CATEGORY_PROTOCOLS_$_",
7131 FullCategoryName);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007132
Fariborz Jahanian61186122012-02-17 18:40:41 +00007133 // Protocol's property metadata.
7134 std::vector<ObjCPropertyDecl *> ClassProperties;
7135 for (ObjCContainerDecl::prop_iterator I = CDecl->prop_begin(),
7136 E = CDecl->prop_end(); I != E; ++I)
David Blaikie262bc182012-04-30 02:36:29 +00007137 ClassProperties.push_back(&*I);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007138
Fariborz Jahanian61186122012-02-17 18:40:41 +00007139 Write_prop_list_t_initializer(*this, Context, Result, ClassProperties,
7140 /* Container */0,
7141 "_OBJC_$_PROP_LIST_",
7142 FullCategoryName);
7143
7144 Write_category_t(*this, Context, Result,
Fariborz Jahaniane0335782012-03-27 18:41:05 +00007145 CDecl,
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00007146 ClassDecl,
Fariborz Jahanian61186122012-02-17 18:40:41 +00007147 InstanceMethods,
7148 ClassMethods,
7149 RefedProtocols,
7150 ClassProperties);
7151
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00007152 // Determine if this category is also "non-lazy".
7153 if (ImplementationIsNonLazy(IDecl))
7154 DefinedNonLazyCategories.push_back(CDecl);
Fariborz Jahaniane0335782012-03-27 18:41:05 +00007155
7156}
7157
7158void RewriteModernObjC::RewriteCategorySetupInitHook(std::string &Result) {
7159 int CatDefCount = CategoryImplementation.size();
7160 if (!CatDefCount)
7161 return;
7162 Result += "#pragma section(\".objc_inithooks$B\", long, read, write)\n";
7163 Result += "__declspec(allocate(\".objc_inithooks$B\")) ";
7164 Result += "static void *OBJC_CATEGORY_SETUP[] = {\n";
7165 for (int i = 0; i < CatDefCount; i++) {
7166 ObjCCategoryImplDecl *IDecl = CategoryImplementation[i];
7167 ObjCCategoryDecl *CatDecl= IDecl->getCategoryDecl();
7168 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
7169 Result += "\t(void *)&OBJC_CATEGORY_SETUP_$_";
7170 Result += ClassDecl->getName();
7171 Result += "_$_";
7172 Result += CatDecl->getName();
7173 Result += ",\n";
7174 }
7175 Result += "};\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007176}
7177
7178// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
7179/// class methods.
7180template<typename MethodIterator>
7181void RewriteModernObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
7182 MethodIterator MethodEnd,
7183 bool IsInstanceMethod,
7184 StringRef prefix,
7185 StringRef ClassName,
7186 std::string &Result) {
7187 if (MethodBegin == MethodEnd) return;
7188
7189 if (!objc_impl_method) {
7190 /* struct _objc_method {
7191 SEL _cmd;
7192 char *method_types;
7193 void *_imp;
7194 }
7195 */
7196 Result += "\nstruct _objc_method {\n";
7197 Result += "\tSEL _cmd;\n";
7198 Result += "\tchar *method_types;\n";
7199 Result += "\tvoid *_imp;\n";
7200 Result += "};\n";
7201
7202 objc_impl_method = true;
7203 }
7204
7205 // Build _objc_method_list for class's methods if needed
7206
7207 /* struct {
7208 struct _objc_method_list *next_method;
7209 int method_count;
7210 struct _objc_method method_list[];
7211 }
7212 */
7213 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00007214 Result += "\n";
7215 if (LangOpts.MicrosoftExt) {
7216 if (IsInstanceMethod)
7217 Result += "__declspec(allocate(\".inst_meth$B\")) ";
7218 else
7219 Result += "__declspec(allocate(\".cls_meth$B\")) ";
7220 }
7221 Result += "static struct {\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007222 Result += "\tstruct _objc_method_list *next_method;\n";
7223 Result += "\tint method_count;\n";
7224 Result += "\tstruct _objc_method method_list[";
7225 Result += utostr(NumMethods);
7226 Result += "];\n} _OBJC_";
7227 Result += prefix;
7228 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
7229 Result += "_METHODS_";
7230 Result += ClassName;
7231 Result += " __attribute__ ((used, section (\"__OBJC, __";
7232 Result += IsInstanceMethod ? "inst" : "cls";
7233 Result += "_meth\")))= ";
7234 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
7235
7236 Result += "\t,{{(SEL)\"";
7237 Result += (*MethodBegin)->getSelector().getAsString().c_str();
7238 std::string MethodTypeString;
7239 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
7240 Result += "\", \"";
7241 Result += MethodTypeString;
7242 Result += "\", (void *)";
7243 Result += MethodInternalNames[*MethodBegin];
7244 Result += "}\n";
7245 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
7246 Result += "\t ,{(SEL)\"";
7247 Result += (*MethodBegin)->getSelector().getAsString().c_str();
7248 std::string MethodTypeString;
7249 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
7250 Result += "\", \"";
7251 Result += MethodTypeString;
7252 Result += "\", (void *)";
7253 Result += MethodInternalNames[*MethodBegin];
7254 Result += "}\n";
7255 }
7256 Result += "\t }\n};\n";
7257}
7258
7259Stmt *RewriteModernObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) {
7260 SourceRange OldRange = IV->getSourceRange();
7261 Expr *BaseExpr = IV->getBase();
7262
7263 // Rewrite the base, but without actually doing replaces.
7264 {
7265 DisableReplaceStmtScope S(*this);
7266 BaseExpr = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(BaseExpr));
7267 IV->setBase(BaseExpr);
7268 }
7269
7270 ObjCIvarDecl *D = IV->getDecl();
7271
7272 Expr *Replacement = IV;
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007273
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007274 if (BaseExpr->getType()->isObjCObjectPointerType()) {
7275 const ObjCInterfaceType *iFaceDecl =
7276 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
7277 assert(iFaceDecl && "RewriteObjCIvarRefExpr - iFaceDecl is null");
7278 // lookup which class implements the instance variable.
7279 ObjCInterfaceDecl *clsDeclared = 0;
7280 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
7281 clsDeclared);
7282 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
7283
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007284 // Build name of symbol holding ivar offset.
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00007285 std::string IvarOffsetName;
7286 WriteInternalIvarName(clsDeclared, D, IvarOffsetName);
7287
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00007288 ReferencedIvars[clsDeclared].insert(D);
7289
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007290 // cast offset to "char *".
7291 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context,
7292 Context->getPointerType(Context->CharTy),
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007293 CK_BitCast,
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007294 BaseExpr);
7295 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
7296 SourceLocation(), &Context->Idents.get(IvarOffsetName),
7297 Context->UnsignedLongTy, 0, SC_Extern, SC_None);
John McCallf4b88a42012-03-10 09:33:50 +00007298 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, false,
7299 Context->UnsignedLongTy, VK_LValue,
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007300 SourceLocation());
7301 BinaryOperator *addExpr =
7302 new (Context) BinaryOperator(castExpr, DRE, BO_Add,
7303 Context->getPointerType(Context->CharTy),
7304 VK_RValue, OK_Ordinary, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007305 // Don't forget the parens to enforce the proper binding.
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007306 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(),
7307 SourceLocation(),
7308 addExpr);
Fariborz Jahanian0d6e22a2012-02-24 17:35:35 +00007309 QualType IvarT = D->getType();
Fariborz Jahanian27fc81b2012-04-27 22:48:54 +00007310
7311 if (IvarT->isRecordType()) {
7312 RecordDecl *RD = IvarT->getAs<RecordType>()->getDecl();
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00007313 RD = RD->getDefinition();
7314 if (RD && !RD->getDeclName().getAsIdentifierInfo()) {
Fariborz Jahanian27fc81b2012-04-27 22:48:54 +00007315 // decltype(((Foo_IMPL*)0)->bar) *
7316 std::string RecName = iFaceDecl->getDecl()->getName();
7317 RecName += "_IMPL";
7318 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
7319 SourceLocation(), SourceLocation(),
7320 &Context->Idents.get(RecName.c_str()));
7321 QualType PtrStructIMPL = Context->getPointerType(Context->getTagDeclType(RD));
7322 unsigned UnsignedIntSize =
7323 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
7324 Expr *Zero = IntegerLiteral::Create(*Context,
7325 llvm::APInt(UnsignedIntSize, 0),
7326 Context->UnsignedIntTy, SourceLocation());
7327 Zero = NoTypeInfoCStyleCastExpr(Context, PtrStructIMPL, CK_BitCast, Zero);
7328 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
7329 Zero);
7330 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
7331 SourceLocation(),
7332 &Context->Idents.get(D->getNameAsString()),
7333 IvarT, 0,
7334 /*BitWidth=*/0, /*Mutable=*/true,
7335 /*HasInit=*/false);
7336 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
7337 FD->getType(), VK_LValue,
7338 OK_Ordinary);
7339 IvarT = Context->getDecltypeType(ME, ME->getType());
7340 }
7341 }
Fariborz Jahanian8e0913d2012-02-29 00:26:20 +00007342 convertObjCTypeToCStyleType(IvarT);
Fariborz Jahanian0d6e22a2012-02-24 17:35:35 +00007343 QualType castT = Context->getPointerType(IvarT);
Fariborz Jahanian27fc81b2012-04-27 22:48:54 +00007344
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007345 castExpr = NoTypeInfoCStyleCastExpr(Context,
7346 castT,
7347 CK_BitCast,
7348 PE);
Fariborz Jahanian27fc81b2012-04-27 22:48:54 +00007349
7350
Fariborz Jahanian8e0913d2012-02-29 00:26:20 +00007351 Expr *Exp = new (Context) UnaryOperator(castExpr, UO_Deref, IvarT,
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007352 VK_LValue, OK_Ordinary,
7353 SourceLocation());
7354 PE = new (Context) ParenExpr(OldRange.getBegin(),
7355 OldRange.getEnd(),
7356 Exp);
7357
7358 Replacement = PE;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007359 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007360
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007361 ReplaceStmtWithRange(IV, Replacement, OldRange);
7362 return Replacement;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007363}