blob: acb0ac73f2cfbe0e949b46cb13aeaf969100a21b [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;
105 FunctionDecl *CurFunctionDeclToDeclareForBlock;
106
107 /* Misc. containers needed for meta-data rewrite. */
108 SmallVector<ObjCImplementationDecl *, 8> ClassImplementation;
109 SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation;
110 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCSynthesizedStructs;
111 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> ObjCSynthesizedProtocols;
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +0000112 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCWrittenInterfaces;
Fariborz Jahanian15f87772012-02-28 22:45:07 +0000113 llvm::SmallPtrSet<TagDecl*, 8> TagsDefinedInIvarDecls;
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +0000114 SmallVector<ObjCInterfaceDecl*, 32> ObjCInterfacesSeen;
Fariborz Jahanian88f7f752012-03-14 23:18:19 +0000115 /// DefinedNonLazyClasses - List of defined "non-lazy" classes.
116 SmallVector<ObjCInterfaceDecl*, 8> DefinedNonLazyClasses;
117
118 /// DefinedNonLazyCategories - List of defined "non-lazy" categories.
119 llvm::SmallVector<ObjCCategoryDecl*, 8> DefinedNonLazyCategories;
120
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000121 SmallVector<Stmt *, 32> Stmts;
122 SmallVector<int, 8> ObjCBcLabelNo;
123 // Remember all the @protocol(<expr>) expressions.
124 llvm::SmallPtrSet<ObjCProtocolDecl *, 32> ProtocolExprDecls;
125
126 llvm::DenseSet<uint64_t> CopyDestroyCache;
127
128 // Block expressions.
129 SmallVector<BlockExpr *, 32> Blocks;
130 SmallVector<int, 32> InnerDeclRefsCount;
John McCallf4b88a42012-03-10 09:33:50 +0000131 SmallVector<DeclRefExpr *, 32> InnerDeclRefs;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000132
John McCallf4b88a42012-03-10 09:33:50 +0000133 SmallVector<DeclRefExpr *, 32> BlockDeclRefs;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000134
135 // Block related declarations.
136 SmallVector<ValueDecl *, 8> BlockByCopyDecls;
137 llvm::SmallPtrSet<ValueDecl *, 8> BlockByCopyDeclsPtrSet;
138 SmallVector<ValueDecl *, 8> BlockByRefDecls;
139 llvm::SmallPtrSet<ValueDecl *, 8> BlockByRefDeclsPtrSet;
140 llvm::DenseMap<ValueDecl *, unsigned> BlockByRefDeclNo;
141 llvm::SmallPtrSet<ValueDecl *, 8> ImportedBlockDecls;
142 llvm::SmallPtrSet<VarDecl *, 8> ImportedLocalExternalDecls;
143
144 llvm::DenseMap<BlockExpr *, std::string> RewrittenBlockExprs;
Fariborz Jahanian72c88f12012-02-22 18:13:25 +0000145 llvm::DenseMap<ObjCInterfaceDecl *,
146 llvm::SmallPtrSet<ObjCIvarDecl *, 8> > ReferencedIvars;
147
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000148 // This maps an original source AST to it's rewritten form. This allows
149 // us to avoid rewriting the same node twice (which is very uncommon).
150 // This is needed to support some of the exotic property rewriting.
151 llvm::DenseMap<Stmt *, Stmt *> ReplacedNodes;
152
153 // Needed for header files being rewritten
154 bool IsHeader;
155 bool SilenceRewriteMacroWarning;
156 bool objc_impl_method;
157
158 bool DisableReplaceStmt;
159 class DisableReplaceStmtScope {
160 RewriteModernObjC &R;
161 bool SavedValue;
162
163 public:
164 DisableReplaceStmtScope(RewriteModernObjC &R)
165 : R(R), SavedValue(R.DisableReplaceStmt) {
166 R.DisableReplaceStmt = true;
167 }
168 ~DisableReplaceStmtScope() {
169 R.DisableReplaceStmt = SavedValue;
170 }
171 };
172 void InitializeCommon(ASTContext &context);
173
174 public:
Fariborz Jahanian90af4e22012-02-14 17:19:02 +0000175 llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000176 // Top Level Driver code.
177 virtual bool HandleTopLevelDecl(DeclGroupRef D) {
178 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
179 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(*I)) {
180 if (!Class->isThisDeclarationADefinition()) {
181 RewriteForwardClassDecl(D);
182 break;
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +0000183 } else {
184 // Keep track of all interface declarations seen.
Fariborz Jahanianf3295272012-02-24 21:42:38 +0000185 ObjCInterfacesSeen.push_back(Class);
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +0000186 break;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000187 }
188 }
189
190 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>(*I)) {
191 if (!Proto->isThisDeclarationADefinition()) {
192 RewriteForwardProtocolDecl(D);
193 break;
194 }
195 }
196
197 HandleTopLevelSingleDecl(*I);
198 }
199 return true;
200 }
201 void HandleTopLevelSingleDecl(Decl *D);
202 void HandleDeclInMainFile(Decl *D);
203 RewriteModernObjC(std::string inFile, raw_ostream *OS,
204 DiagnosticsEngine &D, const LangOptions &LOpts,
205 bool silenceMacroWarn);
206
207 ~RewriteModernObjC() {}
208
209 virtual void HandleTranslationUnit(ASTContext &C);
210
211 void ReplaceStmt(Stmt *Old, Stmt *New) {
212 Stmt *ReplacingStmt = ReplacedNodes[Old];
213
214 if (ReplacingStmt)
215 return; // We can't rewrite the same node twice.
216
217 if (DisableReplaceStmt)
218 return;
219
220 // If replacement succeeded or warning disabled return with no warning.
221 if (!Rewrite.ReplaceStmt(Old, New)) {
222 ReplacedNodes[Old] = New;
223 return;
224 }
225 if (SilenceRewriteMacroWarning)
226 return;
227 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
228 << Old->getSourceRange();
229 }
230
231 void ReplaceStmtWithRange(Stmt *Old, Stmt *New, SourceRange SrcRange) {
232 if (DisableReplaceStmt)
233 return;
234
235 // Measure the old text.
236 int Size = Rewrite.getRangeSize(SrcRange);
237 if (Size == -1) {
238 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
239 << Old->getSourceRange();
240 return;
241 }
242 // Get the new text.
243 std::string SStr;
244 llvm::raw_string_ostream S(SStr);
245 New->printPretty(S, *Context, 0, PrintingPolicy(LangOpts));
246 const std::string &Str = S.str();
247
248 // If replacement succeeded or warning disabled return with no warning.
249 if (!Rewrite.ReplaceText(SrcRange.getBegin(), Size, Str)) {
250 ReplacedNodes[Old] = New;
251 return;
252 }
253 if (SilenceRewriteMacroWarning)
254 return;
255 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
256 << Old->getSourceRange();
257 }
258
259 void InsertText(SourceLocation Loc, StringRef Str,
260 bool InsertAfter = true) {
261 // If insertion succeeded or warning disabled return with no warning.
262 if (!Rewrite.InsertText(Loc, Str, InsertAfter) ||
263 SilenceRewriteMacroWarning)
264 return;
265
266 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
267 }
268
269 void ReplaceText(SourceLocation Start, unsigned OrigLength,
270 StringRef Str) {
271 // If removal succeeded or warning disabled return with no warning.
272 if (!Rewrite.ReplaceText(Start, OrigLength, Str) ||
273 SilenceRewriteMacroWarning)
274 return;
275
276 Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
277 }
278
279 // Syntactic Rewriting.
280 void RewriteRecordBody(RecordDecl *RD);
281 void RewriteInclude();
282 void RewriteForwardClassDecl(DeclGroupRef D);
283 void RewriteForwardClassDecl(const llvm::SmallVector<Decl*, 8> &DG);
284 void RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
285 const std::string &typedefString);
286 void RewriteImplementations();
287 void RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
288 ObjCImplementationDecl *IMD,
289 ObjCCategoryImplDecl *CID);
290 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
291 void RewriteImplementationDecl(Decl *Dcl);
292 void RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
293 ObjCMethodDecl *MDecl, std::string &ResultStr);
294 void RewriteTypeIntoString(QualType T, std::string &ResultStr,
295 const FunctionType *&FPRetType);
296 void RewriteByRefString(std::string &ResultStr, const std::string &Name,
297 ValueDecl *VD, bool def=false);
298 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
299 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
300 void RewriteForwardProtocolDecl(DeclGroupRef D);
301 void RewriteForwardProtocolDecl(const llvm::SmallVector<Decl*, 8> &DG);
302 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
303 void RewriteProperty(ObjCPropertyDecl *prop);
304 void RewriteFunctionDecl(FunctionDecl *FD);
305 void RewriteBlockPointerType(std::string& Str, QualType Type);
306 void RewriteBlockPointerTypeVariable(std::string& Str, ValueDecl *VD);
307 void RewriteBlockLiteralFunctionDecl(FunctionDecl *FD);
308 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
309 void RewriteTypeOfDecl(VarDecl *VD);
310 void RewriteObjCQualifiedInterfaceTypes(Expr *E);
311
312 // Expression Rewriting.
313 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
314 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
315 Stmt *RewritePropertyOrImplicitGetter(PseudoObjectExpr *Pseudo);
316 Stmt *RewritePropertyOrImplicitSetter(PseudoObjectExpr *Pseudo);
317 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
318 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
319 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian55947042012-03-27 20:17:30 +0000320 Stmt *RewriteObjCBoolLiteralExpr(ObjCBoolLiteralExpr *Exp);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000321 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000322 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
323 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
324 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
325 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
326 SourceLocation OrigEnd);
327 Stmt *RewriteBreakStmt(BreakStmt *S);
328 Stmt *RewriteContinueStmt(ContinueStmt *S);
329 void RewriteCastExpr(CStyleCastExpr *CE);
330
331 // Block rewriting.
332 void RewriteBlocksInFunctionProtoType(QualType funcType, NamedDecl *D);
333
334 // Block specific rewrite rules.
335 void RewriteBlockPointerDecl(NamedDecl *VD);
336 void RewriteByRefVar(VarDecl *VD);
John McCallf4b88a42012-03-10 09:33:50 +0000337 Stmt *RewriteBlockDeclRefExpr(DeclRefExpr *VD);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000338 Stmt *RewriteLocalVariableExternalStorage(DeclRefExpr *DRE);
339 void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
340
341 void RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
342 std::string &Result);
343
Fariborz Jahanian15f87772012-02-28 22:45:07 +0000344 void RewriteObjCFieldDecl(FieldDecl *fieldDecl, std::string &Result);
345
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +0000346 bool RewriteObjCFieldDeclType(QualType &Type, std::string &Result);
347
Fariborz Jahanian72c88f12012-02-22 18:13:25 +0000348 void RewriteIvarOffsetSymbols(ObjCInterfaceDecl *CDecl,
349 std::string &Result);
350
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000351 virtual void Initialize(ASTContext &context);
352
353 // Misc. AST transformation routines. Somtimes they end up calling
354 // rewriting routines on the new ASTs.
355 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
356 Expr **args, unsigned nargs,
357 SourceLocation StartLoc=SourceLocation(),
358 SourceLocation EndLoc=SourceLocation());
359
360 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp,
361 SourceLocation StartLoc=SourceLocation(),
362 SourceLocation EndLoc=SourceLocation());
363
364 void SynthCountByEnumWithState(std::string &buf);
365 void SynthMsgSendFunctionDecl();
366 void SynthMsgSendSuperFunctionDecl();
367 void SynthMsgSendStretFunctionDecl();
368 void SynthMsgSendFpretFunctionDecl();
369 void SynthMsgSendSuperStretFunctionDecl();
370 void SynthGetClassFunctionDecl();
371 void SynthGetMetaClassFunctionDecl();
372 void SynthGetSuperClassFunctionDecl();
373 void SynthSelGetUidFunctionDecl();
374 void SynthSuperContructorFunctionDecl();
375
376 // Rewriting metadata
377 template<typename MethodIterator>
378 void RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
379 MethodIterator MethodEnd,
380 bool IsInstanceMethod,
381 StringRef prefix,
382 StringRef ClassName,
383 std::string &Result);
Fariborz Jahanianda9624a2012-02-08 19:53:58 +0000384 void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
385 std::string &Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000386 virtual void RewriteObjCProtocolListMetaData(
387 const ObjCList<ObjCProtocolDecl> &Prots,
388 StringRef prefix, StringRef ClassName, std::string &Result);
389 virtual void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
390 std::string &Result);
Fariborz Jahaniane0335782012-03-27 18:41:05 +0000391 virtual void RewriteClassSetupInitHook(std::string &Result);
392
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000393 virtual void RewriteMetaDataIntoBuffer(std::string &Result);
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +0000394 virtual void WriteImageInfo(std::string &Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000395 virtual void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
396 std::string &Result);
Fariborz Jahaniane0335782012-03-27 18:41:05 +0000397 virtual void RewriteCategorySetupInitHook(std::string &Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000398
399 // Rewriting ivar
400 virtual void RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
401 std::string &Result);
402 virtual Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV);
403
404
405 std::string SynthesizeByrefCopyDestroyHelper(VarDecl *VD, int flag);
406 std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
407 StringRef funcName, std::string Tag);
408 std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
409 StringRef funcName, std::string Tag);
410 std::string SynthesizeBlockImpl(BlockExpr *CE,
411 std::string Tag, std::string Desc);
412 std::string SynthesizeBlockDescriptor(std::string DescTag,
413 std::string ImplTag,
414 int i, StringRef funcName,
415 unsigned hasCopy);
416 Stmt *SynthesizeBlockCall(CallExpr *Exp, const Expr* BlockExp);
417 void SynthesizeBlockLiterals(SourceLocation FunLocStart,
418 StringRef FunName);
419 FunctionDecl *SynthBlockInitFunctionDecl(StringRef name);
420 Stmt *SynthBlockInitExpr(BlockExpr *Exp,
John McCallf4b88a42012-03-10 09:33:50 +0000421 const SmallVector<DeclRefExpr *, 8> &InnerBlockDeclRefs);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000422
423 // Misc. helper routines.
424 QualType getProtocolType();
425 void WarnAboutReturnGotoStmts(Stmt *S);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000426 void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
427 void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
428 void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
429
430 bool IsDeclStmtInForeachHeader(DeclStmt *DS);
431 void CollectBlockDeclRefInfo(BlockExpr *Exp);
432 void GetBlockDeclRefExprs(Stmt *S);
433 void GetInnerBlockDeclRefExprs(Stmt *S,
John McCallf4b88a42012-03-10 09:33:50 +0000434 SmallVector<DeclRefExpr *, 8> &InnerBlockDeclRefs,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000435 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts);
436
437 // We avoid calling Type::isBlockPointerType(), since it operates on the
438 // canonical type. We only care if the top-level type is a closure pointer.
439 bool isTopLevelBlockPointerType(QualType T) {
440 return isa<BlockPointerType>(T);
441 }
442
443 /// convertBlockPointerToFunctionPointer - Converts a block-pointer type
444 /// to a function pointer type and upon success, returns true; false
445 /// otherwise.
446 bool convertBlockPointerToFunctionPointer(QualType &T) {
447 if (isTopLevelBlockPointerType(T)) {
448 const BlockPointerType *BPT = T->getAs<BlockPointerType>();
449 T = Context->getPointerType(BPT->getPointeeType());
450 return true;
451 }
452 return false;
453 }
454
Fariborz Jahanian164d6f82012-02-13 18:57:49 +0000455 bool convertObjCTypeToCStyleType(QualType &T);
456
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000457 bool needToScanForQualifiers(QualType T);
458 QualType getSuperStructType();
459 QualType getConstantStringStructType();
460 QualType convertFunctionTypeOfBlocks(const FunctionType *FT);
461 bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf);
462
463 void convertToUnqualifiedObjCType(QualType &T) {
464 if (T->isObjCQualifiedIdType())
465 T = Context->getObjCIdType();
466 else if (T->isObjCQualifiedClassType())
467 T = Context->getObjCClassType();
468 else if (T->isObjCObjectPointerType() &&
469 T->getPointeeType()->isObjCQualifiedInterfaceType()) {
470 if (const ObjCObjectPointerType * OBJPT =
471 T->getAsObjCInterfacePointerType()) {
472 const ObjCInterfaceType *IFaceT = OBJPT->getInterfaceType();
473 T = QualType(IFaceT, 0);
474 T = Context->getPointerType(T);
475 }
476 }
477 }
478
479 // FIXME: This predicate seems like it would be useful to add to ASTContext.
480 bool isObjCType(QualType T) {
481 if (!LangOpts.ObjC1 && !LangOpts.ObjC2)
482 return false;
483
484 QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
485
486 if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
487 OCT == Context->getCanonicalType(Context->getObjCClassType()))
488 return true;
489
490 if (const PointerType *PT = OCT->getAs<PointerType>()) {
491 if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
492 PT->getPointeeType()->isObjCQualifiedIdType())
493 return true;
494 }
495 return false;
496 }
497 bool PointerTypeTakesAnyBlockArguments(QualType QT);
498 bool PointerTypeTakesAnyObjCQualifiedType(QualType QT);
499 void GetExtentOfArgList(const char *Name, const char *&LParen,
500 const char *&RParen);
501
502 void QuoteDoublequotes(std::string &From, std::string &To) {
503 for (unsigned i = 0; i < From.length(); i++) {
504 if (From[i] == '"')
505 To += "\\\"";
506 else
507 To += From[i];
508 }
509 }
510
511 QualType getSimpleFunctionType(QualType result,
512 const QualType *args,
513 unsigned numArgs,
514 bool variadic = false) {
515 if (result == Context->getObjCInstanceType())
516 result = Context->getObjCIdType();
517 FunctionProtoType::ExtProtoInfo fpi;
518 fpi.Variadic = variadic;
519 return Context->getFunctionType(result, args, numArgs, fpi);
520 }
521
522 // Helper function: create a CStyleCastExpr with trivial type source info.
523 CStyleCastExpr* NoTypeInfoCStyleCastExpr(ASTContext *Ctx, QualType Ty,
524 CastKind Kind, Expr *E) {
525 TypeSourceInfo *TInfo = Ctx->getTrivialTypeSourceInfo(Ty, SourceLocation());
526 return CStyleCastExpr::Create(*Ctx, Ty, VK_RValue, Kind, E, 0, TInfo,
527 SourceLocation(), SourceLocation());
528 }
Fariborz Jahanian88f7f752012-03-14 23:18:19 +0000529
530 bool ImplementationIsNonLazy(const ObjCImplDecl *OD) const {
531 IdentifierInfo* II = &Context->Idents.get("load");
532 Selector LoadSel = Context->Selectors.getSelector(0, &II);
533 return OD->getClassMethod(LoadSel) != 0;
534 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000535 };
536
537}
538
539void RewriteModernObjC::RewriteBlocksInFunctionProtoType(QualType funcType,
540 NamedDecl *D) {
541 if (const FunctionProtoType *fproto
542 = dyn_cast<FunctionProtoType>(funcType.IgnoreParens())) {
543 for (FunctionProtoType::arg_type_iterator I = fproto->arg_type_begin(),
544 E = fproto->arg_type_end(); I && (I != E); ++I)
545 if (isTopLevelBlockPointerType(*I)) {
546 // All the args are checked/rewritten. Don't call twice!
547 RewriteBlockPointerDecl(D);
548 break;
549 }
550 }
551}
552
553void RewriteModernObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
554 const PointerType *PT = funcType->getAs<PointerType>();
555 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
556 RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND);
557}
558
559static bool IsHeaderFile(const std::string &Filename) {
560 std::string::size_type DotPos = Filename.rfind('.');
561
562 if (DotPos == std::string::npos) {
563 // no file extension
564 return false;
565 }
566
567 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
568 // C header: .h
569 // C++ header: .hh or .H;
570 return Ext == "h" || Ext == "hh" || Ext == "H";
571}
572
573RewriteModernObjC::RewriteModernObjC(std::string inFile, raw_ostream* OS,
574 DiagnosticsEngine &D, const LangOptions &LOpts,
575 bool silenceMacroWarn)
576 : Diags(D), LangOpts(LOpts), InFileName(inFile), OutFile(OS),
577 SilenceRewriteMacroWarning(silenceMacroWarn) {
578 IsHeader = IsHeaderFile(inFile);
579 RewriteFailedDiag = Diags.getCustomDiagID(DiagnosticsEngine::Warning,
580 "rewriting sub-expression within a macro (may not be correct)");
Fariborz Jahaniand13c2c22012-03-22 19:54:39 +0000581 // FIXME. This should be an error. But if block is not called, it is OK. And it
582 // may break including some headers.
583 GlobalBlockRewriteFailedDiag = Diags.getCustomDiagID(DiagnosticsEngine::Warning,
584 "rewriting block literal declared in global scope is not implemented");
585
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000586 TryFinallyContainsReturnDiag = Diags.getCustomDiagID(
587 DiagnosticsEngine::Warning,
588 "rewriter doesn't support user-specified control flow semantics "
589 "for @try/@finally (code may not execute properly)");
590}
591
592ASTConsumer *clang::CreateModernObjCRewriter(const std::string& InFile,
593 raw_ostream* OS,
594 DiagnosticsEngine &Diags,
595 const LangOptions &LOpts,
596 bool SilenceRewriteMacroWarning) {
597 return new RewriteModernObjC(InFile, OS, Diags, LOpts, SilenceRewriteMacroWarning);
598}
599
600void RewriteModernObjC::InitializeCommon(ASTContext &context) {
601 Context = &context;
602 SM = &Context->getSourceManager();
603 TUDecl = Context->getTranslationUnitDecl();
604 MsgSendFunctionDecl = 0;
605 MsgSendSuperFunctionDecl = 0;
606 MsgSendStretFunctionDecl = 0;
607 MsgSendSuperStretFunctionDecl = 0;
608 MsgSendFpretFunctionDecl = 0;
609 GetClassFunctionDecl = 0;
610 GetMetaClassFunctionDecl = 0;
611 GetSuperClassFunctionDecl = 0;
612 SelGetUidFunctionDecl = 0;
613 CFStringFunctionDecl = 0;
614 ConstantStringClassReference = 0;
615 NSStringRecord = 0;
616 CurMethodDef = 0;
617 CurFunctionDef = 0;
618 CurFunctionDeclToDeclareForBlock = 0;
619 GlobalVarDecl = 0;
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +0000620 GlobalConstructionExp = 0;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000621 SuperStructDecl = 0;
622 ProtocolTypeDecl = 0;
623 ConstantStringDecl = 0;
624 BcLabelCount = 0;
625 SuperContructorFunctionDecl = 0;
626 NumObjCStringLiterals = 0;
627 PropParentMap = 0;
628 CurrentBody = 0;
629 DisableReplaceStmt = false;
630 objc_impl_method = false;
631
632 // Get the ID and start/end of the main file.
633 MainFileID = SM->getMainFileID();
634 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
635 MainFileStart = MainBuf->getBufferStart();
636 MainFileEnd = MainBuf->getBufferEnd();
637
David Blaikie4e4d0842012-03-11 07:00:24 +0000638 Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOpts());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000639}
640
641//===----------------------------------------------------------------------===//
642// Top Level Driver Code
643//===----------------------------------------------------------------------===//
644
645void RewriteModernObjC::HandleTopLevelSingleDecl(Decl *D) {
646 if (Diags.hasErrorOccurred())
647 return;
648
649 // Two cases: either the decl could be in the main file, or it could be in a
650 // #included file. If the former, rewrite it now. If the later, check to see
651 // if we rewrote the #include/#import.
652 SourceLocation Loc = D->getLocation();
653 Loc = SM->getExpansionLoc(Loc);
654
655 // If this is for a builtin, ignore it.
656 if (Loc.isInvalid()) return;
657
658 // Look for built-in declarations that we need to refer during the rewrite.
659 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
660 RewriteFunctionDecl(FD);
661 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
662 // declared in <Foundation/NSString.h>
663 if (FVD->getName() == "_NSConstantStringClassReference") {
664 ConstantStringClassReference = FVD;
665 return;
666 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000667 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
668 RewriteCategoryDecl(CD);
669 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
670 if (PD->isThisDeclarationADefinition())
671 RewriteProtocolDecl(PD);
672 } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) {
673 // Recurse into linkage specifications
674 for (DeclContext::decl_iterator DI = LSD->decls_begin(),
675 DIEnd = LSD->decls_end();
676 DI != DIEnd; ) {
677 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>((*DI))) {
678 if (!IFace->isThisDeclarationADefinition()) {
679 SmallVector<Decl *, 8> DG;
680 SourceLocation StartLoc = IFace->getLocStart();
681 do {
682 if (isa<ObjCInterfaceDecl>(*DI) &&
683 !cast<ObjCInterfaceDecl>(*DI)->isThisDeclarationADefinition() &&
684 StartLoc == (*DI)->getLocStart())
685 DG.push_back(*DI);
686 else
687 break;
688
689 ++DI;
690 } while (DI != DIEnd);
691 RewriteForwardClassDecl(DG);
692 continue;
693 }
694 }
695
696 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>((*DI))) {
697 if (!Proto->isThisDeclarationADefinition()) {
698 SmallVector<Decl *, 8> DG;
699 SourceLocation StartLoc = Proto->getLocStart();
700 do {
701 if (isa<ObjCProtocolDecl>(*DI) &&
702 !cast<ObjCProtocolDecl>(*DI)->isThisDeclarationADefinition() &&
703 StartLoc == (*DI)->getLocStart())
704 DG.push_back(*DI);
705 else
706 break;
707
708 ++DI;
709 } while (DI != DIEnd);
710 RewriteForwardProtocolDecl(DG);
711 continue;
712 }
713 }
714
715 HandleTopLevelSingleDecl(*DI);
716 ++DI;
717 }
718 }
719 // If we have a decl in the main file, see if we should rewrite it.
720 if (SM->isFromMainFile(Loc))
721 return HandleDeclInMainFile(D);
722}
723
724//===----------------------------------------------------------------------===//
725// Syntactic (non-AST) Rewriting Code
726//===----------------------------------------------------------------------===//
727
728void RewriteModernObjC::RewriteInclude() {
729 SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID);
730 StringRef MainBuf = SM->getBufferData(MainFileID);
731 const char *MainBufStart = MainBuf.begin();
732 const char *MainBufEnd = MainBuf.end();
733 size_t ImportLen = strlen("import");
734
735 // Loop over the whole file, looking for includes.
736 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
737 if (*BufPtr == '#') {
738 if (++BufPtr == MainBufEnd)
739 return;
740 while (*BufPtr == ' ' || *BufPtr == '\t')
741 if (++BufPtr == MainBufEnd)
742 return;
743 if (!strncmp(BufPtr, "import", ImportLen)) {
744 // replace import with include
745 SourceLocation ImportLoc =
746 LocStart.getLocWithOffset(BufPtr-MainBufStart);
747 ReplaceText(ImportLoc, ImportLen, "include");
748 BufPtr += ImportLen;
749 }
750 }
751 }
752}
753
754static std::string getIvarAccessString(ObjCIvarDecl *OID) {
755 const ObjCInterfaceDecl *ClassDecl = OID->getContainingInterface();
756 std::string S;
757 S = "((struct ";
758 S += ClassDecl->getIdentifier()->getName();
759 S += "_IMPL *)self)->";
760 S += OID->getName();
761 return S;
762}
763
764void RewriteModernObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
765 ObjCImplementationDecl *IMD,
766 ObjCCategoryImplDecl *CID) {
767 static bool objcGetPropertyDefined = false;
768 static bool objcSetPropertyDefined = false;
769 SourceLocation startLoc = PID->getLocStart();
770 InsertText(startLoc, "// ");
771 const char *startBuf = SM->getCharacterData(startLoc);
772 assert((*startBuf == '@') && "bogus @synthesize location");
773 const char *semiBuf = strchr(startBuf, ';');
774 assert((*semiBuf == ';') && "@synthesize: can't find ';'");
775 SourceLocation onePastSemiLoc =
776 startLoc.getLocWithOffset(semiBuf-startBuf+1);
777
778 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
779 return; // FIXME: is this correct?
780
781 // Generate the 'getter' function.
782 ObjCPropertyDecl *PD = PID->getPropertyDecl();
783 ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
784
785 if (!OID)
786 return;
787 unsigned Attributes = PD->getPropertyAttributes();
788 if (!PD->getGetterMethodDecl()->isDefined()) {
789 bool GenGetProperty = !(Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic) &&
790 (Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
791 ObjCPropertyDecl::OBJC_PR_copy));
792 std::string Getr;
793 if (GenGetProperty && !objcGetPropertyDefined) {
794 objcGetPropertyDefined = true;
795 // FIXME. Is this attribute correct in all cases?
796 Getr = "\nextern \"C\" __declspec(dllimport) "
797 "id objc_getProperty(id, SEL, long, bool);\n";
798 }
799 RewriteObjCMethodDecl(OID->getContainingInterface(),
800 PD->getGetterMethodDecl(), Getr);
801 Getr += "{ ";
802 // Synthesize an explicit cast to gain access to the ivar.
803 // See objc-act.c:objc_synthesize_new_getter() for details.
804 if (GenGetProperty) {
805 // return objc_getProperty(self, _cmd, offsetof(ClassDecl, OID), 1)
806 Getr += "typedef ";
807 const FunctionType *FPRetType = 0;
808 RewriteTypeIntoString(PD->getGetterMethodDecl()->getResultType(), Getr,
809 FPRetType);
810 Getr += " _TYPE";
811 if (FPRetType) {
812 Getr += ")"; // close the precedence "scope" for "*".
813
814 // Now, emit the argument types (if any).
815 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)){
816 Getr += "(";
817 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
818 if (i) Getr += ", ";
819 std::string ParamStr = FT->getArgType(i).getAsString(
820 Context->getPrintingPolicy());
821 Getr += ParamStr;
822 }
823 if (FT->isVariadic()) {
824 if (FT->getNumArgs()) Getr += ", ";
825 Getr += "...";
826 }
827 Getr += ")";
828 } else
829 Getr += "()";
830 }
831 Getr += ";\n";
832 Getr += "return (_TYPE)";
833 Getr += "objc_getProperty(self, _cmd, ";
834 RewriteIvarOffsetComputation(OID, Getr);
835 Getr += ", 1)";
836 }
837 else
838 Getr += "return " + getIvarAccessString(OID);
839 Getr += "; }";
840 InsertText(onePastSemiLoc, Getr);
841 }
842
843 if (PD->isReadOnly() || PD->getSetterMethodDecl()->isDefined())
844 return;
845
846 // Generate the 'setter' function.
847 std::string Setr;
848 bool GenSetProperty = Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
849 ObjCPropertyDecl::OBJC_PR_copy);
850 if (GenSetProperty && !objcSetPropertyDefined) {
851 objcSetPropertyDefined = true;
852 // FIXME. Is this attribute correct in all cases?
853 Setr = "\nextern \"C\" __declspec(dllimport) "
854 "void objc_setProperty (id, SEL, long, id, bool, bool);\n";
855 }
856
857 RewriteObjCMethodDecl(OID->getContainingInterface(),
858 PD->getSetterMethodDecl(), Setr);
859 Setr += "{ ";
860 // Synthesize an explicit cast to initialize the ivar.
861 // See objc-act.c:objc_synthesize_new_setter() for details.
862 if (GenSetProperty) {
863 Setr += "objc_setProperty (self, _cmd, ";
864 RewriteIvarOffsetComputation(OID, Setr);
865 Setr += ", (id)";
866 Setr += PD->getName();
867 Setr += ", ";
868 if (Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic)
869 Setr += "0, ";
870 else
871 Setr += "1, ";
872 if (Attributes & ObjCPropertyDecl::OBJC_PR_copy)
873 Setr += "1)";
874 else
875 Setr += "0)";
876 }
877 else {
878 Setr += getIvarAccessString(OID) + " = ";
879 Setr += PD->getName();
880 }
881 Setr += "; }";
882 InsertText(onePastSemiLoc, Setr);
883}
884
885static void RewriteOneForwardClassDecl(ObjCInterfaceDecl *ForwardDecl,
886 std::string &typedefString) {
887 typedefString += "#ifndef _REWRITER_typedef_";
888 typedefString += ForwardDecl->getNameAsString();
889 typedefString += "\n";
890 typedefString += "#define _REWRITER_typedef_";
891 typedefString += ForwardDecl->getNameAsString();
892 typedefString += "\n";
893 typedefString += "typedef struct objc_object ";
894 typedefString += ForwardDecl->getNameAsString();
Fariborz Jahanianc38503b2012-03-12 23:58:28 +0000895 // typedef struct { } _objc_exc_Classname;
896 typedefString += ";\ntypedef struct {} _objc_exc_";
897 typedefString += ForwardDecl->getNameAsString();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000898 typedefString += ";\n#endif\n";
899}
900
901void RewriteModernObjC::RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
902 const std::string &typedefString) {
903 SourceLocation startLoc = ClassDecl->getLocStart();
904 const char *startBuf = SM->getCharacterData(startLoc);
905 const char *semiPtr = strchr(startBuf, ';');
906 // Replace the @class with typedefs corresponding to the classes.
907 ReplaceText(startLoc, semiPtr-startBuf+1, typedefString);
908}
909
910void RewriteModernObjC::RewriteForwardClassDecl(DeclGroupRef D) {
911 std::string typedefString;
912 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
913 ObjCInterfaceDecl *ForwardDecl = cast<ObjCInterfaceDecl>(*I);
914 if (I == D.begin()) {
915 // Translate to typedef's that forward reference structs with the same name
916 // as the class. As a convenience, we include the original declaration
917 // as a comment.
918 typedefString += "// @class ";
919 typedefString += ForwardDecl->getNameAsString();
920 typedefString += ";\n";
921 }
922 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
923 }
924 DeclGroupRef::iterator I = D.begin();
925 RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(*I), typedefString);
926}
927
928void RewriteModernObjC::RewriteForwardClassDecl(
929 const llvm::SmallVector<Decl*, 8> &D) {
930 std::string typedefString;
931 for (unsigned i = 0; i < D.size(); i++) {
932 ObjCInterfaceDecl *ForwardDecl = cast<ObjCInterfaceDecl>(D[i]);
933 if (i == 0) {
934 typedefString += "// @class ";
935 typedefString += ForwardDecl->getNameAsString();
936 typedefString += ";\n";
937 }
938 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
939 }
940 RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(D[0]), typedefString);
941}
942
943void RewriteModernObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
944 // When method is a synthesized one, such as a getter/setter there is
945 // nothing to rewrite.
946 if (Method->isImplicit())
947 return;
948 SourceLocation LocStart = Method->getLocStart();
949 SourceLocation LocEnd = Method->getLocEnd();
950
951 if (SM->getExpansionLineNumber(LocEnd) >
952 SM->getExpansionLineNumber(LocStart)) {
953 InsertText(LocStart, "#if 0\n");
954 ReplaceText(LocEnd, 1, ";\n#endif\n");
955 } else {
956 InsertText(LocStart, "// ");
957 }
958}
959
960void RewriteModernObjC::RewriteProperty(ObjCPropertyDecl *prop) {
961 SourceLocation Loc = prop->getAtLoc();
962
963 ReplaceText(Loc, 0, "// ");
964 // FIXME: handle properties that are declared across multiple lines.
965}
966
967void RewriteModernObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
968 SourceLocation LocStart = CatDecl->getLocStart();
969
970 // FIXME: handle category headers that are declared across multiple lines.
971 ReplaceText(LocStart, 0, "// ");
Fariborz Jahanianaf300292012-02-20 20:09:20 +0000972 if (CatDecl->getIvarLBraceLoc().isValid())
973 InsertText(CatDecl->getIvarLBraceLoc(), "// ");
Fariborz Jahaniand2aea122012-02-19 19:00:05 +0000974 for (ObjCCategoryDecl::ivar_iterator
975 I = CatDecl->ivar_begin(), E = CatDecl->ivar_end(); I != E; ++I) {
976 ObjCIvarDecl *Ivar = (*I);
977 SourceLocation LocStart = Ivar->getLocStart();
978 ReplaceText(LocStart, 0, "// ");
979 }
Fariborz Jahanianaf300292012-02-20 20:09:20 +0000980 if (CatDecl->getIvarRBraceLoc().isValid())
981 InsertText(CatDecl->getIvarRBraceLoc(), "// ");
982
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000983 for (ObjCCategoryDecl::prop_iterator I = CatDecl->prop_begin(),
984 E = CatDecl->prop_end(); I != E; ++I)
985 RewriteProperty(*I);
986
987 for (ObjCCategoryDecl::instmeth_iterator
988 I = CatDecl->instmeth_begin(), E = CatDecl->instmeth_end();
989 I != E; ++I)
990 RewriteMethodDeclaration(*I);
991 for (ObjCCategoryDecl::classmeth_iterator
992 I = CatDecl->classmeth_begin(), E = CatDecl->classmeth_end();
993 I != E; ++I)
994 RewriteMethodDeclaration(*I);
995
996 // Lastly, comment out the @end.
997 ReplaceText(CatDecl->getAtEndRange().getBegin(),
998 strlen("@end"), "/* @end */");
999}
1000
1001void RewriteModernObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
1002 SourceLocation LocStart = PDecl->getLocStart();
1003 assert(PDecl->isThisDeclarationADefinition());
1004
1005 // FIXME: handle protocol headers that are declared across multiple lines.
1006 ReplaceText(LocStart, 0, "// ");
1007
1008 for (ObjCProtocolDecl::instmeth_iterator
1009 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
1010 I != E; ++I)
1011 RewriteMethodDeclaration(*I);
1012 for (ObjCProtocolDecl::classmeth_iterator
1013 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
1014 I != E; ++I)
1015 RewriteMethodDeclaration(*I);
1016
1017 for (ObjCInterfaceDecl::prop_iterator I = PDecl->prop_begin(),
1018 E = PDecl->prop_end(); I != E; ++I)
1019 RewriteProperty(*I);
1020
1021 // Lastly, comment out the @end.
1022 SourceLocation LocEnd = PDecl->getAtEndRange().getBegin();
1023 ReplaceText(LocEnd, strlen("@end"), "/* @end */");
1024
1025 // Must comment out @optional/@required
1026 const char *startBuf = SM->getCharacterData(LocStart);
1027 const char *endBuf = SM->getCharacterData(LocEnd);
1028 for (const char *p = startBuf; p < endBuf; p++) {
1029 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
1030 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
1031 ReplaceText(OptionalLoc, strlen("@optional"), "/* @optional */");
1032
1033 }
1034 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
1035 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
1036 ReplaceText(OptionalLoc, strlen("@required"), "/* @required */");
1037
1038 }
1039 }
1040}
1041
1042void RewriteModernObjC::RewriteForwardProtocolDecl(DeclGroupRef D) {
1043 SourceLocation LocStart = (*D.begin())->getLocStart();
1044 if (LocStart.isInvalid())
1045 llvm_unreachable("Invalid SourceLocation");
1046 // FIXME: handle forward protocol that are declared across multiple lines.
1047 ReplaceText(LocStart, 0, "// ");
1048}
1049
1050void
1051RewriteModernObjC::RewriteForwardProtocolDecl(const llvm::SmallVector<Decl*, 8> &DG) {
1052 SourceLocation LocStart = DG[0]->getLocStart();
1053 if (LocStart.isInvalid())
1054 llvm_unreachable("Invalid SourceLocation");
1055 // FIXME: handle forward protocol that are declared across multiple lines.
1056 ReplaceText(LocStart, 0, "// ");
1057}
1058
1059void RewriteModernObjC::RewriteTypeIntoString(QualType T, std::string &ResultStr,
1060 const FunctionType *&FPRetType) {
1061 if (T->isObjCQualifiedIdType())
1062 ResultStr += "id";
1063 else if (T->isFunctionPointerType() ||
1064 T->isBlockPointerType()) {
1065 // needs special handling, since pointer-to-functions have special
1066 // syntax (where a decaration models use).
1067 QualType retType = T;
1068 QualType PointeeTy;
1069 if (const PointerType* PT = retType->getAs<PointerType>())
1070 PointeeTy = PT->getPointeeType();
1071 else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>())
1072 PointeeTy = BPT->getPointeeType();
1073 if ((FPRetType = PointeeTy->getAs<FunctionType>())) {
1074 ResultStr += FPRetType->getResultType().getAsString(
1075 Context->getPrintingPolicy());
1076 ResultStr += "(*";
1077 }
1078 } else
1079 ResultStr += T.getAsString(Context->getPrintingPolicy());
1080}
1081
1082void RewriteModernObjC::RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
1083 ObjCMethodDecl *OMD,
1084 std::string &ResultStr) {
1085 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
1086 const FunctionType *FPRetType = 0;
1087 ResultStr += "\nstatic ";
1088 RewriteTypeIntoString(OMD->getResultType(), ResultStr, FPRetType);
1089 ResultStr += " ";
1090
1091 // Unique method name
1092 std::string NameStr;
1093
1094 if (OMD->isInstanceMethod())
1095 NameStr += "_I_";
1096 else
1097 NameStr += "_C_";
1098
1099 NameStr += IDecl->getNameAsString();
1100 NameStr += "_";
1101
1102 if (ObjCCategoryImplDecl *CID =
1103 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
1104 NameStr += CID->getNameAsString();
1105 NameStr += "_";
1106 }
1107 // Append selector names, replacing ':' with '_'
1108 {
1109 std::string selString = OMD->getSelector().getAsString();
1110 int len = selString.size();
1111 for (int i = 0; i < len; i++)
1112 if (selString[i] == ':')
1113 selString[i] = '_';
1114 NameStr += selString;
1115 }
1116 // Remember this name for metadata emission
1117 MethodInternalNames[OMD] = NameStr;
1118 ResultStr += NameStr;
1119
1120 // Rewrite arguments
1121 ResultStr += "(";
1122
1123 // invisible arguments
1124 if (OMD->isInstanceMethod()) {
1125 QualType selfTy = Context->getObjCInterfaceType(IDecl);
1126 selfTy = Context->getPointerType(selfTy);
1127 if (!LangOpts.MicrosoftExt) {
1128 if (ObjCSynthesizedStructs.count(const_cast<ObjCInterfaceDecl*>(IDecl)))
1129 ResultStr += "struct ";
1130 }
1131 // When rewriting for Microsoft, explicitly omit the structure name.
1132 ResultStr += IDecl->getNameAsString();
1133 ResultStr += " *";
1134 }
1135 else
1136 ResultStr += Context->getObjCClassType().getAsString(
1137 Context->getPrintingPolicy());
1138
1139 ResultStr += " self, ";
1140 ResultStr += Context->getObjCSelType().getAsString(Context->getPrintingPolicy());
1141 ResultStr += " _cmd";
1142
1143 // Method arguments.
1144 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
1145 E = OMD->param_end(); PI != E; ++PI) {
1146 ParmVarDecl *PDecl = *PI;
1147 ResultStr += ", ";
1148 if (PDecl->getType()->isObjCQualifiedIdType()) {
1149 ResultStr += "id ";
1150 ResultStr += PDecl->getNameAsString();
1151 } else {
1152 std::string Name = PDecl->getNameAsString();
1153 QualType QT = PDecl->getType();
1154 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian2610f902012-03-27 16:42:20 +00001155 (void)convertBlockPointerToFunctionPointer(QT);
1156 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001157 ResultStr += Name;
1158 }
1159 }
1160 if (OMD->isVariadic())
1161 ResultStr += ", ...";
1162 ResultStr += ") ";
1163
1164 if (FPRetType) {
1165 ResultStr += ")"; // close the precedence "scope" for "*".
1166
1167 // Now, emit the argument types (if any).
1168 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
1169 ResultStr += "(";
1170 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
1171 if (i) ResultStr += ", ";
1172 std::string ParamStr = FT->getArgType(i).getAsString(
1173 Context->getPrintingPolicy());
1174 ResultStr += ParamStr;
1175 }
1176 if (FT->isVariadic()) {
1177 if (FT->getNumArgs()) ResultStr += ", ";
1178 ResultStr += "...";
1179 }
1180 ResultStr += ")";
1181 } else {
1182 ResultStr += "()";
1183 }
1184 }
1185}
1186void RewriteModernObjC::RewriteImplementationDecl(Decl *OID) {
1187 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
1188 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
1189
Fariborz Jahaniand2aea122012-02-19 19:00:05 +00001190 if (IMD) {
1191 InsertText(IMD->getLocStart(), "// ");
Fariborz Jahanianaf300292012-02-20 20:09:20 +00001192 if (IMD->getIvarLBraceLoc().isValid())
1193 InsertText(IMD->getIvarLBraceLoc(), "// ");
1194 for (ObjCImplementationDecl::ivar_iterator
1195 I = IMD->ivar_begin(), E = IMD->ivar_end(); I != E; ++I) {
1196 ObjCIvarDecl *Ivar = (*I);
1197 SourceLocation LocStart = Ivar->getLocStart();
1198 ReplaceText(LocStart, 0, "// ");
Fariborz Jahaniand2aea122012-02-19 19:00:05 +00001199 }
Fariborz Jahanianaf300292012-02-20 20:09:20 +00001200 if (IMD->getIvarRBraceLoc().isValid())
1201 InsertText(IMD->getIvarRBraceLoc(), "// ");
Fariborz Jahaniand2aea122012-02-19 19:00:05 +00001202 }
1203 else
1204 InsertText(CID->getLocStart(), "// ");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001205
1206 for (ObjCCategoryImplDecl::instmeth_iterator
1207 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
1208 E = IMD ? IMD->instmeth_end() : CID->instmeth_end();
1209 I != E; ++I) {
1210 std::string ResultStr;
1211 ObjCMethodDecl *OMD = *I;
1212 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
1213 SourceLocation LocStart = OMD->getLocStart();
1214 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
1215
1216 const char *startBuf = SM->getCharacterData(LocStart);
1217 const char *endBuf = SM->getCharacterData(LocEnd);
1218 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
1219 }
1220
1221 for (ObjCCategoryImplDecl::classmeth_iterator
1222 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
1223 E = IMD ? IMD->classmeth_end() : CID->classmeth_end();
1224 I != E; ++I) {
1225 std::string ResultStr;
1226 ObjCMethodDecl *OMD = *I;
1227 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
1228 SourceLocation LocStart = OMD->getLocStart();
1229 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
1230
1231 const char *startBuf = SM->getCharacterData(LocStart);
1232 const char *endBuf = SM->getCharacterData(LocEnd);
1233 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
1234 }
1235 for (ObjCCategoryImplDecl::propimpl_iterator
1236 I = IMD ? IMD->propimpl_begin() : CID->propimpl_begin(),
1237 E = IMD ? IMD->propimpl_end() : CID->propimpl_end();
1238 I != E; ++I) {
1239 RewritePropertyImplDecl(*I, IMD, CID);
1240 }
1241
1242 InsertText(IMD ? IMD->getLocEnd() : CID->getLocEnd(), "// ");
1243}
1244
1245void RewriteModernObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00001246 // Do not synthesize more than once.
1247 if (ObjCSynthesizedStructs.count(ClassDecl))
1248 return;
1249 // Make sure super class's are written before current class is written.
1250 ObjCInterfaceDecl *SuperClass = ClassDecl->getSuperClass();
1251 while (SuperClass) {
1252 RewriteInterfaceDecl(SuperClass);
1253 SuperClass = SuperClass->getSuperClass();
1254 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001255 std::string ResultStr;
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +00001256 if (!ObjCWrittenInterfaces.count(ClassDecl->getCanonicalDecl())) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001257 // we haven't seen a forward decl - generate a typedef.
Fariborz Jahanianc38503b2012-03-12 23:58:28 +00001258 RewriteOneForwardClassDecl(ClassDecl, ResultStr);
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00001259 RewriteIvarOffsetSymbols(ClassDecl, ResultStr);
1260
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001261 RewriteObjCInternalStruct(ClassDecl, ResultStr);
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +00001262 // Mark this typedef as having been written into its c++ equivalent.
1263 ObjCWrittenInterfaces.insert(ClassDecl->getCanonicalDecl());
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001264
1265 for (ObjCInterfaceDecl::prop_iterator I = ClassDecl->prop_begin(),
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001266 E = ClassDecl->prop_end(); I != E; ++I)
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001267 RewriteProperty(*I);
1268 for (ObjCInterfaceDecl::instmeth_iterator
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001269 I = ClassDecl->instmeth_begin(), E = ClassDecl->instmeth_end();
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001270 I != E; ++I)
1271 RewriteMethodDeclaration(*I);
1272 for (ObjCInterfaceDecl::classmeth_iterator
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001273 I = ClassDecl->classmeth_begin(), E = ClassDecl->classmeth_end();
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001274 I != E; ++I)
1275 RewriteMethodDeclaration(*I);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001276
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001277 // Lastly, comment out the @end.
1278 ReplaceText(ClassDecl->getAtEndRange().getBegin(), strlen("@end"),
1279 "/* @end */");
1280 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001281}
1282
1283Stmt *RewriteModernObjC::RewritePropertyOrImplicitSetter(PseudoObjectExpr *PseudoOp) {
1284 SourceRange OldRange = PseudoOp->getSourceRange();
1285
1286 // We just magically know some things about the structure of this
1287 // expression.
1288 ObjCMessageExpr *OldMsg =
1289 cast<ObjCMessageExpr>(PseudoOp->getSemanticExpr(
1290 PseudoOp->getNumSemanticExprs() - 1));
1291
1292 // Because the rewriter doesn't allow us to rewrite rewritten code,
1293 // we need to suppress rewriting the sub-statements.
1294 Expr *Base, *RHS;
1295 {
1296 DisableReplaceStmtScope S(*this);
1297
1298 // Rebuild the base expression if we have one.
1299 Base = 0;
1300 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1301 Base = OldMsg->getInstanceReceiver();
1302 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1303 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1304 }
1305
1306 // Rebuild the RHS.
1307 RHS = cast<BinaryOperator>(PseudoOp->getSyntacticForm())->getRHS();
1308 RHS = cast<OpaqueValueExpr>(RHS)->getSourceExpr();
1309 RHS = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(RHS));
1310 }
1311
1312 // TODO: avoid this copy.
1313 SmallVector<SourceLocation, 1> SelLocs;
1314 OldMsg->getSelectorLocs(SelLocs);
1315
1316 ObjCMessageExpr *NewMsg = 0;
1317 switch (OldMsg->getReceiverKind()) {
1318 case ObjCMessageExpr::Class:
1319 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1320 OldMsg->getValueKind(),
1321 OldMsg->getLeftLoc(),
1322 OldMsg->getClassReceiverTypeInfo(),
1323 OldMsg->getSelector(),
1324 SelLocs,
1325 OldMsg->getMethodDecl(),
1326 RHS,
1327 OldMsg->getRightLoc(),
1328 OldMsg->isImplicit());
1329 break;
1330
1331 case ObjCMessageExpr::Instance:
1332 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1333 OldMsg->getValueKind(),
1334 OldMsg->getLeftLoc(),
1335 Base,
1336 OldMsg->getSelector(),
1337 SelLocs,
1338 OldMsg->getMethodDecl(),
1339 RHS,
1340 OldMsg->getRightLoc(),
1341 OldMsg->isImplicit());
1342 break;
1343
1344 case ObjCMessageExpr::SuperClass:
1345 case ObjCMessageExpr::SuperInstance:
1346 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1347 OldMsg->getValueKind(),
1348 OldMsg->getLeftLoc(),
1349 OldMsg->getSuperLoc(),
1350 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1351 OldMsg->getSuperType(),
1352 OldMsg->getSelector(),
1353 SelLocs,
1354 OldMsg->getMethodDecl(),
1355 RHS,
1356 OldMsg->getRightLoc(),
1357 OldMsg->isImplicit());
1358 break;
1359 }
1360
1361 Stmt *Replacement = SynthMessageExpr(NewMsg);
1362 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1363 return Replacement;
1364}
1365
1366Stmt *RewriteModernObjC::RewritePropertyOrImplicitGetter(PseudoObjectExpr *PseudoOp) {
1367 SourceRange OldRange = PseudoOp->getSourceRange();
1368
1369 // We just magically know some things about the structure of this
1370 // expression.
1371 ObjCMessageExpr *OldMsg =
1372 cast<ObjCMessageExpr>(PseudoOp->getResultExpr()->IgnoreImplicit());
1373
1374 // Because the rewriter doesn't allow us to rewrite rewritten code,
1375 // we need to suppress rewriting the sub-statements.
1376 Expr *Base = 0;
1377 {
1378 DisableReplaceStmtScope S(*this);
1379
1380 // Rebuild the base expression if we have one.
1381 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1382 Base = OldMsg->getInstanceReceiver();
1383 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1384 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1385 }
1386 }
1387
1388 // Intentionally empty.
1389 SmallVector<SourceLocation, 1> SelLocs;
1390 SmallVector<Expr*, 1> Args;
1391
1392 ObjCMessageExpr *NewMsg = 0;
1393 switch (OldMsg->getReceiverKind()) {
1394 case ObjCMessageExpr::Class:
1395 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1396 OldMsg->getValueKind(),
1397 OldMsg->getLeftLoc(),
1398 OldMsg->getClassReceiverTypeInfo(),
1399 OldMsg->getSelector(),
1400 SelLocs,
1401 OldMsg->getMethodDecl(),
1402 Args,
1403 OldMsg->getRightLoc(),
1404 OldMsg->isImplicit());
1405 break;
1406
1407 case ObjCMessageExpr::Instance:
1408 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1409 OldMsg->getValueKind(),
1410 OldMsg->getLeftLoc(),
1411 Base,
1412 OldMsg->getSelector(),
1413 SelLocs,
1414 OldMsg->getMethodDecl(),
1415 Args,
1416 OldMsg->getRightLoc(),
1417 OldMsg->isImplicit());
1418 break;
1419
1420 case ObjCMessageExpr::SuperClass:
1421 case ObjCMessageExpr::SuperInstance:
1422 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1423 OldMsg->getValueKind(),
1424 OldMsg->getLeftLoc(),
1425 OldMsg->getSuperLoc(),
1426 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1427 OldMsg->getSuperType(),
1428 OldMsg->getSelector(),
1429 SelLocs,
1430 OldMsg->getMethodDecl(),
1431 Args,
1432 OldMsg->getRightLoc(),
1433 OldMsg->isImplicit());
1434 break;
1435 }
1436
1437 Stmt *Replacement = SynthMessageExpr(NewMsg);
1438 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1439 return Replacement;
1440}
1441
1442/// SynthCountByEnumWithState - To print:
1443/// ((unsigned int (*)
1444/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1445/// (void *)objc_msgSend)((id)l_collection,
1446/// sel_registerName(
1447/// "countByEnumeratingWithState:objects:count:"),
1448/// &enumState,
1449/// (id *)__rw_items, (unsigned int)16)
1450///
1451void RewriteModernObjC::SynthCountByEnumWithState(std::string &buf) {
1452 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1453 "id *, unsigned int))(void *)objc_msgSend)";
1454 buf += "\n\t\t";
1455 buf += "((id)l_collection,\n\t\t";
1456 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1457 buf += "\n\t\t";
1458 buf += "&enumState, "
1459 "(id *)__rw_items, (unsigned int)16)";
1460}
1461
1462/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1463/// statement to exit to its outer synthesized loop.
1464///
1465Stmt *RewriteModernObjC::RewriteBreakStmt(BreakStmt *S) {
1466 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1467 return S;
1468 // replace break with goto __break_label
1469 std::string buf;
1470
1471 SourceLocation startLoc = S->getLocStart();
1472 buf = "goto __break_label_";
1473 buf += utostr(ObjCBcLabelNo.back());
1474 ReplaceText(startLoc, strlen("break"), buf);
1475
1476 return 0;
1477}
1478
1479/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1480/// statement to continue with its inner synthesized loop.
1481///
1482Stmt *RewriteModernObjC::RewriteContinueStmt(ContinueStmt *S) {
1483 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1484 return S;
1485 // replace continue with goto __continue_label
1486 std::string buf;
1487
1488 SourceLocation startLoc = S->getLocStart();
1489 buf = "goto __continue_label_";
1490 buf += utostr(ObjCBcLabelNo.back());
1491 ReplaceText(startLoc, strlen("continue"), buf);
1492
1493 return 0;
1494}
1495
1496/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
1497/// It rewrites:
1498/// for ( type elem in collection) { stmts; }
1499
1500/// Into:
1501/// {
1502/// type elem;
1503/// struct __objcFastEnumerationState enumState = { 0 };
1504/// id __rw_items[16];
1505/// id l_collection = (id)collection;
1506/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1507/// objects:__rw_items count:16];
1508/// if (limit) {
1509/// unsigned long startMutations = *enumState.mutationsPtr;
1510/// do {
1511/// unsigned long counter = 0;
1512/// do {
1513/// if (startMutations != *enumState.mutationsPtr)
1514/// objc_enumerationMutation(l_collection);
1515/// elem = (type)enumState.itemsPtr[counter++];
1516/// stmts;
1517/// __continue_label: ;
1518/// } while (counter < limit);
1519/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1520/// objects:__rw_items count:16]);
1521/// elem = nil;
1522/// __break_label: ;
1523/// }
1524/// else
1525/// elem = nil;
1526/// }
1527///
1528Stmt *RewriteModernObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
1529 SourceLocation OrigEnd) {
1530 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
1531 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
1532 "ObjCForCollectionStmt Statement stack mismatch");
1533 assert(!ObjCBcLabelNo.empty() &&
1534 "ObjCForCollectionStmt - Label No stack empty");
1535
1536 SourceLocation startLoc = S->getLocStart();
1537 const char *startBuf = SM->getCharacterData(startLoc);
1538 StringRef elementName;
1539 std::string elementTypeAsString;
1540 std::string buf;
1541 buf = "\n{\n\t";
1542 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1543 // type elem;
1544 NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
1545 QualType ElementType = cast<ValueDecl>(D)->getType();
1546 if (ElementType->isObjCQualifiedIdType() ||
1547 ElementType->isObjCQualifiedInterfaceType())
1548 // Simply use 'id' for all qualified types.
1549 elementTypeAsString = "id";
1550 else
1551 elementTypeAsString = ElementType.getAsString(Context->getPrintingPolicy());
1552 buf += elementTypeAsString;
1553 buf += " ";
1554 elementName = D->getName();
1555 buf += elementName;
1556 buf += ";\n\t";
1557 }
1558 else {
1559 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
1560 elementName = DR->getDecl()->getName();
1561 ValueDecl *VD = cast<ValueDecl>(DR->getDecl());
1562 if (VD->getType()->isObjCQualifiedIdType() ||
1563 VD->getType()->isObjCQualifiedInterfaceType())
1564 // Simply use 'id' for all qualified types.
1565 elementTypeAsString = "id";
1566 else
1567 elementTypeAsString = VD->getType().getAsString(Context->getPrintingPolicy());
1568 }
1569
1570 // struct __objcFastEnumerationState enumState = { 0 };
1571 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1572 // id __rw_items[16];
1573 buf += "id __rw_items[16];\n\t";
1574 // id l_collection = (id)
1575 buf += "id l_collection = (id)";
1576 // Find start location of 'collection' the hard way!
1577 const char *startCollectionBuf = startBuf;
1578 startCollectionBuf += 3; // skip 'for'
1579 startCollectionBuf = strchr(startCollectionBuf, '(');
1580 startCollectionBuf++; // skip '('
1581 // find 'in' and skip it.
1582 while (*startCollectionBuf != ' ' ||
1583 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1584 (*(startCollectionBuf+3) != ' ' &&
1585 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1586 startCollectionBuf++;
1587 startCollectionBuf += 3;
1588
1589 // Replace: "for (type element in" with string constructed thus far.
1590 ReplaceText(startLoc, startCollectionBuf - startBuf, buf);
1591 // Replace ')' in for '(' type elem in collection ')' with ';'
1592 SourceLocation rightParenLoc = S->getRParenLoc();
1593 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1594 SourceLocation lparenLoc = startLoc.getLocWithOffset(rparenBuf-startBuf);
1595 buf = ";\n\t";
1596
1597 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1598 // objects:__rw_items count:16];
1599 // which is synthesized into:
1600 // unsigned int limit =
1601 // ((unsigned int (*)
1602 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1603 // (void *)objc_msgSend)((id)l_collection,
1604 // sel_registerName(
1605 // "countByEnumeratingWithState:objects:count:"),
1606 // (struct __objcFastEnumerationState *)&state,
1607 // (id *)__rw_items, (unsigned int)16);
1608 buf += "unsigned long limit =\n\t\t";
1609 SynthCountByEnumWithState(buf);
1610 buf += ";\n\t";
1611 /// if (limit) {
1612 /// unsigned long startMutations = *enumState.mutationsPtr;
1613 /// do {
1614 /// unsigned long counter = 0;
1615 /// do {
1616 /// if (startMutations != *enumState.mutationsPtr)
1617 /// objc_enumerationMutation(l_collection);
1618 /// elem = (type)enumState.itemsPtr[counter++];
1619 buf += "if (limit) {\n\t";
1620 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1621 buf += "do {\n\t\t";
1622 buf += "unsigned long counter = 0;\n\t\t";
1623 buf += "do {\n\t\t\t";
1624 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1625 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1626 buf += elementName;
1627 buf += " = (";
1628 buf += elementTypeAsString;
1629 buf += ")enumState.itemsPtr[counter++];";
1630 // Replace ')' in for '(' type elem in collection ')' with all of these.
1631 ReplaceText(lparenLoc, 1, buf);
1632
1633 /// __continue_label: ;
1634 /// } while (counter < limit);
1635 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1636 /// objects:__rw_items count:16]);
1637 /// elem = nil;
1638 /// __break_label: ;
1639 /// }
1640 /// else
1641 /// elem = nil;
1642 /// }
1643 ///
1644 buf = ";\n\t";
1645 buf += "__continue_label_";
1646 buf += utostr(ObjCBcLabelNo.back());
1647 buf += ": ;";
1648 buf += "\n\t\t";
1649 buf += "} while (counter < limit);\n\t";
1650 buf += "} while (limit = ";
1651 SynthCountByEnumWithState(buf);
1652 buf += ");\n\t";
1653 buf += elementName;
1654 buf += " = ((";
1655 buf += elementTypeAsString;
1656 buf += ")0);\n\t";
1657 buf += "__break_label_";
1658 buf += utostr(ObjCBcLabelNo.back());
1659 buf += ": ;\n\t";
1660 buf += "}\n\t";
1661 buf += "else\n\t\t";
1662 buf += elementName;
1663 buf += " = ((";
1664 buf += elementTypeAsString;
1665 buf += ")0);\n\t";
1666 buf += "}\n";
1667
1668 // Insert all these *after* the statement body.
1669 // FIXME: If this should support Obj-C++, support CXXTryStmt
1670 if (isa<CompoundStmt>(S->getBody())) {
1671 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(1);
1672 InsertText(endBodyLoc, buf);
1673 } else {
1674 /* Need to treat single statements specially. For example:
1675 *
1676 * for (A *a in b) if (stuff()) break;
1677 * for (A *a in b) xxxyy;
1678 *
1679 * The following code simply scans ahead to the semi to find the actual end.
1680 */
1681 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1682 const char *semiBuf = strchr(stmtBuf, ';');
1683 assert(semiBuf && "Can't find ';'");
1684 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(semiBuf-stmtBuf+1);
1685 InsertText(endBodyLoc, buf);
1686 }
1687 Stmts.pop_back();
1688 ObjCBcLabelNo.pop_back();
1689 return 0;
1690}
1691
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001692static void Write_RethrowObject(std::string &buf) {
1693 buf += "{ struct _FIN { _FIN(id reth) : rethrow(reth) {}\n";
1694 buf += "\t~_FIN() { if (rethrow) objc_exception_throw(rethrow); }\n";
1695 buf += "\tid rethrow;\n";
1696 buf += "\t} _fin_force_rethow(_rethrow);";
1697}
1698
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001699/// RewriteObjCSynchronizedStmt -
1700/// This routine rewrites @synchronized(expr) stmt;
1701/// into:
1702/// objc_sync_enter(expr);
1703/// @try stmt @finally { objc_sync_exit(expr); }
1704///
1705Stmt *RewriteModernObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
1706 // Get the start location and compute the semi location.
1707 SourceLocation startLoc = S->getLocStart();
1708 const char *startBuf = SM->getCharacterData(startLoc);
1709
1710 assert((*startBuf == '@') && "bogus @synchronized location");
1711
1712 std::string buf;
Fariborz Jahanian22e2f852012-03-17 17:46:02 +00001713 buf = "{ id _rethrow = 0; id _sync_obj = ";
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001714
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001715 const char *lparenBuf = startBuf;
1716 while (*lparenBuf != '(') lparenBuf++;
1717 ReplaceText(startLoc, lparenBuf-startBuf+1, buf);
Fariborz Jahanian22e2f852012-03-17 17:46:02 +00001718
1719 buf = "; objc_sync_enter(_sync_obj);\n";
1720 buf += "try {\n\tstruct _SYNC_EXIT { _SYNC_EXIT(id arg) : sync_exit(arg) {}";
1721 buf += "\n\t~_SYNC_EXIT() {objc_sync_exit(sync_exit);}";
1722 buf += "\n\tid sync_exit;";
1723 buf += "\n\t} _sync_exit(_sync_obj);\n";
1724
1725 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1726 // the sync expression is typically a message expression that's already
1727 // been rewritten! (which implies the SourceLocation's are invalid).
1728 SourceLocation RParenExprLoc = S->getSynchBody()->getLocStart();
1729 const char *RParenExprLocBuf = SM->getCharacterData(RParenExprLoc);
1730 while (*RParenExprLocBuf != ')') RParenExprLocBuf--;
1731 RParenExprLoc = startLoc.getLocWithOffset(RParenExprLocBuf-startBuf);
1732
1733 SourceLocation LBranceLoc = S->getSynchBody()->getLocStart();
1734 const char *LBraceLocBuf = SM->getCharacterData(LBranceLoc);
1735 assert (*LBraceLocBuf == '{');
1736 ReplaceText(RParenExprLoc, (LBraceLocBuf - SM->getCharacterData(RParenExprLoc) + 1), buf);
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001737
Fariborz Jahanianb655bf02012-03-16 21:43:45 +00001738 SourceLocation startRBraceLoc = S->getSynchBody()->getLocEnd();
Matt Beaumont-Gay9ab511c2012-03-16 22:20:39 +00001739 assert((*SM->getCharacterData(startRBraceLoc) == '}') &&
1740 "bogus @synchronized block");
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001741
1742 buf = "} catch (id e) {_rethrow = e;}\n";
1743 Write_RethrowObject(buf);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001744 buf += "}\n";
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001745 buf += "}\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001746
Fariborz Jahanianb655bf02012-03-16 21:43:45 +00001747 ReplaceText(startRBraceLoc, 1, buf);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001748
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001749 return 0;
1750}
1751
1752void RewriteModernObjC::WarnAboutReturnGotoStmts(Stmt *S)
1753{
1754 // Perform a bottom up traversal of all children.
1755 for (Stmt::child_range CI = S->children(); CI; ++CI)
1756 if (*CI)
1757 WarnAboutReturnGotoStmts(*CI);
1758
1759 if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
1760 Diags.Report(Context->getFullLoc(S->getLocStart()),
1761 TryFinallyContainsReturnDiag);
1762 }
1763 return;
1764}
1765
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001766Stmt *RewriteModernObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Fariborz Jahanianb1228182012-03-15 22:42:15 +00001767 ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt();
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001768 bool noCatch = S->getNumCatchStmts() == 0;
Fariborz Jahanianb1228182012-03-15 22:42:15 +00001769 std::string buf;
1770
1771 if (finalStmt) {
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001772 if (noCatch)
1773 buf = "{ id volatile _rethrow = 0;\n";
1774 else {
1775 buf = "{ id volatile _rethrow = 0;\ntry {\n";
1776 }
Fariborz Jahanianb1228182012-03-15 22:42:15 +00001777 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001778 // Get the start location and compute the semi location.
1779 SourceLocation startLoc = S->getLocStart();
1780 const char *startBuf = SM->getCharacterData(startLoc);
1781
1782 assert((*startBuf == '@') && "bogus @try location");
Fariborz Jahanianb1228182012-03-15 22:42:15 +00001783 if (finalStmt)
1784 ReplaceText(startLoc, 1, buf);
1785 else
1786 // @try -> try
1787 ReplaceText(startLoc, 1, "");
1788
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001789 for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I) {
1790 ObjCAtCatchStmt *Catch = S->getCatchStmt(I);
Fariborz Jahanian4c148812012-03-15 20:11:10 +00001791 VarDecl *catchDecl = Catch->getCatchParamDecl();
Fariborz Jahanianc38503b2012-03-12 23:58:28 +00001792
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001793 startLoc = Catch->getLocStart();
Fariborz Jahanian4c148812012-03-15 20:11:10 +00001794 bool AtRemoved = false;
1795 if (catchDecl) {
1796 QualType t = catchDecl->getType();
1797 if (const ObjCObjectPointerType *Ptr = t->getAs<ObjCObjectPointerType>()) {
1798 // Should be a pointer to a class.
1799 ObjCInterfaceDecl *IDecl = Ptr->getObjectType()->getInterface();
1800 if (IDecl) {
1801 std::string Result;
1802 startBuf = SM->getCharacterData(startLoc);
1803 assert((*startBuf == '@') && "bogus @catch location");
1804 SourceLocation rParenLoc = Catch->getRParenLoc();
1805 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1806
1807 // _objc_exc_Foo *_e as argument to catch.
1808 Result = "catch (_objc_exc_"; Result += IDecl->getNameAsString();
1809 Result += " *_"; Result += catchDecl->getNameAsString();
1810 Result += ")";
1811 ReplaceText(startLoc, rParenBuf-startBuf+1, Result);
1812 // Foo *e = (Foo *)_e;
1813 Result.clear();
1814 Result = "{ ";
1815 Result += IDecl->getNameAsString();
1816 Result += " *"; Result += catchDecl->getNameAsString();
1817 Result += " = ("; Result += IDecl->getNameAsString(); Result += "*)";
1818 Result += "_"; Result += catchDecl->getNameAsString();
1819
1820 Result += "; ";
1821 SourceLocation lBraceLoc = Catch->getCatchBody()->getLocStart();
1822 ReplaceText(lBraceLoc, 1, Result);
1823 AtRemoved = true;
1824 }
1825 }
1826 }
1827 if (!AtRemoved)
1828 // @catch -> catch
1829 ReplaceText(startLoc, 1, "");
Fariborz Jahanianc38503b2012-03-12 23:58:28 +00001830
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001831 }
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001832 if (finalStmt) {
1833 buf.clear();
1834 if (noCatch)
1835 buf = "catch (id e) {_rethrow = e;}\n";
1836 else
1837 buf = "}\ncatch (id e) {_rethrow = e;}\n";
1838
1839 SourceLocation startFinalLoc = finalStmt->getLocStart();
1840 ReplaceText(startFinalLoc, 8, buf);
1841 Stmt *body = finalStmt->getFinallyBody();
1842 SourceLocation startFinalBodyLoc = body->getLocStart();
1843 buf.clear();
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001844 Write_RethrowObject(buf);
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001845 ReplaceText(startFinalBodyLoc, 1, buf);
1846
1847 SourceLocation endFinalBodyLoc = body->getLocEnd();
1848 ReplaceText(endFinalBodyLoc, 1, "}\n}");
Fariborz Jahanian22e2f852012-03-17 17:46:02 +00001849 // Now check for any return/continue/go statements within the @try.
1850 WarnAboutReturnGotoStmts(S->getTryBody());
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001851 }
1852
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001853 return 0;
1854}
1855
1856// This can't be done with ReplaceStmt(S, ThrowExpr), since
1857// the throw expression is typically a message expression that's already
1858// been rewritten! (which implies the SourceLocation's are invalid).
1859Stmt *RewriteModernObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
1860 // Get the start location and compute the semi location.
1861 SourceLocation startLoc = S->getLocStart();
1862 const char *startBuf = SM->getCharacterData(startLoc);
1863
1864 assert((*startBuf == '@') && "bogus @throw location");
1865
1866 std::string buf;
1867 /* void objc_exception_throw(id) __attribute__((noreturn)); */
1868 if (S->getThrowExpr())
1869 buf = "objc_exception_throw(";
Fariborz Jahanian40539462012-03-16 16:52:06 +00001870 else
1871 buf = "throw";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001872
1873 // handle "@ throw" correctly.
1874 const char *wBuf = strchr(startBuf, 'w');
1875 assert((*wBuf == 'w') && "@throw: can't find 'w'");
1876 ReplaceText(startLoc, wBuf-startBuf+1, buf);
1877
1878 const char *semiBuf = strchr(startBuf, ';');
1879 assert((*semiBuf == ';') && "@throw: can't find ';'");
1880 SourceLocation semiLoc = startLoc.getLocWithOffset(semiBuf-startBuf);
Fariborz Jahanian40539462012-03-16 16:52:06 +00001881 if (S->getThrowExpr())
1882 ReplaceText(semiLoc, 1, ");");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001883 return 0;
1884}
1885
1886Stmt *RewriteModernObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
1887 // Create a new string expression.
1888 QualType StrType = Context->getPointerType(Context->CharTy);
1889 std::string StrEncoding;
1890 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
1891 Expr *Replacement = StringLiteral::Create(*Context, StrEncoding,
1892 StringLiteral::Ascii, false,
1893 StrType, SourceLocation());
1894 ReplaceStmt(Exp, Replacement);
1895
1896 // Replace this subexpr in the parent.
1897 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
1898 return Replacement;
1899}
1900
1901Stmt *RewriteModernObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
1902 if (!SelGetUidFunctionDecl)
1903 SynthSelGetUidFunctionDecl();
1904 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
1905 // Create a call to sel_registerName("selName").
1906 SmallVector<Expr*, 8> SelExprs;
1907 QualType argType = Context->getPointerType(Context->CharTy);
1908 SelExprs.push_back(StringLiteral::Create(*Context,
1909 Exp->getSelector().getAsString(),
1910 StringLiteral::Ascii, false,
1911 argType, SourceLocation()));
1912 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1913 &SelExprs[0], SelExprs.size());
1914 ReplaceStmt(Exp, SelExp);
1915 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
1916 return SelExp;
1917}
1918
1919CallExpr *RewriteModernObjC::SynthesizeCallToFunctionDecl(
1920 FunctionDecl *FD, Expr **args, unsigned nargs, SourceLocation StartLoc,
1921 SourceLocation EndLoc) {
1922 // Get the type, we will need to reference it in a couple spots.
1923 QualType msgSendType = FD->getType();
1924
1925 // Create a reference to the objc_msgSend() declaration.
1926 DeclRefExpr *DRE =
John McCallf4b88a42012-03-10 09:33:50 +00001927 new (Context) DeclRefExpr(FD, false, msgSendType, VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001928
1929 // Now, we cast the reference to a pointer to the objc_msgSend type.
1930 QualType pToFunc = Context->getPointerType(msgSendType);
1931 ImplicitCastExpr *ICE =
1932 ImplicitCastExpr::Create(*Context, pToFunc, CK_FunctionToPointerDecay,
1933 DRE, 0, VK_RValue);
1934
1935 const FunctionType *FT = msgSendType->getAs<FunctionType>();
1936
1937 CallExpr *Exp =
1938 new (Context) CallExpr(*Context, ICE, args, nargs,
1939 FT->getCallResultType(*Context),
1940 VK_RValue, EndLoc);
1941 return Exp;
1942}
1943
1944static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
1945 const char *&startRef, const char *&endRef) {
1946 while (startBuf < endBuf) {
1947 if (*startBuf == '<')
1948 startRef = startBuf; // mark the start.
1949 if (*startBuf == '>') {
1950 if (startRef && *startRef == '<') {
1951 endRef = startBuf; // mark the end.
1952 return true;
1953 }
1954 return false;
1955 }
1956 startBuf++;
1957 }
1958 return false;
1959}
1960
1961static void scanToNextArgument(const char *&argRef) {
1962 int angle = 0;
1963 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
1964 if (*argRef == '<')
1965 angle++;
1966 else if (*argRef == '>')
1967 angle--;
1968 argRef++;
1969 }
1970 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
1971}
1972
1973bool RewriteModernObjC::needToScanForQualifiers(QualType T) {
1974 if (T->isObjCQualifiedIdType())
1975 return true;
1976 if (const PointerType *PT = T->getAs<PointerType>()) {
1977 if (PT->getPointeeType()->isObjCQualifiedIdType())
1978 return true;
1979 }
1980 if (T->isObjCObjectPointerType()) {
1981 T = T->getPointeeType();
1982 return T->isObjCQualifiedInterfaceType();
1983 }
1984 if (T->isArrayType()) {
1985 QualType ElemTy = Context->getBaseElementType(T);
1986 return needToScanForQualifiers(ElemTy);
1987 }
1988 return false;
1989}
1990
1991void RewriteModernObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
1992 QualType Type = E->getType();
1993 if (needToScanForQualifiers(Type)) {
1994 SourceLocation Loc, EndLoc;
1995
1996 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
1997 Loc = ECE->getLParenLoc();
1998 EndLoc = ECE->getRParenLoc();
1999 } else {
2000 Loc = E->getLocStart();
2001 EndLoc = E->getLocEnd();
2002 }
2003 // This will defend against trying to rewrite synthesized expressions.
2004 if (Loc.isInvalid() || EndLoc.isInvalid())
2005 return;
2006
2007 const char *startBuf = SM->getCharacterData(Loc);
2008 const char *endBuf = SM->getCharacterData(EndLoc);
2009 const char *startRef = 0, *endRef = 0;
2010 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2011 // Get the locations of the startRef, endRef.
2012 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-startBuf);
2013 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-startBuf+1);
2014 // Comment out the protocol references.
2015 InsertText(LessLoc, "/*");
2016 InsertText(GreaterLoc, "*/");
2017 }
2018 }
2019}
2020
2021void RewriteModernObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
2022 SourceLocation Loc;
2023 QualType Type;
2024 const FunctionProtoType *proto = 0;
2025 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
2026 Loc = VD->getLocation();
2027 Type = VD->getType();
2028 }
2029 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
2030 Loc = FD->getLocation();
2031 // Check for ObjC 'id' and class types that have been adorned with protocol
2032 // information (id<p>, C<p>*). The protocol references need to be rewritten!
2033 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2034 assert(funcType && "missing function type");
2035 proto = dyn_cast<FunctionProtoType>(funcType);
2036 if (!proto)
2037 return;
2038 Type = proto->getResultType();
2039 }
2040 else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
2041 Loc = FD->getLocation();
2042 Type = FD->getType();
2043 }
2044 else
2045 return;
2046
2047 if (needToScanForQualifiers(Type)) {
2048 // Since types are unique, we need to scan the buffer.
2049
2050 const char *endBuf = SM->getCharacterData(Loc);
2051 const char *startBuf = endBuf;
2052 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
2053 startBuf--; // scan backward (from the decl location) for return type.
2054 const char *startRef = 0, *endRef = 0;
2055 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2056 // Get the locations of the startRef, endRef.
2057 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-endBuf);
2058 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-endBuf+1);
2059 // Comment out the protocol references.
2060 InsertText(LessLoc, "/*");
2061 InsertText(GreaterLoc, "*/");
2062 }
2063 }
2064 if (!proto)
2065 return; // most likely, was a variable
2066 // Now check arguments.
2067 const char *startBuf = SM->getCharacterData(Loc);
2068 const char *startFuncBuf = startBuf;
2069 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
2070 if (needToScanForQualifiers(proto->getArgType(i))) {
2071 // Since types are unique, we need to scan the buffer.
2072
2073 const char *endBuf = startBuf;
2074 // scan forward (from the decl location) for argument types.
2075 scanToNextArgument(endBuf);
2076 const char *startRef = 0, *endRef = 0;
2077 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2078 // Get the locations of the startRef, endRef.
2079 SourceLocation LessLoc =
2080 Loc.getLocWithOffset(startRef-startFuncBuf);
2081 SourceLocation GreaterLoc =
2082 Loc.getLocWithOffset(endRef-startFuncBuf+1);
2083 // Comment out the protocol references.
2084 InsertText(LessLoc, "/*");
2085 InsertText(GreaterLoc, "*/");
2086 }
2087 startBuf = ++endBuf;
2088 }
2089 else {
2090 // If the function name is derived from a macro expansion, then the
2091 // argument buffer will not follow the name. Need to speak with Chris.
2092 while (*startBuf && *startBuf != ')' && *startBuf != ',')
2093 startBuf++; // scan forward (from the decl location) for argument types.
2094 startBuf++;
2095 }
2096 }
2097}
2098
2099void RewriteModernObjC::RewriteTypeOfDecl(VarDecl *ND) {
2100 QualType QT = ND->getType();
2101 const Type* TypePtr = QT->getAs<Type>();
2102 if (!isa<TypeOfExprType>(TypePtr))
2103 return;
2104 while (isa<TypeOfExprType>(TypePtr)) {
2105 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
2106 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
2107 TypePtr = QT->getAs<Type>();
2108 }
2109 // FIXME. This will not work for multiple declarators; as in:
2110 // __typeof__(a) b,c,d;
2111 std::string TypeAsString(QT.getAsString(Context->getPrintingPolicy()));
2112 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
2113 const char *startBuf = SM->getCharacterData(DeclLoc);
2114 if (ND->getInit()) {
2115 std::string Name(ND->getNameAsString());
2116 TypeAsString += " " + Name + " = ";
2117 Expr *E = ND->getInit();
2118 SourceLocation startLoc;
2119 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
2120 startLoc = ECE->getLParenLoc();
2121 else
2122 startLoc = E->getLocStart();
2123 startLoc = SM->getExpansionLoc(startLoc);
2124 const char *endBuf = SM->getCharacterData(startLoc);
2125 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
2126 }
2127 else {
2128 SourceLocation X = ND->getLocEnd();
2129 X = SM->getExpansionLoc(X);
2130 const char *endBuf = SM->getCharacterData(X);
2131 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
2132 }
2133}
2134
2135// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
2136void RewriteModernObjC::SynthSelGetUidFunctionDecl() {
2137 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
2138 SmallVector<QualType, 16> ArgTys;
2139 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2140 QualType getFuncType =
2141 getSimpleFunctionType(Context->getObjCSelType(), &ArgTys[0], ArgTys.size());
2142 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2143 SourceLocation(),
2144 SourceLocation(),
2145 SelGetUidIdent, getFuncType, 0,
2146 SC_Extern,
2147 SC_None, false);
2148}
2149
2150void RewriteModernObjC::RewriteFunctionDecl(FunctionDecl *FD) {
2151 // declared in <objc/objc.h>
2152 if (FD->getIdentifier() &&
2153 FD->getName() == "sel_registerName") {
2154 SelGetUidFunctionDecl = FD;
2155 return;
2156 }
2157 RewriteObjCQualifiedInterfaceTypes(FD);
2158}
2159
2160void RewriteModernObjC::RewriteBlockPointerType(std::string& Str, QualType Type) {
2161 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
2162 const char *argPtr = TypeString.c_str();
2163 if (!strchr(argPtr, '^')) {
2164 Str += TypeString;
2165 return;
2166 }
2167 while (*argPtr) {
2168 Str += (*argPtr == '^' ? '*' : *argPtr);
2169 argPtr++;
2170 }
2171}
2172
2173// FIXME. Consolidate this routine with RewriteBlockPointerType.
2174void RewriteModernObjC::RewriteBlockPointerTypeVariable(std::string& Str,
2175 ValueDecl *VD) {
2176 QualType Type = VD->getType();
2177 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
2178 const char *argPtr = TypeString.c_str();
2179 int paren = 0;
2180 while (*argPtr) {
2181 switch (*argPtr) {
2182 case '(':
2183 Str += *argPtr;
2184 paren++;
2185 break;
2186 case ')':
2187 Str += *argPtr;
2188 paren--;
2189 break;
2190 case '^':
2191 Str += '*';
2192 if (paren == 1)
2193 Str += VD->getNameAsString();
2194 break;
2195 default:
2196 Str += *argPtr;
2197 break;
2198 }
2199 argPtr++;
2200 }
2201}
2202
2203
2204void RewriteModernObjC::RewriteBlockLiteralFunctionDecl(FunctionDecl *FD) {
2205 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
2206 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2207 const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(funcType);
2208 if (!proto)
2209 return;
2210 QualType Type = proto->getResultType();
2211 std::string FdStr = Type.getAsString(Context->getPrintingPolicy());
2212 FdStr += " ";
2213 FdStr += FD->getName();
2214 FdStr += "(";
2215 unsigned numArgs = proto->getNumArgs();
2216 for (unsigned i = 0; i < numArgs; i++) {
2217 QualType ArgType = proto->getArgType(i);
2218 RewriteBlockPointerType(FdStr, ArgType);
2219 if (i+1 < numArgs)
2220 FdStr += ", ";
2221 }
2222 FdStr += ");\n";
2223 InsertText(FunLocStart, FdStr);
2224 CurFunctionDeclToDeclareForBlock = 0;
2225}
2226
2227// SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
2228void RewriteModernObjC::SynthSuperContructorFunctionDecl() {
2229 if (SuperContructorFunctionDecl)
2230 return;
2231 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
2232 SmallVector<QualType, 16> ArgTys;
2233 QualType argT = Context->getObjCIdType();
2234 assert(!argT.isNull() && "Can't find 'id' type");
2235 ArgTys.push_back(argT);
2236 ArgTys.push_back(argT);
2237 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2238 &ArgTys[0], ArgTys.size());
2239 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2240 SourceLocation(),
2241 SourceLocation(),
2242 msgSendIdent, msgSendType, 0,
2243 SC_Extern,
2244 SC_None, false);
2245}
2246
2247// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
2248void RewriteModernObjC::SynthMsgSendFunctionDecl() {
2249 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
2250 SmallVector<QualType, 16> ArgTys;
2251 QualType argT = Context->getObjCIdType();
2252 assert(!argT.isNull() && "Can't find 'id' type");
2253 ArgTys.push_back(argT);
2254 argT = Context->getObjCSelType();
2255 assert(!argT.isNull() && "Can't find 'SEL' type");
2256 ArgTys.push_back(argT);
2257 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2258 &ArgTys[0], ArgTys.size(),
2259 true /*isVariadic*/);
2260 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2261 SourceLocation(),
2262 SourceLocation(),
2263 msgSendIdent, msgSendType, 0,
2264 SC_Extern,
2265 SC_None, false);
2266}
2267
2268// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
2269void RewriteModernObjC::SynthMsgSendSuperFunctionDecl() {
2270 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
2271 SmallVector<QualType, 16> ArgTys;
2272 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
2273 SourceLocation(), SourceLocation(),
2274 &Context->Idents.get("objc_super"));
2275 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2276 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2277 ArgTys.push_back(argT);
2278 argT = Context->getObjCSelType();
2279 assert(!argT.isNull() && "Can't find 'SEL' type");
2280 ArgTys.push_back(argT);
2281 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2282 &ArgTys[0], ArgTys.size(),
2283 true /*isVariadic*/);
2284 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2285 SourceLocation(),
2286 SourceLocation(),
2287 msgSendIdent, msgSendType, 0,
2288 SC_Extern,
2289 SC_None, false);
2290}
2291
2292// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
2293void RewriteModernObjC::SynthMsgSendStretFunctionDecl() {
2294 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
2295 SmallVector<QualType, 16> ArgTys;
2296 QualType argT = Context->getObjCIdType();
2297 assert(!argT.isNull() && "Can't find 'id' type");
2298 ArgTys.push_back(argT);
2299 argT = Context->getObjCSelType();
2300 assert(!argT.isNull() && "Can't find 'SEL' type");
2301 ArgTys.push_back(argT);
2302 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2303 &ArgTys[0], ArgTys.size(),
2304 true /*isVariadic*/);
2305 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2306 SourceLocation(),
2307 SourceLocation(),
2308 msgSendIdent, msgSendType, 0,
2309 SC_Extern,
2310 SC_None, false);
2311}
2312
2313// SynthMsgSendSuperStretFunctionDecl -
2314// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
2315void RewriteModernObjC::SynthMsgSendSuperStretFunctionDecl() {
2316 IdentifierInfo *msgSendIdent =
2317 &Context->Idents.get("objc_msgSendSuper_stret");
2318 SmallVector<QualType, 16> ArgTys;
2319 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
2320 SourceLocation(), SourceLocation(),
2321 &Context->Idents.get("objc_super"));
2322 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2323 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2324 ArgTys.push_back(argT);
2325 argT = Context->getObjCSelType();
2326 assert(!argT.isNull() && "Can't find 'SEL' type");
2327 ArgTys.push_back(argT);
2328 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2329 &ArgTys[0], ArgTys.size(),
2330 true /*isVariadic*/);
2331 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2332 SourceLocation(),
2333 SourceLocation(),
2334 msgSendIdent, msgSendType, 0,
2335 SC_Extern,
2336 SC_None, false);
2337}
2338
2339// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
2340void RewriteModernObjC::SynthMsgSendFpretFunctionDecl() {
2341 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
2342 SmallVector<QualType, 16> ArgTys;
2343 QualType argT = Context->getObjCIdType();
2344 assert(!argT.isNull() && "Can't find 'id' type");
2345 ArgTys.push_back(argT);
2346 argT = Context->getObjCSelType();
2347 assert(!argT.isNull() && "Can't find 'SEL' type");
2348 ArgTys.push_back(argT);
2349 QualType msgSendType = getSimpleFunctionType(Context->DoubleTy,
2350 &ArgTys[0], ArgTys.size(),
2351 true /*isVariadic*/);
2352 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2353 SourceLocation(),
2354 SourceLocation(),
2355 msgSendIdent, msgSendType, 0,
2356 SC_Extern,
2357 SC_None, false);
2358}
2359
2360// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
2361void RewriteModernObjC::SynthGetClassFunctionDecl() {
2362 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
2363 SmallVector<QualType, 16> ArgTys;
2364 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2365 QualType getClassType = getSimpleFunctionType(Context->getObjCIdType(),
2366 &ArgTys[0], ArgTys.size());
2367 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2368 SourceLocation(),
2369 SourceLocation(),
2370 getClassIdent, getClassType, 0,
2371 SC_Extern,
2372 SC_None, false);
2373}
2374
2375// SynthGetSuperClassFunctionDecl - Class class_getSuperclass(Class cls);
2376void RewriteModernObjC::SynthGetSuperClassFunctionDecl() {
2377 IdentifierInfo *getSuperClassIdent =
2378 &Context->Idents.get("class_getSuperclass");
2379 SmallVector<QualType, 16> ArgTys;
2380 ArgTys.push_back(Context->getObjCClassType());
2381 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
2382 &ArgTys[0], ArgTys.size());
2383 GetSuperClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2384 SourceLocation(),
2385 SourceLocation(),
2386 getSuperClassIdent,
2387 getClassType, 0,
2388 SC_Extern,
2389 SC_None,
2390 false);
2391}
2392
2393// SynthGetMetaClassFunctionDecl - id objc_getMetaClass(const char *name);
2394void RewriteModernObjC::SynthGetMetaClassFunctionDecl() {
2395 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
2396 SmallVector<QualType, 16> ArgTys;
2397 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2398 QualType getClassType = getSimpleFunctionType(Context->getObjCIdType(),
2399 &ArgTys[0], ArgTys.size());
2400 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2401 SourceLocation(),
2402 SourceLocation(),
2403 getClassIdent, getClassType, 0,
2404 SC_Extern,
2405 SC_None, false);
2406}
2407
2408Stmt *RewriteModernObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
2409 QualType strType = getConstantStringStructType();
2410
2411 std::string S = "__NSConstantStringImpl_";
2412
2413 std::string tmpName = InFileName;
2414 unsigned i;
2415 for (i=0; i < tmpName.length(); i++) {
2416 char c = tmpName.at(i);
2417 // replace any non alphanumeric characters with '_'.
2418 if (!isalpha(c) && (c < '0' || c > '9'))
2419 tmpName[i] = '_';
2420 }
2421 S += tmpName;
2422 S += "_";
2423 S += utostr(NumObjCStringLiterals++);
2424
2425 Preamble += "static __NSConstantStringImpl " + S;
2426 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2427 Preamble += "0x000007c8,"; // utf8_str
2428 // The pretty printer for StringLiteral handles escape characters properly.
2429 std::string prettyBufS;
2430 llvm::raw_string_ostream prettyBuf(prettyBufS);
2431 Exp->getString()->printPretty(prettyBuf, *Context, 0,
2432 PrintingPolicy(LangOpts));
2433 Preamble += prettyBuf.str();
2434 Preamble += ",";
2435 Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
2436
2437 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
2438 SourceLocation(), &Context->Idents.get(S),
2439 strType, 0, SC_Static, SC_None);
John McCallf4b88a42012-03-10 09:33:50 +00002440 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, false, strType, VK_LValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002441 SourceLocation());
2442 Expr *Unop = new (Context) UnaryOperator(DRE, UO_AddrOf,
2443 Context->getPointerType(DRE->getType()),
2444 VK_RValue, OK_Ordinary,
2445 SourceLocation());
2446 // cast to NSConstantString *
2447 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Exp->getType(),
2448 CK_CPointerToObjCPointerCast, Unop);
2449 ReplaceStmt(Exp, cast);
2450 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2451 return cast;
2452}
2453
Fariborz Jahanian55947042012-03-27 20:17:30 +00002454Stmt *RewriteModernObjC::RewriteObjCBoolLiteralExpr(ObjCBoolLiteralExpr *Exp) {
2455 unsigned IntSize =
2456 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
2457
2458 Expr *FlagExp = IntegerLiteral::Create(*Context,
2459 llvm::APInt(IntSize, Exp->getValue()),
2460 Context->IntTy, Exp->getLocation());
2461 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Context->ObjCBuiltinBoolTy,
2462 CK_BitCast, FlagExp);
2463 ParenExpr *PE = new (Context) ParenExpr(Exp->getLocation(), Exp->getExprLoc(),
2464 cast);
2465 ReplaceStmt(Exp, PE);
2466 return PE;
2467}
2468
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002469// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
2470QualType RewriteModernObjC::getSuperStructType() {
2471 if (!SuperStructDecl) {
2472 SuperStructDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
2473 SourceLocation(), SourceLocation(),
2474 &Context->Idents.get("objc_super"));
2475 QualType FieldTypes[2];
2476
2477 // struct objc_object *receiver;
2478 FieldTypes[0] = Context->getObjCIdType();
2479 // struct objc_class *super;
2480 FieldTypes[1] = Context->getObjCClassType();
2481
2482 // Create fields
2483 for (unsigned i = 0; i < 2; ++i) {
2484 SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
2485 SourceLocation(),
2486 SourceLocation(), 0,
2487 FieldTypes[i], 0,
2488 /*BitWidth=*/0,
2489 /*Mutable=*/false,
2490 /*HasInit=*/false));
2491 }
2492
2493 SuperStructDecl->completeDefinition();
2494 }
2495 return Context->getTagDeclType(SuperStructDecl);
2496}
2497
2498QualType RewriteModernObjC::getConstantStringStructType() {
2499 if (!ConstantStringDecl) {
2500 ConstantStringDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
2501 SourceLocation(), SourceLocation(),
2502 &Context->Idents.get("__NSConstantStringImpl"));
2503 QualType FieldTypes[4];
2504
2505 // struct objc_object *receiver;
2506 FieldTypes[0] = Context->getObjCIdType();
2507 // int flags;
2508 FieldTypes[1] = Context->IntTy;
2509 // char *str;
2510 FieldTypes[2] = Context->getPointerType(Context->CharTy);
2511 // long length;
2512 FieldTypes[3] = Context->LongTy;
2513
2514 // Create fields
2515 for (unsigned i = 0; i < 4; ++i) {
2516 ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
2517 ConstantStringDecl,
2518 SourceLocation(),
2519 SourceLocation(), 0,
2520 FieldTypes[i], 0,
2521 /*BitWidth=*/0,
2522 /*Mutable=*/true,
2523 /*HasInit=*/false));
2524 }
2525
2526 ConstantStringDecl->completeDefinition();
2527 }
2528 return Context->getTagDeclType(ConstantStringDecl);
2529}
2530
2531Stmt *RewriteModernObjC::SynthMessageExpr(ObjCMessageExpr *Exp,
2532 SourceLocation StartLoc,
2533 SourceLocation EndLoc) {
2534 if (!SelGetUidFunctionDecl)
2535 SynthSelGetUidFunctionDecl();
2536 if (!MsgSendFunctionDecl)
2537 SynthMsgSendFunctionDecl();
2538 if (!MsgSendSuperFunctionDecl)
2539 SynthMsgSendSuperFunctionDecl();
2540 if (!MsgSendStretFunctionDecl)
2541 SynthMsgSendStretFunctionDecl();
2542 if (!MsgSendSuperStretFunctionDecl)
2543 SynthMsgSendSuperStretFunctionDecl();
2544 if (!MsgSendFpretFunctionDecl)
2545 SynthMsgSendFpretFunctionDecl();
2546 if (!GetClassFunctionDecl)
2547 SynthGetClassFunctionDecl();
2548 if (!GetSuperClassFunctionDecl)
2549 SynthGetSuperClassFunctionDecl();
2550 if (!GetMetaClassFunctionDecl)
2551 SynthGetMetaClassFunctionDecl();
2552
2553 // default to objc_msgSend().
2554 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2555 // May need to use objc_msgSend_stret() as well.
2556 FunctionDecl *MsgSendStretFlavor = 0;
2557 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
2558 QualType resultType = mDecl->getResultType();
2559 if (resultType->isRecordType())
2560 MsgSendStretFlavor = MsgSendStretFunctionDecl;
2561 else if (resultType->isRealFloatingType())
2562 MsgSendFlavor = MsgSendFpretFunctionDecl;
2563 }
2564
2565 // Synthesize a call to objc_msgSend().
2566 SmallVector<Expr*, 8> MsgExprs;
2567 switch (Exp->getReceiverKind()) {
2568 case ObjCMessageExpr::SuperClass: {
2569 MsgSendFlavor = MsgSendSuperFunctionDecl;
2570 if (MsgSendStretFlavor)
2571 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2572 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2573
2574 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
2575
2576 SmallVector<Expr*, 4> InitExprs;
2577
2578 // set the receiver to self, the first argument to all methods.
2579 InitExprs.push_back(
2580 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2581 CK_BitCast,
2582 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCallf4b88a42012-03-10 09:33:50 +00002583 false,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002584 Context->getObjCIdType(),
2585 VK_RValue,
2586 SourceLocation()))
2587 ); // set the 'receiver'.
2588
2589 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2590 SmallVector<Expr*, 8> ClsExprs;
2591 QualType argType = Context->getPointerType(Context->CharTy);
2592 ClsExprs.push_back(StringLiteral::Create(*Context,
2593 ClassDecl->getIdentifier()->getName(),
2594 StringLiteral::Ascii, false,
2595 argType, SourceLocation()));
2596 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
2597 &ClsExprs[0],
2598 ClsExprs.size(),
2599 StartLoc,
2600 EndLoc);
2601 // (Class)objc_getClass("CurrentClass")
2602 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
2603 Context->getObjCClassType(),
2604 CK_BitCast, Cls);
2605 ClsExprs.clear();
2606 ClsExprs.push_back(ArgExpr);
2607 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
2608 &ClsExprs[0], ClsExprs.size(),
2609 StartLoc, EndLoc);
2610
2611 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2612 // To turn off a warning, type-cast to 'id'
2613 InitExprs.push_back( // set 'super class', using class_getSuperclass().
2614 NoTypeInfoCStyleCastExpr(Context,
2615 Context->getObjCIdType(),
2616 CK_BitCast, Cls));
2617 // struct objc_super
2618 QualType superType = getSuperStructType();
2619 Expr *SuperRep;
2620
2621 if (LangOpts.MicrosoftExt) {
2622 SynthSuperContructorFunctionDecl();
2623 // Simulate a contructor call...
2624 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
John McCallf4b88a42012-03-10 09:33:50 +00002625 false, superType, VK_LValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002626 SourceLocation());
2627 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
2628 InitExprs.size(),
2629 superType, VK_LValue,
2630 SourceLocation());
2631 // The code for super is a little tricky to prevent collision with
2632 // the structure definition in the header. The rewriter has it's own
2633 // internal definition (__rw_objc_super) that is uses. This is why
2634 // we need the cast below. For example:
2635 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2636 //
2637 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
2638 Context->getPointerType(SuperRep->getType()),
2639 VK_RValue, OK_Ordinary,
2640 SourceLocation());
2641 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2642 Context->getPointerType(superType),
2643 CK_BitCast, SuperRep);
2644 } else {
2645 // (struct objc_super) { <exprs from above> }
2646 InitListExpr *ILE =
2647 new (Context) InitListExpr(*Context, SourceLocation(),
2648 &InitExprs[0], InitExprs.size(),
2649 SourceLocation());
2650 TypeSourceInfo *superTInfo
2651 = Context->getTrivialTypeSourceInfo(superType);
2652 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
2653 superType, VK_LValue,
2654 ILE, false);
2655 // struct objc_super *
2656 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
2657 Context->getPointerType(SuperRep->getType()),
2658 VK_RValue, OK_Ordinary,
2659 SourceLocation());
2660 }
2661 MsgExprs.push_back(SuperRep);
2662 break;
2663 }
2664
2665 case ObjCMessageExpr::Class: {
2666 SmallVector<Expr*, 8> ClsExprs;
2667 QualType argType = Context->getPointerType(Context->CharTy);
2668 ObjCInterfaceDecl *Class
2669 = Exp->getClassReceiver()->getAs<ObjCObjectType>()->getInterface();
2670 IdentifierInfo *clsName = Class->getIdentifier();
2671 ClsExprs.push_back(StringLiteral::Create(*Context,
2672 clsName->getName(),
2673 StringLiteral::Ascii, false,
2674 argType, SourceLocation()));
2675 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2676 &ClsExprs[0],
2677 ClsExprs.size(),
2678 StartLoc, EndLoc);
2679 MsgExprs.push_back(Cls);
2680 break;
2681 }
2682
2683 case ObjCMessageExpr::SuperInstance:{
2684 MsgSendFlavor = MsgSendSuperFunctionDecl;
2685 if (MsgSendStretFlavor)
2686 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2687 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2688 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
2689 SmallVector<Expr*, 4> InitExprs;
2690
2691 InitExprs.push_back(
2692 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2693 CK_BitCast,
2694 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCallf4b88a42012-03-10 09:33:50 +00002695 false,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002696 Context->getObjCIdType(),
2697 VK_RValue, SourceLocation()))
2698 ); // set the 'receiver'.
2699
2700 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2701 SmallVector<Expr*, 8> ClsExprs;
2702 QualType argType = Context->getPointerType(Context->CharTy);
2703 ClsExprs.push_back(StringLiteral::Create(*Context,
2704 ClassDecl->getIdentifier()->getName(),
2705 StringLiteral::Ascii, false, argType,
2706 SourceLocation()));
2707 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2708 &ClsExprs[0],
2709 ClsExprs.size(),
2710 StartLoc, EndLoc);
2711 // (Class)objc_getClass("CurrentClass")
2712 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
2713 Context->getObjCClassType(),
2714 CK_BitCast, Cls);
2715 ClsExprs.clear();
2716 ClsExprs.push_back(ArgExpr);
2717 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
2718 &ClsExprs[0], ClsExprs.size(),
2719 StartLoc, EndLoc);
2720
2721 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2722 // To turn off a warning, type-cast to 'id'
2723 InitExprs.push_back(
2724 // set 'super class', using class_getSuperclass().
2725 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2726 CK_BitCast, Cls));
2727 // struct objc_super
2728 QualType superType = getSuperStructType();
2729 Expr *SuperRep;
2730
2731 if (LangOpts.MicrosoftExt) {
2732 SynthSuperContructorFunctionDecl();
2733 // Simulate a contructor call...
2734 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
John McCallf4b88a42012-03-10 09:33:50 +00002735 false, superType, VK_LValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002736 SourceLocation());
2737 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
2738 InitExprs.size(),
2739 superType, VK_LValue, SourceLocation());
2740 // The code for super is a little tricky to prevent collision with
2741 // the structure definition in the header. The rewriter has it's own
2742 // internal definition (__rw_objc_super) that is uses. This is why
2743 // we need the cast below. For example:
2744 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2745 //
2746 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
2747 Context->getPointerType(SuperRep->getType()),
2748 VK_RValue, OK_Ordinary,
2749 SourceLocation());
2750 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2751 Context->getPointerType(superType),
2752 CK_BitCast, SuperRep);
2753 } else {
2754 // (struct objc_super) { <exprs from above> }
2755 InitListExpr *ILE =
2756 new (Context) InitListExpr(*Context, SourceLocation(),
2757 &InitExprs[0], InitExprs.size(),
2758 SourceLocation());
2759 TypeSourceInfo *superTInfo
2760 = Context->getTrivialTypeSourceInfo(superType);
2761 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
2762 superType, VK_RValue, ILE,
2763 false);
2764 }
2765 MsgExprs.push_back(SuperRep);
2766 break;
2767 }
2768
2769 case ObjCMessageExpr::Instance: {
2770 // Remove all type-casts because it may contain objc-style types; e.g.
2771 // Foo<Proto> *.
2772 Expr *recExpr = Exp->getInstanceReceiver();
2773 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
2774 recExpr = CE->getSubExpr();
2775 CastKind CK = recExpr->getType()->isObjCObjectPointerType()
2776 ? CK_BitCast : recExpr->getType()->isBlockPointerType()
2777 ? CK_BlockPointerToObjCPointerCast
2778 : CK_CPointerToObjCPointerCast;
2779
2780 recExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2781 CK, recExpr);
2782 MsgExprs.push_back(recExpr);
2783 break;
2784 }
2785 }
2786
2787 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
2788 SmallVector<Expr*, 8> SelExprs;
2789 QualType argType = Context->getPointerType(Context->CharTy);
2790 SelExprs.push_back(StringLiteral::Create(*Context,
2791 Exp->getSelector().getAsString(),
2792 StringLiteral::Ascii, false,
2793 argType, SourceLocation()));
2794 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2795 &SelExprs[0], SelExprs.size(),
2796 StartLoc,
2797 EndLoc);
2798 MsgExprs.push_back(SelExp);
2799
2800 // Now push any user supplied arguments.
2801 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
2802 Expr *userExpr = Exp->getArg(i);
2803 // Make all implicit casts explicit...ICE comes in handy:-)
2804 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
2805 // Reuse the ICE type, it is exactly what the doctor ordered.
2806 QualType type = ICE->getType();
2807 if (needToScanForQualifiers(type))
2808 type = Context->getObjCIdType();
2809 // Make sure we convert "type (^)(...)" to "type (*)(...)".
2810 (void)convertBlockPointerToFunctionPointer(type);
2811 const Expr *SubExpr = ICE->IgnoreParenImpCasts();
2812 CastKind CK;
2813 if (SubExpr->getType()->isIntegralType(*Context) &&
2814 type->isBooleanType()) {
2815 CK = CK_IntegralToBoolean;
2816 } else if (type->isObjCObjectPointerType()) {
2817 if (SubExpr->getType()->isBlockPointerType()) {
2818 CK = CK_BlockPointerToObjCPointerCast;
2819 } else if (SubExpr->getType()->isPointerType()) {
2820 CK = CK_CPointerToObjCPointerCast;
2821 } else {
2822 CK = CK_BitCast;
2823 }
2824 } else {
2825 CK = CK_BitCast;
2826 }
2827
2828 userExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, userExpr);
2829 }
2830 // Make id<P...> cast into an 'id' cast.
2831 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
2832 if (CE->getType()->isObjCQualifiedIdType()) {
2833 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
2834 userExpr = CE->getSubExpr();
2835 CastKind CK;
2836 if (userExpr->getType()->isIntegralType(*Context)) {
2837 CK = CK_IntegralToPointer;
2838 } else if (userExpr->getType()->isBlockPointerType()) {
2839 CK = CK_BlockPointerToObjCPointerCast;
2840 } else if (userExpr->getType()->isPointerType()) {
2841 CK = CK_CPointerToObjCPointerCast;
2842 } else {
2843 CK = CK_BitCast;
2844 }
2845 userExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2846 CK, userExpr);
2847 }
2848 }
2849 MsgExprs.push_back(userExpr);
2850 // We've transferred the ownership to MsgExprs. For now, we *don't* null
2851 // out the argument in the original expression (since we aren't deleting
2852 // the ObjCMessageExpr). See RewritePropertyOrImplicitSetter() usage for more info.
2853 //Exp->setArg(i, 0);
2854 }
2855 // Generate the funky cast.
2856 CastExpr *cast;
2857 SmallVector<QualType, 8> ArgTypes;
2858 QualType returnType;
2859
2860 // Push 'id' and 'SEL', the 2 implicit arguments.
2861 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
2862 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
2863 else
2864 ArgTypes.push_back(Context->getObjCIdType());
2865 ArgTypes.push_back(Context->getObjCSelType());
2866 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
2867 // Push any user argument types.
2868 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
2869 E = OMD->param_end(); PI != E; ++PI) {
2870 QualType t = (*PI)->getType()->isObjCQualifiedIdType()
2871 ? Context->getObjCIdType()
2872 : (*PI)->getType();
2873 // Make sure we convert "t (^)(...)" to "t (*)(...)".
2874 (void)convertBlockPointerToFunctionPointer(t);
2875 ArgTypes.push_back(t);
2876 }
2877 returnType = Exp->getType();
2878 convertToUnqualifiedObjCType(returnType);
2879 (void)convertBlockPointerToFunctionPointer(returnType);
2880 } else {
2881 returnType = Context->getObjCIdType();
2882 }
2883 // Get the type, we will need to reference it in a couple spots.
2884 QualType msgSendType = MsgSendFlavor->getType();
2885
2886 // Create a reference to the objc_msgSend() declaration.
John McCallf4b88a42012-03-10 09:33:50 +00002887 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002888 VK_LValue, SourceLocation());
2889
2890 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
2891 // If we don't do this cast, we get the following bizarre warning/note:
2892 // xx.m:13: warning: function called through a non-compatible type
2893 // xx.m:13: note: if this code is reached, the program will abort
2894 cast = NoTypeInfoCStyleCastExpr(Context,
2895 Context->getPointerType(Context->VoidTy),
2896 CK_BitCast, DRE);
2897
2898 // Now do the "normal" pointer to function cast.
2899 QualType castType =
2900 getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
2901 // If we don't have a method decl, force a variadic cast.
2902 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true);
2903 castType = Context->getPointerType(castType);
2904 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2905 cast);
2906
2907 // Don't forget the parens to enforce the proper binding.
2908 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
2909
2910 const FunctionType *FT = msgSendType->getAs<FunctionType>();
2911 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
2912 MsgExprs.size(),
2913 FT->getResultType(), VK_RValue,
2914 EndLoc);
2915 Stmt *ReplacingStmt = CE;
2916 if (MsgSendStretFlavor) {
2917 // We have the method which returns a struct/union. Must also generate
2918 // call to objc_msgSend_stret and hang both varieties on a conditional
2919 // expression which dictate which one to envoke depending on size of
2920 // method's return type.
2921
2922 // Create a reference to the objc_msgSend_stret() declaration.
John McCallf4b88a42012-03-10 09:33:50 +00002923 DeclRefExpr *STDRE = new (Context) DeclRefExpr(MsgSendStretFlavor,
2924 false, msgSendType,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002925 VK_LValue, SourceLocation());
2926 // Need to cast objc_msgSend_stret to "void *" (see above comment).
2927 cast = NoTypeInfoCStyleCastExpr(Context,
2928 Context->getPointerType(Context->VoidTy),
2929 CK_BitCast, STDRE);
2930 // Now do the "normal" pointer to function cast.
2931 castType = getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
2932 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false);
2933 castType = Context->getPointerType(castType);
2934 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2935 cast);
2936
2937 // Don't forget the parens to enforce the proper binding.
2938 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
2939
2940 FT = msgSendType->getAs<FunctionType>();
2941 CallExpr *STCE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
2942 MsgExprs.size(),
2943 FT->getResultType(), VK_RValue,
2944 SourceLocation());
2945
2946 // Build sizeof(returnType)
2947 UnaryExprOrTypeTraitExpr *sizeofExpr =
2948 new (Context) UnaryExprOrTypeTraitExpr(UETT_SizeOf,
2949 Context->getTrivialTypeSourceInfo(returnType),
2950 Context->getSizeType(), SourceLocation(),
2951 SourceLocation());
2952 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2953 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
2954 // For X86 it is more complicated and some kind of target specific routine
2955 // is needed to decide what to do.
2956 unsigned IntSize =
2957 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
2958 IntegerLiteral *limit = IntegerLiteral::Create(*Context,
2959 llvm::APInt(IntSize, 8),
2960 Context->IntTy,
2961 SourceLocation());
2962 BinaryOperator *lessThanExpr =
2963 new (Context) BinaryOperator(sizeofExpr, limit, BO_LE, Context->IntTy,
2964 VK_RValue, OK_Ordinary, SourceLocation());
2965 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2966 ConditionalOperator *CondExpr =
2967 new (Context) ConditionalOperator(lessThanExpr,
2968 SourceLocation(), CE,
2969 SourceLocation(), STCE,
2970 returnType, VK_RValue, OK_Ordinary);
2971 ReplacingStmt = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
2972 CondExpr);
2973 }
2974 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2975 return ReplacingStmt;
2976}
2977
2978Stmt *RewriteModernObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
2979 Stmt *ReplacingStmt = SynthMessageExpr(Exp, Exp->getLocStart(),
2980 Exp->getLocEnd());
2981
2982 // Now do the actual rewrite.
2983 ReplaceStmt(Exp, ReplacingStmt);
2984
2985 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2986 return ReplacingStmt;
2987}
2988
2989// typedef struct objc_object Protocol;
2990QualType RewriteModernObjC::getProtocolType() {
2991 if (!ProtocolTypeDecl) {
2992 TypeSourceInfo *TInfo
2993 = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
2994 ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
2995 SourceLocation(), SourceLocation(),
2996 &Context->Idents.get("Protocol"),
2997 TInfo);
2998 }
2999 return Context->getTypeDeclType(ProtocolTypeDecl);
3000}
3001
3002/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
3003/// a synthesized/forward data reference (to the protocol's metadata).
3004/// The forward references (and metadata) are generated in
3005/// RewriteModernObjC::HandleTranslationUnit().
3006Stmt *RewriteModernObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00003007 std::string Name = "_OBJC_PROTOCOL_REFERENCE_$_" +
3008 Exp->getProtocol()->getNameAsString();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003009 IdentifierInfo *ID = &Context->Idents.get(Name);
3010 VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
3011 SourceLocation(), ID, getProtocolType(), 0,
3012 SC_Extern, SC_None);
John McCallf4b88a42012-03-10 09:33:50 +00003013 DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, false, getProtocolType(),
3014 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003015 Expr *DerefExpr = new (Context) UnaryOperator(DRE, UO_AddrOf,
3016 Context->getPointerType(DRE->getType()),
3017 VK_RValue, OK_Ordinary, SourceLocation());
3018 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, DerefExpr->getType(),
3019 CK_BitCast,
3020 DerefExpr);
3021 ReplaceStmt(Exp, castExpr);
3022 ProtocolExprDecls.insert(Exp->getProtocol()->getCanonicalDecl());
3023 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3024 return castExpr;
3025
3026}
3027
3028bool RewriteModernObjC::BufferContainsPPDirectives(const char *startBuf,
3029 const char *endBuf) {
3030 while (startBuf < endBuf) {
3031 if (*startBuf == '#') {
3032 // Skip whitespace.
3033 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
3034 ;
3035 if (!strncmp(startBuf, "if", strlen("if")) ||
3036 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
3037 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
3038 !strncmp(startBuf, "define", strlen("define")) ||
3039 !strncmp(startBuf, "undef", strlen("undef")) ||
3040 !strncmp(startBuf, "else", strlen("else")) ||
3041 !strncmp(startBuf, "elif", strlen("elif")) ||
3042 !strncmp(startBuf, "endif", strlen("endif")) ||
3043 !strncmp(startBuf, "pragma", strlen("pragma")) ||
3044 !strncmp(startBuf, "include", strlen("include")) ||
3045 !strncmp(startBuf, "import", strlen("import")) ||
3046 !strncmp(startBuf, "include_next", strlen("include_next")))
3047 return true;
3048 }
3049 startBuf++;
3050 }
3051 return false;
3052}
3053
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003054/// RewriteObjCFieldDeclType - This routine rewrites a type into the buffer.
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003055/// It handles elaborated types, as well as enum types in the process.
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003056bool RewriteModernObjC::RewriteObjCFieldDeclType(QualType &Type,
3057 std::string &Result) {
3058 if (Type->isArrayType()) {
3059 QualType ElemTy = Context->getBaseElementType(Type);
3060 return RewriteObjCFieldDeclType(ElemTy, Result);
3061 }
3062 else if (Type->isRecordType()) {
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003063 RecordDecl *RD = Type->getAs<RecordType>()->getDecl();
3064 if (RD->isCompleteDefinition()) {
3065 if (RD->isStruct())
3066 Result += "\n\tstruct ";
3067 else if (RD->isUnion())
3068 Result += "\n\tunion ";
3069 else
3070 assert(false && "class not allowed as an ivar type");
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003071
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003072 Result += RD->getName();
3073 if (TagsDefinedInIvarDecls.count(RD)) {
3074 // This struct is already defined. Do not write its definition again.
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003075 Result += " ";
3076 return true;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003077 }
3078 TagsDefinedInIvarDecls.insert(RD);
3079 Result += " {\n";
3080 for (RecordDecl::field_iterator i = RD->field_begin(),
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003081 e = RD->field_end(); i != e; ++i) {
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003082 FieldDecl *FD = *i;
3083 RewriteObjCFieldDecl(FD, Result);
3084 }
3085 Result += "\t} ";
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003086 return true;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003087 }
3088 }
3089 else if (Type->isEnumeralType()) {
3090 EnumDecl *ED = Type->getAs<EnumType>()->getDecl();
3091 if (ED->isCompleteDefinition()) {
3092 Result += "\n\tenum ";
3093 Result += ED->getName();
3094 if (TagsDefinedInIvarDecls.count(ED)) {
3095 // This enum is already defined. Do not write its definition again.
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003096 Result += " ";
3097 return true;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003098 }
3099 TagsDefinedInIvarDecls.insert(ED);
3100
3101 Result += " {\n";
3102 for (EnumDecl::enumerator_iterator EC = ED->enumerator_begin(),
3103 ECEnd = ED->enumerator_end(); EC != ECEnd; ++EC) {
3104 Result += "\t"; Result += EC->getName(); Result += " = ";
3105 llvm::APSInt Val = EC->getInitVal();
3106 Result += Val.toString(10);
3107 Result += ",\n";
3108 }
3109 Result += "\t} ";
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003110 return true;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003111 }
3112 }
3113
3114 Result += "\t";
3115 convertObjCTypeToCStyleType(Type);
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003116 return false;
3117}
3118
3119
3120/// RewriteObjCFieldDecl - This routine rewrites a field into the buffer.
3121/// It handles elaborated types, as well as enum types in the process.
3122void RewriteModernObjC::RewriteObjCFieldDecl(FieldDecl *fieldDecl,
3123 std::string &Result) {
3124 QualType Type = fieldDecl->getType();
3125 std::string Name = fieldDecl->getNameAsString();
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003126
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003127 bool EleboratedType = RewriteObjCFieldDeclType(Type, Result);
3128 if (!EleboratedType)
3129 Type.getAsStringInternal(Name, Context->getPrintingPolicy());
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003130 Result += Name;
3131 if (fieldDecl->isBitField()) {
3132 Result += " : "; Result += utostr(fieldDecl->getBitWidthValue(*Context));
3133 }
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003134 else if (EleboratedType && Type->isArrayType()) {
3135 CanQualType CType = Context->getCanonicalType(Type);
3136 while (isa<ArrayType>(CType)) {
3137 if (const ConstantArrayType *CAT = Context->getAsConstantArrayType(CType)) {
3138 Result += "[";
3139 llvm::APInt Dim = CAT->getSize();
3140 Result += utostr(Dim.getZExtValue());
3141 Result += "]";
3142 }
3143 CType = CType->getAs<ArrayType>()->getElementType();
3144 }
3145 }
3146
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003147 Result += ";\n";
3148}
3149
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003150/// RewriteObjCInternalStruct - Rewrite one internal struct corresponding to
3151/// an objective-c class with ivars.
3152void RewriteModernObjC::RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
3153 std::string &Result) {
3154 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
3155 assert(CDecl->getName() != "" &&
3156 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003157 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003158 SmallVector<ObjCIvarDecl *, 8> IVars;
3159 for (ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
Fariborz Jahanian9a2105b2012-03-06 17:16:27 +00003160 IVD; IVD = IVD->getNextIvar())
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003161 IVars.push_back(IVD);
Fariborz Jahanian9a2105b2012-03-06 17:16:27 +00003162
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003163 SourceLocation LocStart = CDecl->getLocStart();
3164 SourceLocation LocEnd = CDecl->getEndOfDefinitionLoc();
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003165
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003166 const char *startBuf = SM->getCharacterData(LocStart);
3167 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003168
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003169 // If no ivars and no root or if its root, directly or indirectly,
3170 // have no ivars (thus not synthesized) then no need to synthesize this class.
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003171 if ((!CDecl->isThisDeclarationADefinition() || IVars.size() == 0) &&
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003172 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
3173 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
3174 ReplaceText(LocStart, endBuf-startBuf, Result);
3175 return;
3176 }
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003177
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003178 Result += "\nstruct ";
3179 Result += CDecl->getNameAsString();
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003180 Result += "_IMPL {\n";
3181
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00003182 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003183 Result += "\tstruct "; Result += RCDecl->getNameAsString();
3184 Result += "_IMPL "; Result += RCDecl->getNameAsString();
3185 Result += "_IVARS;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003186 }
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003187 TagsDefinedInIvarDecls.clear();
3188 for (unsigned i = 0, e = IVars.size(); i < e; i++)
3189 RewriteObjCFieldDecl(IVars[i], Result);
Fariborz Jahanian0b17b9a2012-02-12 21:36:23 +00003190
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003191 Result += "};\n";
3192 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
3193 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00003194 // Mark this struct as having been generated.
3195 if (!ObjCSynthesizedStructs.insert(CDecl))
3196 llvm_unreachable("struct already synthesize- RewriteObjCInternalStruct");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003197}
3198
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00003199static void WriteInternalIvarName(ObjCInterfaceDecl *IDecl,
3200 ObjCIvarDecl *IvarDecl, std::string &Result) {
3201 Result += "OBJC_IVAR_$_";
3202 Result += IDecl->getName();
3203 Result += "$";
3204 Result += IvarDecl->getName();
3205}
3206
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00003207/// RewriteIvarOffsetSymbols - Rewrite ivar offset symbols of those ivars which
3208/// have been referenced in an ivar access expression.
3209void RewriteModernObjC::RewriteIvarOffsetSymbols(ObjCInterfaceDecl *CDecl,
3210 std::string &Result) {
3211 // write out ivar offset symbols which have been referenced in an ivar
3212 // access expression.
3213 llvm::SmallPtrSet<ObjCIvarDecl *, 8> Ivars = ReferencedIvars[CDecl];
3214 if (Ivars.empty())
3215 return;
3216 for (llvm::SmallPtrSet<ObjCIvarDecl *, 8>::iterator i = Ivars.begin(),
3217 e = Ivars.end(); i != e; i++) {
3218 ObjCIvarDecl *IvarDecl = (*i);
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00003219 Result += "\n";
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00003220 Result += "extern \"C\" ";
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00003221 if (LangOpts.MicrosoftExt)
3222 Result += "__declspec(allocate(\".objc_ivar$B\")) ";
3223 if (LangOpts.MicrosoftExt &&
3224 IvarDecl->getAccessControl() != ObjCIvarDecl::Private &&
3225 IvarDecl->getAccessControl() != ObjCIvarDecl::Package) {
3226 const ObjCInterfaceDecl *CDecl = IvarDecl->getContainingInterface();
3227 if (CDecl->getImplementation())
3228 Result += "__declspec(dllexport) ";
3229 }
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00003230 Result += "unsigned long ";
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00003231 WriteInternalIvarName(CDecl, IvarDecl, Result);
3232 Result += ";";
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00003233 }
3234}
3235
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003236//===----------------------------------------------------------------------===//
3237// Meta Data Emission
3238//===----------------------------------------------------------------------===//
3239
3240
3241/// RewriteImplementations - This routine rewrites all method implementations
3242/// and emits meta-data.
3243
3244void RewriteModernObjC::RewriteImplementations() {
3245 int ClsDefCount = ClassImplementation.size();
3246 int CatDefCount = CategoryImplementation.size();
3247
3248 // Rewrite implemented methods
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00003249 for (int i = 0; i < ClsDefCount; i++) {
3250 ObjCImplementationDecl *OIMP = ClassImplementation[i];
3251 ObjCInterfaceDecl *CDecl = OIMP->getClassInterface();
3252 if (CDecl->isImplicitInterfaceDecl())
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +00003253 assert(false &&
3254 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00003255 RewriteImplementationDecl(OIMP);
3256 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003257
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00003258 for (int i = 0; i < CatDefCount; i++) {
3259 ObjCCategoryImplDecl *CIMP = CategoryImplementation[i];
3260 ObjCInterfaceDecl *CDecl = CIMP->getClassInterface();
3261 if (CDecl->isImplicitInterfaceDecl())
3262 assert(false &&
3263 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00003264 RewriteImplementationDecl(CIMP);
3265 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003266}
3267
3268void RewriteModernObjC::RewriteByRefString(std::string &ResultStr,
3269 const std::string &Name,
3270 ValueDecl *VD, bool def) {
3271 assert(BlockByRefDeclNo.count(VD) &&
3272 "RewriteByRefString: ByRef decl missing");
3273 if (def)
3274 ResultStr += "struct ";
3275 ResultStr += "__Block_byref_" + Name +
3276 "_" + utostr(BlockByRefDeclNo[VD]) ;
3277}
3278
3279static bool HasLocalVariableExternalStorage(ValueDecl *VD) {
3280 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
3281 return (Var->isFunctionOrMethodVarDecl() && !Var->hasLocalStorage());
3282 return false;
3283}
3284
3285std::string RewriteModernObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
3286 StringRef funcName,
3287 std::string Tag) {
3288 const FunctionType *AFT = CE->getFunctionType();
3289 QualType RT = AFT->getResultType();
3290 std::string StructRef = "struct " + Tag;
3291 std::string S = "static " + RT.getAsString(Context->getPrintingPolicy()) + " __" +
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00003292 funcName.str() + "_block_func_" + utostr(i);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003293
3294 BlockDecl *BD = CE->getBlockDecl();
3295
3296 if (isa<FunctionNoProtoType>(AFT)) {
3297 // No user-supplied arguments. Still need to pass in a pointer to the
3298 // block (to reference imported block decl refs).
3299 S += "(" + StructRef + " *__cself)";
3300 } else if (BD->param_empty()) {
3301 S += "(" + StructRef + " *__cself)";
3302 } else {
3303 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
3304 assert(FT && "SynthesizeBlockFunc: No function proto");
3305 S += '(';
3306 // first add the implicit argument.
3307 S += StructRef + " *__cself, ";
3308 std::string ParamStr;
3309 for (BlockDecl::param_iterator AI = BD->param_begin(),
3310 E = BD->param_end(); AI != E; ++AI) {
3311 if (AI != BD->param_begin()) S += ", ";
3312 ParamStr = (*AI)->getNameAsString();
3313 QualType QT = (*AI)->getType();
Fariborz Jahanian2610f902012-03-27 16:42:20 +00003314 (void)convertBlockPointerToFunctionPointer(QT);
3315 QT.getAsStringInternal(ParamStr, Context->getPrintingPolicy());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003316 S += ParamStr;
3317 }
3318 if (FT->isVariadic()) {
3319 if (!BD->param_empty()) S += ", ";
3320 S += "...";
3321 }
3322 S += ')';
3323 }
3324 S += " {\n";
3325
3326 // Create local declarations to avoid rewriting all closure decl ref exprs.
3327 // First, emit a declaration for all "by ref" decls.
3328 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3329 E = BlockByRefDecls.end(); I != E; ++I) {
3330 S += " ";
3331 std::string Name = (*I)->getNameAsString();
3332 std::string TypeString;
3333 RewriteByRefString(TypeString, Name, (*I));
3334 TypeString += " *";
3335 Name = TypeString + Name;
3336 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
3337 }
3338 // Next, emit a declaration for all "by copy" declarations.
3339 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3340 E = BlockByCopyDecls.end(); I != E; ++I) {
3341 S += " ";
3342 // Handle nested closure invocation. For example:
3343 //
3344 // void (^myImportedClosure)(void);
3345 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
3346 //
3347 // void (^anotherClosure)(void);
3348 // anotherClosure = ^(void) {
3349 // myImportedClosure(); // import and invoke the closure
3350 // };
3351 //
3352 if (isTopLevelBlockPointerType((*I)->getType())) {
3353 RewriteBlockPointerTypeVariable(S, (*I));
3354 S += " = (";
3355 RewriteBlockPointerType(S, (*I)->getType());
3356 S += ")";
3357 S += "__cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
3358 }
3359 else {
3360 std::string Name = (*I)->getNameAsString();
3361 QualType QT = (*I)->getType();
3362 if (HasLocalVariableExternalStorage(*I))
3363 QT = Context->getPointerType(QT);
3364 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
3365 S += Name + " = __cself->" +
3366 (*I)->getNameAsString() + "; // bound by copy\n";
3367 }
3368 }
3369 std::string RewrittenStr = RewrittenBlockExprs[CE];
3370 const char *cstr = RewrittenStr.c_str();
3371 while (*cstr++ != '{') ;
3372 S += cstr;
3373 S += "\n";
3374 return S;
3375}
3376
3377std::string RewriteModernObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
3378 StringRef funcName,
3379 std::string Tag) {
3380 std::string StructRef = "struct " + Tag;
3381 std::string S = "static void __";
3382
3383 S += funcName;
3384 S += "_block_copy_" + utostr(i);
3385 S += "(" + StructRef;
3386 S += "*dst, " + StructRef;
3387 S += "*src) {";
3388 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
3389 E = ImportedBlockDecls.end(); I != E; ++I) {
3390 ValueDecl *VD = (*I);
3391 S += "_Block_object_assign((void*)&dst->";
3392 S += (*I)->getNameAsString();
3393 S += ", (void*)src->";
3394 S += (*I)->getNameAsString();
3395 if (BlockByRefDeclsPtrSet.count((*I)))
3396 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
3397 else if (VD->getType()->isBlockPointerType())
3398 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
3399 else
3400 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
3401 }
3402 S += "}\n";
3403
3404 S += "\nstatic void __";
3405 S += funcName;
3406 S += "_block_dispose_" + utostr(i);
3407 S += "(" + StructRef;
3408 S += "*src) {";
3409 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
3410 E = ImportedBlockDecls.end(); I != E; ++I) {
3411 ValueDecl *VD = (*I);
3412 S += "_Block_object_dispose((void*)src->";
3413 S += (*I)->getNameAsString();
3414 if (BlockByRefDeclsPtrSet.count((*I)))
3415 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
3416 else if (VD->getType()->isBlockPointerType())
3417 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
3418 else
3419 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
3420 }
3421 S += "}\n";
3422 return S;
3423}
3424
3425std::string RewriteModernObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
3426 std::string Desc) {
3427 std::string S = "\nstruct " + Tag;
3428 std::string Constructor = " " + Tag;
3429
3430 S += " {\n struct __block_impl impl;\n";
3431 S += " struct " + Desc;
3432 S += "* Desc;\n";
3433
3434 Constructor += "(void *fp, "; // Invoke function pointer.
3435 Constructor += "struct " + Desc; // Descriptor pointer.
3436 Constructor += " *desc";
3437
3438 if (BlockDeclRefs.size()) {
3439 // Output all "by copy" declarations.
3440 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3441 E = BlockByCopyDecls.end(); I != E; ++I) {
3442 S += " ";
3443 std::string FieldName = (*I)->getNameAsString();
3444 std::string ArgName = "_" + FieldName;
3445 // Handle nested closure invocation. For example:
3446 //
3447 // void (^myImportedBlock)(void);
3448 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
3449 //
3450 // void (^anotherBlock)(void);
3451 // anotherBlock = ^(void) {
3452 // myImportedBlock(); // import and invoke the closure
3453 // };
3454 //
3455 if (isTopLevelBlockPointerType((*I)->getType())) {
3456 S += "struct __block_impl *";
3457 Constructor += ", void *" + ArgName;
3458 } else {
3459 QualType QT = (*I)->getType();
3460 if (HasLocalVariableExternalStorage(*I))
3461 QT = Context->getPointerType(QT);
3462 QT.getAsStringInternal(FieldName, Context->getPrintingPolicy());
3463 QT.getAsStringInternal(ArgName, Context->getPrintingPolicy());
3464 Constructor += ", " + ArgName;
3465 }
3466 S += FieldName + ";\n";
3467 }
3468 // Output all "by ref" declarations.
3469 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3470 E = BlockByRefDecls.end(); I != E; ++I) {
3471 S += " ";
3472 std::string FieldName = (*I)->getNameAsString();
3473 std::string ArgName = "_" + FieldName;
3474 {
3475 std::string TypeString;
3476 RewriteByRefString(TypeString, FieldName, (*I));
3477 TypeString += " *";
3478 FieldName = TypeString + FieldName;
3479 ArgName = TypeString + ArgName;
3480 Constructor += ", " + ArgName;
3481 }
3482 S += FieldName + "; // by ref\n";
3483 }
3484 // Finish writing the constructor.
3485 Constructor += ", int flags=0)";
3486 // Initialize all "by copy" arguments.
3487 bool firsTime = true;
3488 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3489 E = BlockByCopyDecls.end(); I != E; ++I) {
3490 std::string Name = (*I)->getNameAsString();
3491 if (firsTime) {
3492 Constructor += " : ";
3493 firsTime = false;
3494 }
3495 else
3496 Constructor += ", ";
3497 if (isTopLevelBlockPointerType((*I)->getType()))
3498 Constructor += Name + "((struct __block_impl *)_" + Name + ")";
3499 else
3500 Constructor += Name + "(_" + Name + ")";
3501 }
3502 // Initialize all "by ref" arguments.
3503 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3504 E = BlockByRefDecls.end(); I != E; ++I) {
3505 std::string Name = (*I)->getNameAsString();
3506 if (firsTime) {
3507 Constructor += " : ";
3508 firsTime = false;
3509 }
3510 else
3511 Constructor += ", ";
3512 Constructor += Name + "(_" + Name + "->__forwarding)";
3513 }
3514
3515 Constructor += " {\n";
3516 if (GlobalVarDecl)
3517 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
3518 else
3519 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
3520 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3521
3522 Constructor += " Desc = desc;\n";
3523 } else {
3524 // Finish writing the constructor.
3525 Constructor += ", int flags=0) {\n";
3526 if (GlobalVarDecl)
3527 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
3528 else
3529 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
3530 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3531 Constructor += " Desc = desc;\n";
3532 }
3533 Constructor += " ";
3534 Constructor += "}\n";
3535 S += Constructor;
3536 S += "};\n";
3537 return S;
3538}
3539
3540std::string RewriteModernObjC::SynthesizeBlockDescriptor(std::string DescTag,
3541 std::string ImplTag, int i,
3542 StringRef FunName,
3543 unsigned hasCopy) {
3544 std::string S = "\nstatic struct " + DescTag;
3545
3546 S += " {\n unsigned long reserved;\n";
3547 S += " unsigned long Block_size;\n";
3548 if (hasCopy) {
3549 S += " void (*copy)(struct ";
3550 S += ImplTag; S += "*, struct ";
3551 S += ImplTag; S += "*);\n";
3552
3553 S += " void (*dispose)(struct ";
3554 S += ImplTag; S += "*);\n";
3555 }
3556 S += "} ";
3557
3558 S += DescTag + "_DATA = { 0, sizeof(struct ";
3559 S += ImplTag + ")";
3560 if (hasCopy) {
3561 S += ", __" + FunName.str() + "_block_copy_" + utostr(i);
3562 S += ", __" + FunName.str() + "_block_dispose_" + utostr(i);
3563 }
3564 S += "};\n";
3565 return S;
3566}
3567
3568void RewriteModernObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
3569 StringRef FunName) {
3570 // Insert declaration for the function in which block literal is used.
3571 if (CurFunctionDeclToDeclareForBlock && !Blocks.empty())
3572 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
3573 bool RewriteSC = (GlobalVarDecl &&
3574 !Blocks.empty() &&
3575 GlobalVarDecl->getStorageClass() == SC_Static &&
3576 GlobalVarDecl->getType().getCVRQualifiers());
3577 if (RewriteSC) {
3578 std::string SC(" void __");
3579 SC += GlobalVarDecl->getNameAsString();
3580 SC += "() {}";
3581 InsertText(FunLocStart, SC);
3582 }
3583
3584 // Insert closures that were part of the function.
3585 for (unsigned i = 0, count=0; i < Blocks.size(); i++) {
3586 CollectBlockDeclRefInfo(Blocks[i]);
3587 // Need to copy-in the inner copied-in variables not actually used in this
3588 // block.
3589 for (int j = 0; j < InnerDeclRefsCount[i]; j++) {
John McCallf4b88a42012-03-10 09:33:50 +00003590 DeclRefExpr *Exp = InnerDeclRefs[count++];
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003591 ValueDecl *VD = Exp->getDecl();
3592 BlockDeclRefs.push_back(Exp);
John McCallf4b88a42012-03-10 09:33:50 +00003593 if (!VD->hasAttr<BlocksAttr>()) {
3594 if (!BlockByCopyDeclsPtrSet.count(VD)) {
3595 BlockByCopyDeclsPtrSet.insert(VD);
3596 BlockByCopyDecls.push_back(VD);
3597 }
3598 continue;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003599 }
John McCallf4b88a42012-03-10 09:33:50 +00003600
3601 if (!BlockByRefDeclsPtrSet.count(VD)) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003602 BlockByRefDeclsPtrSet.insert(VD);
3603 BlockByRefDecls.push_back(VD);
3604 }
John McCallf4b88a42012-03-10 09:33:50 +00003605
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003606 // imported objects in the inner blocks not used in the outer
3607 // blocks must be copied/disposed in the outer block as well.
John McCallf4b88a42012-03-10 09:33:50 +00003608 if (VD->getType()->isObjCObjectPointerType() ||
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003609 VD->getType()->isBlockPointerType())
3610 ImportedBlockDecls.insert(VD);
3611 }
3612
3613 std::string ImplTag = "__" + FunName.str() + "_block_impl_" + utostr(i);
3614 std::string DescTag = "__" + FunName.str() + "_block_desc_" + utostr(i);
3615
3616 std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
3617
3618 InsertText(FunLocStart, CI);
3619
3620 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
3621
3622 InsertText(FunLocStart, CF);
3623
3624 if (ImportedBlockDecls.size()) {
3625 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
3626 InsertText(FunLocStart, HF);
3627 }
3628 std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
3629 ImportedBlockDecls.size() > 0);
3630 InsertText(FunLocStart, BD);
3631
3632 BlockDeclRefs.clear();
3633 BlockByRefDecls.clear();
3634 BlockByRefDeclsPtrSet.clear();
3635 BlockByCopyDecls.clear();
3636 BlockByCopyDeclsPtrSet.clear();
3637 ImportedBlockDecls.clear();
3638 }
3639 if (RewriteSC) {
3640 // Must insert any 'const/volatile/static here. Since it has been
3641 // removed as result of rewriting of block literals.
3642 std::string SC;
3643 if (GlobalVarDecl->getStorageClass() == SC_Static)
3644 SC = "static ";
3645 if (GlobalVarDecl->getType().isConstQualified())
3646 SC += "const ";
3647 if (GlobalVarDecl->getType().isVolatileQualified())
3648 SC += "volatile ";
3649 if (GlobalVarDecl->getType().isRestrictQualified())
3650 SC += "restrict ";
3651 InsertText(FunLocStart, SC);
3652 }
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00003653 if (GlobalConstructionExp) {
3654 // extra fancy dance for global literal expression.
3655
3656 // Always the latest block expression on the block stack.
3657 std::string Tag = "__";
3658 Tag += FunName;
3659 Tag += "_block_impl_";
3660 Tag += utostr(Blocks.size()-1);
3661 std::string globalBuf = "static ";
3662 globalBuf += Tag; globalBuf += " ";
3663 std::string SStr;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003664
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00003665 llvm::raw_string_ostream constructorExprBuf(SStr);
3666 GlobalConstructionExp->printPretty(constructorExprBuf, *Context, 0,
3667 PrintingPolicy(LangOpts));
3668 globalBuf += constructorExprBuf.str();
3669 globalBuf += ";\n";
3670 InsertText(FunLocStart, globalBuf);
3671 GlobalConstructionExp = 0;
3672 }
3673
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003674 Blocks.clear();
3675 InnerDeclRefsCount.clear();
3676 InnerDeclRefs.clear();
3677 RewrittenBlockExprs.clear();
3678}
3679
3680void RewriteModernObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
3681 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
3682 StringRef FuncName = FD->getName();
3683
3684 SynthesizeBlockLiterals(FunLocStart, FuncName);
3685}
3686
3687static void BuildUniqueMethodName(std::string &Name,
3688 ObjCMethodDecl *MD) {
3689 ObjCInterfaceDecl *IFace = MD->getClassInterface();
3690 Name = IFace->getName();
3691 Name += "__" + MD->getSelector().getAsString();
3692 // Convert colons to underscores.
3693 std::string::size_type loc = 0;
3694 while ((loc = Name.find(":", loc)) != std::string::npos)
3695 Name.replace(loc, 1, "_");
3696}
3697
3698void RewriteModernObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
3699 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
3700 //SourceLocation FunLocStart = MD->getLocStart();
3701 SourceLocation FunLocStart = MD->getLocStart();
3702 std::string FuncName;
3703 BuildUniqueMethodName(FuncName, MD);
3704 SynthesizeBlockLiterals(FunLocStart, FuncName);
3705}
3706
3707void RewriteModernObjC::GetBlockDeclRefExprs(Stmt *S) {
3708 for (Stmt::child_range CI = S->children(); CI; ++CI)
3709 if (*CI) {
3710 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
3711 GetBlockDeclRefExprs(CBE->getBody());
3712 else
3713 GetBlockDeclRefExprs(*CI);
3714 }
3715 // Handle specific things.
John McCallf4b88a42012-03-10 09:33:50 +00003716 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S))
3717 if (DRE->refersToEnclosingLocal() &&
3718 HasLocalVariableExternalStorage(DRE->getDecl())) {
3719 BlockDeclRefs.push_back(DRE);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003720 }
3721
3722 return;
3723}
3724
3725void RewriteModernObjC::GetInnerBlockDeclRefExprs(Stmt *S,
John McCallf4b88a42012-03-10 09:33:50 +00003726 SmallVector<DeclRefExpr *, 8> &InnerBlockDeclRefs,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003727 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts) {
3728 for (Stmt::child_range CI = S->children(); CI; ++CI)
3729 if (*CI) {
3730 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI)) {
3731 InnerContexts.insert(cast<DeclContext>(CBE->getBlockDecl()));
3732 GetInnerBlockDeclRefExprs(CBE->getBody(),
3733 InnerBlockDeclRefs,
3734 InnerContexts);
3735 }
3736 else
3737 GetInnerBlockDeclRefExprs(*CI,
3738 InnerBlockDeclRefs,
3739 InnerContexts);
3740
3741 }
3742 // Handle specific things.
John McCallf4b88a42012-03-10 09:33:50 +00003743 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
3744 if (DRE->refersToEnclosingLocal()) {
3745 if (!isa<FunctionDecl>(DRE->getDecl()) &&
3746 !InnerContexts.count(DRE->getDecl()->getDeclContext()))
3747 InnerBlockDeclRefs.push_back(DRE);
3748 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl()))
3749 if (Var->isFunctionOrMethodVarDecl())
3750 ImportedLocalExternalDecls.insert(Var);
3751 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003752 }
3753
3754 return;
3755}
3756
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00003757/// convertObjCTypeToCStyleType - This routine converts such objc types
3758/// as qualified objects, and blocks to their closest c/c++ types that
3759/// it can. It returns true if input type was modified.
3760bool RewriteModernObjC::convertObjCTypeToCStyleType(QualType &T) {
3761 QualType oldT = T;
3762 convertBlockPointerToFunctionPointer(T);
3763 if (T->isFunctionPointerType()) {
3764 QualType PointeeTy;
3765 if (const PointerType* PT = T->getAs<PointerType>()) {
3766 PointeeTy = PT->getPointeeType();
3767 if (const FunctionType *FT = PointeeTy->getAs<FunctionType>()) {
3768 T = convertFunctionTypeOfBlocks(FT);
3769 T = Context->getPointerType(T);
3770 }
3771 }
3772 }
3773
3774 convertToUnqualifiedObjCType(T);
3775 return T != oldT;
3776}
3777
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003778/// convertFunctionTypeOfBlocks - This routine converts a function type
3779/// whose result type may be a block pointer or whose argument type(s)
3780/// might be block pointers to an equivalent function type replacing
3781/// all block pointers to function pointers.
3782QualType RewriteModernObjC::convertFunctionTypeOfBlocks(const FunctionType *FT) {
3783 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
3784 // FTP will be null for closures that don't take arguments.
3785 // Generate a funky cast.
3786 SmallVector<QualType, 8> ArgTypes;
3787 QualType Res = FT->getResultType();
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00003788 bool modified = convertObjCTypeToCStyleType(Res);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003789
3790 if (FTP) {
3791 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
3792 E = FTP->arg_type_end(); I && (I != E); ++I) {
3793 QualType t = *I;
3794 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00003795 if (convertObjCTypeToCStyleType(t))
3796 modified = true;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003797 ArgTypes.push_back(t);
3798 }
3799 }
3800 QualType FuncType;
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00003801 if (modified)
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003802 FuncType = getSimpleFunctionType(Res, &ArgTypes[0], ArgTypes.size());
3803 else FuncType = QualType(FT, 0);
3804 return FuncType;
3805}
3806
3807Stmt *RewriteModernObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
3808 // Navigate to relevant type information.
3809 const BlockPointerType *CPT = 0;
3810
3811 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
3812 CPT = DRE->getType()->getAs<BlockPointerType>();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003813 } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
3814 CPT = MExpr->getType()->getAs<BlockPointerType>();
3815 }
3816 else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
3817 return SynthesizeBlockCall(Exp, PRE->getSubExpr());
3818 }
3819 else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
3820 CPT = IEXPR->getType()->getAs<BlockPointerType>();
3821 else if (const ConditionalOperator *CEXPR =
3822 dyn_cast<ConditionalOperator>(BlockExp)) {
3823 Expr *LHSExp = CEXPR->getLHS();
3824 Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
3825 Expr *RHSExp = CEXPR->getRHS();
3826 Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
3827 Expr *CONDExp = CEXPR->getCond();
3828 ConditionalOperator *CondExpr =
3829 new (Context) ConditionalOperator(CONDExp,
3830 SourceLocation(), cast<Expr>(LHSStmt),
3831 SourceLocation(), cast<Expr>(RHSStmt),
3832 Exp->getType(), VK_RValue, OK_Ordinary);
3833 return CondExpr;
3834 } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
3835 CPT = IRE->getType()->getAs<BlockPointerType>();
3836 } else if (const PseudoObjectExpr *POE
3837 = dyn_cast<PseudoObjectExpr>(BlockExp)) {
3838 CPT = POE->getType()->castAs<BlockPointerType>();
3839 } else {
3840 assert(1 && "RewriteBlockClass: Bad type");
3841 }
3842 assert(CPT && "RewriteBlockClass: Bad type");
3843 const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
3844 assert(FT && "RewriteBlockClass: Bad type");
3845 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
3846 // FTP will be null for closures that don't take arguments.
3847
3848 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
3849 SourceLocation(), SourceLocation(),
3850 &Context->Idents.get("__block_impl"));
3851 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
3852
3853 // Generate a funky cast.
3854 SmallVector<QualType, 8> ArgTypes;
3855
3856 // Push the block argument type.
3857 ArgTypes.push_back(PtrBlock);
3858 if (FTP) {
3859 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
3860 E = FTP->arg_type_end(); I && (I != E); ++I) {
3861 QualType t = *I;
3862 // Make sure we convert "t (^)(...)" to "t (*)(...)".
3863 if (!convertBlockPointerToFunctionPointer(t))
3864 convertToUnqualifiedObjCType(t);
3865 ArgTypes.push_back(t);
3866 }
3867 }
3868 // Now do the pointer to function cast.
3869 QualType PtrToFuncCastType
3870 = getSimpleFunctionType(Exp->getType(), &ArgTypes[0], ArgTypes.size());
3871
3872 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
3873
3874 CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock,
3875 CK_BitCast,
3876 const_cast<Expr*>(BlockExp));
3877 // Don't forget the parens to enforce the proper binding.
3878 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3879 BlkCast);
3880 //PE->dump();
3881
3882 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
3883 SourceLocation(),
3884 &Context->Idents.get("FuncPtr"),
3885 Context->VoidPtrTy, 0,
3886 /*BitWidth=*/0, /*Mutable=*/true,
3887 /*HasInit=*/false);
3888 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
3889 FD->getType(), VK_LValue,
3890 OK_Ordinary);
3891
3892
3893 CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType,
3894 CK_BitCast, ME);
3895 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
3896
3897 SmallVector<Expr*, 8> BlkExprs;
3898 // Add the implicit argument.
3899 BlkExprs.push_back(BlkCast);
3900 // Add the user arguments.
3901 for (CallExpr::arg_iterator I = Exp->arg_begin(),
3902 E = Exp->arg_end(); I != E; ++I) {
3903 BlkExprs.push_back(*I);
3904 }
3905 CallExpr *CE = new (Context) CallExpr(*Context, PE, &BlkExprs[0],
3906 BlkExprs.size(),
3907 Exp->getType(), VK_RValue,
3908 SourceLocation());
3909 return CE;
3910}
3911
3912// We need to return the rewritten expression to handle cases where the
John McCallf4b88a42012-03-10 09:33:50 +00003913// DeclRefExpr is embedded in another expression being rewritten.
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003914// For example:
3915//
3916// int main() {
3917// __block Foo *f;
3918// __block int i;
3919//
3920// void (^myblock)() = ^() {
John McCallf4b88a42012-03-10 09:33:50 +00003921// [f test]; // f is a DeclRefExpr embedded in a message (which is being rewritten).
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003922// i = 77;
3923// };
3924//}
John McCallf4b88a42012-03-10 09:33:50 +00003925Stmt *RewriteModernObjC::RewriteBlockDeclRefExpr(DeclRefExpr *DeclRefExp) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003926 // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
3927 // for each DeclRefExp where BYREFVAR is name of the variable.
John McCallf4b88a42012-03-10 09:33:50 +00003928 ValueDecl *VD = DeclRefExp->getDecl();
3929 bool isArrow = DeclRefExp->refersToEnclosingLocal();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003930
3931 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
3932 SourceLocation(),
3933 &Context->Idents.get("__forwarding"),
3934 Context->VoidPtrTy, 0,
3935 /*BitWidth=*/0, /*Mutable=*/true,
3936 /*HasInit=*/false);
3937 MemberExpr *ME = new (Context) MemberExpr(DeclRefExp, isArrow,
3938 FD, SourceLocation(),
3939 FD->getType(), VK_LValue,
3940 OK_Ordinary);
3941
3942 StringRef Name = VD->getName();
3943 FD = FieldDecl::Create(*Context, 0, SourceLocation(), SourceLocation(),
3944 &Context->Idents.get(Name),
3945 Context->VoidPtrTy, 0,
3946 /*BitWidth=*/0, /*Mutable=*/true,
3947 /*HasInit=*/false);
3948 ME = new (Context) MemberExpr(ME, true, FD, SourceLocation(),
3949 DeclRefExp->getType(), VK_LValue, OK_Ordinary);
3950
3951
3952
3953 // Need parens to enforce precedence.
3954 ParenExpr *PE = new (Context) ParenExpr(DeclRefExp->getExprLoc(),
3955 DeclRefExp->getExprLoc(),
3956 ME);
3957 ReplaceStmt(DeclRefExp, PE);
3958 return PE;
3959}
3960
3961// Rewrites the imported local variable V with external storage
3962// (static, extern, etc.) as *V
3963//
3964Stmt *RewriteModernObjC::RewriteLocalVariableExternalStorage(DeclRefExpr *DRE) {
3965 ValueDecl *VD = DRE->getDecl();
3966 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
3967 if (!ImportedLocalExternalDecls.count(Var))
3968 return DRE;
3969 Expr *Exp = new (Context) UnaryOperator(DRE, UO_Deref, DRE->getType(),
3970 VK_LValue, OK_Ordinary,
3971 DRE->getLocation());
3972 // Need parens to enforce precedence.
3973 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3974 Exp);
3975 ReplaceStmt(DRE, PE);
3976 return PE;
3977}
3978
3979void RewriteModernObjC::RewriteCastExpr(CStyleCastExpr *CE) {
3980 SourceLocation LocStart = CE->getLParenLoc();
3981 SourceLocation LocEnd = CE->getRParenLoc();
3982
3983 // Need to avoid trying to rewrite synthesized casts.
3984 if (LocStart.isInvalid())
3985 return;
3986 // Need to avoid trying to rewrite casts contained in macros.
3987 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
3988 return;
3989
3990 const char *startBuf = SM->getCharacterData(LocStart);
3991 const char *endBuf = SM->getCharacterData(LocEnd);
3992 QualType QT = CE->getType();
3993 const Type* TypePtr = QT->getAs<Type>();
3994 if (isa<TypeOfExprType>(TypePtr)) {
3995 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
3996 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
3997 std::string TypeAsString = "(";
3998 RewriteBlockPointerType(TypeAsString, QT);
3999 TypeAsString += ")";
4000 ReplaceText(LocStart, endBuf-startBuf+1, TypeAsString);
4001 return;
4002 }
4003 // advance the location to startArgList.
4004 const char *argPtr = startBuf;
4005
4006 while (*argPtr++ && (argPtr < endBuf)) {
4007 switch (*argPtr) {
4008 case '^':
4009 // Replace the '^' with '*'.
4010 LocStart = LocStart.getLocWithOffset(argPtr-startBuf);
4011 ReplaceText(LocStart, 1, "*");
4012 break;
4013 }
4014 }
4015 return;
4016}
4017
4018void RewriteModernObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
4019 SourceLocation DeclLoc = FD->getLocation();
4020 unsigned parenCount = 0;
4021
4022 // We have 1 or more arguments that have closure pointers.
4023 const char *startBuf = SM->getCharacterData(DeclLoc);
4024 const char *startArgList = strchr(startBuf, '(');
4025
4026 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
4027
4028 parenCount++;
4029 // advance the location to startArgList.
4030 DeclLoc = DeclLoc.getLocWithOffset(startArgList-startBuf);
4031 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
4032
4033 const char *argPtr = startArgList;
4034
4035 while (*argPtr++ && parenCount) {
4036 switch (*argPtr) {
4037 case '^':
4038 // Replace the '^' with '*'.
4039 DeclLoc = DeclLoc.getLocWithOffset(argPtr-startArgList);
4040 ReplaceText(DeclLoc, 1, "*");
4041 break;
4042 case '(':
4043 parenCount++;
4044 break;
4045 case ')':
4046 parenCount--;
4047 break;
4048 }
4049 }
4050 return;
4051}
4052
4053bool RewriteModernObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
4054 const FunctionProtoType *FTP;
4055 const PointerType *PT = QT->getAs<PointerType>();
4056 if (PT) {
4057 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4058 } else {
4059 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4060 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4061 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4062 }
4063 if (FTP) {
4064 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4065 E = FTP->arg_type_end(); I != E; ++I)
4066 if (isTopLevelBlockPointerType(*I))
4067 return true;
4068 }
4069 return false;
4070}
4071
4072bool RewriteModernObjC::PointerTypeTakesAnyObjCQualifiedType(QualType QT) {
4073 const FunctionProtoType *FTP;
4074 const PointerType *PT = QT->getAs<PointerType>();
4075 if (PT) {
4076 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4077 } else {
4078 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4079 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4080 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4081 }
4082 if (FTP) {
4083 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4084 E = FTP->arg_type_end(); I != E; ++I) {
4085 if ((*I)->isObjCQualifiedIdType())
4086 return true;
4087 if ((*I)->isObjCObjectPointerType() &&
4088 (*I)->getPointeeType()->isObjCQualifiedInterfaceType())
4089 return true;
4090 }
4091
4092 }
4093 return false;
4094}
4095
4096void RewriteModernObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
4097 const char *&RParen) {
4098 const char *argPtr = strchr(Name, '(');
4099 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
4100
4101 LParen = argPtr; // output the start.
4102 argPtr++; // skip past the left paren.
4103 unsigned parenCount = 1;
4104
4105 while (*argPtr && parenCount) {
4106 switch (*argPtr) {
4107 case '(': parenCount++; break;
4108 case ')': parenCount--; break;
4109 default: break;
4110 }
4111 if (parenCount) argPtr++;
4112 }
4113 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
4114 RParen = argPtr; // output the end
4115}
4116
4117void RewriteModernObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
4118 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4119 RewriteBlockPointerFunctionArgs(FD);
4120 return;
4121 }
4122 // Handle Variables and Typedefs.
4123 SourceLocation DeclLoc = ND->getLocation();
4124 QualType DeclT;
4125 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
4126 DeclT = VD->getType();
4127 else if (TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(ND))
4128 DeclT = TDD->getUnderlyingType();
4129 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
4130 DeclT = FD->getType();
4131 else
4132 llvm_unreachable("RewriteBlockPointerDecl(): Decl type not yet handled");
4133
4134 const char *startBuf = SM->getCharacterData(DeclLoc);
4135 const char *endBuf = startBuf;
4136 // scan backward (from the decl location) for the end of the previous decl.
4137 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
4138 startBuf--;
4139 SourceLocation Start = DeclLoc.getLocWithOffset(startBuf-endBuf);
4140 std::string buf;
4141 unsigned OrigLength=0;
4142 // *startBuf != '^' if we are dealing with a pointer to function that
4143 // may take block argument types (which will be handled below).
4144 if (*startBuf == '^') {
4145 // Replace the '^' with '*', computing a negative offset.
4146 buf = '*';
4147 startBuf++;
4148 OrigLength++;
4149 }
4150 while (*startBuf != ')') {
4151 buf += *startBuf;
4152 startBuf++;
4153 OrigLength++;
4154 }
4155 buf += ')';
4156 OrigLength++;
4157
4158 if (PointerTypeTakesAnyBlockArguments(DeclT) ||
4159 PointerTypeTakesAnyObjCQualifiedType(DeclT)) {
4160 // Replace the '^' with '*' for arguments.
4161 // Replace id<P> with id/*<>*/
4162 DeclLoc = ND->getLocation();
4163 startBuf = SM->getCharacterData(DeclLoc);
4164 const char *argListBegin, *argListEnd;
4165 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
4166 while (argListBegin < argListEnd) {
4167 if (*argListBegin == '^')
4168 buf += '*';
4169 else if (*argListBegin == '<') {
4170 buf += "/*";
4171 buf += *argListBegin++;
4172 OrigLength++;;
4173 while (*argListBegin != '>') {
4174 buf += *argListBegin++;
4175 OrigLength++;
4176 }
4177 buf += *argListBegin;
4178 buf += "*/";
4179 }
4180 else
4181 buf += *argListBegin;
4182 argListBegin++;
4183 OrigLength++;
4184 }
4185 buf += ')';
4186 OrigLength++;
4187 }
4188 ReplaceText(Start, OrigLength, buf);
4189
4190 return;
4191}
4192
4193
4194/// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
4195/// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
4196/// struct Block_byref_id_object *src) {
4197/// _Block_object_assign (&_dest->object, _src->object,
4198/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4199/// [|BLOCK_FIELD_IS_WEAK]) // object
4200/// _Block_object_assign(&_dest->object, _src->object,
4201/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4202/// [|BLOCK_FIELD_IS_WEAK]) // block
4203/// }
4204/// And:
4205/// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
4206/// _Block_object_dispose(_src->object,
4207/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4208/// [|BLOCK_FIELD_IS_WEAK]) // object
4209/// _Block_object_dispose(_src->object,
4210/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4211/// [|BLOCK_FIELD_IS_WEAK]) // block
4212/// }
4213
4214std::string RewriteModernObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
4215 int flag) {
4216 std::string S;
4217 if (CopyDestroyCache.count(flag))
4218 return S;
4219 CopyDestroyCache.insert(flag);
4220 S = "static void __Block_byref_id_object_copy_";
4221 S += utostr(flag);
4222 S += "(void *dst, void *src) {\n";
4223
4224 // offset into the object pointer is computed as:
4225 // void * + void* + int + int + void* + void *
4226 unsigned IntSize =
4227 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
4228 unsigned VoidPtrSize =
4229 static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
4230
4231 unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/Context->getCharWidth();
4232 S += " _Block_object_assign((char*)dst + ";
4233 S += utostr(offset);
4234 S += ", *(void * *) ((char*)src + ";
4235 S += utostr(offset);
4236 S += "), ";
4237 S += utostr(flag);
4238 S += ");\n}\n";
4239
4240 S += "static void __Block_byref_id_object_dispose_";
4241 S += utostr(flag);
4242 S += "(void *src) {\n";
4243 S += " _Block_object_dispose(*(void * *) ((char*)src + ";
4244 S += utostr(offset);
4245 S += "), ";
4246 S += utostr(flag);
4247 S += ");\n}\n";
4248 return S;
4249}
4250
4251/// RewriteByRefVar - For each __block typex ND variable this routine transforms
4252/// the declaration into:
4253/// struct __Block_byref_ND {
4254/// void *__isa; // NULL for everything except __weak pointers
4255/// struct __Block_byref_ND *__forwarding;
4256/// int32_t __flags;
4257/// int32_t __size;
4258/// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
4259/// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
4260/// typex ND;
4261/// };
4262///
4263/// It then replaces declaration of ND variable with:
4264/// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
4265/// __size=sizeof(struct __Block_byref_ND),
4266/// ND=initializer-if-any};
4267///
4268///
4269void RewriteModernObjC::RewriteByRefVar(VarDecl *ND) {
4270 // Insert declaration for the function in which block literal is
4271 // used.
4272 if (CurFunctionDeclToDeclareForBlock)
4273 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
4274 int flag = 0;
4275 int isa = 0;
4276 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
4277 if (DeclLoc.isInvalid())
4278 // If type location is missing, it is because of missing type (a warning).
4279 // Use variable's location which is good for this case.
4280 DeclLoc = ND->getLocation();
4281 const char *startBuf = SM->getCharacterData(DeclLoc);
4282 SourceLocation X = ND->getLocEnd();
4283 X = SM->getExpansionLoc(X);
4284 const char *endBuf = SM->getCharacterData(X);
4285 std::string Name(ND->getNameAsString());
4286 std::string ByrefType;
4287 RewriteByRefString(ByrefType, Name, ND, true);
4288 ByrefType += " {\n";
4289 ByrefType += " void *__isa;\n";
4290 RewriteByRefString(ByrefType, Name, ND);
4291 ByrefType += " *__forwarding;\n";
4292 ByrefType += " int __flags;\n";
4293 ByrefType += " int __size;\n";
4294 // Add void *__Block_byref_id_object_copy;
4295 // void *__Block_byref_id_object_dispose; if needed.
4296 QualType Ty = ND->getType();
4297 bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty);
4298 if (HasCopyAndDispose) {
4299 ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
4300 ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
4301 }
4302
4303 QualType T = Ty;
4304 (void)convertBlockPointerToFunctionPointer(T);
4305 T.getAsStringInternal(Name, Context->getPrintingPolicy());
4306
4307 ByrefType += " " + Name + ";\n";
4308 ByrefType += "};\n";
4309 // Insert this type in global scope. It is needed by helper function.
4310 SourceLocation FunLocStart;
4311 if (CurFunctionDef)
4312 FunLocStart = CurFunctionDef->getTypeSpecStartLoc();
4313 else {
4314 assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null");
4315 FunLocStart = CurMethodDef->getLocStart();
4316 }
4317 InsertText(FunLocStart, ByrefType);
4318 if (Ty.isObjCGCWeak()) {
4319 flag |= BLOCK_FIELD_IS_WEAK;
4320 isa = 1;
4321 }
4322
4323 if (HasCopyAndDispose) {
4324 flag = BLOCK_BYREF_CALLER;
4325 QualType Ty = ND->getType();
4326 // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
4327 if (Ty->isBlockPointerType())
4328 flag |= BLOCK_FIELD_IS_BLOCK;
4329 else
4330 flag |= BLOCK_FIELD_IS_OBJECT;
4331 std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
4332 if (!HF.empty())
4333 InsertText(FunLocStart, HF);
4334 }
4335
4336 // struct __Block_byref_ND ND =
4337 // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
4338 // initializer-if-any};
4339 bool hasInit = (ND->getInit() != 0);
4340 unsigned flags = 0;
4341 if (HasCopyAndDispose)
4342 flags |= BLOCK_HAS_COPY_DISPOSE;
4343 Name = ND->getNameAsString();
4344 ByrefType.clear();
4345 RewriteByRefString(ByrefType, Name, ND);
4346 std::string ForwardingCastType("(");
4347 ForwardingCastType += ByrefType + " *)";
4348 if (!hasInit) {
4349 ByrefType += " " + Name + " = {(void*)";
4350 ByrefType += utostr(isa);
4351 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
4352 ByrefType += utostr(flags);
4353 ByrefType += ", ";
4354 ByrefType += "sizeof(";
4355 RewriteByRefString(ByrefType, Name, ND);
4356 ByrefType += ")";
4357 if (HasCopyAndDispose) {
4358 ByrefType += ", __Block_byref_id_object_copy_";
4359 ByrefType += utostr(flag);
4360 ByrefType += ", __Block_byref_id_object_dispose_";
4361 ByrefType += utostr(flag);
4362 }
4363 ByrefType += "};\n";
4364 unsigned nameSize = Name.size();
4365 // for block or function pointer declaration. Name is aleady
4366 // part of the declaration.
4367 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType())
4368 nameSize = 1;
4369 ReplaceText(DeclLoc, endBuf-startBuf+nameSize, ByrefType);
4370 }
4371 else {
4372 SourceLocation startLoc;
4373 Expr *E = ND->getInit();
4374 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
4375 startLoc = ECE->getLParenLoc();
4376 else
4377 startLoc = E->getLocStart();
4378 startLoc = SM->getExpansionLoc(startLoc);
4379 endBuf = SM->getCharacterData(startLoc);
4380 ByrefType += " " + Name;
4381 ByrefType += " = {(void*)";
4382 ByrefType += utostr(isa);
4383 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
4384 ByrefType += utostr(flags);
4385 ByrefType += ", ";
4386 ByrefType += "sizeof(";
4387 RewriteByRefString(ByrefType, Name, ND);
4388 ByrefType += "), ";
4389 if (HasCopyAndDispose) {
4390 ByrefType += "__Block_byref_id_object_copy_";
4391 ByrefType += utostr(flag);
4392 ByrefType += ", __Block_byref_id_object_dispose_";
4393 ByrefType += utostr(flag);
4394 ByrefType += ", ";
4395 }
4396 ReplaceText(DeclLoc, endBuf-startBuf, ByrefType);
4397
4398 // Complete the newly synthesized compound expression by inserting a right
4399 // curly brace before the end of the declaration.
4400 // FIXME: This approach avoids rewriting the initializer expression. It
4401 // also assumes there is only one declarator. For example, the following
4402 // isn't currently supported by this routine (in general):
4403 //
4404 // double __block BYREFVAR = 1.34, BYREFVAR2 = 1.37;
4405 //
4406 const char *startInitializerBuf = SM->getCharacterData(startLoc);
4407 const char *semiBuf = strchr(startInitializerBuf, ';');
4408 assert((*semiBuf == ';') && "RewriteByRefVar: can't find ';'");
4409 SourceLocation semiLoc =
4410 startLoc.getLocWithOffset(semiBuf-startInitializerBuf);
4411
4412 InsertText(semiLoc, "}");
4413 }
4414 return;
4415}
4416
4417void RewriteModernObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
4418 // Add initializers for any closure decl refs.
4419 GetBlockDeclRefExprs(Exp->getBody());
4420 if (BlockDeclRefs.size()) {
4421 // Unique all "by copy" declarations.
4422 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00004423 if (!BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004424 if (!BlockByCopyDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
4425 BlockByCopyDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
4426 BlockByCopyDecls.push_back(BlockDeclRefs[i]->getDecl());
4427 }
4428 }
4429 // Unique all "by ref" declarations.
4430 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00004431 if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004432 if (!BlockByRefDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
4433 BlockByRefDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
4434 BlockByRefDecls.push_back(BlockDeclRefs[i]->getDecl());
4435 }
4436 }
4437 // Find any imported blocks...they will need special attention.
4438 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00004439 if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004440 BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
4441 BlockDeclRefs[i]->getType()->isBlockPointerType())
4442 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
4443 }
4444}
4445
4446FunctionDecl *RewriteModernObjC::SynthBlockInitFunctionDecl(StringRef name) {
4447 IdentifierInfo *ID = &Context->Idents.get(name);
4448 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
4449 return FunctionDecl::Create(*Context, TUDecl, SourceLocation(),
4450 SourceLocation(), ID, FType, 0, SC_Extern,
4451 SC_None, false, false);
4452}
4453
4454Stmt *RewriteModernObjC::SynthBlockInitExpr(BlockExpr *Exp,
John McCallf4b88a42012-03-10 09:33:50 +00004455 const SmallVector<DeclRefExpr *, 8> &InnerBlockDeclRefs) {
Fariborz Jahaniand13c2c22012-03-22 19:54:39 +00004456
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004457 const BlockDecl *block = Exp->getBlockDecl();
Fariborz Jahaniand13c2c22012-03-22 19:54:39 +00004458
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004459 Blocks.push_back(Exp);
4460
4461 CollectBlockDeclRefInfo(Exp);
4462
4463 // Add inner imported variables now used in current block.
4464 int countOfInnerDecls = 0;
4465 if (!InnerBlockDeclRefs.empty()) {
4466 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++) {
John McCallf4b88a42012-03-10 09:33:50 +00004467 DeclRefExpr *Exp = InnerBlockDeclRefs[i];
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004468 ValueDecl *VD = Exp->getDecl();
John McCallf4b88a42012-03-10 09:33:50 +00004469 if (!VD->hasAttr<BlocksAttr>() && !BlockByCopyDeclsPtrSet.count(VD)) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004470 // We need to save the copied-in variables in nested
4471 // blocks because it is needed at the end for some of the API generations.
4472 // See SynthesizeBlockLiterals routine.
4473 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
4474 BlockDeclRefs.push_back(Exp);
4475 BlockByCopyDeclsPtrSet.insert(VD);
4476 BlockByCopyDecls.push_back(VD);
4477 }
John McCallf4b88a42012-03-10 09:33:50 +00004478 if (VD->hasAttr<BlocksAttr>() && !BlockByRefDeclsPtrSet.count(VD)) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004479 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
4480 BlockDeclRefs.push_back(Exp);
4481 BlockByRefDeclsPtrSet.insert(VD);
4482 BlockByRefDecls.push_back(VD);
4483 }
4484 }
4485 // Find any imported blocks...they will need special attention.
4486 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00004487 if (InnerBlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004488 InnerBlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
4489 InnerBlockDeclRefs[i]->getType()->isBlockPointerType())
4490 ImportedBlockDecls.insert(InnerBlockDeclRefs[i]->getDecl());
4491 }
4492 InnerDeclRefsCount.push_back(countOfInnerDecls);
4493
4494 std::string FuncName;
4495
4496 if (CurFunctionDef)
4497 FuncName = CurFunctionDef->getNameAsString();
4498 else if (CurMethodDef)
4499 BuildUniqueMethodName(FuncName, CurMethodDef);
4500 else if (GlobalVarDecl)
4501 FuncName = std::string(GlobalVarDecl->getNameAsString());
4502
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00004503 bool GlobalBlockExpr =
4504 block->getDeclContext()->getRedeclContext()->isFileContext();
4505
4506 if (GlobalBlockExpr && !GlobalVarDecl) {
4507 Diags.Report(block->getLocation(), GlobalBlockRewriteFailedDiag);
4508 GlobalBlockExpr = false;
4509 }
4510
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004511 std::string BlockNumber = utostr(Blocks.size()-1);
4512
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004513 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
4514
4515 // Get a pointer to the function type so we can cast appropriately.
4516 QualType BFT = convertFunctionTypeOfBlocks(Exp->getFunctionType());
4517 QualType FType = Context->getPointerType(BFT);
4518
4519 FunctionDecl *FD;
4520 Expr *NewRep;
4521
4522 // Simulate a contructor call...
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00004523 std::string Tag;
4524
4525 if (GlobalBlockExpr)
4526 Tag = "__global_";
4527 else
4528 Tag = "__";
4529 Tag += FuncName + "_block_impl_" + BlockNumber;
4530
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004531 FD = SynthBlockInitFunctionDecl(Tag);
John McCallf4b88a42012-03-10 09:33:50 +00004532 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, false, FType, VK_RValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004533 SourceLocation());
4534
4535 SmallVector<Expr*, 4> InitExprs;
4536
4537 // Initialize the block function.
4538 FD = SynthBlockInitFunctionDecl(Func);
John McCallf4b88a42012-03-10 09:33:50 +00004539 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, false, FD->getType(),
4540 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004541 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
4542 CK_BitCast, Arg);
4543 InitExprs.push_back(castExpr);
4544
4545 // Initialize the block descriptor.
4546 std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
4547
4548 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl,
4549 SourceLocation(), SourceLocation(),
4550 &Context->Idents.get(DescData.c_str()),
4551 Context->VoidPtrTy, 0,
4552 SC_Static, SC_None);
4553 UnaryOperator *DescRefExpr =
John McCallf4b88a42012-03-10 09:33:50 +00004554 new (Context) UnaryOperator(new (Context) DeclRefExpr(NewVD, false,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004555 Context->VoidPtrTy,
4556 VK_LValue,
4557 SourceLocation()),
4558 UO_AddrOf,
4559 Context->getPointerType(Context->VoidPtrTy),
4560 VK_RValue, OK_Ordinary,
4561 SourceLocation());
4562 InitExprs.push_back(DescRefExpr);
4563
4564 // Add initializers for any closure decl refs.
4565 if (BlockDeclRefs.size()) {
4566 Expr *Exp;
4567 // Output all "by copy" declarations.
4568 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
4569 E = BlockByCopyDecls.end(); I != E; ++I) {
4570 if (isObjCType((*I)->getType())) {
4571 // FIXME: Conform to ABI ([[obj retain] autorelease]).
4572 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00004573 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(),
4574 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004575 if (HasLocalVariableExternalStorage(*I)) {
4576 QualType QT = (*I)->getType();
4577 QT = Context->getPointerType(QT);
4578 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
4579 OK_Ordinary, SourceLocation());
4580 }
4581 } else if (isTopLevelBlockPointerType((*I)->getType())) {
4582 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00004583 Arg = new (Context) DeclRefExpr(FD, false, FD->getType(),
4584 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004585 Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
4586 CK_BitCast, Arg);
4587 } else {
4588 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00004589 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(),
4590 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004591 if (HasLocalVariableExternalStorage(*I)) {
4592 QualType QT = (*I)->getType();
4593 QT = Context->getPointerType(QT);
4594 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
4595 OK_Ordinary, SourceLocation());
4596 }
4597
4598 }
4599 InitExprs.push_back(Exp);
4600 }
4601 // Output all "by ref" declarations.
4602 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
4603 E = BlockByRefDecls.end(); I != E; ++I) {
4604 ValueDecl *ND = (*I);
4605 std::string Name(ND->getNameAsString());
4606 std::string RecName;
4607 RewriteByRefString(RecName, Name, ND, true);
4608 IdentifierInfo *II = &Context->Idents.get(RecName.c_str()
4609 + sizeof("struct"));
4610 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
4611 SourceLocation(), SourceLocation(),
4612 II);
4613 assert(RD && "SynthBlockInitExpr(): Can't find RecordDecl");
4614 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
4615
4616 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00004617 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(), VK_LValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004618 SourceLocation());
4619 bool isNestedCapturedVar = false;
4620 if (block)
4621 for (BlockDecl::capture_const_iterator ci = block->capture_begin(),
4622 ce = block->capture_end(); ci != ce; ++ci) {
4623 const VarDecl *variable = ci->getVariable();
4624 if (variable == ND && ci->isNested()) {
4625 assert (ci->isByRef() &&
4626 "SynthBlockInitExpr - captured block variable is not byref");
4627 isNestedCapturedVar = true;
4628 break;
4629 }
4630 }
4631 // captured nested byref variable has its address passed. Do not take
4632 // its address again.
4633 if (!isNestedCapturedVar)
4634 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf,
4635 Context->getPointerType(Exp->getType()),
4636 VK_RValue, OK_Ordinary, SourceLocation());
4637 Exp = NoTypeInfoCStyleCastExpr(Context, castT, CK_BitCast, Exp);
4638 InitExprs.push_back(Exp);
4639 }
4640 }
4641 if (ImportedBlockDecls.size()) {
4642 // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
4643 int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
4644 unsigned IntSize =
4645 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
4646 Expr *FlagExp = IntegerLiteral::Create(*Context, llvm::APInt(IntSize, flag),
4647 Context->IntTy, SourceLocation());
4648 InitExprs.push_back(FlagExp);
4649 }
4650 NewRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0], InitExprs.size(),
4651 FType, VK_LValue, SourceLocation());
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00004652
4653 if (GlobalBlockExpr) {
4654 assert (GlobalConstructionExp == 0 &&
4655 "SynthBlockInitExpr - GlobalConstructionExp must be null");
4656 GlobalConstructionExp = NewRep;
4657 NewRep = DRE;
4658 }
4659
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004660 NewRep = new (Context) UnaryOperator(NewRep, UO_AddrOf,
4661 Context->getPointerType(NewRep->getType()),
4662 VK_RValue, OK_Ordinary, SourceLocation());
4663 NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CK_BitCast,
4664 NewRep);
4665 BlockDeclRefs.clear();
4666 BlockByRefDecls.clear();
4667 BlockByRefDeclsPtrSet.clear();
4668 BlockByCopyDecls.clear();
4669 BlockByCopyDeclsPtrSet.clear();
4670 ImportedBlockDecls.clear();
4671 return NewRep;
4672}
4673
4674bool RewriteModernObjC::IsDeclStmtInForeachHeader(DeclStmt *DS) {
4675 if (const ObjCForCollectionStmt * CS =
4676 dyn_cast<ObjCForCollectionStmt>(Stmts.back()))
4677 return CS->getElement() == DS;
4678 return false;
4679}
4680
4681//===----------------------------------------------------------------------===//
4682// Function Body / Expression rewriting
4683//===----------------------------------------------------------------------===//
4684
4685Stmt *RewriteModernObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
4686 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
4687 isa<DoStmt>(S) || isa<ForStmt>(S))
4688 Stmts.push_back(S);
4689 else if (isa<ObjCForCollectionStmt>(S)) {
4690 Stmts.push_back(S);
4691 ObjCBcLabelNo.push_back(++BcLabelCount);
4692 }
4693
4694 // Pseudo-object operations and ivar references need special
4695 // treatment because we're going to recursively rewrite them.
4696 if (PseudoObjectExpr *PseudoOp = dyn_cast<PseudoObjectExpr>(S)) {
4697 if (isa<BinaryOperator>(PseudoOp->getSyntacticForm())) {
4698 return RewritePropertyOrImplicitSetter(PseudoOp);
4699 } else {
4700 return RewritePropertyOrImplicitGetter(PseudoOp);
4701 }
4702 } else if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
4703 return RewriteObjCIvarRefExpr(IvarRefExpr);
4704 }
4705
4706 SourceRange OrigStmtRange = S->getSourceRange();
4707
4708 // Perform a bottom up rewrite of all children.
4709 for (Stmt::child_range CI = S->children(); CI; ++CI)
4710 if (*CI) {
4711 Stmt *childStmt = (*CI);
4712 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(childStmt);
4713 if (newStmt) {
4714 *CI = newStmt;
4715 }
4716 }
4717
4718 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
John McCallf4b88a42012-03-10 09:33:50 +00004719 SmallVector<DeclRefExpr *, 8> InnerBlockDeclRefs;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004720 llvm::SmallPtrSet<const DeclContext *, 8> InnerContexts;
4721 InnerContexts.insert(BE->getBlockDecl());
4722 ImportedLocalExternalDecls.clear();
4723 GetInnerBlockDeclRefExprs(BE->getBody(),
4724 InnerBlockDeclRefs, InnerContexts);
4725 // Rewrite the block body in place.
4726 Stmt *SaveCurrentBody = CurrentBody;
4727 CurrentBody = BE->getBody();
4728 PropParentMap = 0;
4729 // block literal on rhs of a property-dot-sytax assignment
4730 // must be replaced by its synthesize ast so getRewrittenText
4731 // works as expected. In this case, what actually ends up on RHS
4732 // is the blockTranscribed which is the helper function for the
4733 // block literal; as in: self.c = ^() {[ace ARR];};
4734 bool saveDisableReplaceStmt = DisableReplaceStmt;
4735 DisableReplaceStmt = false;
4736 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
4737 DisableReplaceStmt = saveDisableReplaceStmt;
4738 CurrentBody = SaveCurrentBody;
4739 PropParentMap = 0;
4740 ImportedLocalExternalDecls.clear();
4741 // Now we snarf the rewritten text and stash it away for later use.
4742 std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
4743 RewrittenBlockExprs[BE] = Str;
4744
4745 Stmt *blockTranscribed = SynthBlockInitExpr(BE, InnerBlockDeclRefs);
4746
4747 //blockTranscribed->dump();
4748 ReplaceStmt(S, blockTranscribed);
4749 return blockTranscribed;
4750 }
4751 // Handle specific things.
4752 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
4753 return RewriteAtEncode(AtEncode);
4754
4755 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
4756 return RewriteAtSelector(AtSelector);
4757
4758 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
4759 return RewriteObjCStringLiteral(AtString);
Fariborz Jahanian55947042012-03-27 20:17:30 +00004760
4761 if (ObjCBoolLiteralExpr *BoolLitExpr = dyn_cast<ObjCBoolLiteralExpr>(S))
4762 return RewriteObjCBoolLiteralExpr(BoolLitExpr);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004763
4764 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
4765#if 0
4766 // Before we rewrite it, put the original message expression in a comment.
4767 SourceLocation startLoc = MessExpr->getLocStart();
4768 SourceLocation endLoc = MessExpr->getLocEnd();
4769
4770 const char *startBuf = SM->getCharacterData(startLoc);
4771 const char *endBuf = SM->getCharacterData(endLoc);
4772
4773 std::string messString;
4774 messString += "// ";
4775 messString.append(startBuf, endBuf-startBuf+1);
4776 messString += "\n";
4777
4778 // FIXME: Missing definition of
4779 // InsertText(clang::SourceLocation, char const*, unsigned int).
4780 // InsertText(startLoc, messString.c_str(), messString.size());
4781 // Tried this, but it didn't work either...
4782 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
4783#endif
4784 return RewriteMessageExpr(MessExpr);
4785 }
4786
4787 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
4788 return RewriteObjCTryStmt(StmtTry);
4789
4790 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
4791 return RewriteObjCSynchronizedStmt(StmtTry);
4792
4793 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
4794 return RewriteObjCThrowStmt(StmtThrow);
4795
4796 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
4797 return RewriteObjCProtocolExpr(ProtocolExp);
4798
4799 if (ObjCForCollectionStmt *StmtForCollection =
4800 dyn_cast<ObjCForCollectionStmt>(S))
4801 return RewriteObjCForCollectionStmt(StmtForCollection,
4802 OrigStmtRange.getEnd());
4803 if (BreakStmt *StmtBreakStmt =
4804 dyn_cast<BreakStmt>(S))
4805 return RewriteBreakStmt(StmtBreakStmt);
4806 if (ContinueStmt *StmtContinueStmt =
4807 dyn_cast<ContinueStmt>(S))
4808 return RewriteContinueStmt(StmtContinueStmt);
4809
4810 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
4811 // and cast exprs.
4812 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
4813 // FIXME: What we're doing here is modifying the type-specifier that
4814 // precedes the first Decl. In the future the DeclGroup should have
4815 // a separate type-specifier that we can rewrite.
4816 // NOTE: We need to avoid rewriting the DeclStmt if it is within
4817 // the context of an ObjCForCollectionStmt. For example:
4818 // NSArray *someArray;
4819 // for (id <FooProtocol> index in someArray) ;
4820 // This is because RewriteObjCForCollectionStmt() does textual rewriting
4821 // and it depends on the original text locations/positions.
4822 if (Stmts.empty() || !IsDeclStmtInForeachHeader(DS))
4823 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
4824
4825 // Blocks rewrite rules.
4826 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
4827 DI != DE; ++DI) {
4828 Decl *SD = *DI;
4829 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
4830 if (isTopLevelBlockPointerType(ND->getType()))
4831 RewriteBlockPointerDecl(ND);
4832 else if (ND->getType()->isFunctionPointerType())
4833 CheckFunctionPointerDecl(ND->getType(), ND);
4834 if (VarDecl *VD = dyn_cast<VarDecl>(SD)) {
4835 if (VD->hasAttr<BlocksAttr>()) {
4836 static unsigned uniqueByrefDeclCount = 0;
4837 assert(!BlockByRefDeclNo.count(ND) &&
4838 "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl");
4839 BlockByRefDeclNo[ND] = uniqueByrefDeclCount++;
4840 RewriteByRefVar(VD);
4841 }
4842 else
4843 RewriteTypeOfDecl(VD);
4844 }
4845 }
4846 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(SD)) {
4847 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
4848 RewriteBlockPointerDecl(TD);
4849 else if (TD->getUnderlyingType()->isFunctionPointerType())
4850 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
4851 }
4852 }
4853 }
4854
4855 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
4856 RewriteObjCQualifiedInterfaceTypes(CE);
4857
4858 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
4859 isa<DoStmt>(S) || isa<ForStmt>(S)) {
4860 assert(!Stmts.empty() && "Statement stack is empty");
4861 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
4862 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
4863 && "Statement stack mismatch");
4864 Stmts.pop_back();
4865 }
4866 // Handle blocks rewriting.
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004867 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4868 ValueDecl *VD = DRE->getDecl();
4869 if (VD->hasAttr<BlocksAttr>())
4870 return RewriteBlockDeclRefExpr(DRE);
4871 if (HasLocalVariableExternalStorage(VD))
4872 return RewriteLocalVariableExternalStorage(DRE);
4873 }
4874
4875 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
4876 if (CE->getCallee()->getType()->isBlockPointerType()) {
4877 Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
4878 ReplaceStmt(S, BlockCall);
4879 return BlockCall;
4880 }
4881 }
4882 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
4883 RewriteCastExpr(CE);
4884 }
4885#if 0
4886 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
4887 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(),
4888 ICE->getSubExpr(),
4889 SourceLocation());
4890 // Get the new text.
4891 std::string SStr;
4892 llvm::raw_string_ostream Buf(SStr);
4893 Replacement->printPretty(Buf, *Context);
4894 const std::string &Str = Buf.str();
4895
4896 printf("CAST = %s\n", &Str[0]);
4897 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
4898 delete S;
4899 return Replacement;
4900 }
4901#endif
4902 // Return this stmt unmodified.
4903 return S;
4904}
4905
4906void RewriteModernObjC::RewriteRecordBody(RecordDecl *RD) {
4907 for (RecordDecl::field_iterator i = RD->field_begin(),
4908 e = RD->field_end(); i != e; ++i) {
4909 FieldDecl *FD = *i;
4910 if (isTopLevelBlockPointerType(FD->getType()))
4911 RewriteBlockPointerDecl(FD);
4912 if (FD->getType()->isObjCQualifiedIdType() ||
4913 FD->getType()->isObjCQualifiedInterfaceType())
4914 RewriteObjCQualifiedInterfaceTypes(FD);
4915 }
4916}
4917
4918/// HandleDeclInMainFile - This is called for each top-level decl defined in the
4919/// main file of the input.
4920void RewriteModernObjC::HandleDeclInMainFile(Decl *D) {
4921 switch (D->getKind()) {
4922 case Decl::Function: {
4923 FunctionDecl *FD = cast<FunctionDecl>(D);
4924 if (FD->isOverloadedOperator())
4925 return;
4926
4927 // Since function prototypes don't have ParmDecl's, we check the function
4928 // prototype. This enables us to rewrite function declarations and
4929 // definitions using the same code.
4930 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
4931
Argyrios Kyrtzidis9335df32012-02-12 04:48:45 +00004932 if (!FD->isThisDeclarationADefinition())
4933 break;
4934
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004935 // FIXME: If this should support Obj-C++, support CXXTryStmt
4936 if (CompoundStmt *Body = dyn_cast_or_null<CompoundStmt>(FD->getBody())) {
4937 CurFunctionDef = FD;
4938 CurFunctionDeclToDeclareForBlock = FD;
4939 CurrentBody = Body;
4940 Body =
4941 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
4942 FD->setBody(Body);
4943 CurrentBody = 0;
4944 if (PropParentMap) {
4945 delete PropParentMap;
4946 PropParentMap = 0;
4947 }
4948 // This synthesizes and inserts the block "impl" struct, invoke function,
4949 // and any copy/dispose helper functions.
4950 InsertBlockLiteralsWithinFunction(FD);
4951 CurFunctionDef = 0;
4952 CurFunctionDeclToDeclareForBlock = 0;
4953 }
4954 break;
4955 }
4956 case Decl::ObjCMethod: {
4957 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(D);
4958 if (CompoundStmt *Body = MD->getCompoundBody()) {
4959 CurMethodDef = MD;
4960 CurrentBody = Body;
4961 Body =
4962 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
4963 MD->setBody(Body);
4964 CurrentBody = 0;
4965 if (PropParentMap) {
4966 delete PropParentMap;
4967 PropParentMap = 0;
4968 }
4969 InsertBlockLiteralsWithinMethod(MD);
4970 CurMethodDef = 0;
4971 }
4972 break;
4973 }
4974 case Decl::ObjCImplementation: {
4975 ObjCImplementationDecl *CI = cast<ObjCImplementationDecl>(D);
4976 ClassImplementation.push_back(CI);
4977 break;
4978 }
4979 case Decl::ObjCCategoryImpl: {
4980 ObjCCategoryImplDecl *CI = cast<ObjCCategoryImplDecl>(D);
4981 CategoryImplementation.push_back(CI);
4982 break;
4983 }
4984 case Decl::Var: {
4985 VarDecl *VD = cast<VarDecl>(D);
4986 RewriteObjCQualifiedInterfaceTypes(VD);
4987 if (isTopLevelBlockPointerType(VD->getType()))
4988 RewriteBlockPointerDecl(VD);
4989 else if (VD->getType()->isFunctionPointerType()) {
4990 CheckFunctionPointerDecl(VD->getType(), VD);
4991 if (VD->getInit()) {
4992 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
4993 RewriteCastExpr(CE);
4994 }
4995 }
4996 } else if (VD->getType()->isRecordType()) {
4997 RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
4998 if (RD->isCompleteDefinition())
4999 RewriteRecordBody(RD);
5000 }
5001 if (VD->getInit()) {
5002 GlobalVarDecl = VD;
5003 CurrentBody = VD->getInit();
5004 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
5005 CurrentBody = 0;
5006 if (PropParentMap) {
5007 delete PropParentMap;
5008 PropParentMap = 0;
5009 }
5010 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(), VD->getName());
5011 GlobalVarDecl = 0;
5012
5013 // This is needed for blocks.
5014 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
5015 RewriteCastExpr(CE);
5016 }
5017 }
5018 break;
5019 }
5020 case Decl::TypeAlias:
5021 case Decl::Typedef: {
5022 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
5023 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
5024 RewriteBlockPointerDecl(TD);
5025 else if (TD->getUnderlyingType()->isFunctionPointerType())
5026 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5027 }
5028 break;
5029 }
5030 case Decl::CXXRecord:
5031 case Decl::Record: {
5032 RecordDecl *RD = cast<RecordDecl>(D);
5033 if (RD->isCompleteDefinition())
5034 RewriteRecordBody(RD);
5035 break;
5036 }
5037 default:
5038 break;
5039 }
5040 // Nothing yet.
5041}
5042
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00005043/// Write_ProtocolExprReferencedMetadata - This routine writer out the
5044/// protocol reference symbols in the for of:
5045/// struct _protocol_t *PROTOCOL_REF = &PROTOCOL_METADATA.
5046static void Write_ProtocolExprReferencedMetadata(ASTContext *Context,
5047 ObjCProtocolDecl *PDecl,
5048 std::string &Result) {
5049 // Also output .objc_protorefs$B section and its meta-data.
5050 if (Context->getLangOpts().MicrosoftExt)
5051 Result += "__declspec(allocate(\".objc_protorefs$B\")) ";
5052 Result += "struct _protocol_t *";
5053 Result += "_OBJC_PROTOCOL_REFERENCE_$_";
5054 Result += PDecl->getNameAsString();
5055 Result += " = &";
5056 Result += "_OBJC_PROTOCOL_"; Result += PDecl->getNameAsString();
5057 Result += ";\n";
5058}
5059
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005060void RewriteModernObjC::HandleTranslationUnit(ASTContext &C) {
5061 if (Diags.hasErrorOccurred())
5062 return;
5063
5064 RewriteInclude();
5065
5066 // Here's a great place to add any extra declarations that may be needed.
5067 // Write out meta data for each @protocol(<expr>).
5068 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00005069 E = ProtocolExprDecls.end(); I != E; ++I) {
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00005070 RewriteObjCProtocolMetaData(*I, Preamble);
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00005071 Write_ProtocolExprReferencedMetadata(Context, (*I), Preamble);
5072 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005073
5074 InsertText(SM->getLocForStartOfFile(MainFileID), Preamble, false);
Fariborz Jahanian57317782012-02-21 23:58:41 +00005075 for (unsigned i = 0, e = ObjCInterfacesSeen.size(); i < e; i++) {
5076 ObjCInterfaceDecl *CDecl = ObjCInterfacesSeen[i];
5077 // Write struct declaration for the class matching its ivar declarations.
5078 // Note that for modern abi, this is postponed until the end of TU
5079 // because class extensions and the implementation might declare their own
5080 // private ivars.
5081 RewriteInterfaceDecl(CDecl);
5082 }
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00005083
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005084 if (ClassImplementation.size() || CategoryImplementation.size())
5085 RewriteImplementations();
5086
5087 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
5088 // we are done.
5089 if (const RewriteBuffer *RewriteBuf =
5090 Rewrite.getRewriteBufferFor(MainFileID)) {
5091 //printf("Changed:\n");
5092 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
5093 } else {
5094 llvm::errs() << "No changes\n";
5095 }
5096
5097 if (ClassImplementation.size() || CategoryImplementation.size() ||
5098 ProtocolExprDecls.size()) {
5099 // Rewrite Objective-c meta data*
5100 std::string ResultStr;
5101 RewriteMetaDataIntoBuffer(ResultStr);
5102 // Emit metadata.
5103 *OutFile << ResultStr;
5104 }
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005105 // Emit ImageInfo;
5106 {
5107 std::string ResultStr;
5108 WriteImageInfo(ResultStr);
5109 *OutFile << ResultStr;
5110 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005111 OutFile->flush();
5112}
5113
5114void RewriteModernObjC::Initialize(ASTContext &context) {
5115 InitializeCommon(context);
5116
Fariborz Jahanian6991bc52012-03-10 17:45:38 +00005117 Preamble += "#ifndef __OBJC2__\n";
5118 Preamble += "#define __OBJC2__\n";
5119 Preamble += "#endif\n";
5120
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005121 // declaring objc_selector outside the parameter list removes a silly
5122 // scope related warning...
5123 if (IsHeader)
5124 Preamble = "#pragma once\n";
5125 Preamble += "struct objc_selector; struct objc_class;\n";
5126 Preamble += "struct __rw_objc_super { struct objc_object *object; ";
5127 Preamble += "struct objc_object *superClass; ";
5128 if (LangOpts.MicrosoftExt) {
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00005129 // Define all sections using syntax that makes sense.
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005130 // These are currently generated.
5131 Preamble += "\n#pragma section(\".objc_classlist$B\", long, read, write)\n";
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00005132 Preamble += "#pragma section(\".objc_catlist$B\", long, read, write)\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005133 Preamble += "#pragma section(\".objc_protolist$B\", long, read, write)\n";
5134 Preamble += "#pragma section(\".objc_imageinfo$B\", long, read, write)\n";
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00005135 Preamble += "#pragma section(\".objc_nlclslist$B\", long, read, write)\n";
5136 Preamble += "#pragma section(\".objc_nlcatlist$B\", long, read, write)\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005137 Preamble += "#pragma section(\".objc_protorefs$B\", long, read, write)\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005138 // These are generated but not necessary for functionality.
5139 Preamble += "#pragma section(\".datacoal_nt$B\", long, read, write)\n";
5140 Preamble += "#pragma section(\".cat_cls_meth$B\", long, read, write)\n";
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00005141 Preamble += "#pragma section(\".inst_meth$B\", long, read, write)\n";
5142 Preamble += "#pragma section(\".cls_meth$B\", long, read, write)\n";
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00005143 Preamble += "#pragma section(\".objc_ivar$B\", long, read, write)\n";
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00005144
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00005145 // These need be generated for performance. Currently they are not,
5146 // using API calls instead.
5147 Preamble += "#pragma section(\".objc_selrefs$B\", long, read, write)\n";
5148 Preamble += "#pragma section(\".objc_classrefs$B\", long, read, write)\n";
5149 Preamble += "#pragma section(\".objc_superrefs$B\", long, read, write)\n";
5150
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005151 // Add a constructor for creating temporary objects.
5152 Preamble += "__rw_objc_super(struct objc_object *o, struct objc_object *s) "
5153 ": ";
5154 Preamble += "object(o), superClass(s) {} ";
5155 }
5156 Preamble += "};\n";
5157 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
5158 Preamble += "typedef struct objc_object Protocol;\n";
5159 Preamble += "#define _REWRITER_typedef_Protocol\n";
5160 Preamble += "#endif\n";
5161 if (LangOpts.MicrosoftExt) {
5162 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
5163 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
Fariborz Jahanian5cf6b6c2012-03-21 23:41:04 +00005164 }
5165 else
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005166 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
Fariborz Jahanian5cf6b6c2012-03-21 23:41:04 +00005167
5168 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend(void);\n";
5169 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSendSuper(void);\n";
5170 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend_stret(void);\n";
5171 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSendSuper_stret(void);\n";
5172 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend_fpret(void);\n";
5173
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005174 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getClass";
5175 Preamble += "(const char *);\n";
5176 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *class_getSuperclass";
5177 Preamble += "(struct objc_class *);\n";
5178 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getMetaClass";
5179 Preamble += "(const char *);\n";
Fariborz Jahanian55261af2012-03-19 18:11:32 +00005180 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw( struct objc_object *);\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005181 // @synchronized hooks.
Fariborz Jahanian55261af2012-03-19 18:11:32 +00005182 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_enter( struct objc_object *);\n";
5183 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_exit( struct objc_object *);\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005184 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
5185 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
5186 Preamble += "struct __objcFastEnumerationState {\n\t";
5187 Preamble += "unsigned long state;\n\t";
5188 Preamble += "void **itemsPtr;\n\t";
5189 Preamble += "unsigned long *mutationsPtr;\n\t";
5190 Preamble += "unsigned long extra[5];\n};\n";
5191 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
5192 Preamble += "#define __FASTENUMERATIONSTATE\n";
5193 Preamble += "#endif\n";
5194 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
5195 Preamble += "struct __NSConstantStringImpl {\n";
5196 Preamble += " int *isa;\n";
5197 Preamble += " int flags;\n";
5198 Preamble += " char *str;\n";
5199 Preamble += " long length;\n";
5200 Preamble += "};\n";
5201 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
5202 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
5203 Preamble += "#else\n";
5204 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
5205 Preamble += "#endif\n";
5206 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
5207 Preamble += "#endif\n";
5208 // Blocks preamble.
5209 Preamble += "#ifndef BLOCK_IMPL\n";
5210 Preamble += "#define BLOCK_IMPL\n";
5211 Preamble += "struct __block_impl {\n";
5212 Preamble += " void *isa;\n";
5213 Preamble += " int Flags;\n";
5214 Preamble += " int Reserved;\n";
5215 Preamble += " void *FuncPtr;\n";
5216 Preamble += "};\n";
5217 Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
5218 Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n";
5219 Preamble += "extern \"C\" __declspec(dllexport) "
5220 "void _Block_object_assign(void *, const void *, const int);\n";
5221 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
5222 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
5223 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
5224 Preamble += "#else\n";
5225 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n";
5226 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n";
5227 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
5228 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
5229 Preamble += "#endif\n";
5230 Preamble += "#endif\n";
5231 if (LangOpts.MicrosoftExt) {
5232 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
5233 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
5234 Preamble += "#ifndef KEEP_ATTRIBUTES\n"; // We use this for clang tests.
5235 Preamble += "#define __attribute__(X)\n";
5236 Preamble += "#endif\n";
5237 Preamble += "#define __weak\n";
5238 }
5239 else {
5240 Preamble += "#define __block\n";
5241 Preamble += "#define __weak\n";
5242 }
5243 // NOTE! Windows uses LLP64 for 64bit mode. So, cast pointer to long long
5244 // as this avoids warning in any 64bit/32bit compilation model.
5245 Preamble += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long long) &((TYPE *)0)->MEMBER)\n";
5246}
5247
5248/// RewriteIvarOffsetComputation - This rutine synthesizes computation of
5249/// ivar offset.
5250void RewriteModernObjC::RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
5251 std::string &Result) {
5252 if (ivar->isBitField()) {
5253 // FIXME: The hack below doesn't work for bitfields. For now, we simply
5254 // place all bitfields at offset 0.
5255 Result += "0";
5256 } else {
5257 Result += "__OFFSETOFIVAR__(struct ";
5258 Result += ivar->getContainingInterface()->getNameAsString();
5259 if (LangOpts.MicrosoftExt)
5260 Result += "_IMPL";
5261 Result += ", ";
5262 Result += ivar->getNameAsString();
5263 Result += ")";
5264 }
5265}
5266
5267/// WriteModernMetadataDeclarations - Writes out metadata declarations for modern ABI.
5268/// struct _prop_t {
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00005269/// const char *name;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005270/// char *attributes;
5271/// }
5272
5273/// struct _prop_list_t {
5274/// uint32_t entsize; // sizeof(struct _prop_t)
5275/// uint32_t count_of_properties;
5276/// struct _prop_t prop_list[count_of_properties];
5277/// }
5278
5279/// struct _protocol_t;
5280
5281/// struct _protocol_list_t {
5282/// long protocol_count; // Note, this is 32/64 bit
5283/// struct _protocol_t * protocol_list[protocol_count];
5284/// }
5285
5286/// struct _objc_method {
5287/// SEL _cmd;
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005288/// const char *method_type;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005289/// char *_imp;
5290/// }
5291
5292/// struct _method_list_t {
5293/// uint32_t entsize; // sizeof(struct _objc_method)
5294/// uint32_t method_count;
5295/// struct _objc_method method_list[method_count];
5296/// }
5297
5298/// struct _protocol_t {
5299/// id isa; // NULL
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005300/// const char *protocol_name;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005301/// const struct _protocol_list_t * protocol_list; // super protocols
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005302/// const struct method_list_t *instance_methods;
5303/// const struct method_list_t *class_methods;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005304/// const struct method_list_t *optionalInstanceMethods;
5305/// const struct method_list_t *optionalClassMethods;
5306/// const struct _prop_list_t * properties;
5307/// const uint32_t size; // sizeof(struct _protocol_t)
5308/// const uint32_t flags; // = 0
5309/// const char ** extendedMethodTypes;
5310/// }
5311
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005312/// struct _ivar_t {
5313/// unsigned long int *offset; // pointer to ivar offset location
Fariborz Jahanianae932952012-02-10 20:47:10 +00005314/// const char *name;
5315/// const char *type;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005316/// uint32_t alignment;
5317/// uint32_t size;
5318/// }
5319
5320/// struct _ivar_list_t {
5321/// uint32 entsize; // sizeof(struct _ivar_t)
5322/// uint32 count;
Fariborz Jahanianae932952012-02-10 20:47:10 +00005323/// struct _ivar_t list[count];
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005324/// }
5325
5326/// struct _class_ro_t {
Fariborz Jahanian249cd102012-03-24 16:53:16 +00005327/// uint32_t flags;
5328/// uint32_t instanceStart;
5329/// uint32_t instanceSize;
5330/// uint32_t reserved; // only when building for 64bit targets
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005331/// const uint8_t *ivarLayout;
5332/// const char *name;
5333/// const struct _method_list_t *baseMethods;
5334/// const struct _protocol_list_t *baseProtocols;
5335/// const struct _ivar_list_t *ivars;
5336/// const uint8_t *weakIvarLayout;
5337/// const struct _prop_list_t *properties;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005338/// }
5339
5340/// struct _class_t {
5341/// struct _class_t *isa;
Fariborz Jahanianfd4ce2c2012-03-20 17:34:50 +00005342/// struct _class_t *superclass;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005343/// void *cache;
5344/// IMP *vtable;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005345/// struct _class_ro_t *ro;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005346/// }
5347
5348/// struct _category_t {
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005349/// const char *name;
Fariborz Jahanian4b2fe6e2012-03-20 21:41:28 +00005350/// struct _class_t *cls;
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005351/// const struct _method_list_t *instance_methods;
5352/// const struct _method_list_t *class_methods;
5353/// const struct _protocol_list_t *protocols;
5354/// const struct _prop_list_t *properties;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005355/// }
5356
5357/// MessageRefTy - LLVM for:
5358/// struct _message_ref_t {
5359/// IMP messenger;
5360/// SEL name;
5361/// };
5362
5363/// SuperMessageRefTy - LLVM for:
5364/// struct _super_message_ref_t {
5365/// SUPER_IMP messenger;
5366/// SEL name;
5367/// };
5368
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00005369static void WriteModernMetadataDeclarations(ASTContext *Context, std::string &Result) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005370 static bool meta_data_declared = false;
5371 if (meta_data_declared)
5372 return;
5373
5374 Result += "\nstruct _prop_t {\n";
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00005375 Result += "\tconst char *name;\n";
5376 Result += "\tconst char *attributes;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005377 Result += "};\n";
5378
5379 Result += "\nstruct _protocol_t;\n";
5380
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005381 Result += "\nstruct _objc_method {\n";
5382 Result += "\tstruct objc_selector * _cmd;\n";
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005383 Result += "\tconst char *method_type;\n";
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005384 Result += "\tvoid *_imp;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005385 Result += "};\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005386
5387 Result += "\nstruct _protocol_t {\n";
5388 Result += "\tvoid * isa; // NULL\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005389 Result += "\tconst char *protocol_name;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005390 Result += "\tconst struct _protocol_list_t * protocol_list; // super protocols\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005391 Result += "\tconst struct method_list_t *instance_methods;\n";
5392 Result += "\tconst struct method_list_t *class_methods;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005393 Result += "\tconst struct method_list_t *optionalInstanceMethods;\n";
5394 Result += "\tconst struct method_list_t *optionalClassMethods;\n";
5395 Result += "\tconst struct _prop_list_t * properties;\n";
5396 Result += "\tconst unsigned int size; // sizeof(struct _protocol_t)\n";
5397 Result += "\tconst unsigned int flags; // = 0\n";
5398 Result += "\tconst char ** extendedMethodTypes;\n";
5399 Result += "};\n";
5400
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005401 Result += "\nstruct _ivar_t {\n";
5402 Result += "\tunsigned long int *offset; // pointer to ivar offset location\n";
Fariborz Jahanianae932952012-02-10 20:47:10 +00005403 Result += "\tconst char *name;\n";
5404 Result += "\tconst char *type;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005405 Result += "\tunsigned int alignment;\n";
5406 Result += "\tunsigned int size;\n";
5407 Result += "};\n";
5408
5409 Result += "\nstruct _class_ro_t {\n";
Fariborz Jahanian249cd102012-03-24 16:53:16 +00005410 Result += "\tunsigned int flags;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005411 Result += "\tunsigned int instanceStart;\n";
Fariborz Jahanian249cd102012-03-24 16:53:16 +00005412 Result += "\tunsigned int instanceSize;\n";
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00005413 const llvm::Triple &Triple(Context->getTargetInfo().getTriple());
5414 if (Triple.getArch() == llvm::Triple::x86_64)
Fariborz Jahanian249cd102012-03-24 16:53:16 +00005415 Result += "\tunsigned int reserved;\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005416 Result += "\tconst unsigned char *ivarLayout;\n";
5417 Result += "\tconst char *name;\n";
5418 Result += "\tconst struct _method_list_t *baseMethods;\n";
5419 Result += "\tconst struct _objc_protocol_list *baseProtocols;\n";
5420 Result += "\tconst struct _ivar_list_t *ivars;\n";
5421 Result += "\tconst unsigned char *weakIvarLayout;\n";
5422 Result += "\tconst struct _prop_list_t *properties;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005423 Result += "};\n";
5424
5425 Result += "\nstruct _class_t {\n";
5426 Result += "\tstruct _class_t *isa;\n";
Fariborz Jahanianfd4ce2c2012-03-20 17:34:50 +00005427 Result += "\tstruct _class_t *superclass;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005428 Result += "\tvoid *cache;\n";
5429 Result += "\tvoid *vtable;\n";
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005430 Result += "\tstruct _class_ro_t *ro;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005431 Result += "};\n";
5432
5433 Result += "\nstruct _category_t {\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005434 Result += "\tconst char *name;\n";
Fariborz Jahanian4b2fe6e2012-03-20 21:41:28 +00005435 Result += "\tstruct _class_t *cls;\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005436 Result += "\tconst struct _method_list_t *instance_methods;\n";
5437 Result += "\tconst struct _method_list_t *class_methods;\n";
5438 Result += "\tconst struct _protocol_list_t *protocols;\n";
5439 Result += "\tconst struct _prop_list_t *properties;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005440 Result += "};\n";
5441
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00005442 Result += "extern \"C\" __declspec(dllimport) struct objc_cache _objc_empty_cache;\n";
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005443
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005444 meta_data_declared = true;
5445}
5446
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00005447static void Write_protocol_list_t_TypeDecl(std::string &Result,
5448 long super_protocol_count) {
5449 Result += "struct /*_protocol_list_t*/"; Result += " {\n";
5450 Result += "\tlong protocol_count; // Note, this is 32/64 bit\n";
5451 Result += "\tstruct _protocol_t *super_protocols[";
5452 Result += utostr(super_protocol_count); Result += "];\n";
5453 Result += "}";
5454}
5455
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005456static void Write_method_list_t_TypeDecl(std::string &Result,
5457 unsigned int method_count) {
5458 Result += "struct /*_method_list_t*/"; Result += " {\n";
5459 Result += "\tunsigned int entsize; // sizeof(struct _objc_method)\n";
5460 Result += "\tunsigned int method_count;\n";
5461 Result += "\tstruct _objc_method method_list[";
5462 Result += utostr(method_count); Result += "];\n";
5463 Result += "}";
5464}
5465
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00005466static void Write__prop_list_t_TypeDecl(std::string &Result,
5467 unsigned int property_count) {
5468 Result += "struct /*_prop_list_t*/"; Result += " {\n";
5469 Result += "\tunsigned int entsize; // sizeof(struct _prop_t)\n";
5470 Result += "\tunsigned int count_of_properties;\n";
5471 Result += "\tstruct _prop_t prop_list[";
5472 Result += utostr(property_count); Result += "];\n";
5473 Result += "}";
5474}
5475
Fariborz Jahanianae932952012-02-10 20:47:10 +00005476static void Write__ivar_list_t_TypeDecl(std::string &Result,
5477 unsigned int ivar_count) {
5478 Result += "struct /*_ivar_list_t*/"; Result += " {\n";
5479 Result += "\tunsigned int entsize; // sizeof(struct _prop_t)\n";
5480 Result += "\tunsigned int count;\n";
5481 Result += "\tstruct _ivar_t ivar_list[";
5482 Result += utostr(ivar_count); Result += "];\n";
5483 Result += "}";
5484}
5485
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00005486static void Write_protocol_list_initializer(ASTContext *Context, std::string &Result,
5487 ArrayRef<ObjCProtocolDecl *> SuperProtocols,
5488 StringRef VarName,
5489 StringRef ProtocolName) {
5490 if (SuperProtocols.size() > 0) {
5491 Result += "\nstatic ";
5492 Write_protocol_list_t_TypeDecl(Result, SuperProtocols.size());
5493 Result += " "; Result += VarName;
5494 Result += ProtocolName;
5495 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
5496 Result += "\t"; Result += utostr(SuperProtocols.size()); Result += ",\n";
5497 for (unsigned i = 0, e = SuperProtocols.size(); i < e; i++) {
5498 ObjCProtocolDecl *SuperPD = SuperProtocols[i];
5499 Result += "\t&"; Result += "_OBJC_PROTOCOL_";
5500 Result += SuperPD->getNameAsString();
5501 if (i == e-1)
5502 Result += "\n};\n";
5503 else
5504 Result += ",\n";
5505 }
5506 }
5507}
5508
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005509static void Write_method_list_t_initializer(RewriteModernObjC &RewriteObj,
5510 ASTContext *Context, std::string &Result,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005511 ArrayRef<ObjCMethodDecl *> Methods,
5512 StringRef VarName,
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005513 StringRef TopLevelDeclName,
5514 bool MethodImpl) {
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005515 if (Methods.size() > 0) {
5516 Result += "\nstatic ";
5517 Write_method_list_t_TypeDecl(Result, Methods.size());
5518 Result += " "; Result += VarName;
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005519 Result += TopLevelDeclName;
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005520 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
5521 Result += "\t"; Result += "sizeof(_objc_method)"; Result += ",\n";
5522 Result += "\t"; Result += utostr(Methods.size()); Result += ",\n";
5523 for (unsigned i = 0, e = Methods.size(); i < e; i++) {
5524 ObjCMethodDecl *MD = Methods[i];
5525 if (i == 0)
5526 Result += "\t{{(struct objc_selector *)\"";
5527 else
5528 Result += "\t{(struct objc_selector *)\"";
5529 Result += (MD)->getSelector().getAsString(); Result += "\"";
5530 Result += ", ";
5531 std::string MethodTypeString;
5532 Context->getObjCEncodingForMethodDecl(MD, MethodTypeString);
5533 Result += "\""; Result += MethodTypeString; Result += "\"";
5534 Result += ", ";
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005535 if (!MethodImpl)
5536 Result += "0";
5537 else {
5538 Result += "(void *)";
5539 Result += RewriteObj.MethodInternalNames[MD];
5540 }
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005541 if (i == e-1)
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005542 Result += "}}\n";
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005543 else
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005544 Result += "},\n";
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005545 }
5546 Result += "};\n";
5547 }
5548}
5549
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005550static void Write_prop_list_t_initializer(RewriteModernObjC &RewriteObj,
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00005551 ASTContext *Context, std::string &Result,
5552 ArrayRef<ObjCPropertyDecl *> Properties,
5553 const Decl *Container,
5554 StringRef VarName,
5555 StringRef ProtocolName) {
5556 if (Properties.size() > 0) {
5557 Result += "\nstatic ";
5558 Write__prop_list_t_TypeDecl(Result, Properties.size());
5559 Result += " "; Result += VarName;
5560 Result += ProtocolName;
5561 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
5562 Result += "\t"; Result += "sizeof(_prop_t)"; Result += ",\n";
5563 Result += "\t"; Result += utostr(Properties.size()); Result += ",\n";
5564 for (unsigned i = 0, e = Properties.size(); i < e; i++) {
5565 ObjCPropertyDecl *PropDecl = Properties[i];
5566 if (i == 0)
5567 Result += "\t{{\"";
5568 else
5569 Result += "\t{\"";
5570 Result += PropDecl->getName(); Result += "\",";
5571 std::string PropertyTypeString, QuotePropertyTypeString;
5572 Context->getObjCEncodingForPropertyDecl(PropDecl, Container, PropertyTypeString);
5573 RewriteObj.QuoteDoublequotes(PropertyTypeString, QuotePropertyTypeString);
5574 Result += "\""; Result += QuotePropertyTypeString; Result += "\"";
5575 if (i == e-1)
5576 Result += "}}\n";
5577 else
5578 Result += "},\n";
5579 }
5580 Result += "};\n";
5581 }
5582}
5583
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00005584// Metadata flags
5585enum MetaDataDlags {
5586 CLS = 0x0,
5587 CLS_META = 0x1,
5588 CLS_ROOT = 0x2,
5589 OBJC2_CLS_HIDDEN = 0x10,
5590 CLS_EXCEPTION = 0x20,
5591
5592 /// (Obsolete) ARC-specific: this class has a .release_ivars method
5593 CLS_HAS_IVAR_RELEASER = 0x40,
5594 /// class was compiled with -fobjc-arr
5595 CLS_COMPILED_BY_ARC = 0x80 // (1<<7)
5596};
5597
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005598static void Write__class_ro_t_initializer(ASTContext *Context, std::string &Result,
5599 unsigned int flags,
5600 const std::string &InstanceStart,
5601 const std::string &InstanceSize,
5602 ArrayRef<ObjCMethodDecl *>baseMethods,
5603 ArrayRef<ObjCProtocolDecl *>baseProtocols,
5604 ArrayRef<ObjCIvarDecl *>ivars,
5605 ArrayRef<ObjCPropertyDecl *>Properties,
5606 StringRef VarName,
5607 StringRef ClassName) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005608 Result += "\nstatic struct _class_ro_t ";
5609 Result += VarName; Result += ClassName;
5610 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
5611 Result += "\t";
5612 Result += llvm::utostr(flags); Result += ", ";
5613 Result += InstanceStart; Result += ", ";
5614 Result += InstanceSize; Result += ", \n";
5615 Result += "\t";
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00005616 const llvm::Triple &Triple(Context->getTargetInfo().getTriple());
5617 if (Triple.getArch() == llvm::Triple::x86_64)
5618 // uint32_t const reserved; // only when building for 64bit targets
5619 Result += "(unsigned int)0, \n\t";
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005620 // const uint8_t * const ivarLayout;
5621 Result += "0, \n\t";
5622 Result += "\""; Result += ClassName; Result += "\",\n\t";
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00005623 bool metaclass = ((flags & CLS_META) != 0);
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005624 if (baseMethods.size() > 0) {
5625 Result += "(const struct _method_list_t *)&";
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00005626 if (metaclass)
5627 Result += "_OBJC_$_CLASS_METHODS_";
5628 else
5629 Result += "_OBJC_$_INSTANCE_METHODS_";
5630 Result += ClassName;
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005631 Result += ",\n\t";
5632 }
5633 else
5634 Result += "0, \n\t";
5635
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00005636 if (!metaclass && baseProtocols.size() > 0) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005637 Result += "(const struct _objc_protocol_list *)&";
5638 Result += "_OBJC_CLASS_PROTOCOLS_$_"; Result += ClassName;
5639 Result += ",\n\t";
5640 }
5641 else
5642 Result += "0, \n\t";
5643
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00005644 if (!metaclass && ivars.size() > 0) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005645 Result += "(const struct _ivar_list_t *)&";
5646 Result += "_OBJC_$_INSTANCE_VARIABLES_"; Result += ClassName;
5647 Result += ",\n\t";
5648 }
5649 else
5650 Result += "0, \n\t";
5651
5652 // weakIvarLayout
5653 Result += "0, \n\t";
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00005654 if (!metaclass && Properties.size() > 0) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005655 Result += "(const struct _prop_list_t *)&";
Fariborz Jahanianeeabf382012-02-16 21:57:59 +00005656 Result += "_OBJC_$_PROP_LIST_"; Result += ClassName;
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005657 Result += ",\n";
5658 }
5659 else
5660 Result += "0, \n";
5661
5662 Result += "};\n";
5663}
5664
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005665static void Write_class_t(ASTContext *Context, std::string &Result,
5666 StringRef VarName,
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00005667 const ObjCInterfaceDecl *CDecl, bool metaclass) {
5668 bool rootClass = (!CDecl->getSuperClass());
5669 const ObjCInterfaceDecl *RootClass = CDecl;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005670
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00005671 if (!rootClass) {
5672 // Find the Root class
5673 RootClass = CDecl->getSuperClass();
5674 while (RootClass->getSuperClass()) {
5675 RootClass = RootClass->getSuperClass();
5676 }
5677 }
5678
5679 if (metaclass && rootClass) {
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005680 // Need to handle a case of use of forward declaration.
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00005681 Result += "\n";
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00005682 Result += "extern \"C\" ";
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00005683 if (CDecl->getImplementation())
5684 Result += "__declspec(dllexport) ";
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00005685 Result += "struct _class_t OBJC_CLASS_$_";
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005686 Result += CDecl->getNameAsString();
5687 Result += ";\n";
5688 }
5689 // Also, for possibility of 'super' metadata class not having been defined yet.
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00005690 if (!rootClass) {
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00005691 Result += "\n";
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00005692 Result += "extern \"C\" ";
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00005693 if (CDecl->getSuperClass()->getImplementation())
5694 Result += "__declspec(dllexport) ";
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00005695 Result += "struct _class_t ";
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00005696 Result += VarName;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005697 Result += CDecl->getSuperClass()->getNameAsString();
5698 Result += ";\n";
Fariborz Jahanian452eac12012-03-20 21:09:58 +00005699
5700 if (metaclass) {
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00005701 Result += "extern \"C\" ";
Fariborz Jahanian452eac12012-03-20 21:09:58 +00005702 if (RootClass->getImplementation())
5703 Result += "__declspec(dllexport) ";
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00005704 Result += "struct _class_t ";
Fariborz Jahanian452eac12012-03-20 21:09:58 +00005705 Result += VarName;
5706 Result += RootClass->getNameAsString();
5707 Result += ";\n";
5708 }
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005709 }
5710
Fariborz Jahaniane57303c2012-03-10 00:39:34 +00005711 Result += "\n__declspec(dllexport) struct _class_t "; Result += VarName; Result += CDecl->getNameAsString();
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005712 Result += " __attribute__ ((used, section (\"__DATA,__objc_data\"))) = {\n";
5713 Result += "\t";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00005714 if (metaclass) {
5715 if (!rootClass) {
5716 Result += "0, // &"; Result += VarName;
5717 Result += RootClass->getNameAsString();
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005718 Result += ",\n\t";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00005719 Result += "0, // &"; Result += VarName;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005720 Result += CDecl->getSuperClass()->getNameAsString();
5721 Result += ",\n\t";
5722 }
5723 else {
Fariborz Jahanian452eac12012-03-20 21:09:58 +00005724 Result += "0, // &"; Result += VarName;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005725 Result += CDecl->getNameAsString();
5726 Result += ",\n\t";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00005727 Result += "0, // &OBJC_CLASS_$_"; Result += CDecl->getNameAsString();
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005728 Result += ",\n\t";
5729 }
5730 }
5731 else {
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00005732 Result += "0, // &OBJC_METACLASS_$_";
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005733 Result += CDecl->getNameAsString();
5734 Result += ",\n\t";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00005735 if (!rootClass) {
5736 Result += "0, // &"; Result += VarName;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005737 Result += CDecl->getSuperClass()->getNameAsString();
5738 Result += ",\n\t";
5739 }
5740 else
5741 Result += "0,\n\t";
5742 }
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00005743 Result += "0, // (void *)&_objc_empty_cache,\n\t";
5744 Result += "0, // unused, was (void *)&_objc_empty_vtable,\n\t";
5745 if (metaclass)
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005746 Result += "&_OBJC_METACLASS_RO_$_";
5747 else
5748 Result += "&_OBJC_CLASS_RO_$_";
5749 Result += CDecl->getNameAsString();
5750 Result += ",\n};\n";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00005751
5752 // Add static function to initialize some of the meta-data fields.
5753 // avoid doing it twice.
5754 if (metaclass)
5755 return;
5756
5757 const ObjCInterfaceDecl *SuperClass =
5758 rootClass ? CDecl : CDecl->getSuperClass();
5759
5760 Result += "static void OBJC_CLASS_SETUP_$_";
5761 Result += CDecl->getNameAsString();
5762 Result += "(void ) {\n";
5763 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
5764 Result += ".isa = "; Result += "&OBJC_METACLASS_$_";
Fariborz Jahanian452eac12012-03-20 21:09:58 +00005765 Result += RootClass->getNameAsString(); Result += ";\n";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00005766
5767 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
Fariborz Jahanian452eac12012-03-20 21:09:58 +00005768 Result += ".superclass = ";
5769 if (rootClass)
5770 Result += "&OBJC_CLASS_$_";
5771 else
5772 Result += "&OBJC_METACLASS_$_";
5773
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00005774 Result += SuperClass->getNameAsString(); Result += ";\n";
5775
5776 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
5777 Result += ".cache = "; Result += "&_objc_empty_cache"; Result += ";\n";
5778
5779 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
5780 Result += ".isa = "; Result += "&OBJC_METACLASS_$_";
5781 Result += CDecl->getNameAsString(); Result += ";\n";
5782
5783 if (!rootClass) {
5784 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
5785 Result += ".superclass = "; Result += "&OBJC_CLASS_$_";
5786 Result += SuperClass->getNameAsString(); Result += ";\n";
5787 }
5788
5789 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
5790 Result += ".cache = "; Result += "&_objc_empty_cache"; Result += ";\n";
5791 Result += "}\n";
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005792}
5793
Fariborz Jahanian61186122012-02-17 18:40:41 +00005794static void Write_category_t(RewriteModernObjC &RewriteObj, ASTContext *Context,
5795 std::string &Result,
Fariborz Jahaniane0335782012-03-27 18:41:05 +00005796 ObjCCategoryDecl *CatDecl,
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00005797 ObjCInterfaceDecl *ClassDecl,
Fariborz Jahanian61186122012-02-17 18:40:41 +00005798 ArrayRef<ObjCMethodDecl *> InstanceMethods,
5799 ArrayRef<ObjCMethodDecl *> ClassMethods,
5800 ArrayRef<ObjCProtocolDecl *> RefedProtocols,
5801 ArrayRef<ObjCPropertyDecl *> ClassProperties) {
Fariborz Jahaniane0335782012-03-27 18:41:05 +00005802 StringRef CatName = CatDecl->getName();
NAKAMURA Takumi20f89392012-03-21 03:21:46 +00005803 StringRef ClassName = ClassDecl->getName();
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00005804 // must declare an extern class object in case this class is not implemented
5805 // in this TU.
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00005806 Result += "\n";
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00005807 Result += "extern \"C\" ";
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00005808 if (ClassDecl->getImplementation())
5809 Result += "__declspec(dllexport) ";
5810
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00005811 Result += "struct _class_t ";
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00005812 Result += "OBJC_CLASS_$_"; Result += ClassName;
5813 Result += ";\n";
5814
Fariborz Jahanian61186122012-02-17 18:40:41 +00005815 Result += "\nstatic struct _category_t ";
5816 Result += "_OBJC_$_CATEGORY_";
5817 Result += ClassName; Result += "_$_"; Result += CatName;
5818 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = \n";
5819 Result += "{\n";
5820 Result += "\t\""; Result += ClassName; Result += "\",\n";
Fariborz Jahanian4b2fe6e2012-03-20 21:41:28 +00005821 Result += "\t0, // &"; Result += "OBJC_CLASS_$_"; Result += ClassName;
Fariborz Jahanian61186122012-02-17 18:40:41 +00005822 Result += ",\n";
5823 if (InstanceMethods.size() > 0) {
5824 Result += "\t(const struct _method_list_t *)&";
5825 Result += "_OBJC_$_CATEGORY_INSTANCE_METHODS_";
5826 Result += ClassName; Result += "_$_"; Result += CatName;
5827 Result += ",\n";
5828 }
5829 else
5830 Result += "\t0,\n";
5831
5832 if (ClassMethods.size() > 0) {
5833 Result += "\t(const struct _method_list_t *)&";
5834 Result += "_OBJC_$_CATEGORY_CLASS_METHODS_";
5835 Result += ClassName; Result += "_$_"; Result += CatName;
5836 Result += ",\n";
5837 }
5838 else
5839 Result += "\t0,\n";
5840
5841 if (RefedProtocols.size() > 0) {
5842 Result += "\t(const struct _protocol_list_t *)&";
5843 Result += "_OBJC_CATEGORY_PROTOCOLS_$_";
5844 Result += ClassName; Result += "_$_"; Result += CatName;
5845 Result += ",\n";
5846 }
5847 else
5848 Result += "\t0,\n";
5849
5850 if (ClassProperties.size() > 0) {
5851 Result += "\t(const struct _prop_list_t *)&"; Result += "_OBJC_$_PROP_LIST_";
5852 Result += ClassName; Result += "_$_"; Result += CatName;
5853 Result += ",\n";
5854 }
5855 else
5856 Result += "\t0,\n";
5857
5858 Result += "};\n";
Fariborz Jahanian4b2fe6e2012-03-20 21:41:28 +00005859
5860 // Add static function to initialize the class pointer in the category structure.
5861 Result += "static void OBJC_CATEGORY_SETUP_$_";
5862 Result += ClassDecl->getNameAsString();
5863 Result += "_$_";
5864 Result += CatName;
5865 Result += "(void ) {\n";
5866 Result += "\t_OBJC_$_CATEGORY_";
5867 Result += ClassDecl->getNameAsString();
5868 Result += "_$_";
5869 Result += CatName;
5870 Result += ".cls = "; Result += "&OBJC_CLASS_$_"; Result += ClassName;
5871 Result += ";\n}\n";
Fariborz Jahanian61186122012-02-17 18:40:41 +00005872}
5873
Fariborz Jahaniane0adbd82012-02-08 22:23:26 +00005874static void Write__extendedMethodTypes_initializer(RewriteModernObjC &RewriteObj,
5875 ASTContext *Context, std::string &Result,
5876 ArrayRef<ObjCMethodDecl *> Methods,
5877 StringRef VarName,
5878 StringRef ProtocolName) {
5879 if (Methods.size() == 0)
5880 return;
5881
5882 Result += "\nstatic const char *";
5883 Result += VarName; Result += ProtocolName;
5884 Result += " [] __attribute__ ((used, section (\"__DATA,__objc_const\"))) = \n";
5885 Result += "{\n";
5886 for (unsigned i = 0, e = Methods.size(); i < e; i++) {
5887 ObjCMethodDecl *MD = Methods[i];
5888 std::string MethodTypeString, QuoteMethodTypeString;
5889 Context->getObjCEncodingForMethodDecl(MD, MethodTypeString, true);
5890 RewriteObj.QuoteDoublequotes(MethodTypeString, QuoteMethodTypeString);
5891 Result += "\t\""; Result += QuoteMethodTypeString; Result += "\"";
5892 if (i == e-1)
5893 Result += "\n};\n";
5894 else {
5895 Result += ",\n";
5896 }
5897 }
5898}
5899
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00005900static void Write_IvarOffsetVar(ASTContext *Context,
5901 std::string &Result,
Fariborz Jahaniandb649232012-02-13 20:59:02 +00005902 ArrayRef<ObjCIvarDecl *> Ivars,
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00005903 ObjCInterfaceDecl *CDecl) {
Fariborz Jahaniandb649232012-02-13 20:59:02 +00005904 // FIXME. visibilty of offset symbols may have to be set; for Darwin
5905 // this is what happens:
5906 /**
5907 if (Ivar->getAccessControl() == ObjCIvarDecl::Private ||
5908 Ivar->getAccessControl() == ObjCIvarDecl::Package ||
5909 Class->getVisibility() == HiddenVisibility)
5910 Visibility shoud be: HiddenVisibility;
5911 else
5912 Visibility shoud be: DefaultVisibility;
5913 */
5914
Fariborz Jahanian07e52882012-02-13 21:34:45 +00005915 Result += "\n";
5916 for (unsigned i =0, e = Ivars.size(); i < e; i++) {
5917 ObjCIvarDecl *IvarDecl = Ivars[i];
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00005918 if (Context->getLangOpts().MicrosoftExt)
5919 Result += "__declspec(allocate(\".objc_ivar$B\")) ";
5920
5921 if (!Context->getLangOpts().MicrosoftExt ||
5922 IvarDecl->getAccessControl() == ObjCIvarDecl::Private ||
Fariborz Jahanian117591f2012-03-10 01:34:42 +00005923 IvarDecl->getAccessControl() == ObjCIvarDecl::Package)
Fariborz Jahaniand1c84d32012-03-10 00:53:02 +00005924 Result += "unsigned long int ";
5925 else
5926 Result += "__declspec(dllexport) unsigned long int ";
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00005927 WriteInternalIvarName(CDecl, IvarDecl, Result);
Fariborz Jahanian07e52882012-02-13 21:34:45 +00005928 Result += " __attribute__ ((used, section (\"__DATA,__objc_ivar\")))";
5929 Result += " = ";
5930 if (IvarDecl->isBitField()) {
5931 // FIXME: The hack below doesn't work for bitfields. For now, we simply
5932 // place all bitfields at offset 0.
5933 Result += "0;\n";
5934 }
5935 else {
Fariborz Jahaniandb649232012-02-13 20:59:02 +00005936 Result += "__OFFSETOFIVAR__(struct ";
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00005937 Result += CDecl->getNameAsString();
Fariborz Jahaniandb649232012-02-13 20:59:02 +00005938 Result += "_IMPL, ";
5939 Result += IvarDecl->getName(); Result += ");\n";
5940 }
5941 }
5942}
5943
Fariborz Jahanianae932952012-02-10 20:47:10 +00005944static void Write__ivar_list_t_initializer(RewriteModernObjC &RewriteObj,
5945 ASTContext *Context, std::string &Result,
5946 ArrayRef<ObjCIvarDecl *> Ivars,
5947 StringRef VarName,
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00005948 ObjCInterfaceDecl *CDecl) {
Fariborz Jahanianae932952012-02-10 20:47:10 +00005949 if (Ivars.size() > 0) {
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00005950 Write_IvarOffsetVar(Context, Result, Ivars, CDecl);
Fariborz Jahanian07e52882012-02-13 21:34:45 +00005951
Fariborz Jahanianae932952012-02-10 20:47:10 +00005952 Result += "\nstatic ";
5953 Write__ivar_list_t_TypeDecl(Result, Ivars.size());
5954 Result += " "; Result += VarName;
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00005955 Result += CDecl->getNameAsString();
Fariborz Jahanianae932952012-02-10 20:47:10 +00005956 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
5957 Result += "\t"; Result += "sizeof(_ivar_t)"; Result += ",\n";
5958 Result += "\t"; Result += utostr(Ivars.size()); Result += ",\n";
5959 for (unsigned i =0, e = Ivars.size(); i < e; i++) {
5960 ObjCIvarDecl *IvarDecl = Ivars[i];
5961 if (i == 0)
5962 Result += "\t{{";
5963 else
5964 Result += "\t {";
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00005965 Result += "(unsigned long int *)&";
5966 WriteInternalIvarName(CDecl, IvarDecl, Result);
Fariborz Jahaniandb649232012-02-13 20:59:02 +00005967 Result += ", ";
Fariborz Jahanianae932952012-02-10 20:47:10 +00005968
5969 Result += "\""; Result += IvarDecl->getName(); Result += "\", ";
5970 std::string IvarTypeString, QuoteIvarTypeString;
5971 Context->getObjCEncodingForType(IvarDecl->getType(), IvarTypeString,
5972 IvarDecl);
5973 RewriteObj.QuoteDoublequotes(IvarTypeString, QuoteIvarTypeString);
5974 Result += "\""; Result += QuoteIvarTypeString; Result += "\", ";
5975
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00005976 // FIXME. this alignment represents the host alignment and need be changed to
5977 // represent the target alignment.
5978 unsigned Align = Context->getTypeAlign(IvarDecl->getType())/8;
5979 Align = llvm::Log2_32(Align);
Fariborz Jahanianae932952012-02-10 20:47:10 +00005980 Result += llvm::utostr(Align); Result += ", ";
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00005981 CharUnits Size = Context->getTypeSizeInChars(IvarDecl->getType());
5982 Result += llvm::utostr(Size.getQuantity());
Fariborz Jahanianae932952012-02-10 20:47:10 +00005983 if (i == e-1)
5984 Result += "}}\n";
5985 else
5986 Result += "},\n";
5987 }
5988 Result += "};\n";
5989 }
5990}
5991
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005992/// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00005993void RewriteModernObjC::RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl,
5994 std::string &Result) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005995
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005996 // Do not synthesize the protocol more than once.
5997 if (ObjCSynthesizedProtocols.count(PDecl->getCanonicalDecl()))
5998 return;
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00005999 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006000
6001 if (ObjCProtocolDecl *Def = PDecl->getDefinition())
6002 PDecl = Def;
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006003 // Must write out all protocol definitions in current qualifier list,
6004 // and in their nested qualifiers before writing out current definition.
6005 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
6006 E = PDecl->protocol_end(); I != E; ++I)
6007 RewriteObjCProtocolMetaData(*I, Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006008
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006009 // Construct method lists.
6010 std::vector<ObjCMethodDecl *> InstanceMethods, ClassMethods;
6011 std::vector<ObjCMethodDecl *> OptInstanceMethods, OptClassMethods;
6012 for (ObjCProtocolDecl::instmeth_iterator
6013 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
6014 I != E; ++I) {
6015 ObjCMethodDecl *MD = *I;
6016 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
6017 OptInstanceMethods.push_back(MD);
6018 } else {
6019 InstanceMethods.push_back(MD);
6020 }
6021 }
6022
6023 for (ObjCProtocolDecl::classmeth_iterator
6024 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
6025 I != E; ++I) {
6026 ObjCMethodDecl *MD = *I;
6027 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
6028 OptClassMethods.push_back(MD);
6029 } else {
6030 ClassMethods.push_back(MD);
6031 }
6032 }
Fariborz Jahaniane0adbd82012-02-08 22:23:26 +00006033 std::vector<ObjCMethodDecl *> AllMethods;
6034 for (unsigned i = 0, e = InstanceMethods.size(); i < e; i++)
6035 AllMethods.push_back(InstanceMethods[i]);
6036 for (unsigned i = 0, e = ClassMethods.size(); i < e; i++)
6037 AllMethods.push_back(ClassMethods[i]);
6038 for (unsigned i = 0, e = OptInstanceMethods.size(); i < e; i++)
6039 AllMethods.push_back(OptInstanceMethods[i]);
6040 for (unsigned i = 0, e = OptClassMethods.size(); i < e; i++)
6041 AllMethods.push_back(OptClassMethods[i]);
6042
6043 Write__extendedMethodTypes_initializer(*this, Context, Result,
6044 AllMethods,
6045 "_OBJC_PROTOCOL_METHOD_TYPES_",
6046 PDecl->getNameAsString());
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006047 // Protocol's super protocol list
6048 std::vector<ObjCProtocolDecl *> SuperProtocols;
6049 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
6050 E = PDecl->protocol_end(); I != E; ++I)
6051 SuperProtocols.push_back(*I);
6052
6053 Write_protocol_list_initializer(Context, Result, SuperProtocols,
6054 "_OBJC_PROTOCOL_REFS_",
6055 PDecl->getNameAsString());
6056
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006057 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006058 "_OBJC_PROTOCOL_INSTANCE_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006059 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006060
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006061 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006062 "_OBJC_PROTOCOL_CLASS_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006063 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006064
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006065 Write_method_list_t_initializer(*this, Context, Result, OptInstanceMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006066 "_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006067 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006068
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006069 Write_method_list_t_initializer(*this, Context, Result, OptClassMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006070 "_OBJC_PROTOCOL_OPT_CLASS_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006071 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006072
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006073 // Protocol's property metadata.
6074 std::vector<ObjCPropertyDecl *> ProtocolProperties;
6075 for (ObjCContainerDecl::prop_iterator I = PDecl->prop_begin(),
6076 E = PDecl->prop_end(); I != E; ++I)
6077 ProtocolProperties.push_back(*I);
6078
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006079 Write_prop_list_t_initializer(*this, Context, Result, ProtocolProperties,
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006080 /* Container */0,
6081 "_OBJC_PROTOCOL_PROPERTIES_",
6082 PDecl->getNameAsString());
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006083
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006084 // Writer out root metadata for current protocol: struct _protocol_t
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00006085 Result += "\n";
6086 if (LangOpts.MicrosoftExt)
6087 Result += "__declspec(allocate(\".datacoal_nt$B\")) ";
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00006088 Result += "struct _protocol_t _OBJC_PROTOCOL_";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006089 Result += PDecl->getNameAsString();
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006090 Result += " __attribute__ ((used, section (\"__DATA,__datacoal_nt,coalesced\"))) = {\n";
6091 Result += "\t0,\n"; // id is; is null
6092 Result += "\t\""; Result += PDecl->getNameAsString(); Result += "\",\n";
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006093 if (SuperProtocols.size() > 0) {
6094 Result += "\t(const struct _protocol_list_t *)&"; Result += "_OBJC_PROTOCOL_REFS_";
6095 Result += PDecl->getNameAsString(); Result += ",\n";
6096 }
6097 else
6098 Result += "\t0,\n";
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006099 if (InstanceMethods.size() > 0) {
6100 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
6101 Result += PDecl->getNameAsString(); Result += ",\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006102 }
6103 else
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006104 Result += "\t0,\n";
6105
6106 if (ClassMethods.size() > 0) {
6107 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_CLASS_METHODS_";
6108 Result += PDecl->getNameAsString(); Result += ",\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006109 }
6110 else
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006111 Result += "\t0,\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006112
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006113 if (OptInstanceMethods.size() > 0) {
6114 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_";
6115 Result += PDecl->getNameAsString(); Result += ",\n";
6116 }
6117 else
6118 Result += "\t0,\n";
6119
6120 if (OptClassMethods.size() > 0) {
6121 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_CLASS_METHODS_";
6122 Result += PDecl->getNameAsString(); Result += ",\n";
6123 }
6124 else
6125 Result += "\t0,\n";
6126
6127 if (ProtocolProperties.size() > 0) {
6128 Result += "\t(const struct _prop_list_t *)&_OBJC_PROTOCOL_PROPERTIES_";
6129 Result += PDecl->getNameAsString(); Result += ",\n";
6130 }
6131 else
6132 Result += "\t0,\n";
6133
6134 Result += "\t"; Result += "sizeof(_protocol_t)"; Result += ",\n";
6135 Result += "\t0,\n";
6136
Fariborz Jahaniane0adbd82012-02-08 22:23:26 +00006137 if (AllMethods.size() > 0) {
6138 Result += "\t(const char **)&"; Result += "_OBJC_PROTOCOL_METHOD_TYPES_";
6139 Result += PDecl->getNameAsString();
6140 Result += "\n};\n";
6141 }
6142 else
6143 Result += "\t0\n};\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00006144
6145 // Use this protocol meta-data to build protocol list table in section
6146 // .objc_protolist$B
6147 // Unspecified visibility means 'private extern'.
6148 if (LangOpts.MicrosoftExt)
6149 Result += "__declspec(allocate(\".objc_protolist$B\")) ";
6150 Result += "struct _protocol_t *";
6151 Result += "_OBJC_LABEL_PROTOCOL_$_"; Result += PDecl->getNameAsString();
6152 Result += " = &_OBJC_PROTOCOL_"; Result += PDecl->getNameAsString();
6153 Result += ";\n";
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006154
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006155 // Mark this protocol as having been generated.
6156 if (!ObjCSynthesizedProtocols.insert(PDecl->getCanonicalDecl()))
6157 llvm_unreachable("protocol already synthesized");
6158
6159}
6160
6161void RewriteModernObjC::RewriteObjCProtocolListMetaData(
6162 const ObjCList<ObjCProtocolDecl> &Protocols,
6163 StringRef prefix, StringRef ClassName,
6164 std::string &Result) {
6165 if (Protocols.empty()) return;
6166
6167 for (unsigned i = 0; i != Protocols.size(); i++)
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006168 RewriteObjCProtocolMetaData(Protocols[i], Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006169
6170 // Output the top lovel protocol meta-data for the class.
6171 /* struct _objc_protocol_list {
6172 struct _objc_protocol_list *next;
6173 int protocol_count;
6174 struct _objc_protocol *class_protocols[];
6175 }
6176 */
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00006177 Result += "\n";
6178 if (LangOpts.MicrosoftExt)
6179 Result += "__declspec(allocate(\".cat_cls_meth$B\")) ";
6180 Result += "static struct {\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006181 Result += "\tstruct _objc_protocol_list *next;\n";
6182 Result += "\tint protocol_count;\n";
6183 Result += "\tstruct _objc_protocol *class_protocols[";
6184 Result += utostr(Protocols.size());
6185 Result += "];\n} _OBJC_";
6186 Result += prefix;
6187 Result += "_PROTOCOLS_";
6188 Result += ClassName;
6189 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
6190 "{\n\t0, ";
6191 Result += utostr(Protocols.size());
6192 Result += "\n";
6193
6194 Result += "\t,{&_OBJC_PROTOCOL_";
6195 Result += Protocols[0]->getNameAsString();
6196 Result += " \n";
6197
6198 for (unsigned i = 1; i != Protocols.size(); i++) {
6199 Result += "\t ,&_OBJC_PROTOCOL_";
6200 Result += Protocols[i]->getNameAsString();
6201 Result += "\n";
6202 }
6203 Result += "\t }\n};\n";
6204}
6205
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006206/// hasObjCExceptionAttribute - Return true if this class or any super
6207/// class has the __objc_exception__ attribute.
6208/// FIXME. Move this to ASTContext.cpp as it is also used for IRGen.
6209static bool hasObjCExceptionAttribute(ASTContext &Context,
6210 const ObjCInterfaceDecl *OID) {
6211 if (OID->hasAttr<ObjCExceptionAttr>())
6212 return true;
6213 if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
6214 return hasObjCExceptionAttribute(Context, Super);
6215 return false;
6216}
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006217
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006218void RewriteModernObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
6219 std::string &Result) {
6220 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
6221
6222 // Explicitly declared @interface's are already synthesized.
Fariborz Jahanianae932952012-02-10 20:47:10 +00006223 if (CDecl->isImplicitInterfaceDecl())
6224 assert(false &&
6225 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00006226
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00006227 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanianae932952012-02-10 20:47:10 +00006228 SmallVector<ObjCIvarDecl *, 8> IVars;
6229
6230 for (ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
6231 IVD; IVD = IVD->getNextIvar()) {
6232 // Ignore unnamed bit-fields.
6233 if (!IVD->getDeclName())
6234 continue;
6235 IVars.push_back(IVD);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006236 }
6237
Fariborz Jahanianae932952012-02-10 20:47:10 +00006238 Write__ivar_list_t_initializer(*this, Context, Result, IVars,
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006239 "_OBJC_$_INSTANCE_VARIABLES_",
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006240 CDecl);
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006241
6242 // Build _objc_method_list for class's instance methods if needed
6243 SmallVector<ObjCMethodDecl *, 32>
6244 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
6245
6246 // If any of our property implementations have associated getters or
6247 // setters, produce metadata for them as well.
6248 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
6249 PropEnd = IDecl->propimpl_end();
6250 Prop != PropEnd; ++Prop) {
6251 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
6252 continue;
6253 if (!(*Prop)->getPropertyIvarDecl())
6254 continue;
6255 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
6256 if (!PD)
6257 continue;
6258 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
6259 if (!Getter->isDefined())
6260 InstanceMethods.push_back(Getter);
6261 if (PD->isReadOnly())
6262 continue;
6263 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
6264 if (!Setter->isDefined())
6265 InstanceMethods.push_back(Setter);
6266 }
6267
6268 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
6269 "_OBJC_$_INSTANCE_METHODS_",
6270 IDecl->getNameAsString(), true);
6271
6272 SmallVector<ObjCMethodDecl *, 32>
6273 ClassMethods(IDecl->classmeth_begin(), IDecl->classmeth_end());
6274
6275 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
6276 "_OBJC_$_CLASS_METHODS_",
6277 IDecl->getNameAsString(), true);
Fariborz Jahanian0a525342012-02-14 19:31:35 +00006278
6279 // Protocols referenced in class declaration?
6280 // Protocol's super protocol list
6281 std::vector<ObjCProtocolDecl *> RefedProtocols;
6282 const ObjCList<ObjCProtocolDecl> &Protocols = CDecl->getReferencedProtocols();
6283 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
6284 E = Protocols.end();
6285 I != E; ++I) {
6286 RefedProtocols.push_back(*I);
6287 // Must write out all protocol definitions in current qualifier list,
6288 // and in their nested qualifiers before writing out current definition.
6289 RewriteObjCProtocolMetaData(*I, Result);
6290 }
6291
6292 Write_protocol_list_initializer(Context, Result,
6293 RefedProtocols,
6294 "_OBJC_CLASS_PROTOCOLS_$_",
6295 IDecl->getNameAsString());
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006296
6297 // Protocol's property metadata.
6298 std::vector<ObjCPropertyDecl *> ClassProperties;
6299 for (ObjCContainerDecl::prop_iterator I = CDecl->prop_begin(),
6300 E = CDecl->prop_end(); I != E; ++I)
6301 ClassProperties.push_back(*I);
6302
6303 Write_prop_list_t_initializer(*this, Context, Result, ClassProperties,
Fariborz Jahanian2df089d2012-03-22 17:39:35 +00006304 /* Container */IDecl,
Fariborz Jahanianeeabf382012-02-16 21:57:59 +00006305 "_OBJC_$_PROP_LIST_",
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006306 CDecl->getNameAsString());
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006307
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006308
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006309 // Data for initializing _class_ro_t metaclass meta-data
6310 uint32_t flags = CLS_META;
6311 std::string InstanceSize;
6312 std::string InstanceStart;
6313
6314
6315 bool classIsHidden = CDecl->getVisibility() == HiddenVisibility;
6316 if (classIsHidden)
6317 flags |= OBJC2_CLS_HIDDEN;
6318
6319 if (!CDecl->getSuperClass())
6320 // class is root
6321 flags |= CLS_ROOT;
6322 InstanceSize = "sizeof(struct _class_t)";
6323 InstanceStart = InstanceSize;
6324 Write__class_ro_t_initializer(Context, Result, flags,
6325 InstanceStart, InstanceSize,
6326 ClassMethods,
6327 0,
6328 0,
6329 0,
6330 "_OBJC_METACLASS_RO_$_",
6331 CDecl->getNameAsString());
6332
6333
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006334 // Data for initializing _class_ro_t meta-data
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006335 flags = CLS;
6336 if (classIsHidden)
6337 flags |= OBJC2_CLS_HIDDEN;
6338
6339 if (hasObjCExceptionAttribute(*Context, CDecl))
6340 flags |= CLS_EXCEPTION;
6341
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006342 if (!CDecl->getSuperClass())
6343 // class is root
6344 flags |= CLS_ROOT;
6345
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006346 InstanceSize.clear();
6347 InstanceStart.clear();
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006348 if (!ObjCSynthesizedStructs.count(CDecl)) {
6349 InstanceSize = "0";
6350 InstanceStart = "0";
6351 }
6352 else {
6353 InstanceSize = "sizeof(struct ";
6354 InstanceSize += CDecl->getNameAsString();
6355 InstanceSize += "_IMPL)";
6356
6357 ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
6358 if (IVD) {
6359 InstanceStart += "__OFFSETOFIVAR__(struct ";
6360 InstanceStart += CDecl->getNameAsString();
6361 InstanceStart += "_IMPL, ";
6362 InstanceStart += IVD->getNameAsString();
6363 InstanceStart += ")";
6364 }
6365 else
6366 InstanceStart = InstanceSize;
6367 }
6368 Write__class_ro_t_initializer(Context, Result, flags,
6369 InstanceStart, InstanceSize,
6370 InstanceMethods,
6371 RefedProtocols,
6372 IVars,
6373 ClassProperties,
6374 "_OBJC_CLASS_RO_$_",
6375 CDecl->getNameAsString());
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006376
6377 Write_class_t(Context, Result,
6378 "OBJC_METACLASS_$_",
6379 CDecl, /*metaclass*/true);
6380
6381 Write_class_t(Context, Result,
6382 "OBJC_CLASS_$_",
6383 CDecl, /*metaclass*/false);
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006384
6385 if (ImplementationIsNonLazy(IDecl))
6386 DefinedNonLazyClasses.push_back(CDecl);
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006387
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006388}
6389
Fariborz Jahaniane0335782012-03-27 18:41:05 +00006390void RewriteModernObjC::RewriteClassSetupInitHook(std::string &Result) {
6391 int ClsDefCount = ClassImplementation.size();
6392 if (!ClsDefCount)
6393 return;
6394 Result += "#pragma section(\".objc_inithooks$B\", long, read, write)\n";
6395 Result += "__declspec(allocate(\".objc_inithooks$B\")) ";
6396 Result += "static void *OBJC_CLASS_SETUP[] = {\n";
6397 for (int i = 0; i < ClsDefCount; i++) {
6398 ObjCImplementationDecl *IDecl = ClassImplementation[i];
6399 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
6400 Result += "\t(void *)&OBJC_CLASS_SETUP_$_";
6401 Result += CDecl->getName(); Result += ",\n";
6402 }
6403 Result += "};\n";
6404}
6405
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006406void RewriteModernObjC::RewriteMetaDataIntoBuffer(std::string &Result) {
6407 int ClsDefCount = ClassImplementation.size();
6408 int CatDefCount = CategoryImplementation.size();
6409
6410 // For each implemented class, write out all its meta data.
6411 for (int i = 0; i < ClsDefCount; i++)
6412 RewriteObjCClassMetaData(ClassImplementation[i], Result);
6413
Fariborz Jahaniane0335782012-03-27 18:41:05 +00006414 RewriteClassSetupInitHook(Result);
6415
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006416 // For each implemented category, write out all its meta data.
6417 for (int i = 0; i < CatDefCount; i++)
6418 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
6419
Fariborz Jahaniane0335782012-03-27 18:41:05 +00006420 RewriteCategorySetupInitHook(Result);
6421
Fariborz Jahaniandf795672012-02-17 00:06:14 +00006422 if (ClsDefCount > 0) {
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00006423 if (LangOpts.MicrosoftExt)
6424 Result += "__declspec(allocate(\".objc_classlist$B\")) ";
Fariborz Jahaniandf795672012-02-17 00:06:14 +00006425 Result += "static struct _class_t *L_OBJC_LABEL_CLASS_$ [";
6426 Result += llvm::utostr(ClsDefCount); Result += "]";
6427 Result +=
6428 " __attribute__((used, section (\"__DATA, __objc_classlist,"
6429 "regular,no_dead_strip\")))= {\n";
6430 for (int i = 0; i < ClsDefCount; i++) {
6431 Result += "\t&OBJC_CLASS_$_";
6432 Result += ClassImplementation[i]->getNameAsString();
6433 Result += ",\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006434 }
Fariborz Jahaniandf795672012-02-17 00:06:14 +00006435 Result += "};\n";
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006436
6437 if (!DefinedNonLazyClasses.empty()) {
6438 if (LangOpts.MicrosoftExt)
6439 Result += "__declspec(allocate(\".objc_nlclslist$B\")) \n";
6440 Result += "static struct _class_t *_OBJC_LABEL_NONLAZY_CLASS_$[] = {\n\t";
6441 for (unsigned i = 0, e = DefinedNonLazyClasses.size(); i < e; i++) {
6442 Result += "\t&OBJC_CLASS_$_"; Result += DefinedNonLazyClasses[i]->getNameAsString();
6443 Result += ",\n";
6444 }
6445 Result += "};\n";
6446 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006447 }
Fariborz Jahanian61186122012-02-17 18:40:41 +00006448
6449 if (CatDefCount > 0) {
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00006450 if (LangOpts.MicrosoftExt)
6451 Result += "__declspec(allocate(\".objc_catlist$B\")) ";
Fariborz Jahanian61186122012-02-17 18:40:41 +00006452 Result += "static struct _category_t *L_OBJC_LABEL_CATEGORY_$ [";
6453 Result += llvm::utostr(CatDefCount); Result += "]";
6454 Result +=
6455 " __attribute__((used, section (\"__DATA, __objc_catlist,"
6456 "regular,no_dead_strip\")))= {\n";
6457 for (int i = 0; i < CatDefCount; i++) {
6458 Result += "\t&_OBJC_$_CATEGORY_";
6459 Result +=
6460 CategoryImplementation[i]->getClassInterface()->getNameAsString();
6461 Result += "_$_";
6462 Result += CategoryImplementation[i]->getNameAsString();
6463 Result += ",\n";
6464 }
6465 Result += "};\n";
6466 }
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006467
6468 if (!DefinedNonLazyCategories.empty()) {
6469 if (LangOpts.MicrosoftExt)
6470 Result += "__declspec(allocate(\".objc_nlcatlist$B\")) \n";
6471 Result += "static struct _category_t *_OBJC_LABEL_NONLAZY_CATEGORY_$[] = {\n\t";
6472 for (unsigned i = 0, e = DefinedNonLazyCategories.size(); i < e; i++) {
6473 Result += "\t&_OBJC_$_CATEGORY_";
6474 Result +=
6475 DefinedNonLazyCategories[i]->getClassInterface()->getNameAsString();
6476 Result += "_$_";
6477 Result += DefinedNonLazyCategories[i]->getNameAsString();
6478 Result += ",\n";
6479 }
6480 Result += "};\n";
6481 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006482}
6483
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00006484void RewriteModernObjC::WriteImageInfo(std::string &Result) {
6485 if (LangOpts.MicrosoftExt)
6486 Result += "__declspec(allocate(\".objc_imageinfo$B\")) \n";
6487
6488 Result += "static struct IMAGE_INFO { unsigned version; unsigned flag; } ";
6489 // version 0, ObjCABI is 2
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00006490 Result += "_OBJC_IMAGE_INFO = { 0, 2 };\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00006491}
6492
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006493/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
6494/// implementation.
6495void RewriteModernObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
6496 std::string &Result) {
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00006497 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006498 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
6499 // Find category declaration for this implementation.
Fariborz Jahanian61186122012-02-17 18:40:41 +00006500 ObjCCategoryDecl *CDecl=0;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006501 for (CDecl = ClassDecl->getCategoryList(); CDecl;
6502 CDecl = CDecl->getNextClassCategory())
6503 if (CDecl->getIdentifier() == IDecl->getIdentifier())
6504 break;
6505
6506 std::string FullCategoryName = ClassDecl->getNameAsString();
Fariborz Jahanian61186122012-02-17 18:40:41 +00006507 FullCategoryName += "_$_";
6508 FullCategoryName += CDecl->getNameAsString();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006509
6510 // Build _objc_method_list for class's instance methods if needed
6511 SmallVector<ObjCMethodDecl *, 32>
6512 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
6513
6514 // If any of our property implementations have associated getters or
6515 // setters, produce metadata for them as well.
6516 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
6517 PropEnd = IDecl->propimpl_end();
6518 Prop != PropEnd; ++Prop) {
6519 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
6520 continue;
6521 if (!(*Prop)->getPropertyIvarDecl())
6522 continue;
6523 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
6524 if (!PD)
6525 continue;
6526 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
6527 InstanceMethods.push_back(Getter);
6528 if (PD->isReadOnly())
6529 continue;
6530 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
6531 InstanceMethods.push_back(Setter);
6532 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006533
Fariborz Jahanian61186122012-02-17 18:40:41 +00006534 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
6535 "_OBJC_$_CATEGORY_INSTANCE_METHODS_",
6536 FullCategoryName, true);
6537
6538 SmallVector<ObjCMethodDecl *, 32>
6539 ClassMethods(IDecl->classmeth_begin(), IDecl->classmeth_end());
6540
6541 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
6542 "_OBJC_$_CATEGORY_CLASS_METHODS_",
6543 FullCategoryName, true);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006544
6545 // Protocols referenced in class declaration?
Fariborz Jahanian61186122012-02-17 18:40:41 +00006546 // Protocol's super protocol list
6547 std::vector<ObjCProtocolDecl *> RefedProtocols;
Argyrios Kyrtzidisa5f44412012-03-13 01:09:41 +00006548 for (ObjCInterfaceDecl::protocol_iterator I = CDecl->protocol_begin(),
6549 E = CDecl->protocol_end();
6550
6551 I != E; ++I) {
Fariborz Jahanian61186122012-02-17 18:40:41 +00006552 RefedProtocols.push_back(*I);
6553 // Must write out all protocol definitions in current qualifier list,
6554 // and in their nested qualifiers before writing out current definition.
6555 RewriteObjCProtocolMetaData(*I, Result);
6556 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006557
Fariborz Jahanian61186122012-02-17 18:40:41 +00006558 Write_protocol_list_initializer(Context, Result,
6559 RefedProtocols,
6560 "_OBJC_CATEGORY_PROTOCOLS_$_",
6561 FullCategoryName);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006562
Fariborz Jahanian61186122012-02-17 18:40:41 +00006563 // Protocol's property metadata.
6564 std::vector<ObjCPropertyDecl *> ClassProperties;
6565 for (ObjCContainerDecl::prop_iterator I = CDecl->prop_begin(),
6566 E = CDecl->prop_end(); I != E; ++I)
6567 ClassProperties.push_back(*I);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006568
Fariborz Jahanian61186122012-02-17 18:40:41 +00006569 Write_prop_list_t_initializer(*this, Context, Result, ClassProperties,
6570 /* Container */0,
6571 "_OBJC_$_PROP_LIST_",
6572 FullCategoryName);
6573
6574 Write_category_t(*this, Context, Result,
Fariborz Jahaniane0335782012-03-27 18:41:05 +00006575 CDecl,
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006576 ClassDecl,
Fariborz Jahanian61186122012-02-17 18:40:41 +00006577 InstanceMethods,
6578 ClassMethods,
6579 RefedProtocols,
6580 ClassProperties);
6581
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006582 // Determine if this category is also "non-lazy".
6583 if (ImplementationIsNonLazy(IDecl))
6584 DefinedNonLazyCategories.push_back(CDecl);
Fariborz Jahaniane0335782012-03-27 18:41:05 +00006585
6586}
6587
6588void RewriteModernObjC::RewriteCategorySetupInitHook(std::string &Result) {
6589 int CatDefCount = CategoryImplementation.size();
6590 if (!CatDefCount)
6591 return;
6592 Result += "#pragma section(\".objc_inithooks$B\", long, read, write)\n";
6593 Result += "__declspec(allocate(\".objc_inithooks$B\")) ";
6594 Result += "static void *OBJC_CATEGORY_SETUP[] = {\n";
6595 for (int i = 0; i < CatDefCount; i++) {
6596 ObjCCategoryImplDecl *IDecl = CategoryImplementation[i];
6597 ObjCCategoryDecl *CatDecl= IDecl->getCategoryDecl();
6598 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
6599 Result += "\t(void *)&OBJC_CATEGORY_SETUP_$_";
6600 Result += ClassDecl->getName();
6601 Result += "_$_";
6602 Result += CatDecl->getName();
6603 Result += ",\n";
6604 }
6605 Result += "};\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006606}
6607
6608// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
6609/// class methods.
6610template<typename MethodIterator>
6611void RewriteModernObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
6612 MethodIterator MethodEnd,
6613 bool IsInstanceMethod,
6614 StringRef prefix,
6615 StringRef ClassName,
6616 std::string &Result) {
6617 if (MethodBegin == MethodEnd) return;
6618
6619 if (!objc_impl_method) {
6620 /* struct _objc_method {
6621 SEL _cmd;
6622 char *method_types;
6623 void *_imp;
6624 }
6625 */
6626 Result += "\nstruct _objc_method {\n";
6627 Result += "\tSEL _cmd;\n";
6628 Result += "\tchar *method_types;\n";
6629 Result += "\tvoid *_imp;\n";
6630 Result += "};\n";
6631
6632 objc_impl_method = true;
6633 }
6634
6635 // Build _objc_method_list for class's methods if needed
6636
6637 /* struct {
6638 struct _objc_method_list *next_method;
6639 int method_count;
6640 struct _objc_method method_list[];
6641 }
6642 */
6643 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00006644 Result += "\n";
6645 if (LangOpts.MicrosoftExt) {
6646 if (IsInstanceMethod)
6647 Result += "__declspec(allocate(\".inst_meth$B\")) ";
6648 else
6649 Result += "__declspec(allocate(\".cls_meth$B\")) ";
6650 }
6651 Result += "static struct {\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006652 Result += "\tstruct _objc_method_list *next_method;\n";
6653 Result += "\tint method_count;\n";
6654 Result += "\tstruct _objc_method method_list[";
6655 Result += utostr(NumMethods);
6656 Result += "];\n} _OBJC_";
6657 Result += prefix;
6658 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
6659 Result += "_METHODS_";
6660 Result += ClassName;
6661 Result += " __attribute__ ((used, section (\"__OBJC, __";
6662 Result += IsInstanceMethod ? "inst" : "cls";
6663 Result += "_meth\")))= ";
6664 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
6665
6666 Result += "\t,{{(SEL)\"";
6667 Result += (*MethodBegin)->getSelector().getAsString().c_str();
6668 std::string MethodTypeString;
6669 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
6670 Result += "\", \"";
6671 Result += MethodTypeString;
6672 Result += "\", (void *)";
6673 Result += MethodInternalNames[*MethodBegin];
6674 Result += "}\n";
6675 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
6676 Result += "\t ,{(SEL)\"";
6677 Result += (*MethodBegin)->getSelector().getAsString().c_str();
6678 std::string MethodTypeString;
6679 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
6680 Result += "\", \"";
6681 Result += MethodTypeString;
6682 Result += "\", (void *)";
6683 Result += MethodInternalNames[*MethodBegin];
6684 Result += "}\n";
6685 }
6686 Result += "\t }\n};\n";
6687}
6688
6689Stmt *RewriteModernObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) {
6690 SourceRange OldRange = IV->getSourceRange();
6691 Expr *BaseExpr = IV->getBase();
6692
6693 // Rewrite the base, but without actually doing replaces.
6694 {
6695 DisableReplaceStmtScope S(*this);
6696 BaseExpr = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(BaseExpr));
6697 IV->setBase(BaseExpr);
6698 }
6699
6700 ObjCIvarDecl *D = IV->getDecl();
6701
6702 Expr *Replacement = IV;
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00006703
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006704 if (BaseExpr->getType()->isObjCObjectPointerType()) {
6705 const ObjCInterfaceType *iFaceDecl =
6706 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
6707 assert(iFaceDecl && "RewriteObjCIvarRefExpr - iFaceDecl is null");
6708 // lookup which class implements the instance variable.
6709 ObjCInterfaceDecl *clsDeclared = 0;
6710 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
6711 clsDeclared);
6712 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
6713
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00006714 // Build name of symbol holding ivar offset.
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006715 std::string IvarOffsetName;
6716 WriteInternalIvarName(clsDeclared, D, IvarOffsetName);
6717
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00006718 ReferencedIvars[clsDeclared].insert(D);
6719
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00006720 // cast offset to "char *".
6721 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context,
6722 Context->getPointerType(Context->CharTy),
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006723 CK_BitCast,
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00006724 BaseExpr);
6725 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
6726 SourceLocation(), &Context->Idents.get(IvarOffsetName),
6727 Context->UnsignedLongTy, 0, SC_Extern, SC_None);
John McCallf4b88a42012-03-10 09:33:50 +00006728 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, false,
6729 Context->UnsignedLongTy, VK_LValue,
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00006730 SourceLocation());
6731 BinaryOperator *addExpr =
6732 new (Context) BinaryOperator(castExpr, DRE, BO_Add,
6733 Context->getPointerType(Context->CharTy),
6734 VK_RValue, OK_Ordinary, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006735 // Don't forget the parens to enforce the proper binding.
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00006736 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(),
6737 SourceLocation(),
6738 addExpr);
Fariborz Jahanian0d6e22a2012-02-24 17:35:35 +00006739 QualType IvarT = D->getType();
Fariborz Jahanian8e0913d2012-02-29 00:26:20 +00006740 convertObjCTypeToCStyleType(IvarT);
Fariborz Jahanian0d6e22a2012-02-24 17:35:35 +00006741 QualType castT = Context->getPointerType(IvarT);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006742
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00006743 castExpr = NoTypeInfoCStyleCastExpr(Context,
6744 castT,
6745 CK_BitCast,
6746 PE);
Fariborz Jahanian8e0913d2012-02-29 00:26:20 +00006747 Expr *Exp = new (Context) UnaryOperator(castExpr, UO_Deref, IvarT,
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00006748 VK_LValue, OK_Ordinary,
6749 SourceLocation());
6750 PE = new (Context) ParenExpr(OldRange.getBegin(),
6751 OldRange.getEnd(),
6752 Exp);
6753
6754 Replacement = PE;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006755 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006756
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00006757 ReplaceStmtWithRange(IV, Replacement, OldRange);
6758 return Replacement;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006759}