blob: ec7089af575ed56d2304770a8bcd396ac09074da [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";
3220 if (LangOpts.MicrosoftExt)
3221 Result += "__declspec(allocate(\".objc_ivar$B\")) ";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00003222 Result += "extern \"C\" ";
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00003223 if (LangOpts.MicrosoftExt &&
3224 IvarDecl->getAccessControl() != ObjCIvarDecl::Private &&
Fariborz Jahanian297976d2012-03-29 17:51:09 +00003225 IvarDecl->getAccessControl() != ObjCIvarDecl::Package)
3226 Result += "__declspec(dllimport) ";
3227
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00003228 Result += "unsigned long ";
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00003229 WriteInternalIvarName(CDecl, IvarDecl, Result);
3230 Result += ";";
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00003231 }
3232}
3233
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003234//===----------------------------------------------------------------------===//
3235// Meta Data Emission
3236//===----------------------------------------------------------------------===//
3237
3238
3239/// RewriteImplementations - This routine rewrites all method implementations
3240/// and emits meta-data.
3241
3242void RewriteModernObjC::RewriteImplementations() {
3243 int ClsDefCount = ClassImplementation.size();
3244 int CatDefCount = CategoryImplementation.size();
3245
3246 // Rewrite implemented methods
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00003247 for (int i = 0; i < ClsDefCount; i++) {
3248 ObjCImplementationDecl *OIMP = ClassImplementation[i];
3249 ObjCInterfaceDecl *CDecl = OIMP->getClassInterface();
3250 if (CDecl->isImplicitInterfaceDecl())
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +00003251 assert(false &&
3252 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00003253 RewriteImplementationDecl(OIMP);
3254 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003255
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00003256 for (int i = 0; i < CatDefCount; i++) {
3257 ObjCCategoryImplDecl *CIMP = CategoryImplementation[i];
3258 ObjCInterfaceDecl *CDecl = CIMP->getClassInterface();
3259 if (CDecl->isImplicitInterfaceDecl())
3260 assert(false &&
3261 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00003262 RewriteImplementationDecl(CIMP);
3263 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003264}
3265
3266void RewriteModernObjC::RewriteByRefString(std::string &ResultStr,
3267 const std::string &Name,
3268 ValueDecl *VD, bool def) {
3269 assert(BlockByRefDeclNo.count(VD) &&
3270 "RewriteByRefString: ByRef decl missing");
3271 if (def)
3272 ResultStr += "struct ";
3273 ResultStr += "__Block_byref_" + Name +
3274 "_" + utostr(BlockByRefDeclNo[VD]) ;
3275}
3276
3277static bool HasLocalVariableExternalStorage(ValueDecl *VD) {
3278 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
3279 return (Var->isFunctionOrMethodVarDecl() && !Var->hasLocalStorage());
3280 return false;
3281}
3282
3283std::string RewriteModernObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
3284 StringRef funcName,
3285 std::string Tag) {
3286 const FunctionType *AFT = CE->getFunctionType();
3287 QualType RT = AFT->getResultType();
3288 std::string StructRef = "struct " + Tag;
3289 std::string S = "static " + RT.getAsString(Context->getPrintingPolicy()) + " __" +
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00003290 funcName.str() + "_block_func_" + utostr(i);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003291
3292 BlockDecl *BD = CE->getBlockDecl();
3293
3294 if (isa<FunctionNoProtoType>(AFT)) {
3295 // No user-supplied arguments. Still need to pass in a pointer to the
3296 // block (to reference imported block decl refs).
3297 S += "(" + StructRef + " *__cself)";
3298 } else if (BD->param_empty()) {
3299 S += "(" + StructRef + " *__cself)";
3300 } else {
3301 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
3302 assert(FT && "SynthesizeBlockFunc: No function proto");
3303 S += '(';
3304 // first add the implicit argument.
3305 S += StructRef + " *__cself, ";
3306 std::string ParamStr;
3307 for (BlockDecl::param_iterator AI = BD->param_begin(),
3308 E = BD->param_end(); AI != E; ++AI) {
3309 if (AI != BD->param_begin()) S += ", ";
3310 ParamStr = (*AI)->getNameAsString();
3311 QualType QT = (*AI)->getType();
Fariborz Jahanian2610f902012-03-27 16:42:20 +00003312 (void)convertBlockPointerToFunctionPointer(QT);
3313 QT.getAsStringInternal(ParamStr, Context->getPrintingPolicy());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003314 S += ParamStr;
3315 }
3316 if (FT->isVariadic()) {
3317 if (!BD->param_empty()) S += ", ";
3318 S += "...";
3319 }
3320 S += ')';
3321 }
3322 S += " {\n";
3323
3324 // Create local declarations to avoid rewriting all closure decl ref exprs.
3325 // First, emit a declaration for all "by ref" decls.
3326 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3327 E = BlockByRefDecls.end(); I != E; ++I) {
3328 S += " ";
3329 std::string Name = (*I)->getNameAsString();
3330 std::string TypeString;
3331 RewriteByRefString(TypeString, Name, (*I));
3332 TypeString += " *";
3333 Name = TypeString + Name;
3334 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
3335 }
3336 // Next, emit a declaration for all "by copy" declarations.
3337 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3338 E = BlockByCopyDecls.end(); I != E; ++I) {
3339 S += " ";
3340 // Handle nested closure invocation. For example:
3341 //
3342 // void (^myImportedClosure)(void);
3343 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
3344 //
3345 // void (^anotherClosure)(void);
3346 // anotherClosure = ^(void) {
3347 // myImportedClosure(); // import and invoke the closure
3348 // };
3349 //
3350 if (isTopLevelBlockPointerType((*I)->getType())) {
3351 RewriteBlockPointerTypeVariable(S, (*I));
3352 S += " = (";
3353 RewriteBlockPointerType(S, (*I)->getType());
3354 S += ")";
3355 S += "__cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
3356 }
3357 else {
3358 std::string Name = (*I)->getNameAsString();
3359 QualType QT = (*I)->getType();
3360 if (HasLocalVariableExternalStorage(*I))
3361 QT = Context->getPointerType(QT);
3362 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
3363 S += Name + " = __cself->" +
3364 (*I)->getNameAsString() + "; // bound by copy\n";
3365 }
3366 }
3367 std::string RewrittenStr = RewrittenBlockExprs[CE];
3368 const char *cstr = RewrittenStr.c_str();
3369 while (*cstr++ != '{') ;
3370 S += cstr;
3371 S += "\n";
3372 return S;
3373}
3374
3375std::string RewriteModernObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
3376 StringRef funcName,
3377 std::string Tag) {
3378 std::string StructRef = "struct " + Tag;
3379 std::string S = "static void __";
3380
3381 S += funcName;
3382 S += "_block_copy_" + utostr(i);
3383 S += "(" + StructRef;
3384 S += "*dst, " + StructRef;
3385 S += "*src) {";
3386 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
3387 E = ImportedBlockDecls.end(); I != E; ++I) {
3388 ValueDecl *VD = (*I);
3389 S += "_Block_object_assign((void*)&dst->";
3390 S += (*I)->getNameAsString();
3391 S += ", (void*)src->";
3392 S += (*I)->getNameAsString();
3393 if (BlockByRefDeclsPtrSet.count((*I)))
3394 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
3395 else if (VD->getType()->isBlockPointerType())
3396 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
3397 else
3398 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
3399 }
3400 S += "}\n";
3401
3402 S += "\nstatic void __";
3403 S += funcName;
3404 S += "_block_dispose_" + utostr(i);
3405 S += "(" + StructRef;
3406 S += "*src) {";
3407 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
3408 E = ImportedBlockDecls.end(); I != E; ++I) {
3409 ValueDecl *VD = (*I);
3410 S += "_Block_object_dispose((void*)src->";
3411 S += (*I)->getNameAsString();
3412 if (BlockByRefDeclsPtrSet.count((*I)))
3413 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
3414 else if (VD->getType()->isBlockPointerType())
3415 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
3416 else
3417 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
3418 }
3419 S += "}\n";
3420 return S;
3421}
3422
3423std::string RewriteModernObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
3424 std::string Desc) {
3425 std::string S = "\nstruct " + Tag;
3426 std::string Constructor = " " + Tag;
3427
3428 S += " {\n struct __block_impl impl;\n";
3429 S += " struct " + Desc;
3430 S += "* Desc;\n";
3431
3432 Constructor += "(void *fp, "; // Invoke function pointer.
3433 Constructor += "struct " + Desc; // Descriptor pointer.
3434 Constructor += " *desc";
3435
3436 if (BlockDeclRefs.size()) {
3437 // Output all "by copy" declarations.
3438 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3439 E = BlockByCopyDecls.end(); I != E; ++I) {
3440 S += " ";
3441 std::string FieldName = (*I)->getNameAsString();
3442 std::string ArgName = "_" + FieldName;
3443 // Handle nested closure invocation. For example:
3444 //
3445 // void (^myImportedBlock)(void);
3446 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
3447 //
3448 // void (^anotherBlock)(void);
3449 // anotherBlock = ^(void) {
3450 // myImportedBlock(); // import and invoke the closure
3451 // };
3452 //
3453 if (isTopLevelBlockPointerType((*I)->getType())) {
3454 S += "struct __block_impl *";
3455 Constructor += ", void *" + ArgName;
3456 } else {
3457 QualType QT = (*I)->getType();
3458 if (HasLocalVariableExternalStorage(*I))
3459 QT = Context->getPointerType(QT);
3460 QT.getAsStringInternal(FieldName, Context->getPrintingPolicy());
3461 QT.getAsStringInternal(ArgName, Context->getPrintingPolicy());
3462 Constructor += ", " + ArgName;
3463 }
3464 S += FieldName + ";\n";
3465 }
3466 // Output all "by ref" declarations.
3467 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3468 E = BlockByRefDecls.end(); I != E; ++I) {
3469 S += " ";
3470 std::string FieldName = (*I)->getNameAsString();
3471 std::string ArgName = "_" + FieldName;
3472 {
3473 std::string TypeString;
3474 RewriteByRefString(TypeString, FieldName, (*I));
3475 TypeString += " *";
3476 FieldName = TypeString + FieldName;
3477 ArgName = TypeString + ArgName;
3478 Constructor += ", " + ArgName;
3479 }
3480 S += FieldName + "; // by ref\n";
3481 }
3482 // Finish writing the constructor.
3483 Constructor += ", int flags=0)";
3484 // Initialize all "by copy" arguments.
3485 bool firsTime = true;
3486 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3487 E = BlockByCopyDecls.end(); I != E; ++I) {
3488 std::string Name = (*I)->getNameAsString();
3489 if (firsTime) {
3490 Constructor += " : ";
3491 firsTime = false;
3492 }
3493 else
3494 Constructor += ", ";
3495 if (isTopLevelBlockPointerType((*I)->getType()))
3496 Constructor += Name + "((struct __block_impl *)_" + Name + ")";
3497 else
3498 Constructor += Name + "(_" + Name + ")";
3499 }
3500 // Initialize all "by ref" arguments.
3501 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3502 E = BlockByRefDecls.end(); I != E; ++I) {
3503 std::string Name = (*I)->getNameAsString();
3504 if (firsTime) {
3505 Constructor += " : ";
3506 firsTime = false;
3507 }
3508 else
3509 Constructor += ", ";
3510 Constructor += Name + "(_" + Name + "->__forwarding)";
3511 }
3512
3513 Constructor += " {\n";
3514 if (GlobalVarDecl)
3515 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
3516 else
3517 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
3518 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3519
3520 Constructor += " Desc = desc;\n";
3521 } else {
3522 // Finish writing the constructor.
3523 Constructor += ", int flags=0) {\n";
3524 if (GlobalVarDecl)
3525 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
3526 else
3527 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
3528 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3529 Constructor += " Desc = desc;\n";
3530 }
3531 Constructor += " ";
3532 Constructor += "}\n";
3533 S += Constructor;
3534 S += "};\n";
3535 return S;
3536}
3537
3538std::string RewriteModernObjC::SynthesizeBlockDescriptor(std::string DescTag,
3539 std::string ImplTag, int i,
3540 StringRef FunName,
3541 unsigned hasCopy) {
3542 std::string S = "\nstatic struct " + DescTag;
3543
3544 S += " {\n unsigned long reserved;\n";
3545 S += " unsigned long Block_size;\n";
3546 if (hasCopy) {
3547 S += " void (*copy)(struct ";
3548 S += ImplTag; S += "*, struct ";
3549 S += ImplTag; S += "*);\n";
3550
3551 S += " void (*dispose)(struct ";
3552 S += ImplTag; S += "*);\n";
3553 }
3554 S += "} ";
3555
3556 S += DescTag + "_DATA = { 0, sizeof(struct ";
3557 S += ImplTag + ")";
3558 if (hasCopy) {
3559 S += ", __" + FunName.str() + "_block_copy_" + utostr(i);
3560 S += ", __" + FunName.str() + "_block_dispose_" + utostr(i);
3561 }
3562 S += "};\n";
3563 return S;
3564}
3565
3566void RewriteModernObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
3567 StringRef FunName) {
3568 // Insert declaration for the function in which block literal is used.
3569 if (CurFunctionDeclToDeclareForBlock && !Blocks.empty())
3570 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
3571 bool RewriteSC = (GlobalVarDecl &&
3572 !Blocks.empty() &&
3573 GlobalVarDecl->getStorageClass() == SC_Static &&
3574 GlobalVarDecl->getType().getCVRQualifiers());
3575 if (RewriteSC) {
3576 std::string SC(" void __");
3577 SC += GlobalVarDecl->getNameAsString();
3578 SC += "() {}";
3579 InsertText(FunLocStart, SC);
3580 }
3581
3582 // Insert closures that were part of the function.
3583 for (unsigned i = 0, count=0; i < Blocks.size(); i++) {
3584 CollectBlockDeclRefInfo(Blocks[i]);
3585 // Need to copy-in the inner copied-in variables not actually used in this
3586 // block.
3587 for (int j = 0; j < InnerDeclRefsCount[i]; j++) {
John McCallf4b88a42012-03-10 09:33:50 +00003588 DeclRefExpr *Exp = InnerDeclRefs[count++];
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003589 ValueDecl *VD = Exp->getDecl();
3590 BlockDeclRefs.push_back(Exp);
John McCallf4b88a42012-03-10 09:33:50 +00003591 if (!VD->hasAttr<BlocksAttr>()) {
3592 if (!BlockByCopyDeclsPtrSet.count(VD)) {
3593 BlockByCopyDeclsPtrSet.insert(VD);
3594 BlockByCopyDecls.push_back(VD);
3595 }
3596 continue;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003597 }
John McCallf4b88a42012-03-10 09:33:50 +00003598
3599 if (!BlockByRefDeclsPtrSet.count(VD)) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003600 BlockByRefDeclsPtrSet.insert(VD);
3601 BlockByRefDecls.push_back(VD);
3602 }
John McCallf4b88a42012-03-10 09:33:50 +00003603
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003604 // imported objects in the inner blocks not used in the outer
3605 // blocks must be copied/disposed in the outer block as well.
John McCallf4b88a42012-03-10 09:33:50 +00003606 if (VD->getType()->isObjCObjectPointerType() ||
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003607 VD->getType()->isBlockPointerType())
3608 ImportedBlockDecls.insert(VD);
3609 }
3610
3611 std::string ImplTag = "__" + FunName.str() + "_block_impl_" + utostr(i);
3612 std::string DescTag = "__" + FunName.str() + "_block_desc_" + utostr(i);
3613
3614 std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
3615
3616 InsertText(FunLocStart, CI);
3617
3618 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
3619
3620 InsertText(FunLocStart, CF);
3621
3622 if (ImportedBlockDecls.size()) {
3623 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
3624 InsertText(FunLocStart, HF);
3625 }
3626 std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
3627 ImportedBlockDecls.size() > 0);
3628 InsertText(FunLocStart, BD);
3629
3630 BlockDeclRefs.clear();
3631 BlockByRefDecls.clear();
3632 BlockByRefDeclsPtrSet.clear();
3633 BlockByCopyDecls.clear();
3634 BlockByCopyDeclsPtrSet.clear();
3635 ImportedBlockDecls.clear();
3636 }
3637 if (RewriteSC) {
3638 // Must insert any 'const/volatile/static here. Since it has been
3639 // removed as result of rewriting of block literals.
3640 std::string SC;
3641 if (GlobalVarDecl->getStorageClass() == SC_Static)
3642 SC = "static ";
3643 if (GlobalVarDecl->getType().isConstQualified())
3644 SC += "const ";
3645 if (GlobalVarDecl->getType().isVolatileQualified())
3646 SC += "volatile ";
3647 if (GlobalVarDecl->getType().isRestrictQualified())
3648 SC += "restrict ";
3649 InsertText(FunLocStart, SC);
3650 }
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00003651 if (GlobalConstructionExp) {
3652 // extra fancy dance for global literal expression.
3653
3654 // Always the latest block expression on the block stack.
3655 std::string Tag = "__";
3656 Tag += FunName;
3657 Tag += "_block_impl_";
3658 Tag += utostr(Blocks.size()-1);
3659 std::string globalBuf = "static ";
3660 globalBuf += Tag; globalBuf += " ";
3661 std::string SStr;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003662
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00003663 llvm::raw_string_ostream constructorExprBuf(SStr);
3664 GlobalConstructionExp->printPretty(constructorExprBuf, *Context, 0,
3665 PrintingPolicy(LangOpts));
3666 globalBuf += constructorExprBuf.str();
3667 globalBuf += ";\n";
3668 InsertText(FunLocStart, globalBuf);
3669 GlobalConstructionExp = 0;
3670 }
3671
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003672 Blocks.clear();
3673 InnerDeclRefsCount.clear();
3674 InnerDeclRefs.clear();
3675 RewrittenBlockExprs.clear();
3676}
3677
3678void RewriteModernObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
3679 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
3680 StringRef FuncName = FD->getName();
3681
3682 SynthesizeBlockLiterals(FunLocStart, FuncName);
3683}
3684
3685static void BuildUniqueMethodName(std::string &Name,
3686 ObjCMethodDecl *MD) {
3687 ObjCInterfaceDecl *IFace = MD->getClassInterface();
3688 Name = IFace->getName();
3689 Name += "__" + MD->getSelector().getAsString();
3690 // Convert colons to underscores.
3691 std::string::size_type loc = 0;
3692 while ((loc = Name.find(":", loc)) != std::string::npos)
3693 Name.replace(loc, 1, "_");
3694}
3695
3696void RewriteModernObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
3697 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
3698 //SourceLocation FunLocStart = MD->getLocStart();
3699 SourceLocation FunLocStart = MD->getLocStart();
3700 std::string FuncName;
3701 BuildUniqueMethodName(FuncName, MD);
3702 SynthesizeBlockLiterals(FunLocStart, FuncName);
3703}
3704
3705void RewriteModernObjC::GetBlockDeclRefExprs(Stmt *S) {
3706 for (Stmt::child_range CI = S->children(); CI; ++CI)
3707 if (*CI) {
3708 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
3709 GetBlockDeclRefExprs(CBE->getBody());
3710 else
3711 GetBlockDeclRefExprs(*CI);
3712 }
3713 // Handle specific things.
John McCallf4b88a42012-03-10 09:33:50 +00003714 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S))
3715 if (DRE->refersToEnclosingLocal() &&
3716 HasLocalVariableExternalStorage(DRE->getDecl())) {
3717 BlockDeclRefs.push_back(DRE);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003718 }
3719
3720 return;
3721}
3722
3723void RewriteModernObjC::GetInnerBlockDeclRefExprs(Stmt *S,
John McCallf4b88a42012-03-10 09:33:50 +00003724 SmallVector<DeclRefExpr *, 8> &InnerBlockDeclRefs,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003725 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts) {
3726 for (Stmt::child_range CI = S->children(); CI; ++CI)
3727 if (*CI) {
3728 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI)) {
3729 InnerContexts.insert(cast<DeclContext>(CBE->getBlockDecl()));
3730 GetInnerBlockDeclRefExprs(CBE->getBody(),
3731 InnerBlockDeclRefs,
3732 InnerContexts);
3733 }
3734 else
3735 GetInnerBlockDeclRefExprs(*CI,
3736 InnerBlockDeclRefs,
3737 InnerContexts);
3738
3739 }
3740 // Handle specific things.
John McCallf4b88a42012-03-10 09:33:50 +00003741 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
3742 if (DRE->refersToEnclosingLocal()) {
3743 if (!isa<FunctionDecl>(DRE->getDecl()) &&
3744 !InnerContexts.count(DRE->getDecl()->getDeclContext()))
3745 InnerBlockDeclRefs.push_back(DRE);
3746 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl()))
3747 if (Var->isFunctionOrMethodVarDecl())
3748 ImportedLocalExternalDecls.insert(Var);
3749 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003750 }
3751
3752 return;
3753}
3754
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00003755/// convertObjCTypeToCStyleType - This routine converts such objc types
3756/// as qualified objects, and blocks to their closest c/c++ types that
3757/// it can. It returns true if input type was modified.
3758bool RewriteModernObjC::convertObjCTypeToCStyleType(QualType &T) {
3759 QualType oldT = T;
3760 convertBlockPointerToFunctionPointer(T);
3761 if (T->isFunctionPointerType()) {
3762 QualType PointeeTy;
3763 if (const PointerType* PT = T->getAs<PointerType>()) {
3764 PointeeTy = PT->getPointeeType();
3765 if (const FunctionType *FT = PointeeTy->getAs<FunctionType>()) {
3766 T = convertFunctionTypeOfBlocks(FT);
3767 T = Context->getPointerType(T);
3768 }
3769 }
3770 }
3771
3772 convertToUnqualifiedObjCType(T);
3773 return T != oldT;
3774}
3775
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003776/// convertFunctionTypeOfBlocks - This routine converts a function type
3777/// whose result type may be a block pointer or whose argument type(s)
3778/// might be block pointers to an equivalent function type replacing
3779/// all block pointers to function pointers.
3780QualType RewriteModernObjC::convertFunctionTypeOfBlocks(const FunctionType *FT) {
3781 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
3782 // FTP will be null for closures that don't take arguments.
3783 // Generate a funky cast.
3784 SmallVector<QualType, 8> ArgTypes;
3785 QualType Res = FT->getResultType();
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00003786 bool modified = convertObjCTypeToCStyleType(Res);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003787
3788 if (FTP) {
3789 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
3790 E = FTP->arg_type_end(); I && (I != E); ++I) {
3791 QualType t = *I;
3792 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00003793 if (convertObjCTypeToCStyleType(t))
3794 modified = true;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003795 ArgTypes.push_back(t);
3796 }
3797 }
3798 QualType FuncType;
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00003799 if (modified)
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003800 FuncType = getSimpleFunctionType(Res, &ArgTypes[0], ArgTypes.size());
3801 else FuncType = QualType(FT, 0);
3802 return FuncType;
3803}
3804
3805Stmt *RewriteModernObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
3806 // Navigate to relevant type information.
3807 const BlockPointerType *CPT = 0;
3808
3809 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
3810 CPT = DRE->getType()->getAs<BlockPointerType>();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003811 } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
3812 CPT = MExpr->getType()->getAs<BlockPointerType>();
3813 }
3814 else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
3815 return SynthesizeBlockCall(Exp, PRE->getSubExpr());
3816 }
3817 else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
3818 CPT = IEXPR->getType()->getAs<BlockPointerType>();
3819 else if (const ConditionalOperator *CEXPR =
3820 dyn_cast<ConditionalOperator>(BlockExp)) {
3821 Expr *LHSExp = CEXPR->getLHS();
3822 Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
3823 Expr *RHSExp = CEXPR->getRHS();
3824 Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
3825 Expr *CONDExp = CEXPR->getCond();
3826 ConditionalOperator *CondExpr =
3827 new (Context) ConditionalOperator(CONDExp,
3828 SourceLocation(), cast<Expr>(LHSStmt),
3829 SourceLocation(), cast<Expr>(RHSStmt),
3830 Exp->getType(), VK_RValue, OK_Ordinary);
3831 return CondExpr;
3832 } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
3833 CPT = IRE->getType()->getAs<BlockPointerType>();
3834 } else if (const PseudoObjectExpr *POE
3835 = dyn_cast<PseudoObjectExpr>(BlockExp)) {
3836 CPT = POE->getType()->castAs<BlockPointerType>();
3837 } else {
3838 assert(1 && "RewriteBlockClass: Bad type");
3839 }
3840 assert(CPT && "RewriteBlockClass: Bad type");
3841 const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
3842 assert(FT && "RewriteBlockClass: Bad type");
3843 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
3844 // FTP will be null for closures that don't take arguments.
3845
3846 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
3847 SourceLocation(), SourceLocation(),
3848 &Context->Idents.get("__block_impl"));
3849 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
3850
3851 // Generate a funky cast.
3852 SmallVector<QualType, 8> ArgTypes;
3853
3854 // Push the block argument type.
3855 ArgTypes.push_back(PtrBlock);
3856 if (FTP) {
3857 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
3858 E = FTP->arg_type_end(); I && (I != E); ++I) {
3859 QualType t = *I;
3860 // Make sure we convert "t (^)(...)" to "t (*)(...)".
3861 if (!convertBlockPointerToFunctionPointer(t))
3862 convertToUnqualifiedObjCType(t);
3863 ArgTypes.push_back(t);
3864 }
3865 }
3866 // Now do the pointer to function cast.
3867 QualType PtrToFuncCastType
3868 = getSimpleFunctionType(Exp->getType(), &ArgTypes[0], ArgTypes.size());
3869
3870 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
3871
3872 CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock,
3873 CK_BitCast,
3874 const_cast<Expr*>(BlockExp));
3875 // Don't forget the parens to enforce the proper binding.
3876 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3877 BlkCast);
3878 //PE->dump();
3879
3880 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
3881 SourceLocation(),
3882 &Context->Idents.get("FuncPtr"),
3883 Context->VoidPtrTy, 0,
3884 /*BitWidth=*/0, /*Mutable=*/true,
3885 /*HasInit=*/false);
3886 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
3887 FD->getType(), VK_LValue,
3888 OK_Ordinary);
3889
3890
3891 CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType,
3892 CK_BitCast, ME);
3893 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
3894
3895 SmallVector<Expr*, 8> BlkExprs;
3896 // Add the implicit argument.
3897 BlkExprs.push_back(BlkCast);
3898 // Add the user arguments.
3899 for (CallExpr::arg_iterator I = Exp->arg_begin(),
3900 E = Exp->arg_end(); I != E; ++I) {
3901 BlkExprs.push_back(*I);
3902 }
3903 CallExpr *CE = new (Context) CallExpr(*Context, PE, &BlkExprs[0],
3904 BlkExprs.size(),
3905 Exp->getType(), VK_RValue,
3906 SourceLocation());
3907 return CE;
3908}
3909
3910// We need to return the rewritten expression to handle cases where the
John McCallf4b88a42012-03-10 09:33:50 +00003911// DeclRefExpr is embedded in another expression being rewritten.
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003912// For example:
3913//
3914// int main() {
3915// __block Foo *f;
3916// __block int i;
3917//
3918// void (^myblock)() = ^() {
John McCallf4b88a42012-03-10 09:33:50 +00003919// [f test]; // f is a DeclRefExpr embedded in a message (which is being rewritten).
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003920// i = 77;
3921// };
3922//}
John McCallf4b88a42012-03-10 09:33:50 +00003923Stmt *RewriteModernObjC::RewriteBlockDeclRefExpr(DeclRefExpr *DeclRefExp) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003924 // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
3925 // for each DeclRefExp where BYREFVAR is name of the variable.
John McCallf4b88a42012-03-10 09:33:50 +00003926 ValueDecl *VD = DeclRefExp->getDecl();
3927 bool isArrow = DeclRefExp->refersToEnclosingLocal();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003928
3929 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
3930 SourceLocation(),
3931 &Context->Idents.get("__forwarding"),
3932 Context->VoidPtrTy, 0,
3933 /*BitWidth=*/0, /*Mutable=*/true,
3934 /*HasInit=*/false);
3935 MemberExpr *ME = new (Context) MemberExpr(DeclRefExp, isArrow,
3936 FD, SourceLocation(),
3937 FD->getType(), VK_LValue,
3938 OK_Ordinary);
3939
3940 StringRef Name = VD->getName();
3941 FD = FieldDecl::Create(*Context, 0, SourceLocation(), SourceLocation(),
3942 &Context->Idents.get(Name),
3943 Context->VoidPtrTy, 0,
3944 /*BitWidth=*/0, /*Mutable=*/true,
3945 /*HasInit=*/false);
3946 ME = new (Context) MemberExpr(ME, true, FD, SourceLocation(),
3947 DeclRefExp->getType(), VK_LValue, OK_Ordinary);
3948
3949
3950
3951 // Need parens to enforce precedence.
3952 ParenExpr *PE = new (Context) ParenExpr(DeclRefExp->getExprLoc(),
3953 DeclRefExp->getExprLoc(),
3954 ME);
3955 ReplaceStmt(DeclRefExp, PE);
3956 return PE;
3957}
3958
3959// Rewrites the imported local variable V with external storage
3960// (static, extern, etc.) as *V
3961//
3962Stmt *RewriteModernObjC::RewriteLocalVariableExternalStorage(DeclRefExpr *DRE) {
3963 ValueDecl *VD = DRE->getDecl();
3964 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
3965 if (!ImportedLocalExternalDecls.count(Var))
3966 return DRE;
3967 Expr *Exp = new (Context) UnaryOperator(DRE, UO_Deref, DRE->getType(),
3968 VK_LValue, OK_Ordinary,
3969 DRE->getLocation());
3970 // Need parens to enforce precedence.
3971 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3972 Exp);
3973 ReplaceStmt(DRE, PE);
3974 return PE;
3975}
3976
3977void RewriteModernObjC::RewriteCastExpr(CStyleCastExpr *CE) {
3978 SourceLocation LocStart = CE->getLParenLoc();
3979 SourceLocation LocEnd = CE->getRParenLoc();
3980
3981 // Need to avoid trying to rewrite synthesized casts.
3982 if (LocStart.isInvalid())
3983 return;
3984 // Need to avoid trying to rewrite casts contained in macros.
3985 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
3986 return;
3987
3988 const char *startBuf = SM->getCharacterData(LocStart);
3989 const char *endBuf = SM->getCharacterData(LocEnd);
3990 QualType QT = CE->getType();
3991 const Type* TypePtr = QT->getAs<Type>();
3992 if (isa<TypeOfExprType>(TypePtr)) {
3993 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
3994 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
3995 std::string TypeAsString = "(";
3996 RewriteBlockPointerType(TypeAsString, QT);
3997 TypeAsString += ")";
3998 ReplaceText(LocStart, endBuf-startBuf+1, TypeAsString);
3999 return;
4000 }
4001 // advance the location to startArgList.
4002 const char *argPtr = startBuf;
4003
4004 while (*argPtr++ && (argPtr < endBuf)) {
4005 switch (*argPtr) {
4006 case '^':
4007 // Replace the '^' with '*'.
4008 LocStart = LocStart.getLocWithOffset(argPtr-startBuf);
4009 ReplaceText(LocStart, 1, "*");
4010 break;
4011 }
4012 }
4013 return;
4014}
4015
4016void RewriteModernObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
4017 SourceLocation DeclLoc = FD->getLocation();
4018 unsigned parenCount = 0;
4019
4020 // We have 1 or more arguments that have closure pointers.
4021 const char *startBuf = SM->getCharacterData(DeclLoc);
4022 const char *startArgList = strchr(startBuf, '(');
4023
4024 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
4025
4026 parenCount++;
4027 // advance the location to startArgList.
4028 DeclLoc = DeclLoc.getLocWithOffset(startArgList-startBuf);
4029 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
4030
4031 const char *argPtr = startArgList;
4032
4033 while (*argPtr++ && parenCount) {
4034 switch (*argPtr) {
4035 case '^':
4036 // Replace the '^' with '*'.
4037 DeclLoc = DeclLoc.getLocWithOffset(argPtr-startArgList);
4038 ReplaceText(DeclLoc, 1, "*");
4039 break;
4040 case '(':
4041 parenCount++;
4042 break;
4043 case ')':
4044 parenCount--;
4045 break;
4046 }
4047 }
4048 return;
4049}
4050
4051bool RewriteModernObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
4052 const FunctionProtoType *FTP;
4053 const PointerType *PT = QT->getAs<PointerType>();
4054 if (PT) {
4055 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4056 } else {
4057 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4058 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4059 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4060 }
4061 if (FTP) {
4062 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4063 E = FTP->arg_type_end(); I != E; ++I)
4064 if (isTopLevelBlockPointerType(*I))
4065 return true;
4066 }
4067 return false;
4068}
4069
4070bool RewriteModernObjC::PointerTypeTakesAnyObjCQualifiedType(QualType QT) {
4071 const FunctionProtoType *FTP;
4072 const PointerType *PT = QT->getAs<PointerType>();
4073 if (PT) {
4074 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4075 } else {
4076 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4077 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4078 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4079 }
4080 if (FTP) {
4081 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4082 E = FTP->arg_type_end(); I != E; ++I) {
4083 if ((*I)->isObjCQualifiedIdType())
4084 return true;
4085 if ((*I)->isObjCObjectPointerType() &&
4086 (*I)->getPointeeType()->isObjCQualifiedInterfaceType())
4087 return true;
4088 }
4089
4090 }
4091 return false;
4092}
4093
4094void RewriteModernObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
4095 const char *&RParen) {
4096 const char *argPtr = strchr(Name, '(');
4097 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
4098
4099 LParen = argPtr; // output the start.
4100 argPtr++; // skip past the left paren.
4101 unsigned parenCount = 1;
4102
4103 while (*argPtr && parenCount) {
4104 switch (*argPtr) {
4105 case '(': parenCount++; break;
4106 case ')': parenCount--; break;
4107 default: break;
4108 }
4109 if (parenCount) argPtr++;
4110 }
4111 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
4112 RParen = argPtr; // output the end
4113}
4114
4115void RewriteModernObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
4116 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4117 RewriteBlockPointerFunctionArgs(FD);
4118 return;
4119 }
4120 // Handle Variables and Typedefs.
4121 SourceLocation DeclLoc = ND->getLocation();
4122 QualType DeclT;
4123 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
4124 DeclT = VD->getType();
4125 else if (TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(ND))
4126 DeclT = TDD->getUnderlyingType();
4127 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
4128 DeclT = FD->getType();
4129 else
4130 llvm_unreachable("RewriteBlockPointerDecl(): Decl type not yet handled");
4131
4132 const char *startBuf = SM->getCharacterData(DeclLoc);
4133 const char *endBuf = startBuf;
4134 // scan backward (from the decl location) for the end of the previous decl.
4135 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
4136 startBuf--;
4137 SourceLocation Start = DeclLoc.getLocWithOffset(startBuf-endBuf);
4138 std::string buf;
4139 unsigned OrigLength=0;
4140 // *startBuf != '^' if we are dealing with a pointer to function that
4141 // may take block argument types (which will be handled below).
4142 if (*startBuf == '^') {
4143 // Replace the '^' with '*', computing a negative offset.
4144 buf = '*';
4145 startBuf++;
4146 OrigLength++;
4147 }
4148 while (*startBuf != ')') {
4149 buf += *startBuf;
4150 startBuf++;
4151 OrigLength++;
4152 }
4153 buf += ')';
4154 OrigLength++;
4155
4156 if (PointerTypeTakesAnyBlockArguments(DeclT) ||
4157 PointerTypeTakesAnyObjCQualifiedType(DeclT)) {
4158 // Replace the '^' with '*' for arguments.
4159 // Replace id<P> with id/*<>*/
4160 DeclLoc = ND->getLocation();
4161 startBuf = SM->getCharacterData(DeclLoc);
4162 const char *argListBegin, *argListEnd;
4163 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
4164 while (argListBegin < argListEnd) {
4165 if (*argListBegin == '^')
4166 buf += '*';
4167 else if (*argListBegin == '<') {
4168 buf += "/*";
4169 buf += *argListBegin++;
4170 OrigLength++;;
4171 while (*argListBegin != '>') {
4172 buf += *argListBegin++;
4173 OrigLength++;
4174 }
4175 buf += *argListBegin;
4176 buf += "*/";
4177 }
4178 else
4179 buf += *argListBegin;
4180 argListBegin++;
4181 OrigLength++;
4182 }
4183 buf += ')';
4184 OrigLength++;
4185 }
4186 ReplaceText(Start, OrigLength, buf);
4187
4188 return;
4189}
4190
4191
4192/// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
4193/// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
4194/// struct Block_byref_id_object *src) {
4195/// _Block_object_assign (&_dest->object, _src->object,
4196/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4197/// [|BLOCK_FIELD_IS_WEAK]) // object
4198/// _Block_object_assign(&_dest->object, _src->object,
4199/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4200/// [|BLOCK_FIELD_IS_WEAK]) // block
4201/// }
4202/// And:
4203/// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
4204/// _Block_object_dispose(_src->object,
4205/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4206/// [|BLOCK_FIELD_IS_WEAK]) // object
4207/// _Block_object_dispose(_src->object,
4208/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4209/// [|BLOCK_FIELD_IS_WEAK]) // block
4210/// }
4211
4212std::string RewriteModernObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
4213 int flag) {
4214 std::string S;
4215 if (CopyDestroyCache.count(flag))
4216 return S;
4217 CopyDestroyCache.insert(flag);
4218 S = "static void __Block_byref_id_object_copy_";
4219 S += utostr(flag);
4220 S += "(void *dst, void *src) {\n";
4221
4222 // offset into the object pointer is computed as:
4223 // void * + void* + int + int + void* + void *
4224 unsigned IntSize =
4225 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
4226 unsigned VoidPtrSize =
4227 static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
4228
4229 unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/Context->getCharWidth();
4230 S += " _Block_object_assign((char*)dst + ";
4231 S += utostr(offset);
4232 S += ", *(void * *) ((char*)src + ";
4233 S += utostr(offset);
4234 S += "), ";
4235 S += utostr(flag);
4236 S += ");\n}\n";
4237
4238 S += "static void __Block_byref_id_object_dispose_";
4239 S += utostr(flag);
4240 S += "(void *src) {\n";
4241 S += " _Block_object_dispose(*(void * *) ((char*)src + ";
4242 S += utostr(offset);
4243 S += "), ";
4244 S += utostr(flag);
4245 S += ");\n}\n";
4246 return S;
4247}
4248
4249/// RewriteByRefVar - For each __block typex ND variable this routine transforms
4250/// the declaration into:
4251/// struct __Block_byref_ND {
4252/// void *__isa; // NULL for everything except __weak pointers
4253/// struct __Block_byref_ND *__forwarding;
4254/// int32_t __flags;
4255/// int32_t __size;
4256/// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
4257/// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
4258/// typex ND;
4259/// };
4260///
4261/// It then replaces declaration of ND variable with:
4262/// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
4263/// __size=sizeof(struct __Block_byref_ND),
4264/// ND=initializer-if-any};
4265///
4266///
4267void RewriteModernObjC::RewriteByRefVar(VarDecl *ND) {
4268 // Insert declaration for the function in which block literal is
4269 // used.
4270 if (CurFunctionDeclToDeclareForBlock)
4271 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
4272 int flag = 0;
4273 int isa = 0;
4274 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
4275 if (DeclLoc.isInvalid())
4276 // If type location is missing, it is because of missing type (a warning).
4277 // Use variable's location which is good for this case.
4278 DeclLoc = ND->getLocation();
4279 const char *startBuf = SM->getCharacterData(DeclLoc);
4280 SourceLocation X = ND->getLocEnd();
4281 X = SM->getExpansionLoc(X);
4282 const char *endBuf = SM->getCharacterData(X);
4283 std::string Name(ND->getNameAsString());
4284 std::string ByrefType;
4285 RewriteByRefString(ByrefType, Name, ND, true);
4286 ByrefType += " {\n";
4287 ByrefType += " void *__isa;\n";
4288 RewriteByRefString(ByrefType, Name, ND);
4289 ByrefType += " *__forwarding;\n";
4290 ByrefType += " int __flags;\n";
4291 ByrefType += " int __size;\n";
4292 // Add void *__Block_byref_id_object_copy;
4293 // void *__Block_byref_id_object_dispose; if needed.
4294 QualType Ty = ND->getType();
4295 bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty);
4296 if (HasCopyAndDispose) {
4297 ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
4298 ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
4299 }
4300
4301 QualType T = Ty;
4302 (void)convertBlockPointerToFunctionPointer(T);
4303 T.getAsStringInternal(Name, Context->getPrintingPolicy());
4304
4305 ByrefType += " " + Name + ";\n";
4306 ByrefType += "};\n";
4307 // Insert this type in global scope. It is needed by helper function.
4308 SourceLocation FunLocStart;
4309 if (CurFunctionDef)
4310 FunLocStart = CurFunctionDef->getTypeSpecStartLoc();
4311 else {
4312 assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null");
4313 FunLocStart = CurMethodDef->getLocStart();
4314 }
4315 InsertText(FunLocStart, ByrefType);
4316 if (Ty.isObjCGCWeak()) {
4317 flag |= BLOCK_FIELD_IS_WEAK;
4318 isa = 1;
4319 }
4320
4321 if (HasCopyAndDispose) {
4322 flag = BLOCK_BYREF_CALLER;
4323 QualType Ty = ND->getType();
4324 // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
4325 if (Ty->isBlockPointerType())
4326 flag |= BLOCK_FIELD_IS_BLOCK;
4327 else
4328 flag |= BLOCK_FIELD_IS_OBJECT;
4329 std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
4330 if (!HF.empty())
4331 InsertText(FunLocStart, HF);
4332 }
4333
4334 // struct __Block_byref_ND ND =
4335 // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
4336 // initializer-if-any};
4337 bool hasInit = (ND->getInit() != 0);
4338 unsigned flags = 0;
4339 if (HasCopyAndDispose)
4340 flags |= BLOCK_HAS_COPY_DISPOSE;
4341 Name = ND->getNameAsString();
4342 ByrefType.clear();
4343 RewriteByRefString(ByrefType, Name, ND);
4344 std::string ForwardingCastType("(");
4345 ForwardingCastType += ByrefType + " *)";
4346 if (!hasInit) {
4347 ByrefType += " " + Name + " = {(void*)";
4348 ByrefType += utostr(isa);
4349 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
4350 ByrefType += utostr(flags);
4351 ByrefType += ", ";
4352 ByrefType += "sizeof(";
4353 RewriteByRefString(ByrefType, Name, ND);
4354 ByrefType += ")";
4355 if (HasCopyAndDispose) {
4356 ByrefType += ", __Block_byref_id_object_copy_";
4357 ByrefType += utostr(flag);
4358 ByrefType += ", __Block_byref_id_object_dispose_";
4359 ByrefType += utostr(flag);
4360 }
4361 ByrefType += "};\n";
4362 unsigned nameSize = Name.size();
4363 // for block or function pointer declaration. Name is aleady
4364 // part of the declaration.
4365 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType())
4366 nameSize = 1;
4367 ReplaceText(DeclLoc, endBuf-startBuf+nameSize, ByrefType);
4368 }
4369 else {
4370 SourceLocation startLoc;
4371 Expr *E = ND->getInit();
4372 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
4373 startLoc = ECE->getLParenLoc();
4374 else
4375 startLoc = E->getLocStart();
4376 startLoc = SM->getExpansionLoc(startLoc);
4377 endBuf = SM->getCharacterData(startLoc);
4378 ByrefType += " " + Name;
4379 ByrefType += " = {(void*)";
4380 ByrefType += utostr(isa);
4381 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
4382 ByrefType += utostr(flags);
4383 ByrefType += ", ";
4384 ByrefType += "sizeof(";
4385 RewriteByRefString(ByrefType, Name, ND);
4386 ByrefType += "), ";
4387 if (HasCopyAndDispose) {
4388 ByrefType += "__Block_byref_id_object_copy_";
4389 ByrefType += utostr(flag);
4390 ByrefType += ", __Block_byref_id_object_dispose_";
4391 ByrefType += utostr(flag);
4392 ByrefType += ", ";
4393 }
4394 ReplaceText(DeclLoc, endBuf-startBuf, ByrefType);
4395
4396 // Complete the newly synthesized compound expression by inserting a right
4397 // curly brace before the end of the declaration.
4398 // FIXME: This approach avoids rewriting the initializer expression. It
4399 // also assumes there is only one declarator. For example, the following
4400 // isn't currently supported by this routine (in general):
4401 //
4402 // double __block BYREFVAR = 1.34, BYREFVAR2 = 1.37;
4403 //
4404 const char *startInitializerBuf = SM->getCharacterData(startLoc);
4405 const char *semiBuf = strchr(startInitializerBuf, ';');
4406 assert((*semiBuf == ';') && "RewriteByRefVar: can't find ';'");
4407 SourceLocation semiLoc =
4408 startLoc.getLocWithOffset(semiBuf-startInitializerBuf);
4409
4410 InsertText(semiLoc, "}");
4411 }
4412 return;
4413}
4414
4415void RewriteModernObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
4416 // Add initializers for any closure decl refs.
4417 GetBlockDeclRefExprs(Exp->getBody());
4418 if (BlockDeclRefs.size()) {
4419 // Unique all "by copy" declarations.
4420 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00004421 if (!BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004422 if (!BlockByCopyDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
4423 BlockByCopyDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
4424 BlockByCopyDecls.push_back(BlockDeclRefs[i]->getDecl());
4425 }
4426 }
4427 // Unique all "by ref" declarations.
4428 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00004429 if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004430 if (!BlockByRefDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
4431 BlockByRefDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
4432 BlockByRefDecls.push_back(BlockDeclRefs[i]->getDecl());
4433 }
4434 }
4435 // Find any imported blocks...they will need special attention.
4436 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00004437 if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004438 BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
4439 BlockDeclRefs[i]->getType()->isBlockPointerType())
4440 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
4441 }
4442}
4443
4444FunctionDecl *RewriteModernObjC::SynthBlockInitFunctionDecl(StringRef name) {
4445 IdentifierInfo *ID = &Context->Idents.get(name);
4446 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
4447 return FunctionDecl::Create(*Context, TUDecl, SourceLocation(),
4448 SourceLocation(), ID, FType, 0, SC_Extern,
4449 SC_None, false, false);
4450}
4451
4452Stmt *RewriteModernObjC::SynthBlockInitExpr(BlockExpr *Exp,
John McCallf4b88a42012-03-10 09:33:50 +00004453 const SmallVector<DeclRefExpr *, 8> &InnerBlockDeclRefs) {
Fariborz Jahaniand13c2c22012-03-22 19:54:39 +00004454
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004455 const BlockDecl *block = Exp->getBlockDecl();
Fariborz Jahaniand13c2c22012-03-22 19:54:39 +00004456
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004457 Blocks.push_back(Exp);
4458
4459 CollectBlockDeclRefInfo(Exp);
4460
4461 // Add inner imported variables now used in current block.
4462 int countOfInnerDecls = 0;
4463 if (!InnerBlockDeclRefs.empty()) {
4464 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++) {
John McCallf4b88a42012-03-10 09:33:50 +00004465 DeclRefExpr *Exp = InnerBlockDeclRefs[i];
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004466 ValueDecl *VD = Exp->getDecl();
John McCallf4b88a42012-03-10 09:33:50 +00004467 if (!VD->hasAttr<BlocksAttr>() && !BlockByCopyDeclsPtrSet.count(VD)) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004468 // We need to save the copied-in variables in nested
4469 // blocks because it is needed at the end for some of the API generations.
4470 // See SynthesizeBlockLiterals routine.
4471 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
4472 BlockDeclRefs.push_back(Exp);
4473 BlockByCopyDeclsPtrSet.insert(VD);
4474 BlockByCopyDecls.push_back(VD);
4475 }
John McCallf4b88a42012-03-10 09:33:50 +00004476 if (VD->hasAttr<BlocksAttr>() && !BlockByRefDeclsPtrSet.count(VD)) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004477 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
4478 BlockDeclRefs.push_back(Exp);
4479 BlockByRefDeclsPtrSet.insert(VD);
4480 BlockByRefDecls.push_back(VD);
4481 }
4482 }
4483 // Find any imported blocks...they will need special attention.
4484 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00004485 if (InnerBlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004486 InnerBlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
4487 InnerBlockDeclRefs[i]->getType()->isBlockPointerType())
4488 ImportedBlockDecls.insert(InnerBlockDeclRefs[i]->getDecl());
4489 }
4490 InnerDeclRefsCount.push_back(countOfInnerDecls);
4491
4492 std::string FuncName;
4493
4494 if (CurFunctionDef)
4495 FuncName = CurFunctionDef->getNameAsString();
4496 else if (CurMethodDef)
4497 BuildUniqueMethodName(FuncName, CurMethodDef);
4498 else if (GlobalVarDecl)
4499 FuncName = std::string(GlobalVarDecl->getNameAsString());
4500
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00004501 bool GlobalBlockExpr =
4502 block->getDeclContext()->getRedeclContext()->isFileContext();
4503
4504 if (GlobalBlockExpr && !GlobalVarDecl) {
4505 Diags.Report(block->getLocation(), GlobalBlockRewriteFailedDiag);
4506 GlobalBlockExpr = false;
4507 }
4508
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004509 std::string BlockNumber = utostr(Blocks.size()-1);
4510
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004511 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
4512
4513 // Get a pointer to the function type so we can cast appropriately.
4514 QualType BFT = convertFunctionTypeOfBlocks(Exp->getFunctionType());
4515 QualType FType = Context->getPointerType(BFT);
4516
4517 FunctionDecl *FD;
4518 Expr *NewRep;
4519
4520 // Simulate a contructor call...
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00004521 std::string Tag;
4522
4523 if (GlobalBlockExpr)
4524 Tag = "__global_";
4525 else
4526 Tag = "__";
4527 Tag += FuncName + "_block_impl_" + BlockNumber;
4528
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004529 FD = SynthBlockInitFunctionDecl(Tag);
John McCallf4b88a42012-03-10 09:33:50 +00004530 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, false, FType, VK_RValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004531 SourceLocation());
4532
4533 SmallVector<Expr*, 4> InitExprs;
4534
4535 // Initialize the block function.
4536 FD = SynthBlockInitFunctionDecl(Func);
John McCallf4b88a42012-03-10 09:33:50 +00004537 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, false, FD->getType(),
4538 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004539 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
4540 CK_BitCast, Arg);
4541 InitExprs.push_back(castExpr);
4542
4543 // Initialize the block descriptor.
4544 std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
4545
4546 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl,
4547 SourceLocation(), SourceLocation(),
4548 &Context->Idents.get(DescData.c_str()),
4549 Context->VoidPtrTy, 0,
4550 SC_Static, SC_None);
4551 UnaryOperator *DescRefExpr =
John McCallf4b88a42012-03-10 09:33:50 +00004552 new (Context) UnaryOperator(new (Context) DeclRefExpr(NewVD, false,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004553 Context->VoidPtrTy,
4554 VK_LValue,
4555 SourceLocation()),
4556 UO_AddrOf,
4557 Context->getPointerType(Context->VoidPtrTy),
4558 VK_RValue, OK_Ordinary,
4559 SourceLocation());
4560 InitExprs.push_back(DescRefExpr);
4561
4562 // Add initializers for any closure decl refs.
4563 if (BlockDeclRefs.size()) {
4564 Expr *Exp;
4565 // Output all "by copy" declarations.
4566 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
4567 E = BlockByCopyDecls.end(); I != E; ++I) {
4568 if (isObjCType((*I)->getType())) {
4569 // FIXME: Conform to ABI ([[obj retain] autorelease]).
4570 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00004571 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(),
4572 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004573 if (HasLocalVariableExternalStorage(*I)) {
4574 QualType QT = (*I)->getType();
4575 QT = Context->getPointerType(QT);
4576 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
4577 OK_Ordinary, SourceLocation());
4578 }
4579 } else if (isTopLevelBlockPointerType((*I)->getType())) {
4580 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00004581 Arg = new (Context) DeclRefExpr(FD, false, FD->getType(),
4582 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004583 Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
4584 CK_BitCast, Arg);
4585 } else {
4586 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00004587 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(),
4588 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004589 if (HasLocalVariableExternalStorage(*I)) {
4590 QualType QT = (*I)->getType();
4591 QT = Context->getPointerType(QT);
4592 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
4593 OK_Ordinary, SourceLocation());
4594 }
4595
4596 }
4597 InitExprs.push_back(Exp);
4598 }
4599 // Output all "by ref" declarations.
4600 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
4601 E = BlockByRefDecls.end(); I != E; ++I) {
4602 ValueDecl *ND = (*I);
4603 std::string Name(ND->getNameAsString());
4604 std::string RecName;
4605 RewriteByRefString(RecName, Name, ND, true);
4606 IdentifierInfo *II = &Context->Idents.get(RecName.c_str()
4607 + sizeof("struct"));
4608 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
4609 SourceLocation(), SourceLocation(),
4610 II);
4611 assert(RD && "SynthBlockInitExpr(): Can't find RecordDecl");
4612 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
4613
4614 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00004615 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(), VK_LValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004616 SourceLocation());
4617 bool isNestedCapturedVar = false;
4618 if (block)
4619 for (BlockDecl::capture_const_iterator ci = block->capture_begin(),
4620 ce = block->capture_end(); ci != ce; ++ci) {
4621 const VarDecl *variable = ci->getVariable();
4622 if (variable == ND && ci->isNested()) {
4623 assert (ci->isByRef() &&
4624 "SynthBlockInitExpr - captured block variable is not byref");
4625 isNestedCapturedVar = true;
4626 break;
4627 }
4628 }
4629 // captured nested byref variable has its address passed. Do not take
4630 // its address again.
4631 if (!isNestedCapturedVar)
4632 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf,
4633 Context->getPointerType(Exp->getType()),
4634 VK_RValue, OK_Ordinary, SourceLocation());
4635 Exp = NoTypeInfoCStyleCastExpr(Context, castT, CK_BitCast, Exp);
4636 InitExprs.push_back(Exp);
4637 }
4638 }
4639 if (ImportedBlockDecls.size()) {
4640 // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
4641 int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
4642 unsigned IntSize =
4643 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
4644 Expr *FlagExp = IntegerLiteral::Create(*Context, llvm::APInt(IntSize, flag),
4645 Context->IntTy, SourceLocation());
4646 InitExprs.push_back(FlagExp);
4647 }
4648 NewRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0], InitExprs.size(),
4649 FType, VK_LValue, SourceLocation());
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00004650
4651 if (GlobalBlockExpr) {
4652 assert (GlobalConstructionExp == 0 &&
4653 "SynthBlockInitExpr - GlobalConstructionExp must be null");
4654 GlobalConstructionExp = NewRep;
4655 NewRep = DRE;
4656 }
4657
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004658 NewRep = new (Context) UnaryOperator(NewRep, UO_AddrOf,
4659 Context->getPointerType(NewRep->getType()),
4660 VK_RValue, OK_Ordinary, SourceLocation());
4661 NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CK_BitCast,
4662 NewRep);
4663 BlockDeclRefs.clear();
4664 BlockByRefDecls.clear();
4665 BlockByRefDeclsPtrSet.clear();
4666 BlockByCopyDecls.clear();
4667 BlockByCopyDeclsPtrSet.clear();
4668 ImportedBlockDecls.clear();
4669 return NewRep;
4670}
4671
4672bool RewriteModernObjC::IsDeclStmtInForeachHeader(DeclStmt *DS) {
4673 if (const ObjCForCollectionStmt * CS =
4674 dyn_cast<ObjCForCollectionStmt>(Stmts.back()))
4675 return CS->getElement() == DS;
4676 return false;
4677}
4678
4679//===----------------------------------------------------------------------===//
4680// Function Body / Expression rewriting
4681//===----------------------------------------------------------------------===//
4682
4683Stmt *RewriteModernObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
4684 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
4685 isa<DoStmt>(S) || isa<ForStmt>(S))
4686 Stmts.push_back(S);
4687 else if (isa<ObjCForCollectionStmt>(S)) {
4688 Stmts.push_back(S);
4689 ObjCBcLabelNo.push_back(++BcLabelCount);
4690 }
4691
4692 // Pseudo-object operations and ivar references need special
4693 // treatment because we're going to recursively rewrite them.
4694 if (PseudoObjectExpr *PseudoOp = dyn_cast<PseudoObjectExpr>(S)) {
4695 if (isa<BinaryOperator>(PseudoOp->getSyntacticForm())) {
4696 return RewritePropertyOrImplicitSetter(PseudoOp);
4697 } else {
4698 return RewritePropertyOrImplicitGetter(PseudoOp);
4699 }
4700 } else if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
4701 return RewriteObjCIvarRefExpr(IvarRefExpr);
4702 }
4703
4704 SourceRange OrigStmtRange = S->getSourceRange();
4705
4706 // Perform a bottom up rewrite of all children.
4707 for (Stmt::child_range CI = S->children(); CI; ++CI)
4708 if (*CI) {
4709 Stmt *childStmt = (*CI);
4710 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(childStmt);
4711 if (newStmt) {
4712 *CI = newStmt;
4713 }
4714 }
4715
4716 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
John McCallf4b88a42012-03-10 09:33:50 +00004717 SmallVector<DeclRefExpr *, 8> InnerBlockDeclRefs;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004718 llvm::SmallPtrSet<const DeclContext *, 8> InnerContexts;
4719 InnerContexts.insert(BE->getBlockDecl());
4720 ImportedLocalExternalDecls.clear();
4721 GetInnerBlockDeclRefExprs(BE->getBody(),
4722 InnerBlockDeclRefs, InnerContexts);
4723 // Rewrite the block body in place.
4724 Stmt *SaveCurrentBody = CurrentBody;
4725 CurrentBody = BE->getBody();
4726 PropParentMap = 0;
4727 // block literal on rhs of a property-dot-sytax assignment
4728 // must be replaced by its synthesize ast so getRewrittenText
4729 // works as expected. In this case, what actually ends up on RHS
4730 // is the blockTranscribed which is the helper function for the
4731 // block literal; as in: self.c = ^() {[ace ARR];};
4732 bool saveDisableReplaceStmt = DisableReplaceStmt;
4733 DisableReplaceStmt = false;
4734 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
4735 DisableReplaceStmt = saveDisableReplaceStmt;
4736 CurrentBody = SaveCurrentBody;
4737 PropParentMap = 0;
4738 ImportedLocalExternalDecls.clear();
4739 // Now we snarf the rewritten text and stash it away for later use.
4740 std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
4741 RewrittenBlockExprs[BE] = Str;
4742
4743 Stmt *blockTranscribed = SynthBlockInitExpr(BE, InnerBlockDeclRefs);
4744
4745 //blockTranscribed->dump();
4746 ReplaceStmt(S, blockTranscribed);
4747 return blockTranscribed;
4748 }
4749 // Handle specific things.
4750 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
4751 return RewriteAtEncode(AtEncode);
4752
4753 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
4754 return RewriteAtSelector(AtSelector);
4755
4756 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
4757 return RewriteObjCStringLiteral(AtString);
Fariborz Jahanian55947042012-03-27 20:17:30 +00004758
4759 if (ObjCBoolLiteralExpr *BoolLitExpr = dyn_cast<ObjCBoolLiteralExpr>(S))
4760 return RewriteObjCBoolLiteralExpr(BoolLitExpr);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004761
4762 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
4763#if 0
4764 // Before we rewrite it, put the original message expression in a comment.
4765 SourceLocation startLoc = MessExpr->getLocStart();
4766 SourceLocation endLoc = MessExpr->getLocEnd();
4767
4768 const char *startBuf = SM->getCharacterData(startLoc);
4769 const char *endBuf = SM->getCharacterData(endLoc);
4770
4771 std::string messString;
4772 messString += "// ";
4773 messString.append(startBuf, endBuf-startBuf+1);
4774 messString += "\n";
4775
4776 // FIXME: Missing definition of
4777 // InsertText(clang::SourceLocation, char const*, unsigned int).
4778 // InsertText(startLoc, messString.c_str(), messString.size());
4779 // Tried this, but it didn't work either...
4780 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
4781#endif
4782 return RewriteMessageExpr(MessExpr);
4783 }
4784
4785 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
4786 return RewriteObjCTryStmt(StmtTry);
4787
4788 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
4789 return RewriteObjCSynchronizedStmt(StmtTry);
4790
4791 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
4792 return RewriteObjCThrowStmt(StmtThrow);
4793
4794 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
4795 return RewriteObjCProtocolExpr(ProtocolExp);
4796
4797 if (ObjCForCollectionStmt *StmtForCollection =
4798 dyn_cast<ObjCForCollectionStmt>(S))
4799 return RewriteObjCForCollectionStmt(StmtForCollection,
4800 OrigStmtRange.getEnd());
4801 if (BreakStmt *StmtBreakStmt =
4802 dyn_cast<BreakStmt>(S))
4803 return RewriteBreakStmt(StmtBreakStmt);
4804 if (ContinueStmt *StmtContinueStmt =
4805 dyn_cast<ContinueStmt>(S))
4806 return RewriteContinueStmt(StmtContinueStmt);
4807
4808 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
4809 // and cast exprs.
4810 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
4811 // FIXME: What we're doing here is modifying the type-specifier that
4812 // precedes the first Decl. In the future the DeclGroup should have
4813 // a separate type-specifier that we can rewrite.
4814 // NOTE: We need to avoid rewriting the DeclStmt if it is within
4815 // the context of an ObjCForCollectionStmt. For example:
4816 // NSArray *someArray;
4817 // for (id <FooProtocol> index in someArray) ;
4818 // This is because RewriteObjCForCollectionStmt() does textual rewriting
4819 // and it depends on the original text locations/positions.
4820 if (Stmts.empty() || !IsDeclStmtInForeachHeader(DS))
4821 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
4822
4823 // Blocks rewrite rules.
4824 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
4825 DI != DE; ++DI) {
4826 Decl *SD = *DI;
4827 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
4828 if (isTopLevelBlockPointerType(ND->getType()))
4829 RewriteBlockPointerDecl(ND);
4830 else if (ND->getType()->isFunctionPointerType())
4831 CheckFunctionPointerDecl(ND->getType(), ND);
4832 if (VarDecl *VD = dyn_cast<VarDecl>(SD)) {
4833 if (VD->hasAttr<BlocksAttr>()) {
4834 static unsigned uniqueByrefDeclCount = 0;
4835 assert(!BlockByRefDeclNo.count(ND) &&
4836 "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl");
4837 BlockByRefDeclNo[ND] = uniqueByrefDeclCount++;
4838 RewriteByRefVar(VD);
4839 }
4840 else
4841 RewriteTypeOfDecl(VD);
4842 }
4843 }
4844 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(SD)) {
4845 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
4846 RewriteBlockPointerDecl(TD);
4847 else if (TD->getUnderlyingType()->isFunctionPointerType())
4848 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
4849 }
4850 }
4851 }
4852
4853 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
4854 RewriteObjCQualifiedInterfaceTypes(CE);
4855
4856 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
4857 isa<DoStmt>(S) || isa<ForStmt>(S)) {
4858 assert(!Stmts.empty() && "Statement stack is empty");
4859 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
4860 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
4861 && "Statement stack mismatch");
4862 Stmts.pop_back();
4863 }
4864 // Handle blocks rewriting.
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004865 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4866 ValueDecl *VD = DRE->getDecl();
4867 if (VD->hasAttr<BlocksAttr>())
4868 return RewriteBlockDeclRefExpr(DRE);
4869 if (HasLocalVariableExternalStorage(VD))
4870 return RewriteLocalVariableExternalStorage(DRE);
4871 }
4872
4873 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
4874 if (CE->getCallee()->getType()->isBlockPointerType()) {
4875 Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
4876 ReplaceStmt(S, BlockCall);
4877 return BlockCall;
4878 }
4879 }
4880 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
4881 RewriteCastExpr(CE);
4882 }
4883#if 0
4884 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
4885 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(),
4886 ICE->getSubExpr(),
4887 SourceLocation());
4888 // Get the new text.
4889 std::string SStr;
4890 llvm::raw_string_ostream Buf(SStr);
4891 Replacement->printPretty(Buf, *Context);
4892 const std::string &Str = Buf.str();
4893
4894 printf("CAST = %s\n", &Str[0]);
4895 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
4896 delete S;
4897 return Replacement;
4898 }
4899#endif
4900 // Return this stmt unmodified.
4901 return S;
4902}
4903
4904void RewriteModernObjC::RewriteRecordBody(RecordDecl *RD) {
4905 for (RecordDecl::field_iterator i = RD->field_begin(),
4906 e = RD->field_end(); i != e; ++i) {
4907 FieldDecl *FD = *i;
4908 if (isTopLevelBlockPointerType(FD->getType()))
4909 RewriteBlockPointerDecl(FD);
4910 if (FD->getType()->isObjCQualifiedIdType() ||
4911 FD->getType()->isObjCQualifiedInterfaceType())
4912 RewriteObjCQualifiedInterfaceTypes(FD);
4913 }
4914}
4915
4916/// HandleDeclInMainFile - This is called for each top-level decl defined in the
4917/// main file of the input.
4918void RewriteModernObjC::HandleDeclInMainFile(Decl *D) {
4919 switch (D->getKind()) {
4920 case Decl::Function: {
4921 FunctionDecl *FD = cast<FunctionDecl>(D);
4922 if (FD->isOverloadedOperator())
4923 return;
4924
4925 // Since function prototypes don't have ParmDecl's, we check the function
4926 // prototype. This enables us to rewrite function declarations and
4927 // definitions using the same code.
4928 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
4929
Argyrios Kyrtzidis9335df32012-02-12 04:48:45 +00004930 if (!FD->isThisDeclarationADefinition())
4931 break;
4932
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004933 // FIXME: If this should support Obj-C++, support CXXTryStmt
4934 if (CompoundStmt *Body = dyn_cast_or_null<CompoundStmt>(FD->getBody())) {
4935 CurFunctionDef = FD;
4936 CurFunctionDeclToDeclareForBlock = FD;
4937 CurrentBody = Body;
4938 Body =
4939 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
4940 FD->setBody(Body);
4941 CurrentBody = 0;
4942 if (PropParentMap) {
4943 delete PropParentMap;
4944 PropParentMap = 0;
4945 }
4946 // This synthesizes and inserts the block "impl" struct, invoke function,
4947 // and any copy/dispose helper functions.
4948 InsertBlockLiteralsWithinFunction(FD);
4949 CurFunctionDef = 0;
4950 CurFunctionDeclToDeclareForBlock = 0;
4951 }
4952 break;
4953 }
4954 case Decl::ObjCMethod: {
4955 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(D);
4956 if (CompoundStmt *Body = MD->getCompoundBody()) {
4957 CurMethodDef = MD;
4958 CurrentBody = Body;
4959 Body =
4960 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
4961 MD->setBody(Body);
4962 CurrentBody = 0;
4963 if (PropParentMap) {
4964 delete PropParentMap;
4965 PropParentMap = 0;
4966 }
4967 InsertBlockLiteralsWithinMethod(MD);
4968 CurMethodDef = 0;
4969 }
4970 break;
4971 }
4972 case Decl::ObjCImplementation: {
4973 ObjCImplementationDecl *CI = cast<ObjCImplementationDecl>(D);
4974 ClassImplementation.push_back(CI);
4975 break;
4976 }
4977 case Decl::ObjCCategoryImpl: {
4978 ObjCCategoryImplDecl *CI = cast<ObjCCategoryImplDecl>(D);
4979 CategoryImplementation.push_back(CI);
4980 break;
4981 }
4982 case Decl::Var: {
4983 VarDecl *VD = cast<VarDecl>(D);
4984 RewriteObjCQualifiedInterfaceTypes(VD);
4985 if (isTopLevelBlockPointerType(VD->getType()))
4986 RewriteBlockPointerDecl(VD);
4987 else if (VD->getType()->isFunctionPointerType()) {
4988 CheckFunctionPointerDecl(VD->getType(), VD);
4989 if (VD->getInit()) {
4990 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
4991 RewriteCastExpr(CE);
4992 }
4993 }
4994 } else if (VD->getType()->isRecordType()) {
4995 RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
4996 if (RD->isCompleteDefinition())
4997 RewriteRecordBody(RD);
4998 }
4999 if (VD->getInit()) {
5000 GlobalVarDecl = VD;
5001 CurrentBody = VD->getInit();
5002 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
5003 CurrentBody = 0;
5004 if (PropParentMap) {
5005 delete PropParentMap;
5006 PropParentMap = 0;
5007 }
5008 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(), VD->getName());
5009 GlobalVarDecl = 0;
5010
5011 // This is needed for blocks.
5012 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
5013 RewriteCastExpr(CE);
5014 }
5015 }
5016 break;
5017 }
5018 case Decl::TypeAlias:
5019 case Decl::Typedef: {
5020 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
5021 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
5022 RewriteBlockPointerDecl(TD);
5023 else if (TD->getUnderlyingType()->isFunctionPointerType())
5024 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5025 }
5026 break;
5027 }
5028 case Decl::CXXRecord:
5029 case Decl::Record: {
5030 RecordDecl *RD = cast<RecordDecl>(D);
5031 if (RD->isCompleteDefinition())
5032 RewriteRecordBody(RD);
5033 break;
5034 }
5035 default:
5036 break;
5037 }
5038 // Nothing yet.
5039}
5040
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00005041/// Write_ProtocolExprReferencedMetadata - This routine writer out the
5042/// protocol reference symbols in the for of:
5043/// struct _protocol_t *PROTOCOL_REF = &PROTOCOL_METADATA.
5044static void Write_ProtocolExprReferencedMetadata(ASTContext *Context,
5045 ObjCProtocolDecl *PDecl,
5046 std::string &Result) {
5047 // Also output .objc_protorefs$B section and its meta-data.
5048 if (Context->getLangOpts().MicrosoftExt)
5049 Result += "__declspec(allocate(\".objc_protorefs$B\")) ";
5050 Result += "struct _protocol_t *";
5051 Result += "_OBJC_PROTOCOL_REFERENCE_$_";
5052 Result += PDecl->getNameAsString();
5053 Result += " = &";
5054 Result += "_OBJC_PROTOCOL_"; Result += PDecl->getNameAsString();
5055 Result += ";\n";
5056}
5057
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005058void RewriteModernObjC::HandleTranslationUnit(ASTContext &C) {
5059 if (Diags.hasErrorOccurred())
5060 return;
5061
5062 RewriteInclude();
5063
5064 // Here's a great place to add any extra declarations that may be needed.
5065 // Write out meta data for each @protocol(<expr>).
5066 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00005067 E = ProtocolExprDecls.end(); I != E; ++I) {
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00005068 RewriteObjCProtocolMetaData(*I, Preamble);
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00005069 Write_ProtocolExprReferencedMetadata(Context, (*I), Preamble);
5070 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005071
5072 InsertText(SM->getLocForStartOfFile(MainFileID), Preamble, false);
Fariborz Jahanian57317782012-02-21 23:58:41 +00005073 for (unsigned i = 0, e = ObjCInterfacesSeen.size(); i < e; i++) {
5074 ObjCInterfaceDecl *CDecl = ObjCInterfacesSeen[i];
5075 // Write struct declaration for the class matching its ivar declarations.
5076 // Note that for modern abi, this is postponed until the end of TU
5077 // because class extensions and the implementation might declare their own
5078 // private ivars.
5079 RewriteInterfaceDecl(CDecl);
5080 }
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00005081
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005082 if (ClassImplementation.size() || CategoryImplementation.size())
5083 RewriteImplementations();
5084
5085 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
5086 // we are done.
5087 if (const RewriteBuffer *RewriteBuf =
5088 Rewrite.getRewriteBufferFor(MainFileID)) {
5089 //printf("Changed:\n");
5090 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
5091 } else {
5092 llvm::errs() << "No changes\n";
5093 }
5094
5095 if (ClassImplementation.size() || CategoryImplementation.size() ||
5096 ProtocolExprDecls.size()) {
5097 // Rewrite Objective-c meta data*
5098 std::string ResultStr;
5099 RewriteMetaDataIntoBuffer(ResultStr);
5100 // Emit metadata.
5101 *OutFile << ResultStr;
5102 }
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005103 // Emit ImageInfo;
5104 {
5105 std::string ResultStr;
5106 WriteImageInfo(ResultStr);
5107 *OutFile << ResultStr;
5108 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005109 OutFile->flush();
5110}
5111
5112void RewriteModernObjC::Initialize(ASTContext &context) {
5113 InitializeCommon(context);
5114
Fariborz Jahanian6991bc52012-03-10 17:45:38 +00005115 Preamble += "#ifndef __OBJC2__\n";
5116 Preamble += "#define __OBJC2__\n";
5117 Preamble += "#endif\n";
5118
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005119 // declaring objc_selector outside the parameter list removes a silly
5120 // scope related warning...
5121 if (IsHeader)
5122 Preamble = "#pragma once\n";
5123 Preamble += "struct objc_selector; struct objc_class;\n";
5124 Preamble += "struct __rw_objc_super { struct objc_object *object; ";
5125 Preamble += "struct objc_object *superClass; ";
5126 if (LangOpts.MicrosoftExt) {
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00005127 // Define all sections using syntax that makes sense.
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005128 // These are currently generated.
5129 Preamble += "\n#pragma section(\".objc_classlist$B\", long, read, write)\n";
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00005130 Preamble += "#pragma section(\".objc_catlist$B\", long, read, write)\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005131 Preamble += "#pragma section(\".objc_protolist$B\", long, read, write)\n";
5132 Preamble += "#pragma section(\".objc_imageinfo$B\", long, read, write)\n";
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00005133 Preamble += "#pragma section(\".objc_nlclslist$B\", long, read, write)\n";
5134 Preamble += "#pragma section(\".objc_nlcatlist$B\", long, read, write)\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005135 Preamble += "#pragma section(\".objc_protorefs$B\", long, read, write)\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005136 // These are generated but not necessary for functionality.
5137 Preamble += "#pragma section(\".datacoal_nt$B\", long, read, write)\n";
5138 Preamble += "#pragma section(\".cat_cls_meth$B\", long, read, write)\n";
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00005139 Preamble += "#pragma section(\".inst_meth$B\", long, read, write)\n";
5140 Preamble += "#pragma section(\".cls_meth$B\", long, read, write)\n";
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00005141 Preamble += "#pragma section(\".objc_ivar$B\", long, read, write)\n";
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00005142
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00005143 // These need be generated for performance. Currently they are not,
5144 // using API calls instead.
5145 Preamble += "#pragma section(\".objc_selrefs$B\", long, read, write)\n";
5146 Preamble += "#pragma section(\".objc_classrefs$B\", long, read, write)\n";
5147 Preamble += "#pragma section(\".objc_superrefs$B\", long, read, write)\n";
5148
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005149 // Add a constructor for creating temporary objects.
5150 Preamble += "__rw_objc_super(struct objc_object *o, struct objc_object *s) "
5151 ": ";
5152 Preamble += "object(o), superClass(s) {} ";
5153 }
5154 Preamble += "};\n";
5155 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
5156 Preamble += "typedef struct objc_object Protocol;\n";
5157 Preamble += "#define _REWRITER_typedef_Protocol\n";
5158 Preamble += "#endif\n";
5159 if (LangOpts.MicrosoftExt) {
5160 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
5161 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
Fariborz Jahanian5cf6b6c2012-03-21 23:41:04 +00005162 }
5163 else
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005164 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
Fariborz Jahanian5cf6b6c2012-03-21 23:41:04 +00005165
5166 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend(void);\n";
5167 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSendSuper(void);\n";
5168 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend_stret(void);\n";
5169 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSendSuper_stret(void);\n";
5170 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend_fpret(void);\n";
5171
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005172 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getClass";
5173 Preamble += "(const char *);\n";
5174 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *class_getSuperclass";
5175 Preamble += "(struct objc_class *);\n";
5176 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getMetaClass";
5177 Preamble += "(const char *);\n";
Fariborz Jahanian55261af2012-03-19 18:11:32 +00005178 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw( struct objc_object *);\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005179 // @synchronized hooks.
Fariborz Jahanian55261af2012-03-19 18:11:32 +00005180 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_enter( struct objc_object *);\n";
5181 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_exit( struct objc_object *);\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005182 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
5183 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
5184 Preamble += "struct __objcFastEnumerationState {\n\t";
5185 Preamble += "unsigned long state;\n\t";
5186 Preamble += "void **itemsPtr;\n\t";
5187 Preamble += "unsigned long *mutationsPtr;\n\t";
5188 Preamble += "unsigned long extra[5];\n};\n";
5189 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
5190 Preamble += "#define __FASTENUMERATIONSTATE\n";
5191 Preamble += "#endif\n";
5192 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
5193 Preamble += "struct __NSConstantStringImpl {\n";
5194 Preamble += " int *isa;\n";
5195 Preamble += " int flags;\n";
5196 Preamble += " char *str;\n";
5197 Preamble += " long length;\n";
5198 Preamble += "};\n";
5199 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
5200 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
5201 Preamble += "#else\n";
5202 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
5203 Preamble += "#endif\n";
5204 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
5205 Preamble += "#endif\n";
5206 // Blocks preamble.
5207 Preamble += "#ifndef BLOCK_IMPL\n";
5208 Preamble += "#define BLOCK_IMPL\n";
5209 Preamble += "struct __block_impl {\n";
5210 Preamble += " void *isa;\n";
5211 Preamble += " int Flags;\n";
5212 Preamble += " int Reserved;\n";
5213 Preamble += " void *FuncPtr;\n";
5214 Preamble += "};\n";
5215 Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
5216 Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n";
5217 Preamble += "extern \"C\" __declspec(dllexport) "
5218 "void _Block_object_assign(void *, const void *, const int);\n";
5219 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
5220 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
5221 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
5222 Preamble += "#else\n";
5223 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n";
5224 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n";
5225 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
5226 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
5227 Preamble += "#endif\n";
5228 Preamble += "#endif\n";
5229 if (LangOpts.MicrosoftExt) {
5230 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
5231 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
5232 Preamble += "#ifndef KEEP_ATTRIBUTES\n"; // We use this for clang tests.
5233 Preamble += "#define __attribute__(X)\n";
5234 Preamble += "#endif\n";
5235 Preamble += "#define __weak\n";
5236 }
5237 else {
5238 Preamble += "#define __block\n";
5239 Preamble += "#define __weak\n";
5240 }
5241 // NOTE! Windows uses LLP64 for 64bit mode. So, cast pointer to long long
5242 // as this avoids warning in any 64bit/32bit compilation model.
5243 Preamble += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long long) &((TYPE *)0)->MEMBER)\n";
5244}
5245
5246/// RewriteIvarOffsetComputation - This rutine synthesizes computation of
5247/// ivar offset.
5248void RewriteModernObjC::RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
5249 std::string &Result) {
5250 if (ivar->isBitField()) {
5251 // FIXME: The hack below doesn't work for bitfields. For now, we simply
5252 // place all bitfields at offset 0.
5253 Result += "0";
5254 } else {
5255 Result += "__OFFSETOFIVAR__(struct ";
5256 Result += ivar->getContainingInterface()->getNameAsString();
5257 if (LangOpts.MicrosoftExt)
5258 Result += "_IMPL";
5259 Result += ", ";
5260 Result += ivar->getNameAsString();
5261 Result += ")";
5262 }
5263}
5264
5265/// WriteModernMetadataDeclarations - Writes out metadata declarations for modern ABI.
5266/// struct _prop_t {
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00005267/// const char *name;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005268/// char *attributes;
5269/// }
5270
5271/// struct _prop_list_t {
5272/// uint32_t entsize; // sizeof(struct _prop_t)
5273/// uint32_t count_of_properties;
5274/// struct _prop_t prop_list[count_of_properties];
5275/// }
5276
5277/// struct _protocol_t;
5278
5279/// struct _protocol_list_t {
5280/// long protocol_count; // Note, this is 32/64 bit
5281/// struct _protocol_t * protocol_list[protocol_count];
5282/// }
5283
5284/// struct _objc_method {
5285/// SEL _cmd;
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005286/// const char *method_type;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005287/// char *_imp;
5288/// }
5289
5290/// struct _method_list_t {
5291/// uint32_t entsize; // sizeof(struct _objc_method)
5292/// uint32_t method_count;
5293/// struct _objc_method method_list[method_count];
5294/// }
5295
5296/// struct _protocol_t {
5297/// id isa; // NULL
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005298/// const char *protocol_name;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005299/// const struct _protocol_list_t * protocol_list; // super protocols
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005300/// const struct method_list_t *instance_methods;
5301/// const struct method_list_t *class_methods;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005302/// const struct method_list_t *optionalInstanceMethods;
5303/// const struct method_list_t *optionalClassMethods;
5304/// const struct _prop_list_t * properties;
5305/// const uint32_t size; // sizeof(struct _protocol_t)
5306/// const uint32_t flags; // = 0
5307/// const char ** extendedMethodTypes;
5308/// }
5309
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005310/// struct _ivar_t {
5311/// unsigned long int *offset; // pointer to ivar offset location
Fariborz Jahanianae932952012-02-10 20:47:10 +00005312/// const char *name;
5313/// const char *type;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005314/// uint32_t alignment;
5315/// uint32_t size;
5316/// }
5317
5318/// struct _ivar_list_t {
5319/// uint32 entsize; // sizeof(struct _ivar_t)
5320/// uint32 count;
Fariborz Jahanianae932952012-02-10 20:47:10 +00005321/// struct _ivar_t list[count];
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005322/// }
5323
5324/// struct _class_ro_t {
Fariborz Jahanian249cd102012-03-24 16:53:16 +00005325/// uint32_t flags;
5326/// uint32_t instanceStart;
5327/// uint32_t instanceSize;
5328/// uint32_t reserved; // only when building for 64bit targets
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005329/// const uint8_t *ivarLayout;
5330/// const char *name;
5331/// const struct _method_list_t *baseMethods;
5332/// const struct _protocol_list_t *baseProtocols;
5333/// const struct _ivar_list_t *ivars;
5334/// const uint8_t *weakIvarLayout;
5335/// const struct _prop_list_t *properties;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005336/// }
5337
5338/// struct _class_t {
5339/// struct _class_t *isa;
Fariborz Jahanianfd4ce2c2012-03-20 17:34:50 +00005340/// struct _class_t *superclass;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005341/// void *cache;
5342/// IMP *vtable;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005343/// struct _class_ro_t *ro;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005344/// }
5345
5346/// struct _category_t {
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005347/// const char *name;
Fariborz Jahanian4b2fe6e2012-03-20 21:41:28 +00005348/// struct _class_t *cls;
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005349/// const struct _method_list_t *instance_methods;
5350/// const struct _method_list_t *class_methods;
5351/// const struct _protocol_list_t *protocols;
5352/// const struct _prop_list_t *properties;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005353/// }
5354
5355/// MessageRefTy - LLVM for:
5356/// struct _message_ref_t {
5357/// IMP messenger;
5358/// SEL name;
5359/// };
5360
5361/// SuperMessageRefTy - LLVM for:
5362/// struct _super_message_ref_t {
5363/// SUPER_IMP messenger;
5364/// SEL name;
5365/// };
5366
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00005367static void WriteModernMetadataDeclarations(ASTContext *Context, std::string &Result) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005368 static bool meta_data_declared = false;
5369 if (meta_data_declared)
5370 return;
5371
5372 Result += "\nstruct _prop_t {\n";
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00005373 Result += "\tconst char *name;\n";
5374 Result += "\tconst char *attributes;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005375 Result += "};\n";
5376
5377 Result += "\nstruct _protocol_t;\n";
5378
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005379 Result += "\nstruct _objc_method {\n";
5380 Result += "\tstruct objc_selector * _cmd;\n";
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005381 Result += "\tconst char *method_type;\n";
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005382 Result += "\tvoid *_imp;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005383 Result += "};\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005384
5385 Result += "\nstruct _protocol_t {\n";
5386 Result += "\tvoid * isa; // NULL\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005387 Result += "\tconst char *protocol_name;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005388 Result += "\tconst struct _protocol_list_t * protocol_list; // super protocols\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005389 Result += "\tconst struct method_list_t *instance_methods;\n";
5390 Result += "\tconst struct method_list_t *class_methods;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005391 Result += "\tconst struct method_list_t *optionalInstanceMethods;\n";
5392 Result += "\tconst struct method_list_t *optionalClassMethods;\n";
5393 Result += "\tconst struct _prop_list_t * properties;\n";
5394 Result += "\tconst unsigned int size; // sizeof(struct _protocol_t)\n";
5395 Result += "\tconst unsigned int flags; // = 0\n";
5396 Result += "\tconst char ** extendedMethodTypes;\n";
5397 Result += "};\n";
5398
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005399 Result += "\nstruct _ivar_t {\n";
5400 Result += "\tunsigned long int *offset; // pointer to ivar offset location\n";
Fariborz Jahanianae932952012-02-10 20:47:10 +00005401 Result += "\tconst char *name;\n";
5402 Result += "\tconst char *type;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005403 Result += "\tunsigned int alignment;\n";
5404 Result += "\tunsigned int size;\n";
5405 Result += "};\n";
5406
5407 Result += "\nstruct _class_ro_t {\n";
Fariborz Jahanian249cd102012-03-24 16:53:16 +00005408 Result += "\tunsigned int flags;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005409 Result += "\tunsigned int instanceStart;\n";
Fariborz Jahanian249cd102012-03-24 16:53:16 +00005410 Result += "\tunsigned int instanceSize;\n";
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00005411 const llvm::Triple &Triple(Context->getTargetInfo().getTriple());
5412 if (Triple.getArch() == llvm::Triple::x86_64)
Fariborz Jahanian249cd102012-03-24 16:53:16 +00005413 Result += "\tunsigned int reserved;\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005414 Result += "\tconst unsigned char *ivarLayout;\n";
5415 Result += "\tconst char *name;\n";
5416 Result += "\tconst struct _method_list_t *baseMethods;\n";
5417 Result += "\tconst struct _objc_protocol_list *baseProtocols;\n";
5418 Result += "\tconst struct _ivar_list_t *ivars;\n";
5419 Result += "\tconst unsigned char *weakIvarLayout;\n";
5420 Result += "\tconst struct _prop_list_t *properties;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005421 Result += "};\n";
5422
5423 Result += "\nstruct _class_t {\n";
5424 Result += "\tstruct _class_t *isa;\n";
Fariborz Jahanianfd4ce2c2012-03-20 17:34:50 +00005425 Result += "\tstruct _class_t *superclass;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005426 Result += "\tvoid *cache;\n";
5427 Result += "\tvoid *vtable;\n";
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005428 Result += "\tstruct _class_ro_t *ro;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005429 Result += "};\n";
5430
5431 Result += "\nstruct _category_t {\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005432 Result += "\tconst char *name;\n";
Fariborz Jahanian4b2fe6e2012-03-20 21:41:28 +00005433 Result += "\tstruct _class_t *cls;\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005434 Result += "\tconst struct _method_list_t *instance_methods;\n";
5435 Result += "\tconst struct _method_list_t *class_methods;\n";
5436 Result += "\tconst struct _protocol_list_t *protocols;\n";
5437 Result += "\tconst struct _prop_list_t *properties;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005438 Result += "};\n";
5439
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00005440 Result += "extern \"C\" __declspec(dllimport) struct objc_cache _objc_empty_cache;\n";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00005441 Result += "#pragma warning(disable:4273)\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005442 meta_data_declared = true;
5443}
5444
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00005445static void Write_protocol_list_t_TypeDecl(std::string &Result,
5446 long super_protocol_count) {
5447 Result += "struct /*_protocol_list_t*/"; Result += " {\n";
5448 Result += "\tlong protocol_count; // Note, this is 32/64 bit\n";
5449 Result += "\tstruct _protocol_t *super_protocols[";
5450 Result += utostr(super_protocol_count); Result += "];\n";
5451 Result += "}";
5452}
5453
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005454static void Write_method_list_t_TypeDecl(std::string &Result,
5455 unsigned int method_count) {
5456 Result += "struct /*_method_list_t*/"; Result += " {\n";
5457 Result += "\tunsigned int entsize; // sizeof(struct _objc_method)\n";
5458 Result += "\tunsigned int method_count;\n";
5459 Result += "\tstruct _objc_method method_list[";
5460 Result += utostr(method_count); Result += "];\n";
5461 Result += "}";
5462}
5463
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00005464static void Write__prop_list_t_TypeDecl(std::string &Result,
5465 unsigned int property_count) {
5466 Result += "struct /*_prop_list_t*/"; Result += " {\n";
5467 Result += "\tunsigned int entsize; // sizeof(struct _prop_t)\n";
5468 Result += "\tunsigned int count_of_properties;\n";
5469 Result += "\tstruct _prop_t prop_list[";
5470 Result += utostr(property_count); Result += "];\n";
5471 Result += "}";
5472}
5473
Fariborz Jahanianae932952012-02-10 20:47:10 +00005474static void Write__ivar_list_t_TypeDecl(std::string &Result,
5475 unsigned int ivar_count) {
5476 Result += "struct /*_ivar_list_t*/"; Result += " {\n";
5477 Result += "\tunsigned int entsize; // sizeof(struct _prop_t)\n";
5478 Result += "\tunsigned int count;\n";
5479 Result += "\tstruct _ivar_t ivar_list[";
5480 Result += utostr(ivar_count); Result += "];\n";
5481 Result += "}";
5482}
5483
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00005484static void Write_protocol_list_initializer(ASTContext *Context, std::string &Result,
5485 ArrayRef<ObjCProtocolDecl *> SuperProtocols,
5486 StringRef VarName,
5487 StringRef ProtocolName) {
5488 if (SuperProtocols.size() > 0) {
5489 Result += "\nstatic ";
5490 Write_protocol_list_t_TypeDecl(Result, SuperProtocols.size());
5491 Result += " "; Result += VarName;
5492 Result += ProtocolName;
5493 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
5494 Result += "\t"; Result += utostr(SuperProtocols.size()); Result += ",\n";
5495 for (unsigned i = 0, e = SuperProtocols.size(); i < e; i++) {
5496 ObjCProtocolDecl *SuperPD = SuperProtocols[i];
5497 Result += "\t&"; Result += "_OBJC_PROTOCOL_";
5498 Result += SuperPD->getNameAsString();
5499 if (i == e-1)
5500 Result += "\n};\n";
5501 else
5502 Result += ",\n";
5503 }
5504 }
5505}
5506
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005507static void Write_method_list_t_initializer(RewriteModernObjC &RewriteObj,
5508 ASTContext *Context, std::string &Result,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005509 ArrayRef<ObjCMethodDecl *> Methods,
5510 StringRef VarName,
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005511 StringRef TopLevelDeclName,
5512 bool MethodImpl) {
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005513 if (Methods.size() > 0) {
5514 Result += "\nstatic ";
5515 Write_method_list_t_TypeDecl(Result, Methods.size());
5516 Result += " "; Result += VarName;
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005517 Result += TopLevelDeclName;
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005518 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
5519 Result += "\t"; Result += "sizeof(_objc_method)"; Result += ",\n";
5520 Result += "\t"; Result += utostr(Methods.size()); Result += ",\n";
5521 for (unsigned i = 0, e = Methods.size(); i < e; i++) {
5522 ObjCMethodDecl *MD = Methods[i];
5523 if (i == 0)
5524 Result += "\t{{(struct objc_selector *)\"";
5525 else
5526 Result += "\t{(struct objc_selector *)\"";
5527 Result += (MD)->getSelector().getAsString(); Result += "\"";
5528 Result += ", ";
5529 std::string MethodTypeString;
5530 Context->getObjCEncodingForMethodDecl(MD, MethodTypeString);
5531 Result += "\""; Result += MethodTypeString; Result += "\"";
5532 Result += ", ";
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005533 if (!MethodImpl)
5534 Result += "0";
5535 else {
5536 Result += "(void *)";
5537 Result += RewriteObj.MethodInternalNames[MD];
5538 }
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005539 if (i == e-1)
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005540 Result += "}}\n";
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005541 else
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005542 Result += "},\n";
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005543 }
5544 Result += "};\n";
5545 }
5546}
5547
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005548static void Write_prop_list_t_initializer(RewriteModernObjC &RewriteObj,
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00005549 ASTContext *Context, std::string &Result,
5550 ArrayRef<ObjCPropertyDecl *> Properties,
5551 const Decl *Container,
5552 StringRef VarName,
5553 StringRef ProtocolName) {
5554 if (Properties.size() > 0) {
5555 Result += "\nstatic ";
5556 Write__prop_list_t_TypeDecl(Result, Properties.size());
5557 Result += " "; Result += VarName;
5558 Result += ProtocolName;
5559 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
5560 Result += "\t"; Result += "sizeof(_prop_t)"; Result += ",\n";
5561 Result += "\t"; Result += utostr(Properties.size()); Result += ",\n";
5562 for (unsigned i = 0, e = Properties.size(); i < e; i++) {
5563 ObjCPropertyDecl *PropDecl = Properties[i];
5564 if (i == 0)
5565 Result += "\t{{\"";
5566 else
5567 Result += "\t{\"";
5568 Result += PropDecl->getName(); Result += "\",";
5569 std::string PropertyTypeString, QuotePropertyTypeString;
5570 Context->getObjCEncodingForPropertyDecl(PropDecl, Container, PropertyTypeString);
5571 RewriteObj.QuoteDoublequotes(PropertyTypeString, QuotePropertyTypeString);
5572 Result += "\""; Result += QuotePropertyTypeString; Result += "\"";
5573 if (i == e-1)
5574 Result += "}}\n";
5575 else
5576 Result += "},\n";
5577 }
5578 Result += "};\n";
5579 }
5580}
5581
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00005582// Metadata flags
5583enum MetaDataDlags {
5584 CLS = 0x0,
5585 CLS_META = 0x1,
5586 CLS_ROOT = 0x2,
5587 OBJC2_CLS_HIDDEN = 0x10,
5588 CLS_EXCEPTION = 0x20,
5589
5590 /// (Obsolete) ARC-specific: this class has a .release_ivars method
5591 CLS_HAS_IVAR_RELEASER = 0x40,
5592 /// class was compiled with -fobjc-arr
5593 CLS_COMPILED_BY_ARC = 0x80 // (1<<7)
5594};
5595
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005596static void Write__class_ro_t_initializer(ASTContext *Context, std::string &Result,
5597 unsigned int flags,
5598 const std::string &InstanceStart,
5599 const std::string &InstanceSize,
5600 ArrayRef<ObjCMethodDecl *>baseMethods,
5601 ArrayRef<ObjCProtocolDecl *>baseProtocols,
5602 ArrayRef<ObjCIvarDecl *>ivars,
5603 ArrayRef<ObjCPropertyDecl *>Properties,
5604 StringRef VarName,
5605 StringRef ClassName) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005606 Result += "\nstatic struct _class_ro_t ";
5607 Result += VarName; Result += ClassName;
5608 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
5609 Result += "\t";
5610 Result += llvm::utostr(flags); Result += ", ";
5611 Result += InstanceStart; Result += ", ";
5612 Result += InstanceSize; Result += ", \n";
5613 Result += "\t";
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00005614 const llvm::Triple &Triple(Context->getTargetInfo().getTriple());
5615 if (Triple.getArch() == llvm::Triple::x86_64)
5616 // uint32_t const reserved; // only when building for 64bit targets
5617 Result += "(unsigned int)0, \n\t";
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005618 // const uint8_t * const ivarLayout;
5619 Result += "0, \n\t";
5620 Result += "\""; Result += ClassName; Result += "\",\n\t";
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00005621 bool metaclass = ((flags & CLS_META) != 0);
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005622 if (baseMethods.size() > 0) {
5623 Result += "(const struct _method_list_t *)&";
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00005624 if (metaclass)
5625 Result += "_OBJC_$_CLASS_METHODS_";
5626 else
5627 Result += "_OBJC_$_INSTANCE_METHODS_";
5628 Result += ClassName;
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005629 Result += ",\n\t";
5630 }
5631 else
5632 Result += "0, \n\t";
5633
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00005634 if (!metaclass && baseProtocols.size() > 0) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005635 Result += "(const struct _objc_protocol_list *)&";
5636 Result += "_OBJC_CLASS_PROTOCOLS_$_"; Result += ClassName;
5637 Result += ",\n\t";
5638 }
5639 else
5640 Result += "0, \n\t";
5641
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00005642 if (!metaclass && ivars.size() > 0) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005643 Result += "(const struct _ivar_list_t *)&";
5644 Result += "_OBJC_$_INSTANCE_VARIABLES_"; Result += ClassName;
5645 Result += ",\n\t";
5646 }
5647 else
5648 Result += "0, \n\t";
5649
5650 // weakIvarLayout
5651 Result += "0, \n\t";
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00005652 if (!metaclass && Properties.size() > 0) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005653 Result += "(const struct _prop_list_t *)&";
Fariborz Jahanianeeabf382012-02-16 21:57:59 +00005654 Result += "_OBJC_$_PROP_LIST_"; Result += ClassName;
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005655 Result += ",\n";
5656 }
5657 else
5658 Result += "0, \n";
5659
5660 Result += "};\n";
5661}
5662
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005663static void Write_class_t(ASTContext *Context, std::string &Result,
5664 StringRef VarName,
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00005665 const ObjCInterfaceDecl *CDecl, bool metaclass) {
5666 bool rootClass = (!CDecl->getSuperClass());
5667 const ObjCInterfaceDecl *RootClass = CDecl;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005668
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00005669 if (!rootClass) {
5670 // Find the Root class
5671 RootClass = CDecl->getSuperClass();
5672 while (RootClass->getSuperClass()) {
5673 RootClass = RootClass->getSuperClass();
5674 }
5675 }
5676
5677 if (metaclass && rootClass) {
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005678 // Need to handle a case of use of forward declaration.
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00005679 Result += "\n";
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00005680 Result += "extern \"C\" ";
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00005681 if (CDecl->getImplementation())
5682 Result += "__declspec(dllexport) ";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00005683 else
5684 Result += "__declspec(dllimport) ";
5685
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00005686 Result += "struct _class_t OBJC_CLASS_$_";
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005687 Result += CDecl->getNameAsString();
5688 Result += ";\n";
5689 }
5690 // Also, for possibility of 'super' metadata class not having been defined yet.
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00005691 if (!rootClass) {
Fariborz Jahanian868e9852012-03-29 19:04:10 +00005692 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00005693 Result += "\n";
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00005694 Result += "extern \"C\" ";
Fariborz Jahanian868e9852012-03-29 19:04:10 +00005695 if (SuperClass->getImplementation())
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00005696 Result += "__declspec(dllexport) ";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00005697 else
5698 Result += "__declspec(dllimport) ";
5699
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00005700 Result += "struct _class_t ";
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00005701 Result += VarName;
Fariborz Jahanian868e9852012-03-29 19:04:10 +00005702 Result += SuperClass->getNameAsString();
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005703 Result += ";\n";
Fariborz Jahanian452eac12012-03-20 21:09:58 +00005704
Fariborz Jahanian868e9852012-03-29 19:04:10 +00005705 if (metaclass && RootClass != SuperClass) {
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00005706 Result += "extern \"C\" ";
Fariborz Jahanian452eac12012-03-20 21:09:58 +00005707 if (RootClass->getImplementation())
5708 Result += "__declspec(dllexport) ";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00005709 else
5710 Result += "__declspec(dllimport) ";
5711
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00005712 Result += "struct _class_t ";
Fariborz Jahanian452eac12012-03-20 21:09:58 +00005713 Result += VarName;
5714 Result += RootClass->getNameAsString();
5715 Result += ";\n";
5716 }
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005717 }
5718
Fariborz Jahanian297976d2012-03-29 17:51:09 +00005719 Result += "\nextern \"C\" __declspec(dllexport) struct _class_t ";
5720 Result += VarName; Result += CDecl->getNameAsString();
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005721 Result += " __attribute__ ((used, section (\"__DATA,__objc_data\"))) = {\n";
5722 Result += "\t";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00005723 if (metaclass) {
5724 if (!rootClass) {
5725 Result += "0, // &"; Result += VarName;
5726 Result += RootClass->getNameAsString();
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005727 Result += ",\n\t";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00005728 Result += "0, // &"; Result += VarName;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005729 Result += CDecl->getSuperClass()->getNameAsString();
5730 Result += ",\n\t";
5731 }
5732 else {
Fariborz Jahanian452eac12012-03-20 21:09:58 +00005733 Result += "0, // &"; Result += VarName;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005734 Result += CDecl->getNameAsString();
5735 Result += ",\n\t";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00005736 Result += "0, // &OBJC_CLASS_$_"; Result += CDecl->getNameAsString();
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005737 Result += ",\n\t";
5738 }
5739 }
5740 else {
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00005741 Result += "0, // &OBJC_METACLASS_$_";
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005742 Result += CDecl->getNameAsString();
5743 Result += ",\n\t";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00005744 if (!rootClass) {
5745 Result += "0, // &"; Result += VarName;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005746 Result += CDecl->getSuperClass()->getNameAsString();
5747 Result += ",\n\t";
5748 }
5749 else
5750 Result += "0,\n\t";
5751 }
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00005752 Result += "0, // (void *)&_objc_empty_cache,\n\t";
5753 Result += "0, // unused, was (void *)&_objc_empty_vtable,\n\t";
5754 if (metaclass)
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005755 Result += "&_OBJC_METACLASS_RO_$_";
5756 else
5757 Result += "&_OBJC_CLASS_RO_$_";
5758 Result += CDecl->getNameAsString();
5759 Result += ",\n};\n";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00005760
5761 // Add static function to initialize some of the meta-data fields.
5762 // avoid doing it twice.
5763 if (metaclass)
5764 return;
5765
5766 const ObjCInterfaceDecl *SuperClass =
5767 rootClass ? CDecl : CDecl->getSuperClass();
5768
5769 Result += "static void OBJC_CLASS_SETUP_$_";
5770 Result += CDecl->getNameAsString();
5771 Result += "(void ) {\n";
5772 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
5773 Result += ".isa = "; Result += "&OBJC_METACLASS_$_";
Fariborz Jahanian452eac12012-03-20 21:09:58 +00005774 Result += RootClass->getNameAsString(); Result += ";\n";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00005775
5776 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
Fariborz Jahanian452eac12012-03-20 21:09:58 +00005777 Result += ".superclass = ";
5778 if (rootClass)
5779 Result += "&OBJC_CLASS_$_";
5780 else
5781 Result += "&OBJC_METACLASS_$_";
5782
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00005783 Result += SuperClass->getNameAsString(); Result += ";\n";
5784
5785 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
5786 Result += ".cache = "; Result += "&_objc_empty_cache"; Result += ";\n";
5787
5788 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
5789 Result += ".isa = "; Result += "&OBJC_METACLASS_$_";
5790 Result += CDecl->getNameAsString(); Result += ";\n";
5791
5792 if (!rootClass) {
5793 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
5794 Result += ".superclass = "; Result += "&OBJC_CLASS_$_";
5795 Result += SuperClass->getNameAsString(); Result += ";\n";
5796 }
5797
5798 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
5799 Result += ".cache = "; Result += "&_objc_empty_cache"; Result += ";\n";
5800 Result += "}\n";
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005801}
5802
Fariborz Jahanian61186122012-02-17 18:40:41 +00005803static void Write_category_t(RewriteModernObjC &RewriteObj, ASTContext *Context,
5804 std::string &Result,
Fariborz Jahaniane0335782012-03-27 18:41:05 +00005805 ObjCCategoryDecl *CatDecl,
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00005806 ObjCInterfaceDecl *ClassDecl,
Fariborz Jahanian61186122012-02-17 18:40:41 +00005807 ArrayRef<ObjCMethodDecl *> InstanceMethods,
5808 ArrayRef<ObjCMethodDecl *> ClassMethods,
5809 ArrayRef<ObjCProtocolDecl *> RefedProtocols,
5810 ArrayRef<ObjCPropertyDecl *> ClassProperties) {
Fariborz Jahaniane0335782012-03-27 18:41:05 +00005811 StringRef CatName = CatDecl->getName();
NAKAMURA Takumi20f89392012-03-21 03:21:46 +00005812 StringRef ClassName = ClassDecl->getName();
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00005813 // must declare an extern class object in case this class is not implemented
5814 // in this TU.
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00005815 Result += "\n";
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00005816 Result += "extern \"C\" ";
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00005817 if (ClassDecl->getImplementation())
5818 Result += "__declspec(dllexport) ";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00005819 else
5820 Result += "__declspec(dllimport) ";
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00005821
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00005822 Result += "struct _class_t ";
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00005823 Result += "OBJC_CLASS_$_"; Result += ClassName;
5824 Result += ";\n";
5825
Fariborz Jahanian61186122012-02-17 18:40:41 +00005826 Result += "\nstatic struct _category_t ";
5827 Result += "_OBJC_$_CATEGORY_";
5828 Result += ClassName; Result += "_$_"; Result += CatName;
5829 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = \n";
5830 Result += "{\n";
5831 Result += "\t\""; Result += ClassName; Result += "\",\n";
Fariborz Jahanian4b2fe6e2012-03-20 21:41:28 +00005832 Result += "\t0, // &"; Result += "OBJC_CLASS_$_"; Result += ClassName;
Fariborz Jahanian61186122012-02-17 18:40:41 +00005833 Result += ",\n";
5834 if (InstanceMethods.size() > 0) {
5835 Result += "\t(const struct _method_list_t *)&";
5836 Result += "_OBJC_$_CATEGORY_INSTANCE_METHODS_";
5837 Result += ClassName; Result += "_$_"; Result += CatName;
5838 Result += ",\n";
5839 }
5840 else
5841 Result += "\t0,\n";
5842
5843 if (ClassMethods.size() > 0) {
5844 Result += "\t(const struct _method_list_t *)&";
5845 Result += "_OBJC_$_CATEGORY_CLASS_METHODS_";
5846 Result += ClassName; Result += "_$_"; Result += CatName;
5847 Result += ",\n";
5848 }
5849 else
5850 Result += "\t0,\n";
5851
5852 if (RefedProtocols.size() > 0) {
5853 Result += "\t(const struct _protocol_list_t *)&";
5854 Result += "_OBJC_CATEGORY_PROTOCOLS_$_";
5855 Result += ClassName; Result += "_$_"; Result += CatName;
5856 Result += ",\n";
5857 }
5858 else
5859 Result += "\t0,\n";
5860
5861 if (ClassProperties.size() > 0) {
5862 Result += "\t(const struct _prop_list_t *)&"; Result += "_OBJC_$_PROP_LIST_";
5863 Result += ClassName; Result += "_$_"; Result += CatName;
5864 Result += ",\n";
5865 }
5866 else
5867 Result += "\t0,\n";
5868
5869 Result += "};\n";
Fariborz Jahanian4b2fe6e2012-03-20 21:41:28 +00005870
5871 // Add static function to initialize the class pointer in the category structure.
5872 Result += "static void OBJC_CATEGORY_SETUP_$_";
5873 Result += ClassDecl->getNameAsString();
5874 Result += "_$_";
5875 Result += CatName;
5876 Result += "(void ) {\n";
5877 Result += "\t_OBJC_$_CATEGORY_";
5878 Result += ClassDecl->getNameAsString();
5879 Result += "_$_";
5880 Result += CatName;
5881 Result += ".cls = "; Result += "&OBJC_CLASS_$_"; Result += ClassName;
5882 Result += ";\n}\n";
Fariborz Jahanian61186122012-02-17 18:40:41 +00005883}
5884
Fariborz Jahaniane0adbd82012-02-08 22:23:26 +00005885static void Write__extendedMethodTypes_initializer(RewriteModernObjC &RewriteObj,
5886 ASTContext *Context, std::string &Result,
5887 ArrayRef<ObjCMethodDecl *> Methods,
5888 StringRef VarName,
5889 StringRef ProtocolName) {
5890 if (Methods.size() == 0)
5891 return;
5892
5893 Result += "\nstatic const char *";
5894 Result += VarName; Result += ProtocolName;
5895 Result += " [] __attribute__ ((used, section (\"__DATA,__objc_const\"))) = \n";
5896 Result += "{\n";
5897 for (unsigned i = 0, e = Methods.size(); i < e; i++) {
5898 ObjCMethodDecl *MD = Methods[i];
5899 std::string MethodTypeString, QuoteMethodTypeString;
5900 Context->getObjCEncodingForMethodDecl(MD, MethodTypeString, true);
5901 RewriteObj.QuoteDoublequotes(MethodTypeString, QuoteMethodTypeString);
5902 Result += "\t\""; Result += QuoteMethodTypeString; Result += "\"";
5903 if (i == e-1)
5904 Result += "\n};\n";
5905 else {
5906 Result += ",\n";
5907 }
5908 }
5909}
5910
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00005911static void Write_IvarOffsetVar(ASTContext *Context,
5912 std::string &Result,
Fariborz Jahaniandb649232012-02-13 20:59:02 +00005913 ArrayRef<ObjCIvarDecl *> Ivars,
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00005914 ObjCInterfaceDecl *CDecl) {
Fariborz Jahaniandb649232012-02-13 20:59:02 +00005915 // FIXME. visibilty of offset symbols may have to be set; for Darwin
5916 // this is what happens:
5917 /**
5918 if (Ivar->getAccessControl() == ObjCIvarDecl::Private ||
5919 Ivar->getAccessControl() == ObjCIvarDecl::Package ||
5920 Class->getVisibility() == HiddenVisibility)
5921 Visibility shoud be: HiddenVisibility;
5922 else
5923 Visibility shoud be: DefaultVisibility;
5924 */
5925
Fariborz Jahanian07e52882012-02-13 21:34:45 +00005926 Result += "\n";
5927 for (unsigned i =0, e = Ivars.size(); i < e; i++) {
5928 ObjCIvarDecl *IvarDecl = Ivars[i];
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00005929 if (Context->getLangOpts().MicrosoftExt)
5930 Result += "__declspec(allocate(\".objc_ivar$B\")) ";
5931
5932 if (!Context->getLangOpts().MicrosoftExt ||
5933 IvarDecl->getAccessControl() == ObjCIvarDecl::Private ||
Fariborz Jahanian117591f2012-03-10 01:34:42 +00005934 IvarDecl->getAccessControl() == ObjCIvarDecl::Package)
Fariborz Jahanian297976d2012-03-29 17:51:09 +00005935 Result += "extern \"C\" unsigned long int ";
Fariborz Jahaniand1c84d32012-03-10 00:53:02 +00005936 else
Fariborz Jahanian297976d2012-03-29 17:51:09 +00005937 Result += "extern \"C\" __declspec(dllexport) unsigned long int ";
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00005938 WriteInternalIvarName(CDecl, IvarDecl, Result);
Fariborz Jahanian07e52882012-02-13 21:34:45 +00005939 Result += " __attribute__ ((used, section (\"__DATA,__objc_ivar\")))";
5940 Result += " = ";
5941 if (IvarDecl->isBitField()) {
5942 // FIXME: The hack below doesn't work for bitfields. For now, we simply
5943 // place all bitfields at offset 0.
5944 Result += "0;\n";
5945 }
5946 else {
Fariborz Jahaniandb649232012-02-13 20:59:02 +00005947 Result += "__OFFSETOFIVAR__(struct ";
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00005948 Result += CDecl->getNameAsString();
Fariborz Jahaniandb649232012-02-13 20:59:02 +00005949 Result += "_IMPL, ";
5950 Result += IvarDecl->getName(); Result += ");\n";
5951 }
5952 }
5953}
5954
Fariborz Jahanianae932952012-02-10 20:47:10 +00005955static void Write__ivar_list_t_initializer(RewriteModernObjC &RewriteObj,
5956 ASTContext *Context, std::string &Result,
5957 ArrayRef<ObjCIvarDecl *> Ivars,
5958 StringRef VarName,
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00005959 ObjCInterfaceDecl *CDecl) {
Fariborz Jahanianae932952012-02-10 20:47:10 +00005960 if (Ivars.size() > 0) {
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00005961 Write_IvarOffsetVar(Context, Result, Ivars, CDecl);
Fariborz Jahanian07e52882012-02-13 21:34:45 +00005962
Fariborz Jahanianae932952012-02-10 20:47:10 +00005963 Result += "\nstatic ";
5964 Write__ivar_list_t_TypeDecl(Result, Ivars.size());
5965 Result += " "; Result += VarName;
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00005966 Result += CDecl->getNameAsString();
Fariborz Jahanianae932952012-02-10 20:47:10 +00005967 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
5968 Result += "\t"; Result += "sizeof(_ivar_t)"; Result += ",\n";
5969 Result += "\t"; Result += utostr(Ivars.size()); Result += ",\n";
5970 for (unsigned i =0, e = Ivars.size(); i < e; i++) {
5971 ObjCIvarDecl *IvarDecl = Ivars[i];
5972 if (i == 0)
5973 Result += "\t{{";
5974 else
5975 Result += "\t {";
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00005976 Result += "(unsigned long int *)&";
5977 WriteInternalIvarName(CDecl, IvarDecl, Result);
Fariborz Jahaniandb649232012-02-13 20:59:02 +00005978 Result += ", ";
Fariborz Jahanianae932952012-02-10 20:47:10 +00005979
5980 Result += "\""; Result += IvarDecl->getName(); Result += "\", ";
5981 std::string IvarTypeString, QuoteIvarTypeString;
5982 Context->getObjCEncodingForType(IvarDecl->getType(), IvarTypeString,
5983 IvarDecl);
5984 RewriteObj.QuoteDoublequotes(IvarTypeString, QuoteIvarTypeString);
5985 Result += "\""; Result += QuoteIvarTypeString; Result += "\", ";
5986
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00005987 // FIXME. this alignment represents the host alignment and need be changed to
5988 // represent the target alignment.
5989 unsigned Align = Context->getTypeAlign(IvarDecl->getType())/8;
5990 Align = llvm::Log2_32(Align);
Fariborz Jahanianae932952012-02-10 20:47:10 +00005991 Result += llvm::utostr(Align); Result += ", ";
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00005992 CharUnits Size = Context->getTypeSizeInChars(IvarDecl->getType());
5993 Result += llvm::utostr(Size.getQuantity());
Fariborz Jahanianae932952012-02-10 20:47:10 +00005994 if (i == e-1)
5995 Result += "}}\n";
5996 else
5997 Result += "},\n";
5998 }
5999 Result += "};\n";
6000 }
6001}
6002
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006003/// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006004void RewriteModernObjC::RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl,
6005 std::string &Result) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006006
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006007 // Do not synthesize the protocol more than once.
6008 if (ObjCSynthesizedProtocols.count(PDecl->getCanonicalDecl()))
6009 return;
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00006010 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006011
6012 if (ObjCProtocolDecl *Def = PDecl->getDefinition())
6013 PDecl = Def;
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006014 // Must write out all protocol definitions in current qualifier list,
6015 // and in their nested qualifiers before writing out current definition.
6016 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
6017 E = PDecl->protocol_end(); I != E; ++I)
6018 RewriteObjCProtocolMetaData(*I, Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006019
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006020 // Construct method lists.
6021 std::vector<ObjCMethodDecl *> InstanceMethods, ClassMethods;
6022 std::vector<ObjCMethodDecl *> OptInstanceMethods, OptClassMethods;
6023 for (ObjCProtocolDecl::instmeth_iterator
6024 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
6025 I != E; ++I) {
6026 ObjCMethodDecl *MD = *I;
6027 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
6028 OptInstanceMethods.push_back(MD);
6029 } else {
6030 InstanceMethods.push_back(MD);
6031 }
6032 }
6033
6034 for (ObjCProtocolDecl::classmeth_iterator
6035 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
6036 I != E; ++I) {
6037 ObjCMethodDecl *MD = *I;
6038 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
6039 OptClassMethods.push_back(MD);
6040 } else {
6041 ClassMethods.push_back(MD);
6042 }
6043 }
Fariborz Jahaniane0adbd82012-02-08 22:23:26 +00006044 std::vector<ObjCMethodDecl *> AllMethods;
6045 for (unsigned i = 0, e = InstanceMethods.size(); i < e; i++)
6046 AllMethods.push_back(InstanceMethods[i]);
6047 for (unsigned i = 0, e = ClassMethods.size(); i < e; i++)
6048 AllMethods.push_back(ClassMethods[i]);
6049 for (unsigned i = 0, e = OptInstanceMethods.size(); i < e; i++)
6050 AllMethods.push_back(OptInstanceMethods[i]);
6051 for (unsigned i = 0, e = OptClassMethods.size(); i < e; i++)
6052 AllMethods.push_back(OptClassMethods[i]);
6053
6054 Write__extendedMethodTypes_initializer(*this, Context, Result,
6055 AllMethods,
6056 "_OBJC_PROTOCOL_METHOD_TYPES_",
6057 PDecl->getNameAsString());
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006058 // Protocol's super protocol list
6059 std::vector<ObjCProtocolDecl *> SuperProtocols;
6060 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
6061 E = PDecl->protocol_end(); I != E; ++I)
6062 SuperProtocols.push_back(*I);
6063
6064 Write_protocol_list_initializer(Context, Result, SuperProtocols,
6065 "_OBJC_PROTOCOL_REFS_",
6066 PDecl->getNameAsString());
6067
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006068 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006069 "_OBJC_PROTOCOL_INSTANCE_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006070 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006071
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006072 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006073 "_OBJC_PROTOCOL_CLASS_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006074 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006075
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006076 Write_method_list_t_initializer(*this, Context, Result, OptInstanceMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006077 "_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006078 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006079
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006080 Write_method_list_t_initializer(*this, Context, Result, OptClassMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006081 "_OBJC_PROTOCOL_OPT_CLASS_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006082 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006083
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006084 // Protocol's property metadata.
6085 std::vector<ObjCPropertyDecl *> ProtocolProperties;
6086 for (ObjCContainerDecl::prop_iterator I = PDecl->prop_begin(),
6087 E = PDecl->prop_end(); I != E; ++I)
6088 ProtocolProperties.push_back(*I);
6089
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006090 Write_prop_list_t_initializer(*this, Context, Result, ProtocolProperties,
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006091 /* Container */0,
6092 "_OBJC_PROTOCOL_PROPERTIES_",
6093 PDecl->getNameAsString());
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006094
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006095 // Writer out root metadata for current protocol: struct _protocol_t
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00006096 Result += "\n";
6097 if (LangOpts.MicrosoftExt)
6098 Result += "__declspec(allocate(\".datacoal_nt$B\")) ";
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00006099 Result += "struct _protocol_t _OBJC_PROTOCOL_";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006100 Result += PDecl->getNameAsString();
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006101 Result += " __attribute__ ((used, section (\"__DATA,__datacoal_nt,coalesced\"))) = {\n";
6102 Result += "\t0,\n"; // id is; is null
6103 Result += "\t\""; Result += PDecl->getNameAsString(); Result += "\",\n";
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006104 if (SuperProtocols.size() > 0) {
6105 Result += "\t(const struct _protocol_list_t *)&"; Result += "_OBJC_PROTOCOL_REFS_";
6106 Result += PDecl->getNameAsString(); Result += ",\n";
6107 }
6108 else
6109 Result += "\t0,\n";
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006110 if (InstanceMethods.size() > 0) {
6111 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
6112 Result += PDecl->getNameAsString(); Result += ",\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006113 }
6114 else
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006115 Result += "\t0,\n";
6116
6117 if (ClassMethods.size() > 0) {
6118 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_CLASS_METHODS_";
6119 Result += PDecl->getNameAsString(); Result += ",\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006120 }
6121 else
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006122 Result += "\t0,\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006123
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006124 if (OptInstanceMethods.size() > 0) {
6125 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_";
6126 Result += PDecl->getNameAsString(); Result += ",\n";
6127 }
6128 else
6129 Result += "\t0,\n";
6130
6131 if (OptClassMethods.size() > 0) {
6132 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_CLASS_METHODS_";
6133 Result += PDecl->getNameAsString(); Result += ",\n";
6134 }
6135 else
6136 Result += "\t0,\n";
6137
6138 if (ProtocolProperties.size() > 0) {
6139 Result += "\t(const struct _prop_list_t *)&_OBJC_PROTOCOL_PROPERTIES_";
6140 Result += PDecl->getNameAsString(); Result += ",\n";
6141 }
6142 else
6143 Result += "\t0,\n";
6144
6145 Result += "\t"; Result += "sizeof(_protocol_t)"; Result += ",\n";
6146 Result += "\t0,\n";
6147
Fariborz Jahaniane0adbd82012-02-08 22:23:26 +00006148 if (AllMethods.size() > 0) {
6149 Result += "\t(const char **)&"; Result += "_OBJC_PROTOCOL_METHOD_TYPES_";
6150 Result += PDecl->getNameAsString();
6151 Result += "\n};\n";
6152 }
6153 else
6154 Result += "\t0\n};\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00006155
6156 // Use this protocol meta-data to build protocol list table in section
6157 // .objc_protolist$B
6158 // Unspecified visibility means 'private extern'.
6159 if (LangOpts.MicrosoftExt)
6160 Result += "__declspec(allocate(\".objc_protolist$B\")) ";
6161 Result += "struct _protocol_t *";
6162 Result += "_OBJC_LABEL_PROTOCOL_$_"; Result += PDecl->getNameAsString();
6163 Result += " = &_OBJC_PROTOCOL_"; Result += PDecl->getNameAsString();
6164 Result += ";\n";
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006165
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006166 // Mark this protocol as having been generated.
6167 if (!ObjCSynthesizedProtocols.insert(PDecl->getCanonicalDecl()))
6168 llvm_unreachable("protocol already synthesized");
6169
6170}
6171
6172void RewriteModernObjC::RewriteObjCProtocolListMetaData(
6173 const ObjCList<ObjCProtocolDecl> &Protocols,
6174 StringRef prefix, StringRef ClassName,
6175 std::string &Result) {
6176 if (Protocols.empty()) return;
6177
6178 for (unsigned i = 0; i != Protocols.size(); i++)
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006179 RewriteObjCProtocolMetaData(Protocols[i], Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006180
6181 // Output the top lovel protocol meta-data for the class.
6182 /* struct _objc_protocol_list {
6183 struct _objc_protocol_list *next;
6184 int protocol_count;
6185 struct _objc_protocol *class_protocols[];
6186 }
6187 */
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00006188 Result += "\n";
6189 if (LangOpts.MicrosoftExt)
6190 Result += "__declspec(allocate(\".cat_cls_meth$B\")) ";
6191 Result += "static struct {\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006192 Result += "\tstruct _objc_protocol_list *next;\n";
6193 Result += "\tint protocol_count;\n";
6194 Result += "\tstruct _objc_protocol *class_protocols[";
6195 Result += utostr(Protocols.size());
6196 Result += "];\n} _OBJC_";
6197 Result += prefix;
6198 Result += "_PROTOCOLS_";
6199 Result += ClassName;
6200 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
6201 "{\n\t0, ";
6202 Result += utostr(Protocols.size());
6203 Result += "\n";
6204
6205 Result += "\t,{&_OBJC_PROTOCOL_";
6206 Result += Protocols[0]->getNameAsString();
6207 Result += " \n";
6208
6209 for (unsigned i = 1; i != Protocols.size(); i++) {
6210 Result += "\t ,&_OBJC_PROTOCOL_";
6211 Result += Protocols[i]->getNameAsString();
6212 Result += "\n";
6213 }
6214 Result += "\t }\n};\n";
6215}
6216
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006217/// hasObjCExceptionAttribute - Return true if this class or any super
6218/// class has the __objc_exception__ attribute.
6219/// FIXME. Move this to ASTContext.cpp as it is also used for IRGen.
6220static bool hasObjCExceptionAttribute(ASTContext &Context,
6221 const ObjCInterfaceDecl *OID) {
6222 if (OID->hasAttr<ObjCExceptionAttr>())
6223 return true;
6224 if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
6225 return hasObjCExceptionAttribute(Context, Super);
6226 return false;
6227}
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006228
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006229void RewriteModernObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
6230 std::string &Result) {
6231 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
6232
6233 // Explicitly declared @interface's are already synthesized.
Fariborz Jahanianae932952012-02-10 20:47:10 +00006234 if (CDecl->isImplicitInterfaceDecl())
6235 assert(false &&
6236 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00006237
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00006238 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanianae932952012-02-10 20:47:10 +00006239 SmallVector<ObjCIvarDecl *, 8> IVars;
6240
6241 for (ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
6242 IVD; IVD = IVD->getNextIvar()) {
6243 // Ignore unnamed bit-fields.
6244 if (!IVD->getDeclName())
6245 continue;
6246 IVars.push_back(IVD);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006247 }
6248
Fariborz Jahanianae932952012-02-10 20:47:10 +00006249 Write__ivar_list_t_initializer(*this, Context, Result, IVars,
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006250 "_OBJC_$_INSTANCE_VARIABLES_",
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006251 CDecl);
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006252
6253 // Build _objc_method_list for class's instance methods if needed
6254 SmallVector<ObjCMethodDecl *, 32>
6255 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
6256
6257 // If any of our property implementations have associated getters or
6258 // setters, produce metadata for them as well.
6259 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
6260 PropEnd = IDecl->propimpl_end();
6261 Prop != PropEnd; ++Prop) {
6262 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
6263 continue;
6264 if (!(*Prop)->getPropertyIvarDecl())
6265 continue;
6266 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
6267 if (!PD)
6268 continue;
6269 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
6270 if (!Getter->isDefined())
6271 InstanceMethods.push_back(Getter);
6272 if (PD->isReadOnly())
6273 continue;
6274 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
6275 if (!Setter->isDefined())
6276 InstanceMethods.push_back(Setter);
6277 }
6278
6279 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
6280 "_OBJC_$_INSTANCE_METHODS_",
6281 IDecl->getNameAsString(), true);
6282
6283 SmallVector<ObjCMethodDecl *, 32>
6284 ClassMethods(IDecl->classmeth_begin(), IDecl->classmeth_end());
6285
6286 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
6287 "_OBJC_$_CLASS_METHODS_",
6288 IDecl->getNameAsString(), true);
Fariborz Jahanian0a525342012-02-14 19:31:35 +00006289
6290 // Protocols referenced in class declaration?
6291 // Protocol's super protocol list
6292 std::vector<ObjCProtocolDecl *> RefedProtocols;
6293 const ObjCList<ObjCProtocolDecl> &Protocols = CDecl->getReferencedProtocols();
6294 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
6295 E = Protocols.end();
6296 I != E; ++I) {
6297 RefedProtocols.push_back(*I);
6298 // Must write out all protocol definitions in current qualifier list,
6299 // and in their nested qualifiers before writing out current definition.
6300 RewriteObjCProtocolMetaData(*I, Result);
6301 }
6302
6303 Write_protocol_list_initializer(Context, Result,
6304 RefedProtocols,
6305 "_OBJC_CLASS_PROTOCOLS_$_",
6306 IDecl->getNameAsString());
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006307
6308 // Protocol's property metadata.
6309 std::vector<ObjCPropertyDecl *> ClassProperties;
6310 for (ObjCContainerDecl::prop_iterator I = CDecl->prop_begin(),
6311 E = CDecl->prop_end(); I != E; ++I)
6312 ClassProperties.push_back(*I);
6313
6314 Write_prop_list_t_initializer(*this, Context, Result, ClassProperties,
Fariborz Jahanian2df089d2012-03-22 17:39:35 +00006315 /* Container */IDecl,
Fariborz Jahanianeeabf382012-02-16 21:57:59 +00006316 "_OBJC_$_PROP_LIST_",
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006317 CDecl->getNameAsString());
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006318
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006319
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006320 // Data for initializing _class_ro_t metaclass meta-data
6321 uint32_t flags = CLS_META;
6322 std::string InstanceSize;
6323 std::string InstanceStart;
6324
6325
6326 bool classIsHidden = CDecl->getVisibility() == HiddenVisibility;
6327 if (classIsHidden)
6328 flags |= OBJC2_CLS_HIDDEN;
6329
6330 if (!CDecl->getSuperClass())
6331 // class is root
6332 flags |= CLS_ROOT;
6333 InstanceSize = "sizeof(struct _class_t)";
6334 InstanceStart = InstanceSize;
6335 Write__class_ro_t_initializer(Context, Result, flags,
6336 InstanceStart, InstanceSize,
6337 ClassMethods,
6338 0,
6339 0,
6340 0,
6341 "_OBJC_METACLASS_RO_$_",
6342 CDecl->getNameAsString());
6343
6344
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006345 // Data for initializing _class_ro_t meta-data
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006346 flags = CLS;
6347 if (classIsHidden)
6348 flags |= OBJC2_CLS_HIDDEN;
6349
6350 if (hasObjCExceptionAttribute(*Context, CDecl))
6351 flags |= CLS_EXCEPTION;
6352
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006353 if (!CDecl->getSuperClass())
6354 // class is root
6355 flags |= CLS_ROOT;
6356
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006357 InstanceSize.clear();
6358 InstanceStart.clear();
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006359 if (!ObjCSynthesizedStructs.count(CDecl)) {
6360 InstanceSize = "0";
6361 InstanceStart = "0";
6362 }
6363 else {
6364 InstanceSize = "sizeof(struct ";
6365 InstanceSize += CDecl->getNameAsString();
6366 InstanceSize += "_IMPL)";
6367
6368 ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
6369 if (IVD) {
6370 InstanceStart += "__OFFSETOFIVAR__(struct ";
6371 InstanceStart += CDecl->getNameAsString();
6372 InstanceStart += "_IMPL, ";
6373 InstanceStart += IVD->getNameAsString();
6374 InstanceStart += ")";
6375 }
6376 else
6377 InstanceStart = InstanceSize;
6378 }
6379 Write__class_ro_t_initializer(Context, Result, flags,
6380 InstanceStart, InstanceSize,
6381 InstanceMethods,
6382 RefedProtocols,
6383 IVars,
6384 ClassProperties,
6385 "_OBJC_CLASS_RO_$_",
6386 CDecl->getNameAsString());
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006387
6388 Write_class_t(Context, Result,
6389 "OBJC_METACLASS_$_",
6390 CDecl, /*metaclass*/true);
6391
6392 Write_class_t(Context, Result,
6393 "OBJC_CLASS_$_",
6394 CDecl, /*metaclass*/false);
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006395
6396 if (ImplementationIsNonLazy(IDecl))
6397 DefinedNonLazyClasses.push_back(CDecl);
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006398
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006399}
6400
Fariborz Jahaniane0335782012-03-27 18:41:05 +00006401void RewriteModernObjC::RewriteClassSetupInitHook(std::string &Result) {
6402 int ClsDefCount = ClassImplementation.size();
6403 if (!ClsDefCount)
6404 return;
6405 Result += "#pragma section(\".objc_inithooks$B\", long, read, write)\n";
6406 Result += "__declspec(allocate(\".objc_inithooks$B\")) ";
6407 Result += "static void *OBJC_CLASS_SETUP[] = {\n";
6408 for (int i = 0; i < ClsDefCount; i++) {
6409 ObjCImplementationDecl *IDecl = ClassImplementation[i];
6410 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
6411 Result += "\t(void *)&OBJC_CLASS_SETUP_$_";
6412 Result += CDecl->getName(); Result += ",\n";
6413 }
6414 Result += "};\n";
6415}
6416
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006417void RewriteModernObjC::RewriteMetaDataIntoBuffer(std::string &Result) {
6418 int ClsDefCount = ClassImplementation.size();
6419 int CatDefCount = CategoryImplementation.size();
6420
6421 // For each implemented class, write out all its meta data.
6422 for (int i = 0; i < ClsDefCount; i++)
6423 RewriteObjCClassMetaData(ClassImplementation[i], Result);
6424
Fariborz Jahaniane0335782012-03-27 18:41:05 +00006425 RewriteClassSetupInitHook(Result);
6426
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006427 // For each implemented category, write out all its meta data.
6428 for (int i = 0; i < CatDefCount; i++)
6429 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
6430
Fariborz Jahaniane0335782012-03-27 18:41:05 +00006431 RewriteCategorySetupInitHook(Result);
6432
Fariborz Jahaniandf795672012-02-17 00:06:14 +00006433 if (ClsDefCount > 0) {
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00006434 if (LangOpts.MicrosoftExt)
6435 Result += "__declspec(allocate(\".objc_classlist$B\")) ";
Fariborz Jahaniandf795672012-02-17 00:06:14 +00006436 Result += "static struct _class_t *L_OBJC_LABEL_CLASS_$ [";
6437 Result += llvm::utostr(ClsDefCount); Result += "]";
6438 Result +=
6439 " __attribute__((used, section (\"__DATA, __objc_classlist,"
6440 "regular,no_dead_strip\")))= {\n";
6441 for (int i = 0; i < ClsDefCount; i++) {
6442 Result += "\t&OBJC_CLASS_$_";
6443 Result += ClassImplementation[i]->getNameAsString();
6444 Result += ",\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006445 }
Fariborz Jahaniandf795672012-02-17 00:06:14 +00006446 Result += "};\n";
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006447
6448 if (!DefinedNonLazyClasses.empty()) {
6449 if (LangOpts.MicrosoftExt)
6450 Result += "__declspec(allocate(\".objc_nlclslist$B\")) \n";
6451 Result += "static struct _class_t *_OBJC_LABEL_NONLAZY_CLASS_$[] = {\n\t";
6452 for (unsigned i = 0, e = DefinedNonLazyClasses.size(); i < e; i++) {
6453 Result += "\t&OBJC_CLASS_$_"; Result += DefinedNonLazyClasses[i]->getNameAsString();
6454 Result += ",\n";
6455 }
6456 Result += "};\n";
6457 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006458 }
Fariborz Jahanian61186122012-02-17 18:40:41 +00006459
6460 if (CatDefCount > 0) {
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00006461 if (LangOpts.MicrosoftExt)
6462 Result += "__declspec(allocate(\".objc_catlist$B\")) ";
Fariborz Jahanian61186122012-02-17 18:40:41 +00006463 Result += "static struct _category_t *L_OBJC_LABEL_CATEGORY_$ [";
6464 Result += llvm::utostr(CatDefCount); Result += "]";
6465 Result +=
6466 " __attribute__((used, section (\"__DATA, __objc_catlist,"
6467 "regular,no_dead_strip\")))= {\n";
6468 for (int i = 0; i < CatDefCount; i++) {
6469 Result += "\t&_OBJC_$_CATEGORY_";
6470 Result +=
6471 CategoryImplementation[i]->getClassInterface()->getNameAsString();
6472 Result += "_$_";
6473 Result += CategoryImplementation[i]->getNameAsString();
6474 Result += ",\n";
6475 }
6476 Result += "};\n";
6477 }
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006478
6479 if (!DefinedNonLazyCategories.empty()) {
6480 if (LangOpts.MicrosoftExt)
6481 Result += "__declspec(allocate(\".objc_nlcatlist$B\")) \n";
6482 Result += "static struct _category_t *_OBJC_LABEL_NONLAZY_CATEGORY_$[] = {\n\t";
6483 for (unsigned i = 0, e = DefinedNonLazyCategories.size(); i < e; i++) {
6484 Result += "\t&_OBJC_$_CATEGORY_";
6485 Result +=
6486 DefinedNonLazyCategories[i]->getClassInterface()->getNameAsString();
6487 Result += "_$_";
6488 Result += DefinedNonLazyCategories[i]->getNameAsString();
6489 Result += ",\n";
6490 }
6491 Result += "};\n";
6492 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006493}
6494
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00006495void RewriteModernObjC::WriteImageInfo(std::string &Result) {
6496 if (LangOpts.MicrosoftExt)
6497 Result += "__declspec(allocate(\".objc_imageinfo$B\")) \n";
6498
6499 Result += "static struct IMAGE_INFO { unsigned version; unsigned flag; } ";
6500 // version 0, ObjCABI is 2
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00006501 Result += "_OBJC_IMAGE_INFO = { 0, 2 };\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00006502}
6503
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006504/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
6505/// implementation.
6506void RewriteModernObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
6507 std::string &Result) {
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00006508 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006509 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
6510 // Find category declaration for this implementation.
Fariborz Jahanian61186122012-02-17 18:40:41 +00006511 ObjCCategoryDecl *CDecl=0;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006512 for (CDecl = ClassDecl->getCategoryList(); CDecl;
6513 CDecl = CDecl->getNextClassCategory())
6514 if (CDecl->getIdentifier() == IDecl->getIdentifier())
6515 break;
6516
6517 std::string FullCategoryName = ClassDecl->getNameAsString();
Fariborz Jahanian61186122012-02-17 18:40:41 +00006518 FullCategoryName += "_$_";
6519 FullCategoryName += CDecl->getNameAsString();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006520
6521 // Build _objc_method_list for class's instance methods if needed
6522 SmallVector<ObjCMethodDecl *, 32>
6523 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
6524
6525 // If any of our property implementations have associated getters or
6526 // setters, produce metadata for them as well.
6527 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
6528 PropEnd = IDecl->propimpl_end();
6529 Prop != PropEnd; ++Prop) {
6530 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
6531 continue;
6532 if (!(*Prop)->getPropertyIvarDecl())
6533 continue;
6534 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
6535 if (!PD)
6536 continue;
6537 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
6538 InstanceMethods.push_back(Getter);
6539 if (PD->isReadOnly())
6540 continue;
6541 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
6542 InstanceMethods.push_back(Setter);
6543 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006544
Fariborz Jahanian61186122012-02-17 18:40:41 +00006545 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
6546 "_OBJC_$_CATEGORY_INSTANCE_METHODS_",
6547 FullCategoryName, true);
6548
6549 SmallVector<ObjCMethodDecl *, 32>
6550 ClassMethods(IDecl->classmeth_begin(), IDecl->classmeth_end());
6551
6552 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
6553 "_OBJC_$_CATEGORY_CLASS_METHODS_",
6554 FullCategoryName, true);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006555
6556 // Protocols referenced in class declaration?
Fariborz Jahanian61186122012-02-17 18:40:41 +00006557 // Protocol's super protocol list
6558 std::vector<ObjCProtocolDecl *> RefedProtocols;
Argyrios Kyrtzidisa5f44412012-03-13 01:09:41 +00006559 for (ObjCInterfaceDecl::protocol_iterator I = CDecl->protocol_begin(),
6560 E = CDecl->protocol_end();
6561
6562 I != E; ++I) {
Fariborz Jahanian61186122012-02-17 18:40:41 +00006563 RefedProtocols.push_back(*I);
6564 // Must write out all protocol definitions in current qualifier list,
6565 // and in their nested qualifiers before writing out current definition.
6566 RewriteObjCProtocolMetaData(*I, Result);
6567 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006568
Fariborz Jahanian61186122012-02-17 18:40:41 +00006569 Write_protocol_list_initializer(Context, Result,
6570 RefedProtocols,
6571 "_OBJC_CATEGORY_PROTOCOLS_$_",
6572 FullCategoryName);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006573
Fariborz Jahanian61186122012-02-17 18:40:41 +00006574 // Protocol's property metadata.
6575 std::vector<ObjCPropertyDecl *> ClassProperties;
6576 for (ObjCContainerDecl::prop_iterator I = CDecl->prop_begin(),
6577 E = CDecl->prop_end(); I != E; ++I)
6578 ClassProperties.push_back(*I);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006579
Fariborz Jahanian61186122012-02-17 18:40:41 +00006580 Write_prop_list_t_initializer(*this, Context, Result, ClassProperties,
6581 /* Container */0,
6582 "_OBJC_$_PROP_LIST_",
6583 FullCategoryName);
6584
6585 Write_category_t(*this, Context, Result,
Fariborz Jahaniane0335782012-03-27 18:41:05 +00006586 CDecl,
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006587 ClassDecl,
Fariborz Jahanian61186122012-02-17 18:40:41 +00006588 InstanceMethods,
6589 ClassMethods,
6590 RefedProtocols,
6591 ClassProperties);
6592
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006593 // Determine if this category is also "non-lazy".
6594 if (ImplementationIsNonLazy(IDecl))
6595 DefinedNonLazyCategories.push_back(CDecl);
Fariborz Jahaniane0335782012-03-27 18:41:05 +00006596
6597}
6598
6599void RewriteModernObjC::RewriteCategorySetupInitHook(std::string &Result) {
6600 int CatDefCount = CategoryImplementation.size();
6601 if (!CatDefCount)
6602 return;
6603 Result += "#pragma section(\".objc_inithooks$B\", long, read, write)\n";
6604 Result += "__declspec(allocate(\".objc_inithooks$B\")) ";
6605 Result += "static void *OBJC_CATEGORY_SETUP[] = {\n";
6606 for (int i = 0; i < CatDefCount; i++) {
6607 ObjCCategoryImplDecl *IDecl = CategoryImplementation[i];
6608 ObjCCategoryDecl *CatDecl= IDecl->getCategoryDecl();
6609 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
6610 Result += "\t(void *)&OBJC_CATEGORY_SETUP_$_";
6611 Result += ClassDecl->getName();
6612 Result += "_$_";
6613 Result += CatDecl->getName();
6614 Result += ",\n";
6615 }
6616 Result += "};\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006617}
6618
6619// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
6620/// class methods.
6621template<typename MethodIterator>
6622void RewriteModernObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
6623 MethodIterator MethodEnd,
6624 bool IsInstanceMethod,
6625 StringRef prefix,
6626 StringRef ClassName,
6627 std::string &Result) {
6628 if (MethodBegin == MethodEnd) return;
6629
6630 if (!objc_impl_method) {
6631 /* struct _objc_method {
6632 SEL _cmd;
6633 char *method_types;
6634 void *_imp;
6635 }
6636 */
6637 Result += "\nstruct _objc_method {\n";
6638 Result += "\tSEL _cmd;\n";
6639 Result += "\tchar *method_types;\n";
6640 Result += "\tvoid *_imp;\n";
6641 Result += "};\n";
6642
6643 objc_impl_method = true;
6644 }
6645
6646 // Build _objc_method_list for class's methods if needed
6647
6648 /* struct {
6649 struct _objc_method_list *next_method;
6650 int method_count;
6651 struct _objc_method method_list[];
6652 }
6653 */
6654 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00006655 Result += "\n";
6656 if (LangOpts.MicrosoftExt) {
6657 if (IsInstanceMethod)
6658 Result += "__declspec(allocate(\".inst_meth$B\")) ";
6659 else
6660 Result += "__declspec(allocate(\".cls_meth$B\")) ";
6661 }
6662 Result += "static struct {\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006663 Result += "\tstruct _objc_method_list *next_method;\n";
6664 Result += "\tint method_count;\n";
6665 Result += "\tstruct _objc_method method_list[";
6666 Result += utostr(NumMethods);
6667 Result += "];\n} _OBJC_";
6668 Result += prefix;
6669 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
6670 Result += "_METHODS_";
6671 Result += ClassName;
6672 Result += " __attribute__ ((used, section (\"__OBJC, __";
6673 Result += IsInstanceMethod ? "inst" : "cls";
6674 Result += "_meth\")))= ";
6675 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
6676
6677 Result += "\t,{{(SEL)\"";
6678 Result += (*MethodBegin)->getSelector().getAsString().c_str();
6679 std::string MethodTypeString;
6680 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
6681 Result += "\", \"";
6682 Result += MethodTypeString;
6683 Result += "\", (void *)";
6684 Result += MethodInternalNames[*MethodBegin];
6685 Result += "}\n";
6686 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
6687 Result += "\t ,{(SEL)\"";
6688 Result += (*MethodBegin)->getSelector().getAsString().c_str();
6689 std::string MethodTypeString;
6690 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
6691 Result += "\", \"";
6692 Result += MethodTypeString;
6693 Result += "\", (void *)";
6694 Result += MethodInternalNames[*MethodBegin];
6695 Result += "}\n";
6696 }
6697 Result += "\t }\n};\n";
6698}
6699
6700Stmt *RewriteModernObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) {
6701 SourceRange OldRange = IV->getSourceRange();
6702 Expr *BaseExpr = IV->getBase();
6703
6704 // Rewrite the base, but without actually doing replaces.
6705 {
6706 DisableReplaceStmtScope S(*this);
6707 BaseExpr = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(BaseExpr));
6708 IV->setBase(BaseExpr);
6709 }
6710
6711 ObjCIvarDecl *D = IV->getDecl();
6712
6713 Expr *Replacement = IV;
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00006714
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006715 if (BaseExpr->getType()->isObjCObjectPointerType()) {
6716 const ObjCInterfaceType *iFaceDecl =
6717 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
6718 assert(iFaceDecl && "RewriteObjCIvarRefExpr - iFaceDecl is null");
6719 // lookup which class implements the instance variable.
6720 ObjCInterfaceDecl *clsDeclared = 0;
6721 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
6722 clsDeclared);
6723 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
6724
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00006725 // Build name of symbol holding ivar offset.
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006726 std::string IvarOffsetName;
6727 WriteInternalIvarName(clsDeclared, D, IvarOffsetName);
6728
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00006729 ReferencedIvars[clsDeclared].insert(D);
6730
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00006731 // cast offset to "char *".
6732 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context,
6733 Context->getPointerType(Context->CharTy),
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006734 CK_BitCast,
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00006735 BaseExpr);
6736 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
6737 SourceLocation(), &Context->Idents.get(IvarOffsetName),
6738 Context->UnsignedLongTy, 0, SC_Extern, SC_None);
John McCallf4b88a42012-03-10 09:33:50 +00006739 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, false,
6740 Context->UnsignedLongTy, VK_LValue,
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00006741 SourceLocation());
6742 BinaryOperator *addExpr =
6743 new (Context) BinaryOperator(castExpr, DRE, BO_Add,
6744 Context->getPointerType(Context->CharTy),
6745 VK_RValue, OK_Ordinary, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006746 // Don't forget the parens to enforce the proper binding.
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00006747 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(),
6748 SourceLocation(),
6749 addExpr);
Fariborz Jahanian0d6e22a2012-02-24 17:35:35 +00006750 QualType IvarT = D->getType();
Fariborz Jahanian8e0913d2012-02-29 00:26:20 +00006751 convertObjCTypeToCStyleType(IvarT);
Fariborz Jahanian0d6e22a2012-02-24 17:35:35 +00006752 QualType castT = Context->getPointerType(IvarT);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006753
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00006754 castExpr = NoTypeInfoCStyleCastExpr(Context,
6755 castT,
6756 CK_BitCast,
6757 PE);
Fariborz Jahanian8e0913d2012-02-29 00:26:20 +00006758 Expr *Exp = new (Context) UnaryOperator(castExpr, UO_Deref, IvarT,
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00006759 VK_LValue, OK_Ordinary,
6760 SourceLocation());
6761 PE = new (Context) ParenExpr(OldRange.getBegin(),
6762 OldRange.getEnd(),
6763 Exp);
6764
6765 Replacement = PE;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006766 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006767
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00006768 ReplaceStmtWithRange(IV, Replacement, OldRange);
6769 return Replacement;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006770}