blob: fd3efe560b6217e9ab12aacd04139afc2f58223d [file] [log] [blame]
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001//===--- RewriteObjC.cpp - Playground for the code rewriter ---------------===//
Chris Lattnere99c8322007-10-11 00:43:27 +00002//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattnere99c8322007-10-11 00:43:27 +00007//
8//===----------------------------------------------------------------------===//
9//
10// Hacks and fun related to the code rewriter.
11//
12//===----------------------------------------------------------------------===//
13
Eli Friedman9f30fc32009-05-18 22:50:54 +000014#include "clang/Frontend/ASTConsumers.h"
Chris Lattner16a0de42007-10-11 18:38:32 +000015#include "clang/Rewrite/Rewriter.h"
Chris Lattnere99c8322007-10-11 00:43:27 +000016#include "clang/AST/AST.h"
17#include "clang/AST/ASTConsumer.h"
Steve Naroff1042ff32008-12-08 16:43:47 +000018#include "clang/AST/ParentMap.h"
Chris Lattner16a0de42007-10-11 18:38:32 +000019#include "clang/Basic/SourceManager.h"
Steve Naroffdb1ab1c2007-10-23 23:50:29 +000020#include "clang/Basic/IdentifierTable.h"
Chris Lattner4431a1b2007-11-30 22:53:43 +000021#include "clang/Basic/Diagnostic.h"
Chris Lattnerf3a59a12007-12-02 01:13:47 +000022#include "clang/Lex/Lexer.h"
Benjamin Kramer89b422c2009-08-23 12:08:50 +000023#include "llvm/Support/MemoryBuffer.h"
24#include "llvm/Support/raw_ostream.h"
Chris Lattner211f8b82007-10-25 17:07:24 +000025#include "llvm/ADT/StringExtras.h"
Fariborz Jahanian99e96b02007-10-26 19:46:17 +000026#include "llvm/ADT/SmallPtrSet.h"
Ted Kremenek2d470fc2008-09-13 05:16:45 +000027#include "llvm/ADT/OwningPtr.h"
Fariborz Jahaniane3891582010-01-05 18:04:40 +000028#include "llvm/ADT/DenseSet.h"
Chris Lattnere99c8322007-10-11 00:43:27 +000029using namespace clang;
Chris Lattner211f8b82007-10-25 17:07:24 +000030using llvm::utostr;
Chris Lattnere99c8322007-10-11 00:43:27 +000031
Chris Lattnere99c8322007-10-11 00:43:27 +000032namespace {
Steve Naroff1dc53ef2008-04-14 22:03:09 +000033 class RewriteObjC : public ASTConsumer {
Fariborz Jahanian4bf727d2009-12-23 21:18:41 +000034 enum {
35 BLOCK_FIELD_IS_OBJECT = 3, /* id, NSObject, __attribute__((NSObject)),
36 block, ... */
37 BLOCK_FIELD_IS_BLOCK = 7, /* a block variable */
38 BLOCK_FIELD_IS_BYREF = 8, /* the on stack structure holding the
39 __block variable */
40 BLOCK_FIELD_IS_WEAK = 16, /* declared __weak, only used in byref copy
41 helpers */
42 BLOCK_BYREF_CALLER = 128, /* called from __block (byref) copy/dispose
43 support routines */
44 BLOCK_BYREF_CURRENT_MAX = 256
45 };
46
47 enum {
48 BLOCK_NEEDS_FREE = (1 << 24),
49 BLOCK_HAS_COPY_DISPOSE = (1 << 25),
50 BLOCK_HAS_CXX_OBJ = (1 << 26),
51 BLOCK_IS_GC = (1 << 27),
52 BLOCK_IS_GLOBAL = (1 << 28),
53 BLOCK_HAS_DESCRIPTOR = (1 << 29)
54 };
55
Chris Lattner0bd1c972007-10-16 21:07:07 +000056 Rewriter Rewrite;
Chris Lattnere9c810c2007-11-30 22:25:36 +000057 Diagnostic &Diags;
Steve Naroff945a3b12008-03-10 20:43:59 +000058 const LangOptions &LangOpts;
Steve Naroff7b3579b2008-01-30 19:17:43 +000059 unsigned RewriteFailedDiag;
Steve Naroff6d6da252008-12-05 17:03:39 +000060 unsigned TryFinallyContainsReturnDiag;
Mike Stump11289f42009-09-09 15:08:12 +000061
Chris Lattnerc6d91c02007-10-17 22:35:30 +000062 ASTContext *Context;
Chris Lattnere99c8322007-10-11 00:43:27 +000063 SourceManager *SM;
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +000064 TranslationUnitDecl *TUDecl;
Chris Lattnerd32480d2009-01-17 06:22:33 +000065 FileID MainFileID;
Chris Lattnerf3a59a12007-12-02 01:13:47 +000066 const char *MainFileStart, *MainFileEnd;
Chris Lattner0bd1c972007-10-16 21:07:07 +000067 SourceLocation LastIncLoc;
Mike Stump11289f42009-09-09 15:08:12 +000068
Ted Kremenek1b0ea822008-01-07 19:49:32 +000069 llvm::SmallVector<ObjCImplementationDecl *, 8> ClassImplementation;
70 llvm::SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation;
71 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCSynthesizedStructs;
Steve Naroff13e74872008-05-06 18:26:51 +000072 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> ObjCSynthesizedProtocols;
Ted Kremenek1b0ea822008-01-07 19:49:32 +000073 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCForwardDecls;
74 llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames;
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +000075 llvm::SmallVector<Stmt *, 32> Stmts;
76 llvm::SmallVector<int, 8> ObjCBcLabelNo;
Steve Naroffd9803712009-04-29 16:37:50 +000077 // Remember all the @protocol(<expr>) expressions.
78 llvm::SmallPtrSet<ObjCProtocolDecl *, 32> ProtocolExprDecls;
Fariborz Jahaniane3891582010-01-05 18:04:40 +000079
80 llvm::DenseSet<uint64_t> CopyDestroyCache;
81
Steve Naroffce8e8862008-03-15 00:55:56 +000082 unsigned NumObjCStringLiterals;
Mike Stump11289f42009-09-09 15:08:12 +000083
Steve Naroffdb1ab1c2007-10-23 23:50:29 +000084 FunctionDecl *MsgSendFunctionDecl;
Steve Naroff7fa2f042007-11-15 10:28:18 +000085 FunctionDecl *MsgSendSuperFunctionDecl;
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +000086 FunctionDecl *MsgSendStretFunctionDecl;
87 FunctionDecl *MsgSendSuperStretFunctionDecl;
Fariborz Jahanian4f76f222007-12-03 21:26:48 +000088 FunctionDecl *MsgSendFpretFunctionDecl;
Steve Naroffdb1ab1c2007-10-23 23:50:29 +000089 FunctionDecl *GetClassFunctionDecl;
Steve Naroffb2f8ff12007-12-07 03:50:46 +000090 FunctionDecl *GetMetaClassFunctionDecl;
Steve Naroff574440f2007-10-24 22:48:43 +000091 FunctionDecl *SelGetUidFunctionDecl;
Steve Naroff265a6b92007-11-08 14:30:50 +000092 FunctionDecl *CFStringFunctionDecl;
Steve Naroff17978c42008-03-11 17:37:02 +000093 FunctionDecl *SuperContructorFunctionDecl;
Mike Stump11289f42009-09-09 15:08:12 +000094
Steve Naroffa397efd2007-11-03 11:27:19 +000095 // ObjC string constant support.
Steve Naroff08899ff2008-04-15 22:42:06 +000096 VarDecl *ConstantStringClassReference;
Steve Naroffa397efd2007-11-03 11:27:19 +000097 RecordDecl *NSStringRecord;
Mike Stump11289f42009-09-09 15:08:12 +000098
Fariborz Jahanian19d42bf2008-01-16 00:09:11 +000099 // ObjC foreach break/continue generation support.
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +0000100 int BcLabelCount;
Mike Stump11289f42009-09-09 15:08:12 +0000101
Steve Naroff7fa2f042007-11-15 10:28:18 +0000102 // Needed for super.
Steve Naroff677ab3a2008-10-27 17:20:55 +0000103 ObjCMethodDecl *CurMethodDef;
Steve Naroff7fa2f042007-11-15 10:28:18 +0000104 RecordDecl *SuperStructDecl;
Steve Naroffce8e8862008-03-15 00:55:56 +0000105 RecordDecl *ConstantStringDecl;
Mike Stump11289f42009-09-09 15:08:12 +0000106
Steve Naroffd9803712009-04-29 16:37:50 +0000107 TypeDecl *ProtocolTypeDecl;
108 QualType getProtocolType();
Mike Stump11289f42009-09-09 15:08:12 +0000109
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000110 // Needed for header files being rewritten
111 bool IsHeader;
Mike Stump11289f42009-09-09 15:08:12 +0000112
Steve Narofff9e7c902008-03-28 22:26:09 +0000113 std::string InFileName;
Eli Friedman94cf21e2009-05-18 22:20:00 +0000114 llvm::raw_ostream* OutFile;
Eli Friedmanf22439a2009-05-18 22:39:16 +0000115
116 bool SilenceRewriteMacroWarning;
117
Steve Naroff00a31762008-03-27 22:29:16 +0000118 std::string Preamble;
Steve Naroff677ab3a2008-10-27 17:20:55 +0000119
120 // Block expressions.
121 llvm::SmallVector<BlockExpr *, 32> Blocks;
122 llvm::SmallVector<BlockDeclRefExpr *, 32> BlockDeclRefs;
123 llvm::DenseMap<BlockDeclRefExpr *, CallExpr *> BlockCallExprs;
Mike Stump11289f42009-09-09 15:08:12 +0000124
Steve Naroff677ab3a2008-10-27 17:20:55 +0000125 // Block related declarations.
126 llvm::SmallPtrSet<ValueDecl *, 8> BlockByCopyDecls;
127 llvm::SmallPtrSet<ValueDecl *, 8> BlockByRefDecls;
128 llvm::SmallPtrSet<ValueDecl *, 8> ImportedBlockDecls;
129
130 llvm::DenseMap<BlockExpr *, std::string> RewrittenBlockExprs;
131
Steve Naroff4588d0f2008-12-04 16:24:46 +0000132 // This maps a property to it's assignment statement.
133 llvm::DenseMap<ObjCPropertyRefExpr *, BinaryOperator *> PropSetters;
Steve Naroff1042ff32008-12-08 16:43:47 +0000134 // This maps a property to it's synthesied message expression.
135 // This allows us to rewrite chained getters (e.g. o.a.b.c).
136 llvm::DenseMap<ObjCPropertyRefExpr *, Stmt *> PropGetters;
Mike Stump11289f42009-09-09 15:08:12 +0000137
Steve Naroff22216db2008-12-04 23:50:32 +0000138 // This maps an original source AST to it's rewritten form. This allows
139 // us to avoid rewriting the same node twice (which is very uncommon).
140 // This is needed to support some of the exotic property rewriting.
141 llvm::DenseMap<Stmt *, Stmt *> ReplacedNodes;
Steve Narofff326f402008-12-03 00:56:33 +0000142
Steve Naroff677ab3a2008-10-27 17:20:55 +0000143 FunctionDecl *CurFunctionDef;
Steve Naroffd8907b72008-10-29 18:15:37 +0000144 VarDecl *GlobalVarDecl;
Mike Stump11289f42009-09-09 15:08:12 +0000145
Steve Naroff08628db2008-12-09 12:56:34 +0000146 bool DisableReplaceStmt;
Mike Stump11289f42009-09-09 15:08:12 +0000147
Fariborz Jahanian93191af2007-10-18 19:23:00 +0000148 static const int OBJC_ABI_VERSION =7 ;
Chris Lattnere99c8322007-10-11 00:43:27 +0000149 public:
Ted Kremenek380df932008-05-31 20:11:04 +0000150 virtual void Initialize(ASTContext &context);
151
Chris Lattner3c799d72007-10-24 17:06:59 +0000152 // Top Level Driver code.
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000153 virtual void HandleTopLevelDecl(DeclGroupRef D) {
154 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I)
155 HandleTopLevelSingleDecl(*I);
156 }
157 void HandleTopLevelSingleDecl(Decl *D);
Chris Lattner0bd1c972007-10-16 21:07:07 +0000158 void HandleDeclInMainFile(Decl *D);
Eli Friedman94cf21e2009-05-18 22:20:00 +0000159 RewriteObjC(std::string inFile, llvm::raw_ostream *OS,
Eli Friedmanf22439a2009-05-18 22:39:16 +0000160 Diagnostic &D, const LangOptions &LOpts,
161 bool silenceMacroWarn);
Ted Kremenek6231e7e2008-08-08 04:15:52 +0000162
163 ~RewriteObjC() {}
Mike Stump11289f42009-09-09 15:08:12 +0000164
Chris Lattnercf169832009-03-28 04:11:33 +0000165 virtual void HandleTranslationUnit(ASTContext &C);
Mike Stump11289f42009-09-09 15:08:12 +0000166
Chris Lattner2e0d2602008-01-31 19:37:57 +0000167 void ReplaceStmt(Stmt *Old, Stmt *New) {
Steve Naroff22216db2008-12-04 23:50:32 +0000168 Stmt *ReplacingStmt = ReplacedNodes[Old];
Mike Stump11289f42009-09-09 15:08:12 +0000169
Steve Naroff22216db2008-12-04 23:50:32 +0000170 if (ReplacingStmt)
171 return; // We can't rewrite the same node twice.
Chris Lattner2e0d2602008-01-31 19:37:57 +0000172
Steve Naroff08628db2008-12-09 12:56:34 +0000173 if (DisableReplaceStmt)
174 return; // Used when rewriting the assignment of a property setter.
175
Steve Naroff22216db2008-12-04 23:50:32 +0000176 // If replacement succeeded or warning disabled return with no warning.
177 if (!Rewrite.ReplaceStmt(Old, New)) {
178 ReplacedNodes[Old] = New;
179 return;
180 }
181 if (SilenceRewriteMacroWarning)
182 return;
Chris Lattner8488c822008-11-18 07:04:44 +0000183 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
184 << Old->getSourceRange();
Chris Lattner2e0d2602008-01-31 19:37:57 +0000185 }
Steve Naroff08628db2008-12-09 12:56:34 +0000186
187 void ReplaceStmtWithRange(Stmt *Old, Stmt *New, SourceRange SrcRange) {
188 // Measaure the old text.
189 int Size = Rewrite.getRangeSize(SrcRange);
190 if (Size == -1) {
191 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
192 << Old->getSourceRange();
193 return;
194 }
195 // Get the new text.
196 std::string SStr;
197 llvm::raw_string_ostream S(SStr);
Chris Lattnerc61089a2009-06-30 01:26:17 +0000198 New->printPretty(S, *Context, 0, PrintingPolicy(LangOpts));
Steve Naroff08628db2008-12-09 12:56:34 +0000199 const std::string &Str = S.str();
200
201 // If replacement succeeded or warning disabled return with no warning.
Daniel Dunbardec484a2009-08-19 19:10:30 +0000202 if (!Rewrite.ReplaceText(SrcRange.getBegin(), Size, Str)) {
Steve Naroff08628db2008-12-09 12:56:34 +0000203 ReplacedNodes[Old] = New;
204 return;
205 }
206 if (SilenceRewriteMacroWarning)
207 return;
208 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
209 << Old->getSourceRange();
210 }
211
Steve Naroff00a31762008-03-27 22:29:16 +0000212 void InsertText(SourceLocation Loc, const char *StrData, unsigned StrLen,
213 bool InsertAfter = true) {
Chris Lattner9cc55f52008-01-31 19:51:04 +0000214 // If insertion succeeded or warning disabled return with no warning.
Daniel Dunbardec484a2009-08-19 19:10:30 +0000215 if (!Rewrite.InsertText(Loc, llvm::StringRef(StrData, StrLen),
216 InsertAfter) ||
Chris Lattner1780a852008-01-31 19:42:41 +0000217 SilenceRewriteMacroWarning)
218 return;
Mike Stump11289f42009-09-09 15:08:12 +0000219
Chris Lattner1780a852008-01-31 19:42:41 +0000220 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
221 }
Mike Stump11289f42009-09-09 15:08:12 +0000222
Chris Lattner9cc55f52008-01-31 19:51:04 +0000223 void RemoveText(SourceLocation Loc, unsigned StrLen) {
224 // If removal succeeded or warning disabled return with no warning.
225 if (!Rewrite.RemoveText(Loc, StrLen) || SilenceRewriteMacroWarning)
226 return;
Mike Stump11289f42009-09-09 15:08:12 +0000227
Chris Lattner9cc55f52008-01-31 19:51:04 +0000228 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
229 }
Chris Lattner3c799d72007-10-24 17:06:59 +0000230
Chris Lattner9cc55f52008-01-31 19:51:04 +0000231 void ReplaceText(SourceLocation Start, unsigned OrigLength,
232 const char *NewStr, unsigned NewLength) {
233 // If removal succeeded or warning disabled return with no warning.
Daniel Dunbardec484a2009-08-19 19:10:30 +0000234 if (!Rewrite.ReplaceText(Start, OrigLength,
235 llvm::StringRef(NewStr, NewLength)) ||
Chris Lattner9cc55f52008-01-31 19:51:04 +0000236 SilenceRewriteMacroWarning)
237 return;
Mike Stump11289f42009-09-09 15:08:12 +0000238
Chris Lattner9cc55f52008-01-31 19:51:04 +0000239 Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
240 }
Mike Stump11289f42009-09-09 15:08:12 +0000241
Chris Lattner3c799d72007-10-24 17:06:59 +0000242 // Syntactic Rewriting.
Steve Narofff36987c2007-11-04 22:37:50 +0000243 void RewritePrologue(SourceLocation Loc);
Fariborz Jahanian80258362008-01-19 00:30:35 +0000244 void RewriteInclude();
Chris Lattner3c799d72007-10-24 17:06:59 +0000245 void RewriteTabs();
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000246 void RewriteForwardClassDecl(ObjCClassDecl *Dcl);
Steve Naroffc038b3a2008-12-02 17:36:43 +0000247 void RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
248 ObjCImplementationDecl *IMD,
249 ObjCCategoryImplDecl *CID);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000250 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
Douglas Gregor6e6ad602009-01-20 01:17:11 +0000251 void RewriteImplementationDecl(Decl *Dcl);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000252 void RewriteObjCMethodDecl(ObjCMethodDecl *MDecl, std::string &ResultStr);
253 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
254 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
255 void RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *Dcl);
256 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
Steve Naroff0c0f5ba2009-01-11 01:06:09 +0000257 void RewriteProperty(ObjCPropertyDecl *prop);
Steve Naroff5cdcd9b2007-10-30 23:14:51 +0000258 void RewriteFunctionDecl(FunctionDecl *FD);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000259 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
Steve Naroff873bd842008-07-29 18:15:38 +0000260 void RewriteObjCQualifiedInterfaceTypes(Expr *E);
Steve Naroff50d42052007-11-01 13:24:47 +0000261 bool needToScanForQualifiers(QualType T);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000262 ObjCInterfaceDecl *isSuperReceiver(Expr *recExpr);
Steve Naroff7fa2f042007-11-15 10:28:18 +0000263 QualType getSuperStructType();
Steve Naroffce8e8862008-03-15 00:55:56 +0000264 QualType getConstantStringStructType();
Steve Naroffcd92aeb2008-05-31 14:15:04 +0000265 bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf);
Mike Stump11289f42009-09-09 15:08:12 +0000266
Chris Lattner3c799d72007-10-24 17:06:59 +0000267 // Expression Rewriting.
Steve Naroff20113382007-11-09 15:20:18 +0000268 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
Steve Naroff4588d0f2008-12-04 16:24:46 +0000269 void CollectPropertySetters(Stmt *S);
Mike Stump11289f42009-09-09 15:08:12 +0000270
Steve Naroff1042ff32008-12-08 16:43:47 +0000271 Stmt *CurrentBody;
272 ParentMap *PropParentMap; // created lazily.
Mike Stump11289f42009-09-09 15:08:12 +0000273
Chris Lattner69534692007-10-24 16:57:36 +0000274 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
Chris Lattner37f5b7d2008-05-23 20:40:52 +0000275 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV, SourceLocation OrigStart);
Steve Naroff4588d0f2008-12-04 16:24:46 +0000276 Stmt *RewritePropertyGetter(ObjCPropertyRefExpr *PropRefExpr);
Mike Stump11289f42009-09-09 15:08:12 +0000277 Stmt *RewritePropertySetter(BinaryOperator *BinOp, Expr *newStmt,
Steve Naroff08628db2008-12-09 12:56:34 +0000278 SourceRange SrcRange);
Steve Naroffe4f9b232007-11-05 14:50:49 +0000279 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
Chris Lattner69534692007-10-24 16:57:36 +0000280 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroffa397efd2007-11-03 11:27:19 +0000281 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian33c0e812007-12-07 18:47:10 +0000282 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Steve Naroffec60b432009-12-05 21:43:12 +0000283 void WarnAboutReturnGotoStmts(Stmt *S);
284 void HasReturnStmts(Stmt *S, bool &hasReturns);
285 void RewriteTryReturnStmts(Stmt *S);
286 void RewriteSyncReturnStmts(Stmt *S, std::string buf);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000287 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
Fariborz Jahanian284011b2008-01-29 22:59:37 +0000288 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000289 Stmt *RewriteObjCCatchStmt(ObjCAtCatchStmt *S);
290 Stmt *RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S);
291 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
Chris Lattnera779d692008-01-31 05:10:40 +0000292 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
293 SourceLocation OrigEnd);
Mike Stump11289f42009-09-09 15:08:12 +0000294 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
Steve Naroff574440f2007-10-24 22:48:43 +0000295 Expr **args, unsigned nargs);
Fariborz Jahanian965a8962008-01-08 22:06:28 +0000296 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp);
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +0000297 Stmt *RewriteBreakStmt(BreakStmt *S);
298 Stmt *RewriteContinueStmt(ContinueStmt *S);
Fariborz Jahanian965a8962008-01-08 22:06:28 +0000299 void SynthCountByEnumWithState(std::string &buf);
Mike Stump11289f42009-09-09 15:08:12 +0000300
Steve Naroff5cdcd9b2007-10-30 23:14:51 +0000301 void SynthMsgSendFunctionDecl();
Steve Naroff7fa2f042007-11-15 10:28:18 +0000302 void SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +0000303 void SynthMsgSendStretFunctionDecl();
Fariborz Jahanian4f76f222007-12-03 21:26:48 +0000304 void SynthMsgSendFpretFunctionDecl();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +0000305 void SynthMsgSendSuperStretFunctionDecl();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +0000306 void SynthGetClassFunctionDecl();
Steve Naroffb2f8ff12007-12-07 03:50:46 +0000307 void SynthGetMetaClassFunctionDecl();
Fariborz Jahanian31e18502007-12-04 21:47:40 +0000308 void SynthSelGetUidFunctionDecl();
Steve Naroff17978c42008-03-11 17:37:02 +0000309 void SynthSuperContructorFunctionDecl();
Mike Stump11289f42009-09-09 15:08:12 +0000310
Chris Lattner3c799d72007-10-24 17:06:59 +0000311 // Metadata emission.
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000312 void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanian51f21822007-10-25 20:55:25 +0000313 std::string &Result);
Mike Stump11289f42009-09-09 15:08:12 +0000314
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000315 void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
Fariborz Jahanian51f21822007-10-25 20:55:25 +0000316 std::string &Result);
Mike Stump11289f42009-09-09 15:08:12 +0000317
Douglas Gregor29bd76f2009-04-23 01:02:12 +0000318 template<typename MethodIterator>
319 void RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
320 MethodIterator MethodEnd,
Fariborz Jahanian3df412a2007-10-25 00:14:44 +0000321 bool IsInstanceMethod,
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +0000322 const char *prefix,
Chris Lattner211f8b82007-10-25 17:07:24 +0000323 const char *ClassName,
324 std::string &Result);
Mike Stump11289f42009-09-09 15:08:12 +0000325
Steve Naroffd9803712009-04-29 16:37:50 +0000326 void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
327 const char *prefix,
328 const char *ClassName,
329 std::string &Result);
330 void RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> &Prots,
Mike Stump11289f42009-09-09 15:08:12 +0000331 const char *prefix,
Steve Naroffd9803712009-04-29 16:37:50 +0000332 const char *ClassName,
333 std::string &Result);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000334 void SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian99e96b02007-10-26 19:46:17 +0000335 std::string &Result);
Mike Stump11289f42009-09-09 15:08:12 +0000336 void SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
337 ObjCIvarDecl *ivar,
Fariborz Jahanian99e96b02007-10-26 19:46:17 +0000338 std::string &Result);
Steve Narofff8cfd162008-11-13 20:07:04 +0000339 void RewriteImplementations();
340 void SynthesizeMetaDataIntoBuffer(std::string &Result);
Mike Stump11289f42009-09-09 15:08:12 +0000341
Steve Naroff677ab3a2008-10-27 17:20:55 +0000342 // Block rewriting.
Mike Stump11289f42009-09-09 15:08:12 +0000343 void RewriteBlocksInFunctionProtoType(QualType funcType, NamedDecl *D);
Steve Naroff677ab3a2008-10-27 17:20:55 +0000344 void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
Mike Stump11289f42009-09-09 15:08:12 +0000345
Steve Naroff677ab3a2008-10-27 17:20:55 +0000346 void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
347 void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
Mike Stump11289f42009-09-09 15:08:12 +0000348
349 // Block specific rewrite rules.
Steve Naroff677ab3a2008-10-27 17:20:55 +0000350 void RewriteBlockCall(CallExpr *Exp);
351 void RewriteBlockPointerDecl(NamedDecl *VD);
Fariborz Jahanian02e07732009-12-23 02:07:37 +0000352 void RewriteByRefVar(VarDecl *VD);
Fariborz Jahaniane3891582010-01-05 18:04:40 +0000353 std::string SynthesizeByrefCopyDestroyHelper(VarDecl *VD, int flag);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +0000354 Stmt *RewriteBlockDeclRefExpr(Expr *VD);
Steve Naroff677ab3a2008-10-27 17:20:55 +0000355 void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
Mike Stump11289f42009-09-09 15:08:12 +0000356
357 std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
Steve Naroff677ab3a2008-10-27 17:20:55 +0000358 const char *funcName, std::string Tag);
Mike Stump11289f42009-09-09 15:08:12 +0000359 std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
Steve Naroff677ab3a2008-10-27 17:20:55 +0000360 const char *funcName, std::string Tag);
Steve Naroff30484702009-12-06 21:14:13 +0000361 std::string SynthesizeBlockImpl(BlockExpr *CE,
362 std::string Tag, std::string Desc);
363 std::string SynthesizeBlockDescriptor(std::string DescTag,
364 std::string ImplTag,
365 int i, const char *funcName,
366 unsigned hasCopy);
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +0000367 Stmt *SynthesizeBlockCall(CallExpr *Exp, const Expr* BlockExp);
Steve Naroff677ab3a2008-10-27 17:20:55 +0000368 void SynthesizeBlockLiterals(SourceLocation FunLocStart,
369 const char *FunName);
Steve Naroffe70a52a2009-12-05 15:55:59 +0000370 void RewriteRecordBody(RecordDecl *RD);
Mike Stump11289f42009-09-09 15:08:12 +0000371
Steve Naroff677ab3a2008-10-27 17:20:55 +0000372 void CollectBlockDeclRefInfo(BlockExpr *Exp);
373 void GetBlockCallExprs(Stmt *S);
374 void GetBlockDeclRefExprs(Stmt *S);
Mike Stump11289f42009-09-09 15:08:12 +0000375
Steve Naroff677ab3a2008-10-27 17:20:55 +0000376 // We avoid calling Type::isBlockPointerType(), since it operates on the
377 // canonical type. We only care if the top-level type is a closure pointer.
Ted Kremenek5a201952009-02-07 01:47:29 +0000378 bool isTopLevelBlockPointerType(QualType T) {
379 return isa<BlockPointerType>(T);
380 }
Mike Stump11289f42009-09-09 15:08:12 +0000381
Steve Naroff677ab3a2008-10-27 17:20:55 +0000382 // FIXME: This predicate seems like it would be useful to add to ASTContext.
383 bool isObjCType(QualType T) {
384 if (!LangOpts.ObjC1 && !LangOpts.ObjC2)
385 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000386
Steve Naroff677ab3a2008-10-27 17:20:55 +0000387 QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +0000388
Steve Naroff677ab3a2008-10-27 17:20:55 +0000389 if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
390 OCT == Context->getCanonicalType(Context->getObjCClassType()))
391 return true;
Mike Stump11289f42009-09-09 15:08:12 +0000392
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000393 if (const PointerType *PT = OCT->getAs<PointerType>()) {
Mike Stump11289f42009-09-09 15:08:12 +0000394 if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
Steve Narofffb4330f2009-06-17 22:40:22 +0000395 PT->getPointeeType()->isObjCQualifiedIdType())
Steve Naroff677ab3a2008-10-27 17:20:55 +0000396 return true;
397 }
398 return false;
399 }
400 bool PointerTypeTakesAnyBlockArguments(QualType QT);
Ted Kremenek5a201952009-02-07 01:47:29 +0000401 void GetExtentOfArgList(const char *Name, const char *&LParen,
402 const char *&RParen);
Steve Naroffc989a7b2008-11-03 23:29:32 +0000403 void RewriteCastExpr(CStyleCastExpr *CE);
Mike Stump11289f42009-09-09 15:08:12 +0000404
Steve Narofff4b992a2008-10-28 20:29:00 +0000405 FunctionDecl *SynthBlockInitFunctionDecl(const char *name);
Steve Naroffd8907b72008-10-29 18:15:37 +0000406 Stmt *SynthBlockInitExpr(BlockExpr *Exp);
Mike Stump11289f42009-09-09 15:08:12 +0000407
Steve Naroffd9803712009-04-29 16:37:50 +0000408 void QuoteDoublequotes(std::string &From, std::string &To) {
Mike Stump11289f42009-09-09 15:08:12 +0000409 for (unsigned i = 0; i < From.length(); i++) {
Steve Naroffd9803712009-04-29 16:37:50 +0000410 if (From[i] == '"')
411 To += "\\\"";
412 else
413 To += From[i];
414 }
415 }
Chris Lattnere99c8322007-10-11 00:43:27 +0000416 };
417}
418
Mike Stump11289f42009-09-09 15:08:12 +0000419void RewriteObjC::RewriteBlocksInFunctionProtoType(QualType funcType,
420 NamedDecl *D) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000421 if (FunctionProtoType *fproto = dyn_cast<FunctionProtoType>(funcType)) {
Mike Stump11289f42009-09-09 15:08:12 +0000422 for (FunctionProtoType::arg_type_iterator I = fproto->arg_type_begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +0000423 E = fproto->arg_type_end(); I && (I != E); ++I)
Steve Naroffa5c0db82008-12-11 21:05:33 +0000424 if (isTopLevelBlockPointerType(*I)) {
Steve Naroff677ab3a2008-10-27 17:20:55 +0000425 // All the args are checked/rewritten. Don't call twice!
426 RewriteBlockPointerDecl(D);
427 break;
428 }
429 }
430}
431
432void RewriteObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000433 const PointerType *PT = funcType->getAs<PointerType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +0000434 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000435 RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND);
Steve Naroff677ab3a2008-10-27 17:20:55 +0000436}
437
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000438static bool IsHeaderFile(const std::string &Filename) {
439 std::string::size_type DotPos = Filename.rfind('.');
Mike Stump11289f42009-09-09 15:08:12 +0000440
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000441 if (DotPos == std::string::npos) {
442 // no file extension
Mike Stump11289f42009-09-09 15:08:12 +0000443 return false;
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000444 }
Mike Stump11289f42009-09-09 15:08:12 +0000445
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000446 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
447 // C header: .h
448 // C++ header: .hh or .H;
449 return Ext == "h" || Ext == "hh" || Ext == "H";
Mike Stump11289f42009-09-09 15:08:12 +0000450}
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000451
Eli Friedman94cf21e2009-05-18 22:20:00 +0000452RewriteObjC::RewriteObjC(std::string inFile, llvm::raw_ostream* OS,
Eli Friedmanf22439a2009-05-18 22:39:16 +0000453 Diagnostic &D, const LangOptions &LOpts,
454 bool silenceMacroWarn)
455 : Diags(D), LangOpts(LOpts), InFileName(inFile), OutFile(OS),
456 SilenceRewriteMacroWarning(silenceMacroWarn) {
Steve Narofff9e7c902008-03-28 22:26:09 +0000457 IsHeader = IsHeaderFile(inFile);
Mike Stump11289f42009-09-09 15:08:12 +0000458 RewriteFailedDiag = Diags.getCustomDiagID(Diagnostic::Warning,
Steve Narofff9e7c902008-03-28 22:26:09 +0000459 "rewriting sub-expression within a macro (may not be correct)");
Mike Stump11289f42009-09-09 15:08:12 +0000460 TryFinallyContainsReturnDiag = Diags.getCustomDiagID(Diagnostic::Warning,
Ted Kremenek5a201952009-02-07 01:47:29 +0000461 "rewriter doesn't support user-specified control flow semantics "
462 "for @try/@finally (code may not execute properly)");
Steve Narofff9e7c902008-03-28 22:26:09 +0000463}
464
Eli Friedmana63ab2d2009-05-18 22:29:17 +0000465ASTConsumer *clang::CreateObjCRewriter(const std::string& InFile,
466 llvm::raw_ostream* OS,
Mike Stump11289f42009-09-09 15:08:12 +0000467 Diagnostic &Diags,
Eli Friedmanf22439a2009-05-18 22:39:16 +0000468 const LangOptions &LOpts,
469 bool SilenceRewriteMacroWarning) {
470 return new RewriteObjC(InFile, OS, Diags, LOpts, SilenceRewriteMacroWarning);
Chris Lattnere9c810c2007-11-30 22:25:36 +0000471}
Chris Lattnere99c8322007-10-11 00:43:27 +0000472
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000473void RewriteObjC::Initialize(ASTContext &context) {
Chris Lattner187f6262008-01-31 19:38:44 +0000474 Context = &context;
475 SM = &Context->getSourceManager();
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +0000476 TUDecl = Context->getTranslationUnitDecl();
Chris Lattner187f6262008-01-31 19:38:44 +0000477 MsgSendFunctionDecl = 0;
478 MsgSendSuperFunctionDecl = 0;
479 MsgSendStretFunctionDecl = 0;
480 MsgSendSuperStretFunctionDecl = 0;
481 MsgSendFpretFunctionDecl = 0;
482 GetClassFunctionDecl = 0;
483 GetMetaClassFunctionDecl = 0;
484 SelGetUidFunctionDecl = 0;
485 CFStringFunctionDecl = 0;
Chris Lattner187f6262008-01-31 19:38:44 +0000486 ConstantStringClassReference = 0;
487 NSStringRecord = 0;
Steve Naroff677ab3a2008-10-27 17:20:55 +0000488 CurMethodDef = 0;
489 CurFunctionDef = 0;
Steve Naroff08628db2008-12-09 12:56:34 +0000490 GlobalVarDecl = 0;
Chris Lattner187f6262008-01-31 19:38:44 +0000491 SuperStructDecl = 0;
Steve Naroffd9803712009-04-29 16:37:50 +0000492 ProtocolTypeDecl = 0;
Steve Naroff60a9ef62008-03-27 22:59:54 +0000493 ConstantStringDecl = 0;
Chris Lattner187f6262008-01-31 19:38:44 +0000494 BcLabelCount = 0;
Steve Naroff17978c42008-03-11 17:37:02 +0000495 SuperContructorFunctionDecl = 0;
Steve Naroffce8e8862008-03-15 00:55:56 +0000496 NumObjCStringLiterals = 0;
Steve Narofff1ab6002008-12-08 20:01:41 +0000497 PropParentMap = 0;
498 CurrentBody = 0;
Steve Naroff08628db2008-12-09 12:56:34 +0000499 DisableReplaceStmt = false;
Mike Stump11289f42009-09-09 15:08:12 +0000500
Chris Lattner187f6262008-01-31 19:38:44 +0000501 // Get the ID and start/end of the main file.
502 MainFileID = SM->getMainFileID();
503 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
504 MainFileStart = MainBuf->getBufferStart();
505 MainFileEnd = MainBuf->getBufferEnd();
Mike Stump11289f42009-09-09 15:08:12 +0000506
Chris Lattner184e65d2009-04-14 23:22:57 +0000507 Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOptions());
Mike Stump11289f42009-09-09 15:08:12 +0000508
Chris Lattner187f6262008-01-31 19:38:44 +0000509 // declaring objc_selector outside the parameter list removes a silly
510 // scope related warning...
Steve Naroff00a31762008-03-27 22:29:16 +0000511 if (IsHeader)
Steve Narofffcc6fd52009-02-03 20:39:18 +0000512 Preamble = "#pragma once\n";
Steve Naroff00a31762008-03-27 22:29:16 +0000513 Preamble += "struct objc_selector; struct objc_class;\n";
Steve Naroff6ab6dc72008-12-23 20:11:22 +0000514 Preamble += "struct __rw_objc_super { struct objc_object *object; ";
Steve Naroff00a31762008-03-27 22:29:16 +0000515 Preamble += "struct objc_object *superClass; ";
Steve Naroff17978c42008-03-11 17:37:02 +0000516 if (LangOpts.Microsoft) {
517 // Add a constructor for creating temporary objects.
Ted Kremenek5a201952009-02-07 01:47:29 +0000518 Preamble += "__rw_objc_super(struct objc_object *o, struct objc_object *s) "
519 ": ";
Steve Naroff00a31762008-03-27 22:29:16 +0000520 Preamble += "object(o), superClass(s) {} ";
Steve Naroff17978c42008-03-11 17:37:02 +0000521 }
Steve Naroff00a31762008-03-27 22:29:16 +0000522 Preamble += "};\n";
Steve Naroff00a31762008-03-27 22:29:16 +0000523 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
524 Preamble += "typedef struct objc_object Protocol;\n";
525 Preamble += "#define _REWRITER_typedef_Protocol\n";
526 Preamble += "#endif\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000527 if (LangOpts.Microsoft) {
528 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
529 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
530 } else
531 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
532 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend";
Steve Naroff00a31762008-03-27 22:29:16 +0000533 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000534 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper";
Steve Naroff00a31762008-03-27 22:29:16 +0000535 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000536 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend_stret";
Steve Naroff00a31762008-03-27 22:29:16 +0000537 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000538 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper_stret";
Steve Naroff00a31762008-03-27 22:29:16 +0000539 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000540 Preamble += "__OBJC_RW_DLLIMPORT double objc_msgSend_fpret";
Steve Naroff00a31762008-03-27 22:29:16 +0000541 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000542 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getClass";
Steve Naroff00a31762008-03-27 22:29:16 +0000543 Preamble += "(const char *);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000544 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getMetaClass";
Steve Naroff00a31762008-03-27 22:29:16 +0000545 Preamble += "(const char *);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000546 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw(struct objc_object *);\n";
547 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_enter(void *);\n";
548 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_exit(void *);\n";
549 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_exception_extract(void *);\n";
550 Preamble += "__OBJC_RW_DLLIMPORT int objc_exception_match";
Steve Naroffd30f8c52008-05-09 21:17:56 +0000551 Preamble += "(struct objc_class *, struct objc_object *);\n";
Steve Naroff8dd15252008-07-16 18:58:11 +0000552 // @synchronized hooks.
Steve Narofff122ff02008-12-08 17:30:33 +0000553 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_enter(struct objc_object *);\n";
554 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_exit(struct objc_object *);\n";
555 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
Steve Naroff00a31762008-03-27 22:29:16 +0000556 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
557 Preamble += "struct __objcFastEnumerationState {\n\t";
558 Preamble += "unsigned long state;\n\t";
Steve Naroff4dbab8a2008-04-04 22:58:22 +0000559 Preamble += "void **itemsPtr;\n\t";
Steve Naroff00a31762008-03-27 22:29:16 +0000560 Preamble += "unsigned long *mutationsPtr;\n\t";
561 Preamble += "unsigned long extra[5];\n};\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000562 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
Steve Naroff00a31762008-03-27 22:29:16 +0000563 Preamble += "#define __FASTENUMERATIONSTATE\n";
564 Preamble += "#endif\n";
565 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
566 Preamble += "struct __NSConstantStringImpl {\n";
567 Preamble += " int *isa;\n";
568 Preamble += " int flags;\n";
569 Preamble += " char *str;\n";
570 Preamble += " long length;\n";
571 Preamble += "};\n";
Steve Naroffdd514e02008-08-05 20:04:48 +0000572 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
573 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
574 Preamble += "#else\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000575 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
Steve Naroffdd514e02008-08-05 20:04:48 +0000576 Preamble += "#endif\n";
Steve Naroff00a31762008-03-27 22:29:16 +0000577 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
578 Preamble += "#endif\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +0000579 // Blocks preamble.
580 Preamble += "#ifndef BLOCK_IMPL\n";
581 Preamble += "#define BLOCK_IMPL\n";
582 Preamble += "struct __block_impl {\n";
583 Preamble += " void *isa;\n";
584 Preamble += " int Flags;\n";
Steve Naroff30484702009-12-06 21:14:13 +0000585 Preamble += " int Reserved;\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +0000586 Preamble += " void *FuncPtr;\n";
587 Preamble += "};\n";
Steve Naroff61d879e2008-12-16 15:50:30 +0000588 Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
Steve Naroff287a2bf2009-12-06 01:52:22 +0000589 Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n";
Steve Naroff2b3843d2009-12-06 01:33:56 +0000590 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_assign(void *, const void *, const int);\n";
591 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
592 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
593 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
594 Preamble += "#else\n";
Steve Naroff7bf01ea2010-01-05 18:09:31 +0000595 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n";
596 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n";
Steve Naroff2b3843d2009-12-06 01:33:56 +0000597 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
598 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
599 Preamble += "#endif\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +0000600 Preamble += "#endif\n";
Steve Naroffcb04e882008-10-27 18:50:14 +0000601 if (LangOpts.Microsoft) {
Steve Narofff122ff02008-12-08 17:30:33 +0000602 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
603 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
Steve Naroffcb04e882008-10-27 18:50:14 +0000604 Preamble += "#define __attribute__(X)\n";
605 }
Fariborz Jahanian7fac6552010-01-05 19:21:35 +0000606 else {
Fariborz Jahanian02e07732009-12-23 02:07:37 +0000607 Preamble += "#define __block\n";
Fariborz Jahanian7fac6552010-01-05 19:21:35 +0000608 Preamble += "#define __weak\n";
609 }
Chris Lattner187f6262008-01-31 19:38:44 +0000610}
611
612
Chris Lattner3c799d72007-10-24 17:06:59 +0000613//===----------------------------------------------------------------------===//
614// Top Level Driver Code
615//===----------------------------------------------------------------------===//
616
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000617void RewriteObjC::HandleTopLevelSingleDecl(Decl *D) {
Chris Lattner0bd1c972007-10-16 21:07:07 +0000618 // Two cases: either the decl could be in the main file, or it could be in a
619 // #included file. If the former, rewrite it now. If the later, check to see
620 // if we rewrote the #include/#import.
621 SourceLocation Loc = D->getLocation();
Chris Lattner8a425862009-01-16 07:36:28 +0000622 Loc = SM->getInstantiationLoc(Loc);
Mike Stump11289f42009-09-09 15:08:12 +0000623
Chris Lattner0bd1c972007-10-16 21:07:07 +0000624 // If this is for a builtin, ignore it.
625 if (Loc.isInvalid()) return;
626
Steve Naroffdb1ab1c2007-10-23 23:50:29 +0000627 // Look for built-in declarations that we need to refer during the rewrite.
628 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +0000629 RewriteFunctionDecl(FD);
Steve Naroff08899ff2008-04-15 22:42:06 +0000630 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
Steve Naroffa397efd2007-11-03 11:27:19 +0000631 // declared in <Foundation/NSString.h>
Chris Lattner86d7d912008-11-24 03:54:41 +0000632 if (strcmp(FVD->getNameAsCString(), "_NSConstantStringClassReference") == 0) {
Steve Naroffa397efd2007-11-03 11:27:19 +0000633 ConstantStringClassReference = FVD;
634 return;
635 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000636 } else if (ObjCInterfaceDecl *MD = dyn_cast<ObjCInterfaceDecl>(D)) {
Steve Naroff161a92b2007-10-26 20:53:56 +0000637 RewriteInterfaceDecl(MD);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000638 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
Steve Naroff5448cf62007-10-30 13:30:57 +0000639 RewriteCategoryDecl(CD);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000640 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
Steve Narofff921385f2007-10-30 16:42:30 +0000641 RewriteProtocolDecl(PD);
Mike Stump11289f42009-09-09 15:08:12 +0000642 } else if (ObjCForwardProtocolDecl *FP =
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000643 dyn_cast<ObjCForwardProtocolDecl>(D)){
Fariborz Jahanianda6165c2007-11-14 00:42:16 +0000644 RewriteForwardProtocolDecl(FP);
Douglas Gregorc25d7a72009-01-09 00:49:46 +0000645 } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) {
646 // Recurse into linkage specifications
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000647 for (DeclContext::decl_iterator DI = LSD->decls_begin(),
648 DIEnd = LSD->decls_end();
Douglas Gregorc25d7a72009-01-09 00:49:46 +0000649 DI != DIEnd; ++DI)
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000650 HandleTopLevelSingleDecl(*DI);
Steve Naroffdb1ab1c2007-10-23 23:50:29 +0000651 }
Chris Lattner3c799d72007-10-24 17:06:59 +0000652 // If we have a decl in the main file, see if we should rewrite it.
Ted Kremenekd61ed3b2008-04-14 21:24:13 +0000653 if (SM->isFromMainFile(Loc))
Chris Lattner0bd1c972007-10-16 21:07:07 +0000654 return HandleDeclInMainFile(D);
Chris Lattner0bd1c972007-10-16 21:07:07 +0000655}
656
Chris Lattner3c799d72007-10-24 17:06:59 +0000657//===----------------------------------------------------------------------===//
658// Syntactic (non-AST) Rewriting Code
659//===----------------------------------------------------------------------===//
660
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000661void RewriteObjC::RewriteInclude() {
Chris Lattnerd32480d2009-01-17 06:22:33 +0000662 SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID);
Fariborz Jahanian80258362008-01-19 00:30:35 +0000663 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
664 const char *MainBufStart = MainBuf.first;
665 const char *MainBufEnd = MainBuf.second;
666 size_t ImportLen = strlen("import");
667 size_t IncludeLen = strlen("include");
Mike Stump11289f42009-09-09 15:08:12 +0000668
Fariborz Jahanian137d6932008-01-19 01:03:17 +0000669 // Loop over the whole file, looking for includes.
Fariborz Jahanian80258362008-01-19 00:30:35 +0000670 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
671 if (*BufPtr == '#') {
672 if (++BufPtr == MainBufEnd)
673 return;
674 while (*BufPtr == ' ' || *BufPtr == '\t')
675 if (++BufPtr == MainBufEnd)
676 return;
677 if (!strncmp(BufPtr, "import", ImportLen)) {
678 // replace import with include
Mike Stump11289f42009-09-09 15:08:12 +0000679 SourceLocation ImportLoc =
Fariborz Jahanian80258362008-01-19 00:30:35 +0000680 LocStart.getFileLocWithOffset(BufPtr-MainBufStart);
Chris Lattner9cc55f52008-01-31 19:51:04 +0000681 ReplaceText(ImportLoc, ImportLen, "include", IncludeLen);
Fariborz Jahanian80258362008-01-19 00:30:35 +0000682 BufPtr += ImportLen;
683 }
684 }
685 }
Chris Lattner0bd1c972007-10-16 21:07:07 +0000686}
687
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000688void RewriteObjC::RewriteTabs() {
Chris Lattner3c799d72007-10-24 17:06:59 +0000689 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
690 const char *MainBufStart = MainBuf.first;
691 const char *MainBufEnd = MainBuf.second;
Mike Stump11289f42009-09-09 15:08:12 +0000692
Chris Lattner3c799d72007-10-24 17:06:59 +0000693 // Loop over the whole file, looking for tabs.
694 for (const char *BufPtr = MainBufStart; BufPtr != MainBufEnd; ++BufPtr) {
695 if (*BufPtr != '\t')
696 continue;
Mike Stump11289f42009-09-09 15:08:12 +0000697
Chris Lattner3c799d72007-10-24 17:06:59 +0000698 // Okay, we found a tab. This tab will turn into at least one character,
699 // but it depends on which 'virtual column' it is in. Compute that now.
700 unsigned VCol = 0;
701 while (BufPtr-VCol != MainBufStart && BufPtr[-VCol-1] != '\t' &&
702 BufPtr[-VCol-1] != '\n' && BufPtr[-VCol-1] != '\r')
703 ++VCol;
Mike Stump11289f42009-09-09 15:08:12 +0000704
Chris Lattner3c799d72007-10-24 17:06:59 +0000705 // Okay, now that we know the virtual column, we know how many spaces to
706 // insert. We assume 8-character tab-stops.
707 unsigned Spaces = 8-(VCol & 7);
Mike Stump11289f42009-09-09 15:08:12 +0000708
Chris Lattner3c799d72007-10-24 17:06:59 +0000709 // Get the location of the tab.
Chris Lattnerd32480d2009-01-17 06:22:33 +0000710 SourceLocation TabLoc = SM->getLocForStartOfFile(MainFileID);
711 TabLoc = TabLoc.getFileLocWithOffset(BufPtr-MainBufStart);
Mike Stump11289f42009-09-09 15:08:12 +0000712
Chris Lattner3c799d72007-10-24 17:06:59 +0000713 // Rewrite the single tab character into a sequence of spaces.
Chris Lattner9cc55f52008-01-31 19:51:04 +0000714 ReplaceText(TabLoc, 1, " ", Spaces);
Chris Lattner3c799d72007-10-24 17:06:59 +0000715 }
Chris Lattner16a0de42007-10-11 18:38:32 +0000716}
717
Steve Naroff9af94912008-12-02 15:48:25 +0000718static std::string getIvarAccessString(ObjCInterfaceDecl *ClassDecl,
719 ObjCIvarDecl *OID) {
720 std::string S;
721 S = "((struct ";
722 S += ClassDecl->getIdentifier()->getName();
723 S += "_IMPL *)self)->";
Daniel Dunbar70e7ead2009-10-18 20:26:27 +0000724 S += OID->getName();
Steve Naroff9af94912008-12-02 15:48:25 +0000725 return S;
726}
727
Steve Naroffc038b3a2008-12-02 17:36:43 +0000728void RewriteObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
729 ObjCImplementationDecl *IMD,
730 ObjCCategoryImplDecl *CID) {
Steve Naroffe1908e32008-12-01 20:33:01 +0000731 SourceLocation startLoc = PID->getLocStart();
732 InsertText(startLoc, "// ", 3);
Steve Naroff9af94912008-12-02 15:48:25 +0000733 const char *startBuf = SM->getCharacterData(startLoc);
734 assert((*startBuf == '@') && "bogus @synthesize location");
735 const char *semiBuf = strchr(startBuf, ';');
736 assert((*semiBuf == ';') && "@synthesize: can't find ';'");
Ted Kremenek5a201952009-02-07 01:47:29 +0000737 SourceLocation onePastSemiLoc =
738 startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
Steve Naroff9af94912008-12-02 15:48:25 +0000739
740 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
741 return; // FIXME: is this correct?
Mike Stump11289f42009-09-09 15:08:12 +0000742
Steve Naroff9af94912008-12-02 15:48:25 +0000743 // Generate the 'getter' function.
Steve Naroff9af94912008-12-02 15:48:25 +0000744 ObjCPropertyDecl *PD = PID->getPropertyDecl();
Steve Naroff9af94912008-12-02 15:48:25 +0000745 ObjCInterfaceDecl *ClassDecl = PD->getGetterMethodDecl()->getClassInterface();
Steve Naroff9af94912008-12-02 15:48:25 +0000746 ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
Mike Stump11289f42009-09-09 15:08:12 +0000747
Steve Naroff003d00e2008-12-02 16:05:55 +0000748 if (!OID)
749 return;
Mike Stump11289f42009-09-09 15:08:12 +0000750
Steve Naroff003d00e2008-12-02 16:05:55 +0000751 std::string Getr;
752 RewriteObjCMethodDecl(PD->getGetterMethodDecl(), Getr);
753 Getr += "{ ";
754 // Synthesize an explicit cast to gain access to the ivar.
Mike Stump11289f42009-09-09 15:08:12 +0000755 // FIXME: deal with code generation implications for various property
756 // attributes (copy, retain, nonatomic).
Steve Naroff06297042008-12-02 17:54:50 +0000757 // See objc-act.c:objc_synthesize_new_getter() for details.
Steve Naroff003d00e2008-12-02 16:05:55 +0000758 Getr += "return " + getIvarAccessString(ClassDecl, OID);
759 Getr += "; }";
Steve Naroff9af94912008-12-02 15:48:25 +0000760 InsertText(onePastSemiLoc, Getr.c_str(), Getr.size());
Steve Naroff9af94912008-12-02 15:48:25 +0000761 if (PD->isReadOnly())
762 return;
Mike Stump11289f42009-09-09 15:08:12 +0000763
Steve Naroff9af94912008-12-02 15:48:25 +0000764 // Generate the 'setter' function.
765 std::string Setr;
766 RewriteObjCMethodDecl(PD->getSetterMethodDecl(), Setr);
Steve Naroff9af94912008-12-02 15:48:25 +0000767 Setr += "{ ";
Steve Naroff003d00e2008-12-02 16:05:55 +0000768 // Synthesize an explicit cast to initialize the ivar.
Mike Stump11289f42009-09-09 15:08:12 +0000769 // FIXME: deal with code generation implications for various property
770 // attributes (copy, retain, nonatomic).
Steve Narofff326f402008-12-03 00:56:33 +0000771 // See objc-act.c:objc_synthesize_new_setter() for details.
Steve Naroff003d00e2008-12-02 16:05:55 +0000772 Setr += getIvarAccessString(ClassDecl, OID) + " = ";
Steve Naroff1fa7bd12008-12-11 19:29:16 +0000773 Setr += PD->getNameAsCString();
Steve Naroff003d00e2008-12-02 16:05:55 +0000774 Setr += "; }";
Steve Naroff9af94912008-12-02 15:48:25 +0000775 InsertText(onePastSemiLoc, Setr.c_str(), Setr.size());
Steve Naroffe1908e32008-12-01 20:33:01 +0000776}
Chris Lattner16a0de42007-10-11 18:38:32 +0000777
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000778void RewriteObjC::RewriteForwardClassDecl(ObjCClassDecl *ClassDecl) {
Chris Lattner3c799d72007-10-24 17:06:59 +0000779 // Get the start location and compute the semi location.
780 SourceLocation startLoc = ClassDecl->getLocation();
781 const char *startBuf = SM->getCharacterData(startLoc);
782 const char *semiPtr = strchr(startBuf, ';');
Mike Stump11289f42009-09-09 15:08:12 +0000783
Chris Lattner3c799d72007-10-24 17:06:59 +0000784 // Translate to typedef's that forward reference structs with the same name
785 // as the class. As a convenience, we include the original declaration
786 // as a comment.
787 std::string typedefString;
788 typedefString += "// ";
Steve Naroff574440f2007-10-24 22:48:43 +0000789 typedefString.append(startBuf, semiPtr-startBuf+1);
790 typedefString += "\n";
Chris Lattner9ee23b72009-02-20 18:04:31 +0000791 for (ObjCClassDecl::iterator I = ClassDecl->begin(), E = ClassDecl->end();
792 I != E; ++I) {
Ted Kremenek9b124e12009-11-18 00:28:11 +0000793 ObjCInterfaceDecl *ForwardDecl = I->getInterface();
Steve Naroff1b232132007-11-09 12:50:28 +0000794 typedefString += "#ifndef _REWRITER_typedef_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000795 typedefString += ForwardDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +0000796 typedefString += "\n";
797 typedefString += "#define _REWRITER_typedef_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000798 typedefString += ForwardDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +0000799 typedefString += "\n";
Steve Naroff98eb8d12007-11-05 14:36:37 +0000800 typedefString += "typedef struct objc_object ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000801 typedefString += ForwardDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +0000802 typedefString += ";\n#endif\n";
Steve Naroff574440f2007-10-24 22:48:43 +0000803 }
Mike Stump11289f42009-09-09 15:08:12 +0000804
Steve Naroff574440f2007-10-24 22:48:43 +0000805 // Replace the @class with typedefs corresponding to the classes.
Mike Stump11289f42009-09-09 15:08:12 +0000806 ReplaceText(startLoc, semiPtr-startBuf+1,
Chris Lattner9cc55f52008-01-31 19:51:04 +0000807 typedefString.c_str(), typedefString.size());
Chris Lattner3c799d72007-10-24 17:06:59 +0000808}
809
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000810void RewriteObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
Steve Naroff3ce37a62007-12-14 23:37:57 +0000811 SourceLocation LocStart = Method->getLocStart();
812 SourceLocation LocEnd = Method->getLocEnd();
Mike Stump11289f42009-09-09 15:08:12 +0000813
Chris Lattner88ea93e2009-02-04 01:06:56 +0000814 if (SM->getInstantiationLineNumber(LocEnd) >
815 SM->getInstantiationLineNumber(LocStart)) {
Steve Naroffe020fa12008-10-21 13:37:27 +0000816 InsertText(LocStart, "#if 0\n", 6);
817 ReplaceText(LocEnd, 1, ";\n#endif\n", 9);
Steve Naroff3ce37a62007-12-14 23:37:57 +0000818 } else {
Chris Lattner1780a852008-01-31 19:42:41 +0000819 InsertText(LocStart, "// ", 3);
Steve Naroff5448cf62007-10-30 13:30:57 +0000820 }
821}
822
Mike Stump11289f42009-09-09 15:08:12 +0000823void RewriteObjC::RewriteProperty(ObjCPropertyDecl *prop) {
Steve Naroff0c0f5ba2009-01-11 01:06:09 +0000824 SourceLocation Loc = prop->getLocation();
Mike Stump11289f42009-09-09 15:08:12 +0000825
Steve Naroff0c0f5ba2009-01-11 01:06:09 +0000826 ReplaceText(Loc, 0, "// ", 3);
Mike Stump11289f42009-09-09 15:08:12 +0000827
Steve Naroff0c0f5ba2009-01-11 01:06:09 +0000828 // FIXME: handle properties that are declared across multiple lines.
Fariborz Jahaniane8a30162007-11-07 00:09:37 +0000829}
830
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000831void RewriteObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
Steve Naroff5448cf62007-10-30 13:30:57 +0000832 SourceLocation LocStart = CatDecl->getLocStart();
Mike Stump11289f42009-09-09 15:08:12 +0000833
Steve Naroff5448cf62007-10-30 13:30:57 +0000834 // FIXME: handle category headers that are declared across multiple lines.
Chris Lattner9cc55f52008-01-31 19:51:04 +0000835 ReplaceText(LocStart, 0, "// ", 3);
Mike Stump11289f42009-09-09 15:08:12 +0000836
837 for (ObjCCategoryDecl::instmeth_iterator
838 I = CatDecl->instmeth_begin(), E = CatDecl->instmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000839 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +0000840 RewriteMethodDeclaration(*I);
Mike Stump11289f42009-09-09 15:08:12 +0000841 for (ObjCCategoryDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000842 I = CatDecl->classmeth_begin(), E = CatDecl->classmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000843 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +0000844 RewriteMethodDeclaration(*I);
845
Steve Naroff5448cf62007-10-30 13:30:57 +0000846 // Lastly, comment out the @end.
Chris Lattner9cc55f52008-01-31 19:51:04 +0000847 ReplaceText(CatDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroff5448cf62007-10-30 13:30:57 +0000848}
849
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000850void RewriteObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
Fariborz Jahanianfe38ba22007-11-14 01:37:46 +0000851 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
Mike Stump11289f42009-09-09 15:08:12 +0000852
Steve Narofff921385f2007-10-30 16:42:30 +0000853 SourceLocation LocStart = PDecl->getLocStart();
Mike Stump11289f42009-09-09 15:08:12 +0000854
Steve Narofff921385f2007-10-30 16:42:30 +0000855 // FIXME: handle protocol headers that are declared across multiple lines.
Chris Lattner9cc55f52008-01-31 19:51:04 +0000856 ReplaceText(LocStart, 0, "// ", 3);
Mike Stump11289f42009-09-09 15:08:12 +0000857
858 for (ObjCProtocolDecl::instmeth_iterator
859 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000860 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +0000861 RewriteMethodDeclaration(*I);
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000862 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000863 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000864 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +0000865 RewriteMethodDeclaration(*I);
866
Steve Narofff921385f2007-10-30 16:42:30 +0000867 // Lastly, comment out the @end.
Fariborz Jahanianfe38ba22007-11-14 01:37:46 +0000868 SourceLocation LocEnd = PDecl->getAtEndLoc();
Chris Lattner9cc55f52008-01-31 19:51:04 +0000869 ReplaceText(LocEnd, 0, "// ", 3);
Steve Naroffa509f042007-11-14 15:03:57 +0000870
Fariborz Jahanianfe38ba22007-11-14 01:37:46 +0000871 // Must comment out @optional/@required
872 const char *startBuf = SM->getCharacterData(LocStart);
873 const char *endBuf = SM->getCharacterData(LocEnd);
874 for (const char *p = startBuf; p < endBuf; p++) {
875 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
876 std::string CommentedOptional = "/* @optional */";
Steve Naroffa509f042007-11-14 15:03:57 +0000877 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattner9cc55f52008-01-31 19:51:04 +0000878 ReplaceText(OptionalLoc, strlen("@optional"),
879 CommentedOptional.c_str(), CommentedOptional.size());
Mike Stump11289f42009-09-09 15:08:12 +0000880
Fariborz Jahanianfe38ba22007-11-14 01:37:46 +0000881 }
882 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
883 std::string CommentedRequired = "/* @required */";
Steve Naroffa509f042007-11-14 15:03:57 +0000884 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattner9cc55f52008-01-31 19:51:04 +0000885 ReplaceText(OptionalLoc, strlen("@required"),
886 CommentedRequired.c_str(), CommentedRequired.size());
Mike Stump11289f42009-09-09 15:08:12 +0000887
Fariborz Jahanianfe38ba22007-11-14 01:37:46 +0000888 }
889 }
Steve Narofff921385f2007-10-30 16:42:30 +0000890}
891
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000892void RewriteObjC::RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *PDecl) {
Fariborz Jahanianda6165c2007-11-14 00:42:16 +0000893 SourceLocation LocStart = PDecl->getLocation();
Steve Naroffc17b0562007-11-14 03:37:28 +0000894 if (LocStart.isInvalid())
895 assert(false && "Invalid SourceLocation");
Fariborz Jahanianda6165c2007-11-14 00:42:16 +0000896 // FIXME: handle forward protocol that are declared across multiple lines.
Chris Lattner9cc55f52008-01-31 19:51:04 +0000897 ReplaceText(LocStart, 0, "// ", 3);
Fariborz Jahanianda6165c2007-11-14 00:42:16 +0000898}
899
Mike Stump11289f42009-09-09 15:08:12 +0000900void RewriteObjC::RewriteObjCMethodDecl(ObjCMethodDecl *OMD,
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000901 std::string &ResultStr) {
Steve Naroff295570a2008-10-30 12:09:33 +0000902 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
Steve Naroffb067bbd2008-07-16 14:40:40 +0000903 const FunctionType *FPRetType = 0;
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000904 ResultStr += "\nstatic ";
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000905 if (OMD->getResultType()->isObjCQualifiedIdType())
Fariborz Jahanian24cb52c2007-12-17 21:03:50 +0000906 ResultStr += "id";
Steve Naroff1fa7bd12008-12-11 19:29:16 +0000907 else if (OMD->getResultType()->isFunctionPointerType() ||
908 OMD->getResultType()->isBlockPointerType()) {
Steve Naroffb067bbd2008-07-16 14:40:40 +0000909 // needs special handling, since pointer-to-functions have special
910 // syntax (where a decaration models use).
911 QualType retType = OMD->getResultType();
Steve Naroff1fa7bd12008-12-11 19:29:16 +0000912 QualType PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000913 if (const PointerType* PT = retType->getAs<PointerType>())
Steve Naroff1fa7bd12008-12-11 19:29:16 +0000914 PointeeTy = PT->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000915 else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>())
Steve Naroff1fa7bd12008-12-11 19:29:16 +0000916 PointeeTy = BPT->getPointeeType();
John McCall9dd450b2009-09-21 23:43:11 +0000917 if ((FPRetType = PointeeTy->getAs<FunctionType>())) {
Steve Naroff1fa7bd12008-12-11 19:29:16 +0000918 ResultStr += FPRetType->getResultType().getAsString();
919 ResultStr += "(*";
Steve Naroffb067bbd2008-07-16 14:40:40 +0000920 }
921 } else
Fariborz Jahanian24cb52c2007-12-17 21:03:50 +0000922 ResultStr += OMD->getResultType().getAsString();
Fariborz Jahanian7262fca2008-01-10 01:39:52 +0000923 ResultStr += " ";
Mike Stump11289f42009-09-09 15:08:12 +0000924
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000925 // Unique method name
Fariborz Jahanian56338352007-11-13 21:02:00 +0000926 std::string NameStr;
Mike Stump11289f42009-09-09 15:08:12 +0000927
Douglas Gregorffca3a22009-01-09 17:18:27 +0000928 if (OMD->isInstanceMethod())
Fariborz Jahanian56338352007-11-13 21:02:00 +0000929 NameStr += "_I_";
930 else
931 NameStr += "_C_";
Mike Stump11289f42009-09-09 15:08:12 +0000932
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000933 NameStr += OMD->getClassInterface()->getNameAsString();
Fariborz Jahanian56338352007-11-13 21:02:00 +0000934 NameStr += "_";
Mike Stump11289f42009-09-09 15:08:12 +0000935
936 if (ObjCCategoryImplDecl *CID =
Steve Naroff11b387f2009-01-08 19:41:02 +0000937 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000938 NameStr += CID->getNameAsString();
Fariborz Jahanian56338352007-11-13 21:02:00 +0000939 NameStr += "_";
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000940 }
Mike Stump11289f42009-09-09 15:08:12 +0000941 // Append selector names, replacing ':' with '_'
Chris Lattnere4b95692008-11-24 03:33:13 +0000942 {
943 std::string selString = OMD->getSelector().getAsString();
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000944 int len = selString.size();
945 for (int i = 0; i < len; i++)
946 if (selString[i] == ':')
947 selString[i] = '_';
Fariborz Jahanian56338352007-11-13 21:02:00 +0000948 NameStr += selString;
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000949 }
Fariborz Jahanian56338352007-11-13 21:02:00 +0000950 // Remember this name for metadata emission
951 MethodInternalNames[OMD] = NameStr;
952 ResultStr += NameStr;
Mike Stump11289f42009-09-09 15:08:12 +0000953
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000954 // Rewrite arguments
955 ResultStr += "(";
Mike Stump11289f42009-09-09 15:08:12 +0000956
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000957 // invisible arguments
Douglas Gregorffca3a22009-01-09 17:18:27 +0000958 if (OMD->isInstanceMethod()) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000959 QualType selfTy = Context->getObjCInterfaceType(OMD->getClassInterface());
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000960 selfTy = Context->getPointerType(selfTy);
Steve Naroffdc5b6b22008-03-12 00:25:36 +0000961 if (!LangOpts.Microsoft) {
962 if (ObjCSynthesizedStructs.count(OMD->getClassInterface()))
963 ResultStr += "struct ";
964 }
965 // When rewriting for Microsoft, explicitly omit the structure name.
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000966 ResultStr += OMD->getClassInterface()->getNameAsString();
Steve Naroffa1e115e2008-03-10 23:16:54 +0000967 ResultStr += " *";
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000968 }
969 else
Steve Naroffd9803712009-04-29 16:37:50 +0000970 ResultStr += Context->getObjCClassType().getAsString();
Mike Stump11289f42009-09-09 15:08:12 +0000971
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000972 ResultStr += " self, ";
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000973 ResultStr += Context->getObjCSelType().getAsString();
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000974 ResultStr += " _cmd";
Mike Stump11289f42009-09-09 15:08:12 +0000975
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000976 // Method arguments.
Chris Lattnera4997152009-02-20 18:43:26 +0000977 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
978 E = OMD->param_end(); PI != E; ++PI) {
979 ParmVarDecl *PDecl = *PI;
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000980 ResultStr += ", ";
Steve Naroffdcdcdcd2008-04-18 21:13:19 +0000981 if (PDecl->getType()->isObjCQualifiedIdType()) {
982 ResultStr += "id ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000983 ResultStr += PDecl->getNameAsString();
Steve Naroffdcdcdcd2008-04-18 21:13:19 +0000984 } else {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000985 std::string Name = PDecl->getNameAsString();
Steve Naroffa5c0db82008-12-11 21:05:33 +0000986 if (isTopLevelBlockPointerType(PDecl->getType())) {
Steve Naroff44df6a22008-10-30 14:45:29 +0000987 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000988 const BlockPointerType *BPT = PDecl->getType()->getAs<BlockPointerType>();
Douglas Gregor7de59662009-05-29 20:38:28 +0000989 Context->getPointerType(BPT->getPointeeType()).getAsStringInternal(Name,
990 Context->PrintingPolicy);
Steve Naroff44df6a22008-10-30 14:45:29 +0000991 } else
Douglas Gregor7de59662009-05-29 20:38:28 +0000992 PDecl->getType().getAsStringInternal(Name, Context->PrintingPolicy);
Steve Naroffdcdcdcd2008-04-18 21:13:19 +0000993 ResultStr += Name;
994 }
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000995 }
Fariborz Jahanianeab81cd2008-01-21 20:14:23 +0000996 if (OMD->isVariadic())
997 ResultStr += ", ...";
Fariborz Jahanian7262fca2008-01-10 01:39:52 +0000998 ResultStr += ") ";
Mike Stump11289f42009-09-09 15:08:12 +0000999
Steve Naroffb067bbd2008-07-16 14:40:40 +00001000 if (FPRetType) {
1001 ResultStr += ")"; // close the precedence "scope" for "*".
Mike Stump11289f42009-09-09 15:08:12 +00001002
Steve Naroffb067bbd2008-07-16 14:40:40 +00001003 // Now, emit the argument types (if any).
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001004 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
Steve Naroffb067bbd2008-07-16 14:40:40 +00001005 ResultStr += "(";
1006 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
1007 if (i) ResultStr += ", ";
1008 std::string ParamStr = FT->getArgType(i).getAsString();
1009 ResultStr += ParamStr;
1010 }
1011 if (FT->isVariadic()) {
1012 if (FT->getNumArgs()) ResultStr += ", ";
1013 ResultStr += "...";
1014 }
1015 ResultStr += ")";
1016 } else {
1017 ResultStr += "()";
1018 }
1019 }
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001020}
Douglas Gregor6e6ad602009-01-20 01:17:11 +00001021void RewriteObjC::RewriteImplementationDecl(Decl *OID) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001022 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
1023 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
Mike Stump11289f42009-09-09 15:08:12 +00001024
Fariborz Jahanianc54d8462007-11-13 20:04:28 +00001025 if (IMD)
Chris Lattner1780a852008-01-31 19:42:41 +00001026 InsertText(IMD->getLocStart(), "// ", 3);
Fariborz Jahanianc54d8462007-11-13 20:04:28 +00001027 else
Chris Lattner1780a852008-01-31 19:42:41 +00001028 InsertText(CID->getLocStart(), "// ", 3);
Mike Stump11289f42009-09-09 15:08:12 +00001029
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001030 for (ObjCCategoryImplDecl::instmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001031 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
1032 E = IMD ? IMD->instmeth_end() : CID->instmeth_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00001033 I != E; ++I) {
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001034 std::string ResultStr;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001035 ObjCMethodDecl *OMD = *I;
1036 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001037 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00001038 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Sebastian Redla7b98a72009-04-26 20:35:05 +00001039
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001040 const char *startBuf = SM->getCharacterData(LocStart);
1041 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattner9cc55f52008-01-31 19:51:04 +00001042 ReplaceText(LocStart, endBuf-startBuf,
1043 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001044 }
Mike Stump11289f42009-09-09 15:08:12 +00001045
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001046 for (ObjCCategoryImplDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001047 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
1048 E = IMD ? IMD->classmeth_end() : CID->classmeth_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00001049 I != E; ++I) {
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001050 std::string ResultStr;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001051 ObjCMethodDecl *OMD = *I;
1052 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001053 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00001054 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Mike Stump11289f42009-09-09 15:08:12 +00001055
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001056 const char *startBuf = SM->getCharacterData(LocStart);
1057 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattner9cc55f52008-01-31 19:51:04 +00001058 ReplaceText(LocStart, endBuf-startBuf,
Mike Stump11289f42009-09-09 15:08:12 +00001059 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001060 }
Steve Naroffe1908e32008-12-01 20:33:01 +00001061 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001062 I = IMD ? IMD->propimpl_begin() : CID->propimpl_begin(),
Mike Stump11289f42009-09-09 15:08:12 +00001063 E = IMD ? IMD->propimpl_end() : CID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00001064 I != E; ++I) {
Steve Naroffc038b3a2008-12-02 17:36:43 +00001065 RewritePropertyImplDecl(*I, IMD, CID);
Steve Naroffe1908e32008-12-01 20:33:01 +00001066 }
1067
Fariborz Jahanianc54d8462007-11-13 20:04:28 +00001068 if (IMD)
Chris Lattner1780a852008-01-31 19:42:41 +00001069 InsertText(IMD->getLocEnd(), "// ", 3);
Fariborz Jahanianc54d8462007-11-13 20:04:28 +00001070 else
Mike Stump11289f42009-09-09 15:08:12 +00001071 InsertText(CID->getLocEnd(), "// ", 3);
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001072}
1073
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001074void RewriteObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Steve Naroffc5484042007-10-30 02:23:23 +00001075 std::string ResultStr;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001076 if (!ObjCForwardDecls.count(ClassDecl)) {
Steve Naroff2f55b982007-11-01 03:35:41 +00001077 // we haven't seen a forward decl - generate a typedef.
Steve Naroff03f27672007-11-14 23:02:56 +00001078 ResultStr = "#ifndef _REWRITER_typedef_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001079 ResultStr += ClassDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +00001080 ResultStr += "\n";
1081 ResultStr += "#define _REWRITER_typedef_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001082 ResultStr += ClassDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +00001083 ResultStr += "\n";
Steve Naroffa1e115e2008-03-10 23:16:54 +00001084 ResultStr += "typedef struct objc_object ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001085 ResultStr += ClassDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +00001086 ResultStr += ";\n#endif\n";
Steve Naroff2f55b982007-11-01 03:35:41 +00001087 // Mark this typedef as having been generated.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001088 ObjCForwardDecls.insert(ClassDecl);
Steve Naroff2f55b982007-11-01 03:35:41 +00001089 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001090 SynthesizeObjCInternalStruct(ClassDecl, ResultStr);
Mike Stump11289f42009-09-09 15:08:12 +00001091
1092 for (ObjCInterfaceDecl::prop_iterator I = ClassDecl->prop_begin(),
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001093 E = ClassDecl->prop_end(); I != E; ++I)
Steve Naroff0c0f5ba2009-01-11 01:06:09 +00001094 RewriteProperty(*I);
Mike Stump11289f42009-09-09 15:08:12 +00001095 for (ObjCInterfaceDecl::instmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001096 I = ClassDecl->instmeth_begin(), E = ClassDecl->instmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +00001097 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +00001098 RewriteMethodDeclaration(*I);
Mike Stump11289f42009-09-09 15:08:12 +00001099 for (ObjCInterfaceDecl::classmeth_iterator
1100 I = ClassDecl->classmeth_begin(), E = ClassDecl->classmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +00001101 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +00001102 RewriteMethodDeclaration(*I);
1103
Steve Naroff4cd61ac2007-10-30 03:43:13 +00001104 // Lastly, comment out the @end.
Chris Lattner9cc55f52008-01-31 19:51:04 +00001105 ReplaceText(ClassDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroff161a92b2007-10-26 20:53:56 +00001106}
1107
Steve Naroff08628db2008-12-09 12:56:34 +00001108Stmt *RewriteObjC::RewritePropertySetter(BinaryOperator *BinOp, Expr *newStmt,
1109 SourceRange SrcRange) {
Steve Naroff4588d0f2008-12-04 16:24:46 +00001110 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr.
1111 // This allows us to reuse all the fun and games in SynthMessageExpr().
1112 ObjCPropertyRefExpr *PropRefExpr = dyn_cast<ObjCPropertyRefExpr>(BinOp->getLHS());
1113 ObjCMessageExpr *MsgExpr;
1114 ObjCPropertyDecl *PDecl = PropRefExpr->getProperty();
1115 llvm::SmallVector<Expr *, 1> ExprVec;
1116 ExprVec.push_back(newStmt);
Mike Stump11289f42009-09-09 15:08:12 +00001117
Steve Naroff1042ff32008-12-08 16:43:47 +00001118 Stmt *Receiver = PropRefExpr->getBase();
1119 ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(Receiver);
1120 if (PRE && PropGetters[PRE]) {
1121 // This allows us to handle chain/nested property getters.
1122 Receiver = PropGetters[PRE];
1123 }
Mike Stump11289f42009-09-09 15:08:12 +00001124 MsgExpr = new (Context) ObjCMessageExpr(dyn_cast<Expr>(Receiver),
1125 PDecl->getSetterName(), PDecl->getType(),
1126 PDecl->getSetterMethodDecl(),
1127 SourceLocation(), SourceLocation(),
Steve Naroff4588d0f2008-12-04 16:24:46 +00001128 &ExprVec[0], 1);
1129 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr);
Mike Stump11289f42009-09-09 15:08:12 +00001130
Steve Naroff4588d0f2008-12-04 16:24:46 +00001131 // Now do the actual rewrite.
Steve Naroff08628db2008-12-09 12:56:34 +00001132 ReplaceStmtWithRange(BinOp, ReplacingStmt, SrcRange);
Steve Naroffdf705772008-12-10 14:53:27 +00001133 //delete BinOp;
Ted Kremenek5a201952009-02-07 01:47:29 +00001134 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1135 // to things that stay around.
1136 Context->Deallocate(MsgExpr);
Steve Naroff4588d0f2008-12-04 16:24:46 +00001137 return ReplacingStmt;
Steve Narofff326f402008-12-03 00:56:33 +00001138}
1139
Steve Naroff4588d0f2008-12-04 16:24:46 +00001140Stmt *RewriteObjC::RewritePropertyGetter(ObjCPropertyRefExpr *PropRefExpr) {
Steve Narofff326f402008-12-03 00:56:33 +00001141 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr.
1142 // This allows us to reuse all the fun and games in SynthMessageExpr().
1143 ObjCMessageExpr *MsgExpr;
1144 ObjCPropertyDecl *PDecl = PropRefExpr->getProperty();
Mike Stump11289f42009-09-09 15:08:12 +00001145
Steve Naroff1042ff32008-12-08 16:43:47 +00001146 Stmt *Receiver = PropRefExpr->getBase();
Mike Stump11289f42009-09-09 15:08:12 +00001147
Steve Naroff1042ff32008-12-08 16:43:47 +00001148 ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(Receiver);
1149 if (PRE && PropGetters[PRE]) {
1150 // This allows us to handle chain/nested property getters.
1151 Receiver = PropGetters[PRE];
1152 }
Mike Stump11289f42009-09-09 15:08:12 +00001153 MsgExpr = new (Context) ObjCMessageExpr(dyn_cast<Expr>(Receiver),
1154 PDecl->getGetterName(), PDecl->getType(),
1155 PDecl->getGetterMethodDecl(),
1156 SourceLocation(), SourceLocation(),
Steve Narofff326f402008-12-03 00:56:33 +00001157 0, 0);
1158
Steve Naroff22216db2008-12-04 23:50:32 +00001159 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr);
Steve Naroff1042ff32008-12-08 16:43:47 +00001160
1161 if (!PropParentMap)
1162 PropParentMap = new ParentMap(CurrentBody);
1163
1164 Stmt *Parent = PropParentMap->getParent(PropRefExpr);
1165 if (Parent && isa<ObjCPropertyRefExpr>(Parent)) {
1166 // We stash away the ReplacingStmt since actually doing the
1167 // replacement/rewrite won't work for nested getters (e.g. obj.p.i)
1168 PropGetters[PropRefExpr] = ReplacingStmt;
Ted Kremenek5a201952009-02-07 01:47:29 +00001169 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1170 // to things that stay around.
1171 Context->Deallocate(MsgExpr);
Steve Naroff1042ff32008-12-08 16:43:47 +00001172 return PropRefExpr; // return the original...
1173 } else {
1174 ReplaceStmt(PropRefExpr, ReplacingStmt);
Mike Stump11289f42009-09-09 15:08:12 +00001175 // delete PropRefExpr; elsewhere...
Ted Kremenek5a201952009-02-07 01:47:29 +00001176 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1177 // to things that stay around.
1178 Context->Deallocate(MsgExpr);
Steve Naroff1042ff32008-12-08 16:43:47 +00001179 return ReplacingStmt;
1180 }
Steve Narofff326f402008-12-03 00:56:33 +00001181}
1182
Mike Stump11289f42009-09-09 15:08:12 +00001183Stmt *RewriteObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV,
Chris Lattner37f5b7d2008-05-23 20:40:52 +00001184 SourceLocation OrigStart) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001185 ObjCIvarDecl *D = IV->getDecl();
Steve Naroff677ab3a2008-10-27 17:20:55 +00001186 if (CurMethodDef) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001187 if (const PointerType *pType = IV->getBase()->getType()->getAs<PointerType>()) {
Ted Kremenek5a201952009-02-07 01:47:29 +00001188 ObjCInterfaceType *iFaceDecl =
1189 dyn_cast<ObjCInterfaceType>(pType->getPointeeType());
Steve Naroffb1c02372008-05-08 17:52:16 +00001190 // lookup which class implements the instance variable.
1191 ObjCInterfaceDecl *clsDeclared = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001192 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
Douglas Gregorbcced4e2009-04-09 21:40:53 +00001193 clsDeclared);
Steve Naroffb1c02372008-05-08 17:52:16 +00001194 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
Mike Stump11289f42009-09-09 15:08:12 +00001195
Steve Naroffb1c02372008-05-08 17:52:16 +00001196 // Synthesize an explicit cast to gain access to the ivar.
1197 std::string RecName = clsDeclared->getIdentifier()->getName();
1198 RecName += "_IMPL";
1199 IdentifierInfo *II = &Context->Idents.get(RecName.c_str());
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00001200 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Ted Kremenek47923c72008-09-05 01:34:33 +00001201 SourceLocation(), II);
Steve Naroffb1c02372008-05-08 17:52:16 +00001202 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1203 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
Mike Stump11289f42009-09-09 15:08:12 +00001204 CastExpr *castExpr = new (Context) CStyleCastExpr(castT,
Anders Carlssona2615922009-07-31 00:48:10 +00001205 CastExpr::CK_Unknown,
1206 IV->getBase(),
1207 castT,SourceLocation(),
1208 SourceLocation());
Steve Naroffb1c02372008-05-08 17:52:16 +00001209 // Don't forget the parens to enforce the proper binding.
Ted Kremenek5a201952009-02-07 01:47:29 +00001210 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
1211 IV->getBase()->getLocEnd(),
1212 castExpr);
Mike Stump11289f42009-09-09 15:08:12 +00001213 if (IV->isFreeIvar() &&
Steve Naroff677ab3a2008-10-27 17:20:55 +00001214 CurMethodDef->getClassInterface() == iFaceDecl->getDecl()) {
Ted Kremenek5a201952009-02-07 01:47:29 +00001215 MemberExpr *ME = new (Context) MemberExpr(PE, true, D,
1216 IV->getLocation(),
1217 D->getType());
Steve Naroffb1c02372008-05-08 17:52:16 +00001218 ReplaceStmt(IV, ME);
Steve Naroff22216db2008-12-04 23:50:32 +00001219 // delete IV; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroffb1c02372008-05-08 17:52:16 +00001220 return ME;
Steve Naroff05caa482007-11-15 11:33:00 +00001221 }
Mike Stump11289f42009-09-09 15:08:12 +00001222
Chris Lattner37f5b7d2008-05-23 20:40:52 +00001223 ReplaceStmt(IV->getBase(), PE);
1224 // Cannot delete IV->getBase(), since PE points to it.
1225 // Replace the old base with the cast. This is important when doing
1226 // embedded rewrites. For example, [newInv->_container addObject:0].
Mike Stump11289f42009-09-09 15:08:12 +00001227 IV->setBase(PE);
Chris Lattner37f5b7d2008-05-23 20:40:52 +00001228 return IV;
Steve Naroff05caa482007-11-15 11:33:00 +00001229 }
Steve Naroff24840f62008-04-18 21:55:08 +00001230 } else { // we are outside a method.
Steve Naroff29ce4e52008-05-06 23:20:07 +00001231 assert(!IV->isFreeIvar() && "Cannot have a free standing ivar outside a method");
Mike Stump11289f42009-09-09 15:08:12 +00001232
Steve Naroff29ce4e52008-05-06 23:20:07 +00001233 // Explicit ivar refs need to have a cast inserted.
1234 // FIXME: consider sharing some of this code with the code above.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001235 if (const PointerType *pType = IV->getBase()->getType()->getAs<PointerType>()) {
Steve Naroffb1c02372008-05-08 17:52:16 +00001236 ObjCInterfaceType *iFaceDecl = dyn_cast<ObjCInterfaceType>(pType->getPointeeType());
Steve Naroff29ce4e52008-05-06 23:20:07 +00001237 // lookup which class implements the instance variable.
1238 ObjCInterfaceDecl *clsDeclared = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001239 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
Douglas Gregorbcced4e2009-04-09 21:40:53 +00001240 clsDeclared);
Steve Naroff29ce4e52008-05-06 23:20:07 +00001241 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
Mike Stump11289f42009-09-09 15:08:12 +00001242
Steve Naroff29ce4e52008-05-06 23:20:07 +00001243 // Synthesize an explicit cast to gain access to the ivar.
1244 std::string RecName = clsDeclared->getIdentifier()->getName();
1245 RecName += "_IMPL";
1246 IdentifierInfo *II = &Context->Idents.get(RecName.c_str());
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00001247 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Ted Kremenek47923c72008-09-05 01:34:33 +00001248 SourceLocation(), II);
Steve Naroff29ce4e52008-05-06 23:20:07 +00001249 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1250 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
Mike Stump11289f42009-09-09 15:08:12 +00001251 CastExpr *castExpr = new (Context) CStyleCastExpr(castT,
Anders Carlssona2615922009-07-31 00:48:10 +00001252 CastExpr::CK_Unknown,
1253 IV->getBase(),
Ted Kremenek5a201952009-02-07 01:47:29 +00001254 castT, SourceLocation(),
1255 SourceLocation());
Steve Naroff29ce4e52008-05-06 23:20:07 +00001256 // Don't forget the parens to enforce the proper binding.
Ted Kremenek5a201952009-02-07 01:47:29 +00001257 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
Chris Lattner34873d22008-05-28 16:38:23 +00001258 IV->getBase()->getLocEnd(), castExpr);
Steve Naroff29ce4e52008-05-06 23:20:07 +00001259 ReplaceStmt(IV->getBase(), PE);
1260 // Cannot delete IV->getBase(), since PE points to it.
1261 // Replace the old base with the cast. This is important when doing
1262 // embedded rewrites. For example, [newInv->_container addObject:0].
Mike Stump11289f42009-09-09 15:08:12 +00001263 IV->setBase(PE);
Steve Naroff29ce4e52008-05-06 23:20:07 +00001264 return IV;
1265 }
Steve Naroff05caa482007-11-15 11:33:00 +00001266 }
Steve Naroff24840f62008-04-18 21:55:08 +00001267 return IV;
Steve Narofff60782b2007-11-15 02:58:25 +00001268}
1269
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001270/// SynthCountByEnumWithState - To print:
1271/// ((unsigned int (*)
1272/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump11289f42009-09-09 15:08:12 +00001273/// (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001274/// sel_registerName(
Mike Stump11289f42009-09-09 15:08:12 +00001275/// "countByEnumeratingWithState:objects:count:"),
1276/// &enumState,
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001277/// (id *)items, (unsigned int)16)
1278///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001279void RewriteObjC::SynthCountByEnumWithState(std::string &buf) {
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001280 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1281 "id *, unsigned int))(void *)objc_msgSend)";
1282 buf += "\n\t\t";
1283 buf += "((id)l_collection,\n\t\t";
1284 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1285 buf += "\n\t\t";
1286 buf += "&enumState, "
1287 "(id *)items, (unsigned int)16)";
1288}
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001289
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001290/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1291/// statement to exit to its outer synthesized loop.
1292///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001293Stmt *RewriteObjC::RewriteBreakStmt(BreakStmt *S) {
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001294 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1295 return S;
1296 // replace break with goto __break_label
1297 std::string buf;
Mike Stump11289f42009-09-09 15:08:12 +00001298
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001299 SourceLocation startLoc = S->getLocStart();
1300 buf = "goto __break_label_";
1301 buf += utostr(ObjCBcLabelNo.back());
Chris Lattner9cc55f52008-01-31 19:51:04 +00001302 ReplaceText(startLoc, strlen("break"), buf.c_str(), buf.size());
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001303
1304 return 0;
1305}
1306
1307/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1308/// statement to continue with its inner synthesized loop.
1309///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001310Stmt *RewriteObjC::RewriteContinueStmt(ContinueStmt *S) {
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001311 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1312 return S;
1313 // replace continue with goto __continue_label
1314 std::string buf;
Mike Stump11289f42009-09-09 15:08:12 +00001315
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001316 SourceLocation startLoc = S->getLocStart();
1317 buf = "goto __continue_label_";
1318 buf += utostr(ObjCBcLabelNo.back());
Chris Lattner9cc55f52008-01-31 19:51:04 +00001319 ReplaceText(startLoc, strlen("continue"), buf.c_str(), buf.size());
Mike Stump11289f42009-09-09 15:08:12 +00001320
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001321 return 0;
1322}
1323
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001324/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001325/// It rewrites:
1326/// for ( type elem in collection) { stmts; }
Mike Stump11289f42009-09-09 15:08:12 +00001327
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001328/// Into:
1329/// {
Mike Stump11289f42009-09-09 15:08:12 +00001330/// type elem;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001331/// struct __objcFastEnumerationState enumState = { 0 };
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001332/// id items[16];
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001333/// id l_collection = (id)collection;
Mike Stump11289f42009-09-09 15:08:12 +00001334/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001335/// objects:items count:16];
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001336/// if (limit) {
1337/// unsigned long startMutations = *enumState.mutationsPtr;
1338/// do {
1339/// unsigned long counter = 0;
1340/// do {
Mike Stump11289f42009-09-09 15:08:12 +00001341/// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001342/// objc_enumerationMutation(l_collection);
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001343/// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001344/// stmts;
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001345/// __continue_label: ;
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001346/// } while (counter < limit);
Mike Stump11289f42009-09-09 15:08:12 +00001347/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001348/// objects:items count:16]);
1349/// elem = nil;
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001350/// __break_label: ;
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001351/// }
1352/// else
1353/// elem = nil;
1354/// }
1355///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001356Stmt *RewriteObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
Chris Lattnera779d692008-01-31 05:10:40 +00001357 SourceLocation OrigEnd) {
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001358 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
Mike Stump11289f42009-09-09 15:08:12 +00001359 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001360 "ObjCForCollectionStmt Statement stack mismatch");
Mike Stump11289f42009-09-09 15:08:12 +00001361 assert(!ObjCBcLabelNo.empty() &&
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001362 "ObjCForCollectionStmt - Label No stack empty");
Mike Stump11289f42009-09-09 15:08:12 +00001363
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001364 SourceLocation startLoc = S->getLocStart();
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001365 const char *startBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001366 const char *elementName;
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001367 std::string elementTypeAsString;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001368 std::string buf;
1369 buf = "\n{\n\t";
1370 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1371 // type elem;
Chris Lattner529efc72009-03-28 06:33:19 +00001372 NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
Ted Kremenek292b3842008-10-06 22:16:13 +00001373 QualType ElementType = cast<ValueDecl>(D)->getType();
Steve Naroff3ce3af22009-12-04 21:18:19 +00001374 if (ElementType->isObjCQualifiedIdType() ||
1375 ElementType->isObjCQualifiedInterfaceType())
1376 // Simply use 'id' for all qualified types.
1377 elementTypeAsString = "id";
1378 else
1379 elementTypeAsString = ElementType.getAsString();
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001380 buf += elementTypeAsString;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001381 buf += " ";
Chris Lattner86d7d912008-11-24 03:54:41 +00001382 elementName = D->getNameAsCString();
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001383 buf += elementName;
1384 buf += ";\n\t";
1385 }
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001386 else {
1387 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
Chris Lattner86d7d912008-11-24 03:54:41 +00001388 elementName = DR->getDecl()->getNameAsCString();
Steve Naroff3ce3af22009-12-04 21:18:19 +00001389 ValueDecl *VD = cast<ValueDecl>(DR->getDecl());
1390 if (VD->getType()->isObjCQualifiedIdType() ||
1391 VD->getType()->isObjCQualifiedInterfaceType())
1392 // Simply use 'id' for all qualified types.
1393 elementTypeAsString = "id";
1394 else
1395 elementTypeAsString = VD->getType().getAsString();
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001396 }
Mike Stump11289f42009-09-09 15:08:12 +00001397
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001398 // struct __objcFastEnumerationState enumState = { 0 };
1399 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1400 // id items[16];
1401 buf += "id items[16];\n\t";
1402 // id l_collection = (id)
1403 buf += "id l_collection = (id)";
Fariborz Jahanian82ae0152008-01-10 00:24:29 +00001404 // Find start location of 'collection' the hard way!
1405 const char *startCollectionBuf = startBuf;
1406 startCollectionBuf += 3; // skip 'for'
1407 startCollectionBuf = strchr(startCollectionBuf, '(');
1408 startCollectionBuf++; // skip '('
1409 // find 'in' and skip it.
1410 while (*startCollectionBuf != ' ' ||
1411 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1412 (*(startCollectionBuf+3) != ' ' &&
1413 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1414 startCollectionBuf++;
1415 startCollectionBuf += 3;
Mike Stump11289f42009-09-09 15:08:12 +00001416
1417 // Replace: "for (type element in" with string constructed thus far.
Chris Lattner9cc55f52008-01-31 19:51:04 +00001418 ReplaceText(startLoc, startCollectionBuf - startBuf,
1419 buf.c_str(), buf.size());
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001420 // Replace ')' in for '(' type elem in collection ')' with ';'
Fariborz Jahanian82ae0152008-01-10 00:24:29 +00001421 SourceLocation rightParenLoc = S->getRParenLoc();
1422 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1423 SourceLocation lparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001424 buf = ";\n\t";
Mike Stump11289f42009-09-09 15:08:12 +00001425
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001426 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1427 // objects:items count:16];
1428 // which is synthesized into:
Mike Stump11289f42009-09-09 15:08:12 +00001429 // unsigned int limit =
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001430 // ((unsigned int (*)
1431 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump11289f42009-09-09 15:08:12 +00001432 // (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001433 // sel_registerName(
Mike Stump11289f42009-09-09 15:08:12 +00001434 // "countByEnumeratingWithState:objects:count:"),
1435 // (struct __objcFastEnumerationState *)&state,
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001436 // (id *)items, (unsigned int)16);
1437 buf += "unsigned long limit =\n\t\t";
1438 SynthCountByEnumWithState(buf);
1439 buf += ";\n\t";
1440 /// if (limit) {
1441 /// unsigned long startMutations = *enumState.mutationsPtr;
1442 /// do {
1443 /// unsigned long counter = 0;
1444 /// do {
Mike Stump11289f42009-09-09 15:08:12 +00001445 /// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001446 /// objc_enumerationMutation(l_collection);
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001447 /// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001448 buf += "if (limit) {\n\t";
1449 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1450 buf += "do {\n\t\t";
1451 buf += "unsigned long counter = 0;\n\t\t";
1452 buf += "do {\n\t\t\t";
1453 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1454 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1455 buf += elementName;
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001456 buf += " = (";
1457 buf += elementTypeAsString;
1458 buf += ")enumState.itemsPtr[counter++];";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001459 // Replace ')' in for '(' type elem in collection ')' with all of these.
Chris Lattner9cc55f52008-01-31 19:51:04 +00001460 ReplaceText(lparenLoc, 1, buf.c_str(), buf.size());
Mike Stump11289f42009-09-09 15:08:12 +00001461
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001462 /// __continue_label: ;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001463 /// } while (counter < limit);
Mike Stump11289f42009-09-09 15:08:12 +00001464 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001465 /// objects:items count:16]);
1466 /// elem = nil;
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001467 /// __break_label: ;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001468 /// }
1469 /// else
1470 /// elem = nil;
1471 /// }
Mike Stump11289f42009-09-09 15:08:12 +00001472 ///
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001473 buf = ";\n\t";
1474 buf += "__continue_label_";
1475 buf += utostr(ObjCBcLabelNo.back());
1476 buf += ": ;";
1477 buf += "\n\t\t";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001478 buf += "} while (counter < limit);\n\t";
1479 buf += "} while (limit = ";
1480 SynthCountByEnumWithState(buf);
1481 buf += ");\n\t";
1482 buf += elementName;
Steve Naroffd1a36792008-12-17 14:24:39 +00001483 buf += " = ((id)0);\n\t";
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001484 buf += "__break_label_";
1485 buf += utostr(ObjCBcLabelNo.back());
1486 buf += ": ;\n\t";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001487 buf += "}\n\t";
1488 buf += "else\n\t\t";
1489 buf += elementName;
Steve Naroffd1a36792008-12-17 14:24:39 +00001490 buf += " = ((id)0);\n";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001491 buf += "}\n";
Mike Stump11289f42009-09-09 15:08:12 +00001492
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001493 // Insert all these *after* the statement body.
Sebastian Redla7b98a72009-04-26 20:35:05 +00001494 // FIXME: If this should support Obj-C++, support CXXTryStmt
Steve Narofff0ff8792008-07-21 18:26:02 +00001495 if (isa<CompoundStmt>(S->getBody())) {
1496 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(1);
1497 InsertText(endBodyLoc, buf.c_str(), buf.size());
1498 } else {
1499 /* Need to treat single statements specially. For example:
1500 *
1501 * for (A *a in b) if (stuff()) break;
1502 * for (A *a in b) xxxyy;
1503 *
1504 * The following code simply scans ahead to the semi to find the actual end.
1505 */
1506 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1507 const char *semiBuf = strchr(stmtBuf, ';');
1508 assert(semiBuf && "Can't find ';'");
1509 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(semiBuf-stmtBuf+1);
1510 InsertText(endBodyLoc, buf.c_str(), buf.size());
1511 }
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001512 Stmts.pop_back();
1513 ObjCBcLabelNo.pop_back();
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001514 return 0;
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001515}
1516
Mike Stump11289f42009-09-09 15:08:12 +00001517/// RewriteObjCSynchronizedStmt -
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001518/// This routine rewrites @synchronized(expr) stmt;
1519/// into:
1520/// objc_sync_enter(expr);
1521/// @try stmt @finally { objc_sync_exit(expr); }
1522///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001523Stmt *RewriteObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001524 // Get the start location and compute the semi location.
1525 SourceLocation startLoc = S->getLocStart();
1526 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001527
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001528 assert((*startBuf == '@') && "bogus @synchronized location");
Mike Stump11289f42009-09-09 15:08:12 +00001529
1530 std::string buf;
Steve Naroffb2fc0522008-08-21 13:03:03 +00001531 buf = "objc_sync_enter((id)";
1532 const char *lparenBuf = startBuf;
1533 while (*lparenBuf != '(') lparenBuf++;
1534 ReplaceText(startLoc, lparenBuf-startBuf+1, buf.c_str(), buf.size());
Mike Stump11289f42009-09-09 15:08:12 +00001535 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1536 // the sync expression is typically a message expression that's already
Steve Naroffad7013b2008-08-19 13:04:19 +00001537 // been rewritten! (which implies the SourceLocation's are invalid).
1538 SourceLocation endLoc = S->getSynchBody()->getLocStart();
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001539 const char *endBuf = SM->getCharacterData(endLoc);
Steve Naroffad7013b2008-08-19 13:04:19 +00001540 while (*endBuf != ')') endBuf--;
1541 SourceLocation rparenLoc = startLoc.getFileLocWithOffset(endBuf-startBuf);
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001542 buf = ");\n";
1543 // declare a new scope with two variables, _stack and _rethrow.
1544 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1545 buf += "int buf[18/*32-bit i386*/];\n";
1546 buf += "char *pointers[4];} _stack;\n";
1547 buf += "id volatile _rethrow = 0;\n";
1548 buf += "objc_exception_try_enter(&_stack);\n";
1549 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Chris Lattner9cc55f52008-01-31 19:51:04 +00001550 ReplaceText(rparenLoc, 1, buf.c_str(), buf.size());
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001551 startLoc = S->getSynchBody()->getLocEnd();
1552 startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001553
Steve Naroffad7013b2008-08-19 13:04:19 +00001554 assert((*startBuf == '}') && "bogus @synchronized block");
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001555 SourceLocation lastCurlyLoc = startLoc;
1556 buf = "}\nelse {\n";
1557 buf += " _rethrow = objc_exception_extract(&_stack);\n";
Steve Naroffd9803712009-04-29 16:37:50 +00001558 buf += "}\n";
1559 buf += "{ /* implicit finally clause */\n";
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001560 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Steve Naroffec60b432009-12-05 21:43:12 +00001561
1562 std::string syncBuf;
1563 syncBuf += " objc_sync_exit(";
Mike Stump11289f42009-09-09 15:08:12 +00001564 Expr *syncExpr = new (Context) CStyleCastExpr(Context->getObjCIdType(),
Anders Carlssona2615922009-07-31 00:48:10 +00001565 CastExpr::CK_Unknown,
Mike Stump11289f42009-09-09 15:08:12 +00001566 S->getSynchExpr(),
Ted Kremenek5a201952009-02-07 01:47:29 +00001567 Context->getObjCIdType(),
1568 SourceLocation(),
1569 SourceLocation());
Ted Kremenek2d470fc2008-09-13 05:16:45 +00001570 std::string syncExprBufS;
1571 llvm::raw_string_ostream syncExprBuf(syncExprBufS);
Chris Lattnerc61089a2009-06-30 01:26:17 +00001572 syncExpr->printPretty(syncExprBuf, *Context, 0,
1573 PrintingPolicy(LangOpts));
Steve Naroffec60b432009-12-05 21:43:12 +00001574 syncBuf += syncExprBuf.str();
1575 syncBuf += ");";
1576
1577 buf += syncBuf;
1578 buf += "\n if (_rethrow) objc_exception_throw(_rethrow);\n";
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001579 buf += "}\n";
1580 buf += "}";
Mike Stump11289f42009-09-09 15:08:12 +00001581
Chris Lattner9cc55f52008-01-31 19:51:04 +00001582 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Steve Naroffec60b432009-12-05 21:43:12 +00001583
1584 bool hasReturns = false;
1585 HasReturnStmts(S->getSynchBody(), hasReturns);
1586 if (hasReturns)
1587 RewriteSyncReturnStmts(S->getSynchBody(), syncBuf);
1588
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001589 return 0;
1590}
1591
Steve Naroffec60b432009-12-05 21:43:12 +00001592void RewriteObjC::WarnAboutReturnGotoStmts(Stmt *S)
1593{
Steve Naroff6d6da252008-12-05 17:03:39 +00001594 // Perform a bottom up traversal of all children.
1595 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1596 CI != E; ++CI)
1597 if (*CI)
Steve Naroffec60b432009-12-05 21:43:12 +00001598 WarnAboutReturnGotoStmts(*CI);
Steve Naroff6d6da252008-12-05 17:03:39 +00001599
Steve Naroffec60b432009-12-05 21:43:12 +00001600 if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
Mike Stump11289f42009-09-09 15:08:12 +00001601 Diags.Report(Context->getFullLoc(S->getLocStart()),
Steve Naroff6d6da252008-12-05 17:03:39 +00001602 TryFinallyContainsReturnDiag);
1603 }
1604 return;
1605}
1606
Steve Naroffec60b432009-12-05 21:43:12 +00001607void RewriteObjC::HasReturnStmts(Stmt *S, bool &hasReturns)
1608{
1609 // Perform a bottom up traversal of all children.
1610 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1611 CI != E; ++CI)
1612 if (*CI)
1613 HasReturnStmts(*CI, hasReturns);
1614
1615 if (isa<ReturnStmt>(S))
1616 hasReturns = true;
1617 return;
1618}
1619
1620void RewriteObjC::RewriteTryReturnStmts(Stmt *S) {
1621 // Perform a bottom up traversal of all children.
1622 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1623 CI != E; ++CI)
1624 if (*CI) {
1625 RewriteTryReturnStmts(*CI);
1626 }
1627 if (isa<ReturnStmt>(S)) {
1628 SourceLocation startLoc = S->getLocStart();
1629 const char *startBuf = SM->getCharacterData(startLoc);
1630
1631 const char *semiBuf = strchr(startBuf, ';');
1632 assert((*semiBuf == ';') && "RewriteTryReturnStmts: can't find ';'");
1633 SourceLocation onePastSemiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
1634
1635 std::string buf;
1636 buf = "{ objc_exception_try_exit(&_stack); return";
1637
1638 ReplaceText(startLoc, 6, buf.c_str(), buf.size());
1639 InsertText(onePastSemiLoc, "}", 1);
1640 }
1641 return;
1642}
1643
1644void RewriteObjC::RewriteSyncReturnStmts(Stmt *S, std::string syncExitBuf) {
1645 // Perform a bottom up traversal of all children.
1646 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1647 CI != E; ++CI)
1648 if (*CI) {
1649 RewriteSyncReturnStmts(*CI, syncExitBuf);
1650 }
1651 if (isa<ReturnStmt>(S)) {
1652 SourceLocation startLoc = S->getLocStart();
1653 const char *startBuf = SM->getCharacterData(startLoc);
1654
1655 const char *semiBuf = strchr(startBuf, ';');
1656 assert((*semiBuf == ';') && "RewriteSyncReturnStmts: can't find ';'");
1657 SourceLocation onePastSemiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
1658
1659 std::string buf;
1660 buf = "{ objc_exception_try_exit(&_stack);";
1661 buf += syncExitBuf;
1662 buf += " return";
1663
1664 ReplaceText(startLoc, 6, buf.c_str(), buf.size());
1665 InsertText(onePastSemiLoc, "}", 1);
1666 }
1667 return;
1668}
1669
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001670Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Steve Naroffbf478ec2007-11-07 04:08:17 +00001671 // Get the start location and compute the semi location.
1672 SourceLocation startLoc = S->getLocStart();
1673 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001674
Steve Naroffbf478ec2007-11-07 04:08:17 +00001675 assert((*startBuf == '@') && "bogus @try location");
1676
1677 std::string buf;
1678 // declare a new scope with two variables, _stack and _rethrow.
1679 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1680 buf += "int buf[18/*32-bit i386*/];\n";
1681 buf += "char *pointers[4];} _stack;\n";
1682 buf += "id volatile _rethrow = 0;\n";
1683 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroff16018582007-11-07 18:43:40 +00001684 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroffbf478ec2007-11-07 04:08:17 +00001685
Chris Lattner9cc55f52008-01-31 19:51:04 +00001686 ReplaceText(startLoc, 4, buf.c_str(), buf.size());
Mike Stump11289f42009-09-09 15:08:12 +00001687
Steve Naroffbf478ec2007-11-07 04:08:17 +00001688 startLoc = S->getTryBody()->getLocEnd();
1689 startBuf = SM->getCharacterData(startLoc);
1690
1691 assert((*startBuf == '}') && "bogus @try block");
Mike Stump11289f42009-09-09 15:08:12 +00001692
Steve Naroffbf478ec2007-11-07 04:08:17 +00001693 SourceLocation lastCurlyLoc = startLoc;
Steve Naroffce2dca12008-07-16 15:31:30 +00001694 ObjCAtCatchStmt *catchList = S->getCatchStmts();
1695 if (catchList) {
1696 startLoc = startLoc.getFileLocWithOffset(1);
1697 buf = " /* @catch begin */ else {\n";
1698 buf += " id _caught = objc_exception_extract(&_stack);\n";
1699 buf += " objc_exception_try_enter (&_stack);\n";
1700 buf += " if (_setjmp(_stack.buf))\n";
1701 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1702 buf += " else { /* @catch continue */";
Mike Stump11289f42009-09-09 15:08:12 +00001703
Steve Naroffce2dca12008-07-16 15:31:30 +00001704 InsertText(startLoc, buf.c_str(), buf.size());
Steve Narofffac18fe2008-09-09 19:59:12 +00001705 } else { /* no catch list */
1706 buf = "}\nelse {\n";
1707 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1708 buf += "}";
1709 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Steve Naroffce2dca12008-07-16 15:31:30 +00001710 }
Steve Naroffbf478ec2007-11-07 04:08:17 +00001711 bool sawIdTypedCatch = false;
1712 Stmt *lastCatchBody = 0;
Steve Naroffbf478ec2007-11-07 04:08:17 +00001713 while (catchList) {
Steve Naroff371b8fb2009-03-03 19:52:17 +00001714 ParmVarDecl *catchDecl = catchList->getCatchParamDecl();
Steve Naroffbf478ec2007-11-07 04:08:17 +00001715
Mike Stump11289f42009-09-09 15:08:12 +00001716 if (catchList == S->getCatchStmts())
Steve Naroffbf478ec2007-11-07 04:08:17 +00001717 buf = "if ("; // we are generating code for the first catch clause
1718 else
1719 buf = "else if (";
1720 startLoc = catchList->getLocStart();
1721 startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001722
Steve Naroffbf478ec2007-11-07 04:08:17 +00001723 assert((*startBuf == '@') && "bogus @catch location");
Mike Stump11289f42009-09-09 15:08:12 +00001724
Steve Naroffbf478ec2007-11-07 04:08:17 +00001725 const char *lParenLoc = strchr(startBuf, '(');
1726
Steve Naroffe6b7ffd2008-02-01 22:08:12 +00001727 if (catchList->hasEllipsis()) {
Steve Naroffedb5bc62008-02-01 20:02:07 +00001728 // Now rewrite the body...
1729 lastCatchBody = catchList->getCatchBody();
Steve Naroffedb5bc62008-02-01 20:02:07 +00001730 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1731 const char *bodyBuf = SM->getCharacterData(bodyLoc);
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001732 assert(*SM->getCharacterData(catchList->getRParenLoc()) == ')' &&
1733 "bogus @catch paren location");
Steve Naroffedb5bc62008-02-01 20:02:07 +00001734 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump11289f42009-09-09 15:08:12 +00001735
Steve Naroffedb5bc62008-02-01 20:02:07 +00001736 buf += "1) { id _tmp = _caught;";
Daniel Dunbardec484a2009-08-19 19:10:30 +00001737 Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1, buf);
Steve Naroff371b8fb2009-03-03 19:52:17 +00001738 } else if (catchDecl) {
1739 QualType t = catchDecl->getType();
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001740 if (t == Context->getObjCIdType()) {
Steve Naroffbf478ec2007-11-07 04:08:17 +00001741 buf += "1) { ";
Chris Lattner9cc55f52008-01-31 19:51:04 +00001742 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroffbf478ec2007-11-07 04:08:17 +00001743 sawIdTypedCatch = true;
Mike Stump11289f42009-09-09 15:08:12 +00001744 } else if (const PointerType *pType = t->getAs<PointerType>()) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001745 ObjCInterfaceType *cls; // Should be a pointer to a class.
Mike Stump11289f42009-09-09 15:08:12 +00001746
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001747 cls = dyn_cast<ObjCInterfaceType>(pType->getPointeeType().getTypePtr());
Steve Naroffbf478ec2007-11-07 04:08:17 +00001748 if (cls) {
Steve Naroff16018582007-11-07 18:43:40 +00001749 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001750 buf += cls->getDecl()->getNameAsString();
Steve Naroff16018582007-11-07 18:43:40 +00001751 buf += "\"), (struct objc_object *)_caught)) { ";
Chris Lattner9cc55f52008-01-31 19:51:04 +00001752 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroffbf478ec2007-11-07 04:08:17 +00001753 }
1754 }
1755 // Now rewrite the body...
1756 lastCatchBody = catchList->getCatchBody();
1757 SourceLocation rParenLoc = catchList->getRParenLoc();
1758 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1759 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1760 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1761 assert((*rParenBuf == ')') && "bogus @catch paren location");
1762 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump11289f42009-09-09 15:08:12 +00001763
Steve Naroffbf478ec2007-11-07 04:08:17 +00001764 buf = " = _caught;";
Mike Stump11289f42009-09-09 15:08:12 +00001765 // Here we replace ") {" with "= _caught;" (which initializes and
Steve Naroffbf478ec2007-11-07 04:08:17 +00001766 // declares the @catch parameter).
Chris Lattner9cc55f52008-01-31 19:51:04 +00001767 ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, buf.c_str(), buf.size());
Steve Naroff371b8fb2009-03-03 19:52:17 +00001768 } else {
Steve Naroffbf478ec2007-11-07 04:08:17 +00001769 assert(false && "@catch rewrite bug");
Steve Naroffa733c7f2007-11-07 15:32:26 +00001770 }
Steve Naroffedb5bc62008-02-01 20:02:07 +00001771 // make sure all the catch bodies get rewritten!
Steve Naroffbf478ec2007-11-07 04:08:17 +00001772 catchList = catchList->getNextCatchStmt();
1773 }
1774 // Complete the catch list...
1775 if (lastCatchBody) {
1776 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001777 assert(*SM->getCharacterData(bodyLoc) == '}' &&
1778 "bogus @catch body location");
Mike Stump11289f42009-09-09 15:08:12 +00001779
Steve Naroff4adbe312008-09-11 15:29:03 +00001780 // Insert the last (implicit) else clause *before* the right curly brace.
1781 bodyLoc = bodyLoc.getFileLocWithOffset(-1);
1782 buf = "} /* last catch end */\n";
1783 buf += "else {\n";
1784 buf += " _rethrow = _caught;\n";
1785 buf += " objc_exception_try_exit(&_stack);\n";
1786 buf += "} } /* @catch end */\n";
1787 if (!S->getFinallyStmt())
1788 buf += "}\n";
Chris Lattner1780a852008-01-31 19:42:41 +00001789 InsertText(bodyLoc, buf.c_str(), buf.size());
Mike Stump11289f42009-09-09 15:08:12 +00001790
Steve Naroffbf478ec2007-11-07 04:08:17 +00001791 // Set lastCurlyLoc
1792 lastCurlyLoc = lastCatchBody->getLocEnd();
1793 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001794 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
Steve Naroffbf478ec2007-11-07 04:08:17 +00001795 startLoc = finalStmt->getLocStart();
1796 startBuf = SM->getCharacterData(startLoc);
1797 assert((*startBuf == '@') && "bogus @finally start");
Mike Stump11289f42009-09-09 15:08:12 +00001798
Steve Naroffbf478ec2007-11-07 04:08:17 +00001799 buf = "/* @finally */";
Chris Lattner9cc55f52008-01-31 19:51:04 +00001800 ReplaceText(startLoc, 8, buf.c_str(), buf.size());
Mike Stump11289f42009-09-09 15:08:12 +00001801
Steve Naroffbf478ec2007-11-07 04:08:17 +00001802 Stmt *body = finalStmt->getFinallyBody();
1803 SourceLocation startLoc = body->getLocStart();
1804 SourceLocation endLoc = body->getLocEnd();
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001805 assert(*SM->getCharacterData(startLoc) == '{' &&
1806 "bogus @finally body location");
Mike Stump11289f42009-09-09 15:08:12 +00001807 assert(*SM->getCharacterData(endLoc) == '}' &&
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001808 "bogus @finally body location");
Mike Stump11289f42009-09-09 15:08:12 +00001809
Steve Naroffbf478ec2007-11-07 04:08:17 +00001810 startLoc = startLoc.getFileLocWithOffset(1);
1811 buf = " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Chris Lattner1780a852008-01-31 19:42:41 +00001812 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroffbf478ec2007-11-07 04:08:17 +00001813 endLoc = endLoc.getFileLocWithOffset(-1);
1814 buf = " if (_rethrow) objc_exception_throw(_rethrow);\n";
Chris Lattner1780a852008-01-31 19:42:41 +00001815 InsertText(endLoc, buf.c_str(), buf.size());
Mike Stump11289f42009-09-09 15:08:12 +00001816
Steve Naroffbf478ec2007-11-07 04:08:17 +00001817 // Set lastCurlyLoc
1818 lastCurlyLoc = body->getLocEnd();
Mike Stump11289f42009-09-09 15:08:12 +00001819
Steve Naroff6d6da252008-12-05 17:03:39 +00001820 // Now check for any return/continue/go statements within the @try.
Steve Naroffec60b432009-12-05 21:43:12 +00001821 WarnAboutReturnGotoStmts(S->getTryBody());
Steve Naroff4adbe312008-09-11 15:29:03 +00001822 } else { /* no finally clause - make sure we synthesize an implicit one */
1823 buf = "{ /* implicit finally clause */\n";
1824 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
1825 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1826 buf += "}";
1827 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Steve Naroffec60b432009-12-05 21:43:12 +00001828
1829 // Now check for any return/continue/go statements within the @try.
1830 // The implicit finally clause won't called if the @try contains any
1831 // jump statements.
1832 bool hasReturns = false;
1833 HasReturnStmts(S->getTryBody(), hasReturns);
1834 if (hasReturns)
1835 RewriteTryReturnStmts(S->getTryBody());
Steve Naroffbf478ec2007-11-07 04:08:17 +00001836 }
1837 // Now emit the final closing curly brace...
1838 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
1839 buf = " } /* @try scope end */\n";
Chris Lattner1780a852008-01-31 19:42:41 +00001840 InsertText(lastCurlyLoc, buf.c_str(), buf.size());
Fariborz Jahanian63ac80e2007-11-05 17:47:33 +00001841 return 0;
1842}
1843
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001844Stmt *RewriteObjC::RewriteObjCCatchStmt(ObjCAtCatchStmt *S) {
Fariborz Jahanian63ac80e2007-11-05 17:47:33 +00001845 return 0;
1846}
1847
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001848Stmt *RewriteObjC::RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S) {
Fariborz Jahanian63ac80e2007-11-05 17:47:33 +00001849 return 0;
1850}
1851
Mike Stump11289f42009-09-09 15:08:12 +00001852// This can't be done with ReplaceStmt(S, ThrowExpr), since
1853// the throw expression is typically a message expression that's already
Steve Naroffa733c7f2007-11-07 15:32:26 +00001854// been rewritten! (which implies the SourceLocation's are invalid).
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001855Stmt *RewriteObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
Steve Naroffa733c7f2007-11-07 15:32:26 +00001856 // Get the start location and compute the semi location.
1857 SourceLocation startLoc = S->getLocStart();
1858 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001859
Steve Naroffa733c7f2007-11-07 15:32:26 +00001860 assert((*startBuf == '@') && "bogus @throw location");
1861
1862 std::string buf;
1863 /* void objc_exception_throw(id) __attribute__((noreturn)); */
Steve Naroffc7d2df22008-01-19 00:42:38 +00001864 if (S->getThrowExpr())
1865 buf = "objc_exception_throw(";
1866 else // add an implicit argument
1867 buf = "objc_exception_throw(_caught";
Mike Stump11289f42009-09-09 15:08:12 +00001868
Steve Naroff29788342008-07-25 15:41:30 +00001869 // handle "@ throw" correctly.
1870 const char *wBuf = strchr(startBuf, 'w');
1871 assert((*wBuf == 'w') && "@throw: can't find 'w'");
1872 ReplaceText(startLoc, wBuf-startBuf+1, buf.c_str(), buf.size());
Mike Stump11289f42009-09-09 15:08:12 +00001873
Steve Naroffa733c7f2007-11-07 15:32:26 +00001874 const char *semiBuf = strchr(startBuf, ';');
1875 assert((*semiBuf == ';') && "@throw: can't find ';'");
1876 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
1877 buf = ");";
Chris Lattner9cc55f52008-01-31 19:51:04 +00001878 ReplaceText(semiLoc, 1, buf.c_str(), buf.size());
Steve Naroffa733c7f2007-11-07 15:32:26 +00001879 return 0;
1880}
Fariborz Jahanian63ac80e2007-11-05 17:47:33 +00001881
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001882Stmt *RewriteObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattnerc6d91c02007-10-17 22:35:30 +00001883 // Create a new string expression.
1884 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlssond8499822007-10-29 05:01:08 +00001885 std::string StrEncoding;
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00001886 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
Chris Lattnerf83b5af2009-02-18 06:40:38 +00001887 Expr *Replacement = StringLiteral::Create(*Context,StrEncoding.c_str(),
1888 StrEncoding.length(), false,StrType,
1889 SourceLocation());
Chris Lattner2e0d2602008-01-31 19:37:57 +00001890 ReplaceStmt(Exp, Replacement);
Mike Stump11289f42009-09-09 15:08:12 +00001891
Chris Lattner4431a1b2007-11-30 22:53:43 +00001892 // Replace this subexpr in the parent.
Steve Naroff22216db2008-12-04 23:50:32 +00001893 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Chris Lattner69534692007-10-24 16:57:36 +00001894 return Replacement;
Chris Lattnera7c19fe2007-10-16 22:36:42 +00001895}
1896
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001897Stmt *RewriteObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
Steve Naroff2654e182008-12-22 22:16:07 +00001898 if (!SelGetUidFunctionDecl)
1899 SynthSelGetUidFunctionDecl();
Steve Naroffe4f9b232007-11-05 14:50:49 +00001900 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
1901 // Create a call to sel_registerName("selName").
1902 llvm::SmallVector<Expr*, 8> SelExprs;
1903 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump11289f42009-09-09 15:08:12 +00001904 SelExprs.push_back(StringLiteral::Create(*Context,
Ted Kremenek6b7ecf62009-02-06 19:55:15 +00001905 Exp->getSelector().getAsString().c_str(),
Chris Lattnere4b95692008-11-24 03:33:13 +00001906 Exp->getSelector().getAsString().size(),
Chris Lattner630970d2009-02-18 05:49:11 +00001907 false, argType, SourceLocation()));
Steve Naroffe4f9b232007-11-05 14:50:49 +00001908 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1909 &SelExprs[0], SelExprs.size());
Chris Lattner2e0d2602008-01-31 19:37:57 +00001910 ReplaceStmt(Exp, SelExp);
Steve Naroff22216db2008-12-04 23:50:32 +00001911 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroffe4f9b232007-11-05 14:50:49 +00001912 return SelExp;
1913}
1914
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001915CallExpr *RewriteObjC::SynthesizeCallToFunctionDecl(
Steve Naroff574440f2007-10-24 22:48:43 +00001916 FunctionDecl *FD, Expr **args, unsigned nargs) {
Steve Naroffdb1ab1c2007-10-23 23:50:29 +00001917 // Get the type, we will need to reference it in a couple spots.
Steve Naroff574440f2007-10-24 22:48:43 +00001918 QualType msgSendType = FD->getType();
Mike Stump11289f42009-09-09 15:08:12 +00001919
Steve Naroffdb1ab1c2007-10-23 23:50:29 +00001920 // Create a reference to the objc_msgSend() declaration.
Ted Kremenek5a201952009-02-07 01:47:29 +00001921 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, msgSendType, SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00001922
Steve Naroffdb1ab1c2007-10-23 23:50:29 +00001923 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattner3c799d72007-10-24 17:06:59 +00001924 QualType pToFunc = Context->getPointerType(msgSendType);
Mike Stump11289f42009-09-09 15:08:12 +00001925 ImplicitCastExpr *ICE = new (Context) ImplicitCastExpr(pToFunc,
Anders Carlssona2615922009-07-31 00:48:10 +00001926 CastExpr::CK_Unknown,
Mike Stump11289f42009-09-09 15:08:12 +00001927 DRE,
Douglas Gregora11693b2008-11-12 17:17:38 +00001928 /*isLvalue=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00001929
John McCall9dd450b2009-09-21 23:43:11 +00001930 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Mike Stump11289f42009-09-09 15:08:12 +00001931
Ted Kremenekd7b4f402009-02-09 20:51:47 +00001932 return new (Context) CallExpr(*Context, ICE, args, nargs, FT->getResultType(),
1933 SourceLocation());
Steve Naroff574440f2007-10-24 22:48:43 +00001934}
1935
Steve Naroff50d42052007-11-01 13:24:47 +00001936static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
1937 const char *&startRef, const char *&endRef) {
1938 while (startBuf < endBuf) {
1939 if (*startBuf == '<')
1940 startRef = startBuf; // mark the start.
1941 if (*startBuf == '>') {
Steve Naroff1b232132007-11-09 12:50:28 +00001942 if (startRef && *startRef == '<') {
1943 endRef = startBuf; // mark the end.
1944 return true;
1945 }
1946 return false;
Steve Naroff50d42052007-11-01 13:24:47 +00001947 }
1948 startBuf++;
1949 }
1950 return false;
1951}
1952
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00001953static void scanToNextArgument(const char *&argRef) {
1954 int angle = 0;
1955 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
1956 if (*argRef == '<')
1957 angle++;
1958 else if (*argRef == '>')
1959 angle--;
1960 argRef++;
1961 }
1962 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
1963}
Fariborz Jahanian16e703a2007-12-11 23:04:08 +00001964
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001965bool RewriteObjC::needToScanForQualifiers(QualType T) {
Steve Naroffc277ad12009-07-18 15:33:26 +00001966 return T->isObjCQualifiedIdType() || T->isObjCQualifiedInterfaceType();
Steve Naroff50d42052007-11-01 13:24:47 +00001967}
1968
Steve Naroff873bd842008-07-29 18:15:38 +00001969void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
1970 QualType Type = E->getType();
1971 if (needToScanForQualifiers(Type)) {
Steve Naroffdbfc6932008-11-19 21:15:47 +00001972 SourceLocation Loc, EndLoc;
Mike Stump11289f42009-09-09 15:08:12 +00001973
Steve Naroffdbfc6932008-11-19 21:15:47 +00001974 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
1975 Loc = ECE->getLParenLoc();
1976 EndLoc = ECE->getRParenLoc();
1977 } else {
1978 Loc = E->getLocStart();
1979 EndLoc = E->getLocEnd();
1980 }
1981 // This will defend against trying to rewrite synthesized expressions.
1982 if (Loc.isInvalid() || EndLoc.isInvalid())
1983 return;
1984
Steve Naroff873bd842008-07-29 18:15:38 +00001985 const char *startBuf = SM->getCharacterData(Loc);
Steve Naroffdbfc6932008-11-19 21:15:47 +00001986 const char *endBuf = SM->getCharacterData(EndLoc);
Steve Naroff873bd842008-07-29 18:15:38 +00001987 const char *startRef = 0, *endRef = 0;
1988 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1989 // Get the locations of the startRef, endRef.
1990 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-startBuf);
1991 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-startBuf+1);
1992 // Comment out the protocol references.
1993 InsertText(LessLoc, "/*", 2);
1994 InsertText(GreaterLoc, "*/", 2);
1995 }
1996 }
1997}
1998
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001999void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002000 SourceLocation Loc;
2001 QualType Type;
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002002 const FunctionProtoType *proto = 0;
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002003 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
2004 Loc = VD->getLocation();
2005 Type = VD->getType();
2006 }
2007 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
2008 Loc = FD->getLocation();
2009 // Check for ObjC 'id' and class types that have been adorned with protocol
2010 // information (id<p>, C<p>*). The protocol references need to be rewritten!
John McCall9dd450b2009-09-21 23:43:11 +00002011 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002012 assert(funcType && "missing function type");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002013 proto = dyn_cast<FunctionProtoType>(funcType);
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002014 if (!proto)
2015 return;
2016 Type = proto->getResultType();
2017 }
Steve Naroffe70a52a2009-12-05 15:55:59 +00002018 else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
2019 Loc = FD->getLocation();
2020 Type = FD->getType();
2021 }
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002022 else
2023 return;
Mike Stump11289f42009-09-09 15:08:12 +00002024
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002025 if (needToScanForQualifiers(Type)) {
Steve Naroff50d42052007-11-01 13:24:47 +00002026 // Since types are unique, we need to scan the buffer.
Mike Stump11289f42009-09-09 15:08:12 +00002027
Steve Naroff50d42052007-11-01 13:24:47 +00002028 const char *endBuf = SM->getCharacterData(Loc);
2029 const char *startBuf = endBuf;
Steve Naroff930e0992008-05-31 05:02:17 +00002030 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
Steve Naroff50d42052007-11-01 13:24:47 +00002031 startBuf--; // scan backward (from the decl location) for return type.
2032 const char *startRef = 0, *endRef = 0;
2033 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2034 // Get the locations of the startRef, endRef.
2035 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
2036 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
2037 // Comment out the protocol references.
Chris Lattner1780a852008-01-31 19:42:41 +00002038 InsertText(LessLoc, "/*", 2);
2039 InsertText(GreaterLoc, "*/", 2);
Steve Naroff37e011c2007-10-31 04:38:33 +00002040 }
2041 }
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002042 if (!proto)
2043 return; // most likely, was a variable
Steve Naroff50d42052007-11-01 13:24:47 +00002044 // Now check arguments.
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002045 const char *startBuf = SM->getCharacterData(Loc);
2046 const char *startFuncBuf = startBuf;
Steve Naroff50d42052007-11-01 13:24:47 +00002047 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
2048 if (needToScanForQualifiers(proto->getArgType(i))) {
2049 // Since types are unique, we need to scan the buffer.
Mike Stump11289f42009-09-09 15:08:12 +00002050
Steve Naroff50d42052007-11-01 13:24:47 +00002051 const char *endBuf = startBuf;
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002052 // scan forward (from the decl location) for argument types.
2053 scanToNextArgument(endBuf);
Steve Naroff50d42052007-11-01 13:24:47 +00002054 const char *startRef = 0, *endRef = 0;
2055 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2056 // Get the locations of the startRef, endRef.
Mike Stump11289f42009-09-09 15:08:12 +00002057 SourceLocation LessLoc =
Fariborz Jahanian16e703a2007-12-11 23:04:08 +00002058 Loc.getFileLocWithOffset(startRef-startFuncBuf);
Mike Stump11289f42009-09-09 15:08:12 +00002059 SourceLocation GreaterLoc =
Fariborz Jahanian16e703a2007-12-11 23:04:08 +00002060 Loc.getFileLocWithOffset(endRef-startFuncBuf+1);
Steve Naroff50d42052007-11-01 13:24:47 +00002061 // Comment out the protocol references.
Chris Lattner1780a852008-01-31 19:42:41 +00002062 InsertText(LessLoc, "/*", 2);
2063 InsertText(GreaterLoc, "*/", 2);
Steve Naroff50d42052007-11-01 13:24:47 +00002064 }
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002065 startBuf = ++endBuf;
2066 }
2067 else {
Steve Naroffc884aa82008-08-06 15:58:23 +00002068 // If the function name is derived from a macro expansion, then the
2069 // argument buffer will not follow the name. Need to speak with Chris.
2070 while (*startBuf && *startBuf != ')' && *startBuf != ',')
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002071 startBuf++; // scan forward (from the decl location) for argument types.
2072 startBuf++;
2073 }
Steve Naroff50d42052007-11-01 13:24:47 +00002074 }
Steve Naroff37e011c2007-10-31 04:38:33 +00002075}
2076
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002077// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002078void RewriteObjC::SynthSelGetUidFunctionDecl() {
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002079 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
2080 llvm::SmallVector<QualType, 16> ArgTys;
John McCall8ccfcb52009-09-24 19:53:00 +00002081 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002082 QualType getFuncType = Context->getFunctionType(Context->getObjCSelType(),
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002083 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002084 false /*isVariadic*/, 0);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002085 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002086 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002087 SelGetUidIdent, getFuncType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002088 FunctionDecl::Extern, false);
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002089}
2090
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002091void RewriteObjC::RewriteFunctionDecl(FunctionDecl *FD) {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002092 // declared in <objc/objc.h>
Douglas Gregor1e21c192009-01-09 01:47:02 +00002093 if (FD->getIdentifier() &&
2094 strcmp(FD->getNameAsCString(), "sel_registerName") == 0) {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002095 SelGetUidFunctionDecl = FD;
Steve Naroff37e011c2007-10-31 04:38:33 +00002096 return;
2097 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002098 RewriteObjCQualifiedInterfaceTypes(FD);
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002099}
2100
Steve Naroff17978c42008-03-11 17:37:02 +00002101// SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002102void RewriteObjC::SynthSuperContructorFunctionDecl() {
Steve Naroff17978c42008-03-11 17:37:02 +00002103 if (SuperContructorFunctionDecl)
2104 return;
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002105 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
Steve Naroff17978c42008-03-11 17:37:02 +00002106 llvm::SmallVector<QualType, 16> ArgTys;
2107 QualType argT = Context->getObjCIdType();
2108 assert(!argT.isNull() && "Can't find 'id' type");
2109 ArgTys.push_back(argT);
2110 ArgTys.push_back(argT);
2111 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
2112 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002113 false, 0);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002114 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002115 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002116 msgSendIdent, msgSendType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002117 FunctionDecl::Extern, false);
Steve Naroff17978c42008-03-11 17:37:02 +00002118}
2119
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002120// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002121void RewriteObjC::SynthMsgSendFunctionDecl() {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002122 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
2123 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002124 QualType argT = Context->getObjCIdType();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002125 assert(!argT.isNull() && "Can't find 'id' type");
2126 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002127 argT = Context->getObjCSelType();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002128 assert(!argT.isNull() && "Can't find 'SEL' type");
2129 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002130 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002131 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002132 true /*isVariadic*/, 0);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002133 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnerc5ffed42008-04-04 06:12:32 +00002134 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002135 msgSendIdent, msgSendType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002136 FunctionDecl::Extern, false);
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002137}
2138
Steve Naroff7fa2f042007-11-15 10:28:18 +00002139// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002140void RewriteObjC::SynthMsgSendSuperFunctionDecl() {
Steve Naroff7fa2f042007-11-15 10:28:18 +00002141 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
2142 llvm::SmallVector<QualType, 16> ArgTys;
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00002143 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattnerc5ffed42008-04-04 06:12:32 +00002144 SourceLocation(),
Ted Kremenek47923c72008-09-05 01:34:33 +00002145 &Context->Idents.get("objc_super"));
Steve Naroff7fa2f042007-11-15 10:28:18 +00002146 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2147 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2148 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002149 argT = Context->getObjCSelType();
Steve Naroff7fa2f042007-11-15 10:28:18 +00002150 assert(!argT.isNull() && "Can't find 'SEL' type");
2151 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002152 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff7fa2f042007-11-15 10:28:18 +00002153 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002154 true /*isVariadic*/, 0);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002155 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002156 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002157 msgSendIdent, msgSendType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002158 FunctionDecl::Extern, false);
Steve Naroff7fa2f042007-11-15 10:28:18 +00002159}
2160
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002161// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002162void RewriteObjC::SynthMsgSendStretFunctionDecl() {
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002163 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
2164 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002165 QualType argT = Context->getObjCIdType();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002166 assert(!argT.isNull() && "Can't find 'id' type");
2167 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002168 argT = Context->getObjCSelType();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002169 assert(!argT.isNull() && "Can't find 'SEL' type");
2170 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002171 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002172 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002173 true /*isVariadic*/, 0);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002174 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002175 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002176 msgSendIdent, msgSendType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002177 FunctionDecl::Extern, false);
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002178}
2179
Mike Stump11289f42009-09-09 15:08:12 +00002180// SynthMsgSendSuperStretFunctionDecl -
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002181// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002182void RewriteObjC::SynthMsgSendSuperStretFunctionDecl() {
Mike Stump11289f42009-09-09 15:08:12 +00002183 IdentifierInfo *msgSendIdent =
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002184 &Context->Idents.get("objc_msgSendSuper_stret");
2185 llvm::SmallVector<QualType, 16> ArgTys;
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00002186 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattnerc5ffed42008-04-04 06:12:32 +00002187 SourceLocation(),
Ted Kremenek47923c72008-09-05 01:34:33 +00002188 &Context->Idents.get("objc_super"));
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002189 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2190 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2191 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002192 argT = Context->getObjCSelType();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002193 assert(!argT.isNull() && "Can't find 'SEL' type");
2194 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002195 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002196 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002197 true /*isVariadic*/, 0);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002198 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002199 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002200 msgSendIdent, msgSendType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002201 FunctionDecl::Extern, false);
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002202}
2203
Steve Naroff2e4e3852008-05-08 22:02:18 +00002204// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002205void RewriteObjC::SynthMsgSendFpretFunctionDecl() {
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002206 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
2207 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002208 QualType argT = Context->getObjCIdType();
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002209 assert(!argT.isNull() && "Can't find 'id' type");
2210 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002211 argT = Context->getObjCSelType();
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002212 assert(!argT.isNull() && "Can't find 'SEL' type");
2213 ArgTys.push_back(argT);
Steve Naroff2e4e3852008-05-08 22:02:18 +00002214 QualType msgSendType = Context->getFunctionType(Context->DoubleTy,
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002215 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002216 true /*isVariadic*/, 0);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002217 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002218 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002219 msgSendIdent, msgSendType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002220 FunctionDecl::Extern, false);
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002221}
2222
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002223// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002224void RewriteObjC::SynthGetClassFunctionDecl() {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002225 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
2226 llvm::SmallVector<QualType, 16> ArgTys;
John McCall8ccfcb52009-09-24 19:53:00 +00002227 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002228 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002229 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002230 false /*isVariadic*/, 0);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002231 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002232 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002233 getClassIdent, getClassType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002234 FunctionDecl::Extern, false);
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002235}
2236
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002237// SynthGetMetaClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002238void RewriteObjC::SynthGetMetaClassFunctionDecl() {
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002239 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
2240 llvm::SmallVector<QualType, 16> ArgTys;
John McCall8ccfcb52009-09-24 19:53:00 +00002241 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002242 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002243 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002244 false /*isVariadic*/, 0);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002245 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002246 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002247 getClassIdent, getClassType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002248 FunctionDecl::Extern, false);
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002249}
2250
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002251Stmt *RewriteObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroffce8e8862008-03-15 00:55:56 +00002252 QualType strType = getConstantStringStructType();
2253
2254 std::string S = "__NSConstantStringImpl_";
Steve Naroffa6141f02008-05-31 03:35:42 +00002255
2256 std::string tmpName = InFileName;
2257 unsigned i;
2258 for (i=0; i < tmpName.length(); i++) {
2259 char c = tmpName.at(i);
2260 // replace any non alphanumeric characters with '_'.
2261 if (!isalpha(c) && (c < '0' || c > '9'))
2262 tmpName[i] = '_';
2263 }
2264 S += tmpName;
2265 S += "_";
Steve Naroffce8e8862008-03-15 00:55:56 +00002266 S += utostr(NumObjCStringLiterals++);
2267
Steve Naroff00a31762008-03-27 22:29:16 +00002268 Preamble += "static __NSConstantStringImpl " + S;
2269 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2270 Preamble += "0x000007c8,"; // utf8_str
Steve Naroffce8e8862008-03-15 00:55:56 +00002271 // The pretty printer for StringLiteral handles escape characters properly.
Ted Kremenek2d470fc2008-09-13 05:16:45 +00002272 std::string prettyBufS;
2273 llvm::raw_string_ostream prettyBuf(prettyBufS);
Chris Lattnerc61089a2009-06-30 01:26:17 +00002274 Exp->getString()->printPretty(prettyBuf, *Context, 0,
2275 PrintingPolicy(LangOpts));
Steve Naroff00a31762008-03-27 22:29:16 +00002276 Preamble += prettyBuf.str();
2277 Preamble += ",";
Steve Naroff94ed6dc2009-12-06 01:48:44 +00002278 Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00002279
2280 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
2281 &Context->Idents.get(S.c_str()), strType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002282 VarDecl::Static);
Ted Kremenek5a201952009-02-07 01:47:29 +00002283 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, strType, SourceLocation());
2284 Expr *Unop = new (Context) UnaryOperator(DRE, UnaryOperator::AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00002285 Context->getPointerType(DRE->getType()),
Steve Naroffce8e8862008-03-15 00:55:56 +00002286 SourceLocation());
Steve Naroff265a6b92007-11-08 14:30:50 +00002287 // cast to NSConstantString *
Mike Stump11289f42009-09-09 15:08:12 +00002288 CastExpr *cast = new (Context) CStyleCastExpr(Exp->getType(),
Anders Carlssona2615922009-07-31 00:48:10 +00002289 CastExpr::CK_Unknown,
Mike Stump11289f42009-09-09 15:08:12 +00002290 Unop, Exp->getType(),
2291 SourceLocation(),
Anders Carlssona2615922009-07-31 00:48:10 +00002292 SourceLocation());
Chris Lattner2e0d2602008-01-31 19:37:57 +00002293 ReplaceStmt(Exp, cast);
Steve Naroff22216db2008-12-04 23:50:32 +00002294 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroff265a6b92007-11-08 14:30:50 +00002295 return cast;
Steve Naroffa397efd2007-11-03 11:27:19 +00002296}
2297
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002298ObjCInterfaceDecl *RewriteObjC::isSuperReceiver(Expr *recExpr) {
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002299 // check if we are sending a message to 'super'
Douglas Gregorffca3a22009-01-09 17:18:27 +00002300 if (!CurMethodDef || !CurMethodDef->isInstanceMethod()) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00002301
Douglas Gregor8ea1f532008-11-04 14:56:14 +00002302 if (ObjCSuperExpr *Super = dyn_cast<ObjCSuperExpr>(recExpr)) {
Mike Stump11289f42009-09-09 15:08:12 +00002303 const ObjCObjectPointerType *OPT =
John McCall9dd450b2009-09-21 23:43:11 +00002304 Super->getType()->getAs<ObjCObjectPointerType>();
Steve Naroff7cae42b2009-07-10 23:34:53 +00002305 assert(OPT);
2306 const ObjCInterfaceType *IT = OPT->getInterfaceType();
Chris Lattnera9b3cae2008-06-21 18:04:54 +00002307 return IT->getDecl();
2308 }
2309 return 0;
Steve Naroff7fa2f042007-11-15 10:28:18 +00002310}
2311
2312// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002313QualType RewriteObjC::getSuperStructType() {
Steve Naroff7fa2f042007-11-15 10:28:18 +00002314 if (!SuperStructDecl) {
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00002315 SuperStructDecl = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002316 SourceLocation(),
Ted Kremenek47923c72008-09-05 01:34:33 +00002317 &Context->Idents.get("objc_super"));
Steve Naroff7fa2f042007-11-15 10:28:18 +00002318 QualType FieldTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00002319
Steve Naroff7fa2f042007-11-15 10:28:18 +00002320 // struct objc_object *receiver;
Mike Stump11289f42009-09-09 15:08:12 +00002321 FieldTypes[0] = Context->getObjCIdType();
Steve Naroff7fa2f042007-11-15 10:28:18 +00002322 // struct objc_class *super;
Mike Stump11289f42009-09-09 15:08:12 +00002323 FieldTypes[1] = Context->getObjCClassType();
Douglas Gregor91f84212008-12-11 16:49:14 +00002324
Steve Naroff7fa2f042007-11-15 10:28:18 +00002325 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00002326 for (unsigned i = 0; i < 2; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00002327 SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
2328 SourceLocation(), 0,
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002329 FieldTypes[i], 0,
2330 /*BitWidth=*/0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002331 /*Mutable=*/false));
Douglas Gregor91f84212008-12-11 16:49:14 +00002332 }
Mike Stump11289f42009-09-09 15:08:12 +00002333
Douglas Gregor91f84212008-12-11 16:49:14 +00002334 SuperStructDecl->completeDefinition(*Context);
Steve Naroff7fa2f042007-11-15 10:28:18 +00002335 }
2336 return Context->getTagDeclType(SuperStructDecl);
2337}
2338
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002339QualType RewriteObjC::getConstantStringStructType() {
Steve Naroffce8e8862008-03-15 00:55:56 +00002340 if (!ConstantStringDecl) {
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00002341 ConstantStringDecl = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002342 SourceLocation(),
Ted Kremenek47923c72008-09-05 01:34:33 +00002343 &Context->Idents.get("__NSConstantStringImpl"));
Steve Naroffce8e8862008-03-15 00:55:56 +00002344 QualType FieldTypes[4];
Mike Stump11289f42009-09-09 15:08:12 +00002345
Steve Naroffce8e8862008-03-15 00:55:56 +00002346 // struct objc_object *receiver;
Mike Stump11289f42009-09-09 15:08:12 +00002347 FieldTypes[0] = Context->getObjCIdType();
Steve Naroffce8e8862008-03-15 00:55:56 +00002348 // int flags;
Mike Stump11289f42009-09-09 15:08:12 +00002349 FieldTypes[1] = Context->IntTy;
Steve Naroffce8e8862008-03-15 00:55:56 +00002350 // char *str;
Mike Stump11289f42009-09-09 15:08:12 +00002351 FieldTypes[2] = Context->getPointerType(Context->CharTy);
Steve Naroffce8e8862008-03-15 00:55:56 +00002352 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00002353 FieldTypes[3] = Context->LongTy;
Douglas Gregor91f84212008-12-11 16:49:14 +00002354
Steve Naroffce8e8862008-03-15 00:55:56 +00002355 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00002356 for (unsigned i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00002357 ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
2358 ConstantStringDecl,
Douglas Gregor91f84212008-12-11 16:49:14 +00002359 SourceLocation(), 0,
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002360 FieldTypes[i], 0,
Douglas Gregor91f84212008-12-11 16:49:14 +00002361 /*BitWidth=*/0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002362 /*Mutable=*/true));
Douglas Gregor91f84212008-12-11 16:49:14 +00002363 }
2364
2365 ConstantStringDecl->completeDefinition(*Context);
Steve Naroffce8e8862008-03-15 00:55:56 +00002366 }
2367 return Context->getTagDeclType(ConstantStringDecl);
2368}
2369
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002370Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002371 if (!SelGetUidFunctionDecl)
2372 SynthSelGetUidFunctionDecl();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002373 if (!MsgSendFunctionDecl)
2374 SynthMsgSendFunctionDecl();
Steve Naroff7fa2f042007-11-15 10:28:18 +00002375 if (!MsgSendSuperFunctionDecl)
2376 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002377 if (!MsgSendStretFunctionDecl)
2378 SynthMsgSendStretFunctionDecl();
2379 if (!MsgSendSuperStretFunctionDecl)
2380 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002381 if (!MsgSendFpretFunctionDecl)
2382 SynthMsgSendFpretFunctionDecl();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002383 if (!GetClassFunctionDecl)
2384 SynthGetClassFunctionDecl();
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002385 if (!GetMetaClassFunctionDecl)
2386 SynthGetMetaClassFunctionDecl();
Mike Stump11289f42009-09-09 15:08:12 +00002387
Steve Naroff7fa2f042007-11-15 10:28:18 +00002388 // default to objc_msgSend().
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002389 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2390 // May need to use objc_msgSend_stret() as well.
2391 FunctionDecl *MsgSendStretFlavor = 0;
Steve Naroffd9803712009-04-29 16:37:50 +00002392 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
2393 QualType resultType = mDecl->getResultType();
Chris Lattner3f6cd0b2008-07-26 22:36:27 +00002394 if (resultType->isStructureType() || resultType->isUnionType())
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002395 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Chris Lattner3f6cd0b2008-07-26 22:36:27 +00002396 else if (resultType->isRealFloatingType())
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002397 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002398 }
Mike Stump11289f42009-09-09 15:08:12 +00002399
Steve Naroff574440f2007-10-24 22:48:43 +00002400 // Synthesize a call to objc_msgSend().
2401 llvm::SmallVector<Expr*, 8> MsgExprs;
2402 IdentifierInfo *clsName = Exp->getClassName();
Mike Stump11289f42009-09-09 15:08:12 +00002403
Steve Naroff574440f2007-10-24 22:48:43 +00002404 // Derive/push the receiver/selector, 2 implicit arguments to objc_msgSend().
2405 if (clsName) { // class message.
Steve Naroff6c79f972008-07-24 19:44:33 +00002406 // FIXME: We need to fix Sema (and the AST for ObjCMessageExpr) to handle
2407 // the 'super' idiom within a class method.
Daniel Dunbar07d07852009-10-18 21:17:35 +00002408 if (clsName->getName() == "super") {
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002409 MsgSendFlavor = MsgSendSuperFunctionDecl;
2410 if (MsgSendStretFlavor)
2411 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2412 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
Mike Stump11289f42009-09-09 15:08:12 +00002413
2414 ObjCInterfaceDecl *SuperDecl =
Steve Naroff677ab3a2008-10-27 17:20:55 +00002415 CurMethodDef->getClassInterface()->getSuperClass();
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002416
2417 llvm::SmallVector<Expr*, 4> InitExprs;
Mike Stump11289f42009-09-09 15:08:12 +00002418
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002419 // set the receiver to self, the first argument to all methods.
Steve Naroffd9803712009-04-29 16:37:50 +00002420 InitExprs.push_back(
Mike Stump11289f42009-09-09 15:08:12 +00002421 new (Context) CStyleCastExpr(Context->getObjCIdType(),
Anders Carlssona2615922009-07-31 00:48:10 +00002422 CastExpr::CK_Unknown,
Mike Stump11289f42009-09-09 15:08:12 +00002423 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
Steve Naroffd9803712009-04-29 16:37:50 +00002424 Context->getObjCIdType(),
2425 SourceLocation()),
2426 Context->getObjCIdType(),
2427 SourceLocation(), SourceLocation())); // set the 'receiver'.
2428
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002429 llvm::SmallVector<Expr*, 8> ClsExprs;
2430 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattnerf83b5af2009-02-18 06:40:38 +00002431 ClsExprs.push_back(StringLiteral::Create(*Context,
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00002432 SuperDecl->getIdentifier()->getNameStart(),
2433 SuperDecl->getIdentifier()->getLength(),
2434 false, argType, SourceLocation()));
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002435 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002436 &ClsExprs[0],
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002437 ClsExprs.size());
2438 // To turn off a warning, type-cast to 'id'
Douglas Gregore200adc2008-10-27 19:41:14 +00002439 InitExprs.push_back( // set 'super class', using objc_getClass().
Mike Stump11289f42009-09-09 15:08:12 +00002440 new (Context) CStyleCastExpr(Context->getObjCIdType(),
Anders Carlssona2615922009-07-31 00:48:10 +00002441 CastExpr::CK_Unknown,
Douglas Gregore200adc2008-10-27 19:41:14 +00002442 Cls, Context->getObjCIdType(),
Mike Stump11289f42009-09-09 15:08:12 +00002443 SourceLocation(), SourceLocation()));
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002444 // struct objc_super
2445 QualType superType = getSuperStructType();
Steve Naroff0b844f02008-03-11 18:14:26 +00002446 Expr *SuperRep;
Mike Stump11289f42009-09-09 15:08:12 +00002447
Steve Naroff0b844f02008-03-11 18:14:26 +00002448 if (LangOpts.Microsoft) {
2449 SynthSuperContructorFunctionDecl();
2450 // Simulate a contructor call...
Mike Stump11289f42009-09-09 15:08:12 +00002451 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
Steve Naroff0b844f02008-03-11 18:14:26 +00002452 superType, SourceLocation());
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002453 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
Mike Stump11289f42009-09-09 15:08:12 +00002454 InitExprs.size(),
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002455 superType, SourceLocation());
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002456 // The code for super is a little tricky to prevent collision with
2457 // the structure definition in the header. The rewriter has it's own
2458 // internal definition (__rw_objc_super) that is uses. This is why
2459 // we need the cast below. For example:
2460 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2461 //
Ted Kremenek5a201952009-02-07 01:47:29 +00002462 SuperRep = new (Context) UnaryOperator(SuperRep, UnaryOperator::AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00002463 Context->getPointerType(SuperRep->getType()),
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002464 SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002465 SuperRep = new (Context) CStyleCastExpr(Context->getPointerType(superType),
2466 CastExpr::CK_Unknown, SuperRep,
Anders Carlssona2615922009-07-31 00:48:10 +00002467 Context->getPointerType(superType),
Mike Stump11289f42009-09-09 15:08:12 +00002468 SourceLocation(), SourceLocation());
2469 } else {
Steve Naroff0b844f02008-03-11 18:14:26 +00002470 // (struct objc_super) { <exprs from above> }
Mike Stump11289f42009-09-09 15:08:12 +00002471 InitListExpr *ILE = new (Context) InitListExpr(SourceLocation(),
2472 &InitExprs[0], InitExprs.size(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002473 SourceLocation());
Ted Kremenek5a201952009-02-07 01:47:29 +00002474 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superType, ILE,
Chris Lattner07d754a2008-10-26 23:43:26 +00002475 false);
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002476 // struct objc_super *
Ted Kremenek5a201952009-02-07 01:47:29 +00002477 SuperRep = new (Context) UnaryOperator(SuperRep, UnaryOperator::AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00002478 Context->getPointerType(SuperRep->getType()),
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002479 SourceLocation());
Steve Naroff0b844f02008-03-11 18:14:26 +00002480 }
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002481 MsgExprs.push_back(SuperRep);
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002482 } else {
2483 llvm::SmallVector<Expr*, 8> ClsExprs;
2484 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattnerf83b5af2009-02-18 06:40:38 +00002485 ClsExprs.push_back(StringLiteral::Create(*Context,
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00002486 clsName->getNameStart(),
Chris Lattnerf83b5af2009-02-18 06:40:38 +00002487 clsName->getLength(),
2488 false, argType,
2489 SourceLocation()));
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002490 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002491 &ClsExprs[0],
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002492 ClsExprs.size());
2493 MsgExprs.push_back(Cls);
2494 }
Steve Naroffe7f18192007-11-14 23:54:14 +00002495 } else { // instance message.
2496 Expr *recExpr = Exp->getReceiver();
Steve Naroff7fa2f042007-11-15 10:28:18 +00002497
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002498 if (ObjCInterfaceDecl *SuperDecl = isSuperReceiver(recExpr)) {
Steve Naroff7fa2f042007-11-15 10:28:18 +00002499 MsgSendFlavor = MsgSendSuperFunctionDecl;
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002500 if (MsgSendStretFlavor)
2501 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
Steve Naroff7fa2f042007-11-15 10:28:18 +00002502 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
Mike Stump11289f42009-09-09 15:08:12 +00002503
Steve Naroff7fa2f042007-11-15 10:28:18 +00002504 llvm::SmallVector<Expr*, 4> InitExprs;
Mike Stump11289f42009-09-09 15:08:12 +00002505
Fariborz Jahanian1e34ce12007-12-04 22:32:58 +00002506 InitExprs.push_back(
Mike Stump11289f42009-09-09 15:08:12 +00002507 new (Context) CStyleCastExpr(Context->getObjCIdType(),
Anders Carlssona2615922009-07-31 00:48:10 +00002508 CastExpr::CK_Unknown,
Mike Stump11289f42009-09-09 15:08:12 +00002509 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
Steve Naroff97adf602008-07-16 22:35:27 +00002510 Context->getObjCIdType(),
Douglas Gregore200adc2008-10-27 19:41:14 +00002511 SourceLocation()),
2512 Context->getObjCIdType(),
Steve Naroffc989a7b2008-11-03 23:29:32 +00002513 SourceLocation(), SourceLocation())); // set the 'receiver'.
Mike Stump11289f42009-09-09 15:08:12 +00002514
Steve Naroff7fa2f042007-11-15 10:28:18 +00002515 llvm::SmallVector<Expr*, 8> ClsExprs;
2516 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump11289f42009-09-09 15:08:12 +00002517 ClsExprs.push_back(StringLiteral::Create(*Context,
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00002518 SuperDecl->getIdentifier()->getNameStart(),
2519 SuperDecl->getIdentifier()->getLength(),
2520 false, argType, SourceLocation()));
Steve Naroff7fa2f042007-11-15 10:28:18 +00002521 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002522 &ClsExprs[0],
Fariborz Jahanian1e34ce12007-12-04 22:32:58 +00002523 ClsExprs.size());
Fariborz Jahaniand5db92b2007-12-05 17:29:46 +00002524 // To turn off a warning, type-cast to 'id'
Fariborz Jahanian1e34ce12007-12-04 22:32:58 +00002525 InitExprs.push_back(
Douglas Gregore200adc2008-10-27 19:41:14 +00002526 // set 'super class', using objc_getClass().
Mike Stump11289f42009-09-09 15:08:12 +00002527 new (Context) CStyleCastExpr(Context->getObjCIdType(),
Anders Carlssona2615922009-07-31 00:48:10 +00002528 CastExpr::CK_Unknown,
Mike Stump11289f42009-09-09 15:08:12 +00002529 Cls, Context->getObjCIdType(), SourceLocation(), SourceLocation()));
Steve Naroff7fa2f042007-11-15 10:28:18 +00002530 // struct objc_super
2531 QualType superType = getSuperStructType();
Steve Naroff17978c42008-03-11 17:37:02 +00002532 Expr *SuperRep;
Mike Stump11289f42009-09-09 15:08:12 +00002533
Steve Naroff17978c42008-03-11 17:37:02 +00002534 if (LangOpts.Microsoft) {
2535 SynthSuperContructorFunctionDecl();
2536 // Simulate a contructor call...
Mike Stump11289f42009-09-09 15:08:12 +00002537 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
Steve Naroff17978c42008-03-11 17:37:02 +00002538 superType, SourceLocation());
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002539 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
Mike Stump11289f42009-09-09 15:08:12 +00002540 InitExprs.size(),
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002541 superType, SourceLocation());
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002542 // The code for super is a little tricky to prevent collision with
2543 // the structure definition in the header. The rewriter has it's own
2544 // internal definition (__rw_objc_super) that is uses. This is why
2545 // we need the cast below. For example:
2546 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2547 //
Ted Kremenek5a201952009-02-07 01:47:29 +00002548 SuperRep = new (Context) UnaryOperator(SuperRep, UnaryOperator::AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00002549 Context->getPointerType(SuperRep->getType()),
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002550 SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002551 SuperRep = new (Context) CStyleCastExpr(Context->getPointerType(superType),
Anders Carlssona2615922009-07-31 00:48:10 +00002552 CastExpr::CK_Unknown,
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002553 SuperRep, Context->getPointerType(superType),
Mike Stump11289f42009-09-09 15:08:12 +00002554 SourceLocation(), SourceLocation());
Steve Naroff17978c42008-03-11 17:37:02 +00002555 } else {
2556 // (struct objc_super) { <exprs from above> }
Mike Stump11289f42009-09-09 15:08:12 +00002557 InitListExpr *ILE = new (Context) InitListExpr(SourceLocation(),
2558 &InitExprs[0], InitExprs.size(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002559 SourceLocation());
Ted Kremenek5a201952009-02-07 01:47:29 +00002560 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superType, ILE, false);
Steve Naroff17978c42008-03-11 17:37:02 +00002561 }
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002562 MsgExprs.push_back(SuperRep);
Steve Naroff7fa2f042007-11-15 10:28:18 +00002563 } else {
Fariborz Jahanianff6a4552007-12-07 21:21:21 +00002564 // Remove all type-casts because it may contain objc-style types; e.g.
2565 // Foo<Proto> *.
Douglas Gregorf19b2312008-10-28 15:36:24 +00002566 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
Fariborz Jahanianff6a4552007-12-07 21:21:21 +00002567 recExpr = CE->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00002568 recExpr = new (Context) CStyleCastExpr(Context->getObjCIdType(),
Anders Carlssona2615922009-07-31 00:48:10 +00002569 CastExpr::CK_Unknown, recExpr,
Mike Stump11289f42009-09-09 15:08:12 +00002570 Context->getObjCIdType(),
Steve Naroffc989a7b2008-11-03 23:29:32 +00002571 SourceLocation(), SourceLocation());
Steve Naroff7fa2f042007-11-15 10:28:18 +00002572 MsgExprs.push_back(recExpr);
2573 }
Steve Naroffe7f18192007-11-14 23:54:14 +00002574 }
Steve Naroffa397efd2007-11-03 11:27:19 +00002575 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff574440f2007-10-24 22:48:43 +00002576 llvm::SmallVector<Expr*, 8> SelExprs;
2577 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump11289f42009-09-09 15:08:12 +00002578 SelExprs.push_back(StringLiteral::Create(*Context,
Ted Kremenek6b7ecf62009-02-06 19:55:15 +00002579 Exp->getSelector().getAsString().c_str(),
Chris Lattnere4b95692008-11-24 03:33:13 +00002580 Exp->getSelector().getAsString().size(),
Chris Lattner630970d2009-02-18 05:49:11 +00002581 false, argType, SourceLocation()));
Steve Naroff574440f2007-10-24 22:48:43 +00002582 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2583 &SelExprs[0], SelExprs.size());
2584 MsgExprs.push_back(SelExp);
Mike Stump11289f42009-09-09 15:08:12 +00002585
Steve Naroff574440f2007-10-24 22:48:43 +00002586 // Now push any user supplied arguments.
2587 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroffe7f18192007-11-14 23:54:14 +00002588 Expr *userExpr = Exp->getArg(i);
Steve Narofff60782b2007-11-15 02:58:25 +00002589 // Make all implicit casts explicit...ICE comes in handy:-)
2590 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
2591 // Reuse the ICE type, it is exactly what the doctor ordered.
Douglas Gregore200adc2008-10-27 19:41:14 +00002592 QualType type = ICE->getType()->isObjCQualifiedIdType()
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002593 ? Context->getObjCIdType()
Douglas Gregore200adc2008-10-27 19:41:14 +00002594 : ICE->getType();
Anders Carlssona2615922009-07-31 00:48:10 +00002595 userExpr = new (Context) CStyleCastExpr(type, CastExpr::CK_Unknown,
Mike Stump11289f42009-09-09 15:08:12 +00002596 userExpr, type, SourceLocation(),
Anders Carlssona2615922009-07-31 00:48:10 +00002597 SourceLocation());
Fariborz Jahanian9f0e3102007-12-18 21:33:44 +00002598 }
2599 // Make id<P...> cast into an 'id' cast.
Douglas Gregorf19b2312008-10-28 15:36:24 +00002600 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002601 if (CE->getType()->isObjCQualifiedIdType()) {
Douglas Gregorf19b2312008-10-28 15:36:24 +00002602 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
Fariborz Jahanian9f0e3102007-12-18 21:33:44 +00002603 userExpr = CE->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00002604 userExpr = new (Context) CStyleCastExpr(Context->getObjCIdType(),
Anders Carlssona2615922009-07-31 00:48:10 +00002605 CastExpr::CK_Unknown,
Mike Stump11289f42009-09-09 15:08:12 +00002606 userExpr, Context->getObjCIdType(),
Steve Naroffc989a7b2008-11-03 23:29:32 +00002607 SourceLocation(), SourceLocation());
Fariborz Jahanian9f0e3102007-12-18 21:33:44 +00002608 }
Mike Stump11289f42009-09-09 15:08:12 +00002609 }
Steve Naroffe7f18192007-11-14 23:54:14 +00002610 MsgExprs.push_back(userExpr);
Steve Naroffd9803712009-04-29 16:37:50 +00002611 // We've transferred the ownership to MsgExprs. For now, we *don't* null
2612 // out the argument in the original expression (since we aren't deleting
2613 // the ObjCMessageExpr). See RewritePropertySetter() usage for more info.
2614 //Exp->setArg(i, 0);
Steve Naroff574440f2007-10-24 22:48:43 +00002615 }
Steve Narofff36987c2007-11-04 22:37:50 +00002616 // Generate the funky cast.
2617 CastExpr *cast;
2618 llvm::SmallVector<QualType, 8> ArgTypes;
2619 QualType returnType;
Mike Stump11289f42009-09-09 15:08:12 +00002620
Steve Narofff36987c2007-11-04 22:37:50 +00002621 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroff44864e42007-11-15 10:43:57 +00002622 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
2623 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
2624 else
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002625 ArgTypes.push_back(Context->getObjCIdType());
2626 ArgTypes.push_back(Context->getObjCSelType());
Chris Lattnera4997152009-02-20 18:43:26 +00002627 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
Steve Narofff36987c2007-11-04 22:37:50 +00002628 // Push any user argument types.
Chris Lattnera4997152009-02-20 18:43:26 +00002629 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
2630 E = OMD->param_end(); PI != E; ++PI) {
2631 QualType t = (*PI)->getType()->isObjCQualifiedIdType()
Mike Stump11289f42009-09-09 15:08:12 +00002632 ? Context->getObjCIdType()
Chris Lattnera4997152009-02-20 18:43:26 +00002633 : (*PI)->getType();
Steve Naroff52c65fa2008-10-29 14:49:46 +00002634 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Steve Naroffa5c0db82008-12-11 21:05:33 +00002635 if (isTopLevelBlockPointerType(t)) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002636 const BlockPointerType *BPT = t->getAs<BlockPointerType>();
Steve Naroff52c65fa2008-10-29 14:49:46 +00002637 t = Context->getPointerType(BPT->getPointeeType());
2638 }
Steve Naroff98eb8d12007-11-05 14:36:37 +00002639 ArgTypes.push_back(t);
2640 }
Chris Lattnera4997152009-02-20 18:43:26 +00002641 returnType = OMD->getResultType()->isObjCQualifiedIdType()
2642 ? Context->getObjCIdType() : OMD->getResultType();
Steve Narofff36987c2007-11-04 22:37:50 +00002643 } else {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002644 returnType = Context->getObjCIdType();
Steve Narofff36987c2007-11-04 22:37:50 +00002645 }
2646 // Get the type, we will need to reference it in a couple spots.
Steve Naroff7fa2f042007-11-15 10:28:18 +00002647 QualType msgSendType = MsgSendFlavor->getType();
Mike Stump11289f42009-09-09 15:08:12 +00002648
Steve Narofff36987c2007-11-04 22:37:50 +00002649 // Create a reference to the objc_msgSend() declaration.
Mike Stump11289f42009-09-09 15:08:12 +00002650 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, msgSendType,
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002651 SourceLocation());
Steve Narofff36987c2007-11-04 22:37:50 +00002652
Mike Stump11289f42009-09-09 15:08:12 +00002653 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
Steve Narofff36987c2007-11-04 22:37:50 +00002654 // If we don't do this cast, we get the following bizarre warning/note:
2655 // xx.m:13: warning: function called through a non-compatible type
2656 // xx.m:13: note: if this code is reached, the program will abort
Mike Stump11289f42009-09-09 15:08:12 +00002657 cast = new (Context) CStyleCastExpr(Context->getPointerType(Context->VoidTy),
2658 CastExpr::CK_Unknown, DRE,
Douglas Gregore200adc2008-10-27 19:41:14 +00002659 Context->getPointerType(Context->VoidTy),
Steve Naroffc989a7b2008-11-03 23:29:32 +00002660 SourceLocation(), SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002661
Steve Narofff36987c2007-11-04 22:37:50 +00002662 // Now do the "normal" pointer to function cast.
Mike Stump11289f42009-09-09 15:08:12 +00002663 QualType castType = Context->getFunctionType(returnType,
Fariborz Jahanian227c0d12007-12-06 19:49:56 +00002664 &ArgTypes[0], ArgTypes.size(),
Steve Naroff327f0f42008-03-18 02:02:04 +00002665 // If we don't have a method decl, force a variadic cast.
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002666 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true, 0);
Steve Narofff36987c2007-11-04 22:37:50 +00002667 castType = Context->getPointerType(castType);
Mike Stump11289f42009-09-09 15:08:12 +00002668 cast = new (Context) CStyleCastExpr(castType, CastExpr::CK_Unknown, cast,
2669 castType, SourceLocation(),
Anders Carlssona2615922009-07-31 00:48:10 +00002670 SourceLocation());
Steve Narofff36987c2007-11-04 22:37:50 +00002671
2672 // Don't forget the parens to enforce the proper binding.
Ted Kremenek5a201952009-02-07 01:47:29 +00002673 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
Mike Stump11289f42009-09-09 15:08:12 +00002674
John McCall9dd450b2009-09-21 23:43:11 +00002675 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002676 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
Mike Stump11289f42009-09-09 15:08:12 +00002677 MsgExprs.size(),
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002678 FT->getResultType(), SourceLocation());
Fariborz Jahanian965a8962008-01-08 22:06:28 +00002679 Stmt *ReplacingStmt = CE;
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002680 if (MsgSendStretFlavor) {
2681 // We have the method which returns a struct/union. Must also generate
2682 // call to objc_msgSend_stret and hang both varieties on a conditional
2683 // expression which dictate which one to envoke depending on size of
2684 // method's return type.
Mike Stump11289f42009-09-09 15:08:12 +00002685
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002686 // Create a reference to the objc_msgSend_stret() declaration.
Mike Stump11289f42009-09-09 15:08:12 +00002687 DeclRefExpr *STDRE = new (Context) DeclRefExpr(MsgSendStretFlavor, msgSendType,
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002688 SourceLocation());
2689 // Need to cast objc_msgSend_stret to "void *" (see above comment).
Mike Stump11289f42009-09-09 15:08:12 +00002690 cast = new (Context) CStyleCastExpr(Context->getPointerType(Context->VoidTy),
2691 CastExpr::CK_Unknown, STDRE,
Douglas Gregore200adc2008-10-27 19:41:14 +00002692 Context->getPointerType(Context->VoidTy),
Steve Naroffc989a7b2008-11-03 23:29:32 +00002693 SourceLocation(), SourceLocation());
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002694 // Now do the "normal" pointer to function cast.
Mike Stump11289f42009-09-09 15:08:12 +00002695 castType = Context->getFunctionType(returnType,
Fariborz Jahanian227c0d12007-12-06 19:49:56 +00002696 &ArgTypes[0], ArgTypes.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002697 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false, 0);
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002698 castType = Context->getPointerType(castType);
Anders Carlssona2615922009-07-31 00:48:10 +00002699 cast = new (Context) CStyleCastExpr(castType, CastExpr::CK_Unknown,
2700 cast, castType, SourceLocation(), SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002701
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002702 // Don't forget the parens to enforce the proper binding.
Ted Kremenek5a201952009-02-07 01:47:29 +00002703 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
Mike Stump11289f42009-09-09 15:08:12 +00002704
John McCall9dd450b2009-09-21 23:43:11 +00002705 FT = msgSendType->getAs<FunctionType>();
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002706 CallExpr *STCE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
Mike Stump11289f42009-09-09 15:08:12 +00002707 MsgExprs.size(),
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002708 FT->getResultType(), SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002709
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002710 // Build sizeof(returnType)
Mike Stump11289f42009-09-09 15:08:12 +00002711 SizeOfAlignOfExpr *sizeofExpr = new (Context) SizeOfAlignOfExpr(true,
John McCallbcd03502009-12-07 02:54:59 +00002712 Context->getTrivialTypeSourceInfo(returnType),
Sebastian Redl6f282892008-11-11 17:56:53 +00002713 Context->getSizeType(),
2714 SourceLocation(), SourceLocation());
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002715 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2716 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
2717 // For X86 it is more complicated and some kind of target specific routine
2718 // is needed to decide what to do.
Mike Stump11289f42009-09-09 15:08:12 +00002719 unsigned IntSize =
Chris Lattner37e05872008-03-05 18:54:05 +00002720 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Mike Stump11289f42009-09-09 15:08:12 +00002721 IntegerLiteral *limit = new (Context) IntegerLiteral(llvm::APInt(IntSize, 8),
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002722 Context->IntTy,
2723 SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002724 BinaryOperator *lessThanExpr = new (Context) BinaryOperator(sizeofExpr, limit,
2725 BinaryOperator::LE,
2726 Context->IntTy,
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002727 SourceLocation());
2728 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
Mike Stump11289f42009-09-09 15:08:12 +00002729 ConditionalOperator *CondExpr =
Douglas Gregor7e112b02009-08-26 14:37:04 +00002730 new (Context) ConditionalOperator(lessThanExpr,
2731 SourceLocation(), CE,
2732 SourceLocation(), STCE, returnType);
Ted Kremenek5a201952009-02-07 01:47:29 +00002733 ReplacingStmt = new (Context) ParenExpr(SourceLocation(), SourceLocation(), CondExpr);
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002734 }
Mike Stump11289f42009-09-09 15:08:12 +00002735 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Fariborz Jahanian965a8962008-01-08 22:06:28 +00002736 return ReplacingStmt;
2737}
2738
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002739Stmt *RewriteObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanian965a8962008-01-08 22:06:28 +00002740 Stmt *ReplacingStmt = SynthMessageExpr(Exp);
Mike Stump11289f42009-09-09 15:08:12 +00002741
Steve Naroff574440f2007-10-24 22:48:43 +00002742 // Now do the actual rewrite.
Chris Lattner2e0d2602008-01-31 19:37:57 +00002743 ReplaceStmt(Exp, ReplacingStmt);
Mike Stump11289f42009-09-09 15:08:12 +00002744
2745 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Fariborz Jahanian965a8962008-01-08 22:06:28 +00002746 return ReplacingStmt;
Steve Naroffdb1ab1c2007-10-23 23:50:29 +00002747}
2748
Steve Naroffd9803712009-04-29 16:37:50 +00002749// typedef struct objc_object Protocol;
2750QualType RewriteObjC::getProtocolType() {
2751 if (!ProtocolTypeDecl) {
John McCallbcd03502009-12-07 02:54:59 +00002752 TypeSourceInfo *TInfo
2753 = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
Steve Naroffd9803712009-04-29 16:37:50 +00002754 ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002755 SourceLocation(),
Steve Naroffd9803712009-04-29 16:37:50 +00002756 &Context->Idents.get("Protocol"),
John McCallbcd03502009-12-07 02:54:59 +00002757 TInfo);
Steve Naroffd9803712009-04-29 16:37:50 +00002758 }
2759 return Context->getTypeDeclType(ProtocolTypeDecl);
2760}
2761
Fariborz Jahanian33c0e812007-12-07 18:47:10 +00002762/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
Steve Naroffd9803712009-04-29 16:37:50 +00002763/// a synthesized/forward data reference (to the protocol's metadata).
2764/// The forward references (and metadata) are generated in
2765/// RewriteObjC::HandleTranslationUnit().
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002766Stmt *RewriteObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Steve Naroffd9803712009-04-29 16:37:50 +00002767 std::string Name = "_OBJC_PROTOCOL_" + Exp->getProtocol()->getNameAsString();
2768 IdentifierInfo *ID = &Context->Idents.get(Name);
Mike Stump11289f42009-09-09 15:08:12 +00002769 VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Douglas Gregored6c7442009-11-23 11:41:28 +00002770 ID, getProtocolType(), 0, VarDecl::Extern);
Steve Naroffd9803712009-04-29 16:37:50 +00002771 DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, getProtocolType(), SourceLocation());
2772 Expr *DerefExpr = new (Context) UnaryOperator(DRE, UnaryOperator::AddrOf,
2773 Context->getPointerType(DRE->getType()),
2774 SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002775 CastExpr *castExpr = new (Context) CStyleCastExpr(DerefExpr->getType(),
2776 CastExpr::CK_Unknown,
2777 DerefExpr, DerefExpr->getType(),
Steve Naroffd9803712009-04-29 16:37:50 +00002778 SourceLocation(), SourceLocation());
2779 ReplaceStmt(Exp, castExpr);
2780 ProtocolExprDecls.insert(Exp->getProtocol());
Mike Stump11289f42009-09-09 15:08:12 +00002781 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroffd9803712009-04-29 16:37:50 +00002782 return castExpr;
Mike Stump11289f42009-09-09 15:08:12 +00002783
Fariborz Jahanian33c0e812007-12-07 18:47:10 +00002784}
2785
Mike Stump11289f42009-09-09 15:08:12 +00002786bool RewriteObjC::BufferContainsPPDirectives(const char *startBuf,
Steve Naroffcd92aeb2008-05-31 14:15:04 +00002787 const char *endBuf) {
2788 while (startBuf < endBuf) {
2789 if (*startBuf == '#') {
2790 // Skip whitespace.
2791 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
2792 ;
2793 if (!strncmp(startBuf, "if", strlen("if")) ||
2794 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
2795 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
2796 !strncmp(startBuf, "define", strlen("define")) ||
2797 !strncmp(startBuf, "undef", strlen("undef")) ||
2798 !strncmp(startBuf, "else", strlen("else")) ||
2799 !strncmp(startBuf, "elif", strlen("elif")) ||
2800 !strncmp(startBuf, "endif", strlen("endif")) ||
2801 !strncmp(startBuf, "pragma", strlen("pragma")) ||
2802 !strncmp(startBuf, "include", strlen("include")) ||
2803 !strncmp(startBuf, "import", strlen("import")) ||
2804 !strncmp(startBuf, "include_next", strlen("include_next")))
2805 return true;
2806 }
2807 startBuf++;
2808 }
2809 return false;
2810}
2811
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002812/// SynthesizeObjCInternalStruct - Rewrite one internal struct corresponding to
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00002813/// an objective-c class with ivars.
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002814void RewriteObjC::SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00002815 std::string &Result) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002816 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
Mike Stump11289f42009-09-09 15:08:12 +00002817 assert(CDecl->getNameAsCString() &&
Douglas Gregor77324f32008-11-17 14:58:09 +00002818 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanianc3cda762007-10-31 23:08:24 +00002819 // Do not synthesize more than once.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002820 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanianc3cda762007-10-31 23:08:24 +00002821 return;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002822 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Chris Lattner8d1c04f2008-03-16 21:08:55 +00002823 int NumIvars = CDecl->ivar_size();
Steve Naroffdde78982007-11-14 19:25:57 +00002824 SourceLocation LocStart = CDecl->getLocStart();
2825 SourceLocation LocEnd = CDecl->getLocEnd();
Mike Stump11289f42009-09-09 15:08:12 +00002826
Steve Naroffdde78982007-11-14 19:25:57 +00002827 const char *startBuf = SM->getCharacterData(LocStart);
2828 const char *endBuf = SM->getCharacterData(LocEnd);
Mike Stump11289f42009-09-09 15:08:12 +00002829
Fariborz Jahaniana883d6e2007-11-26 19:52:57 +00002830 // If no ivars and no root or if its root, directly or indirectly,
2831 // have no ivars (thus not synthesized) then no need to synthesize this class.
Chris Lattner8d1c04f2008-03-16 21:08:55 +00002832 if ((CDecl->isForwardDecl() || NumIvars == 0) &&
2833 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Chris Lattner184e65d2009-04-14 23:22:57 +00002834 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Chris Lattner9cc55f52008-01-31 19:51:04 +00002835 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahaniana883d6e2007-11-26 19:52:57 +00002836 return;
2837 }
Mike Stump11289f42009-09-09 15:08:12 +00002838
2839 // FIXME: This has potential of causing problem. If
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002840 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahaniana883d6e2007-11-26 19:52:57 +00002841 Result += "\nstruct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002842 Result += CDecl->getNameAsString();
Steve Naroffa1e115e2008-03-10 23:16:54 +00002843 if (LangOpts.Microsoft)
2844 Result += "_IMPL";
Steve Naroffdc5b6b22008-03-12 00:25:36 +00002845
Fariborz Jahanianaff228df2007-10-31 17:29:28 +00002846 if (NumIvars > 0) {
Steve Naroffdde78982007-11-14 19:25:57 +00002847 const char *cursor = strchr(startBuf, '{');
Mike Stump11289f42009-09-09 15:08:12 +00002848 assert((cursor && endBuf)
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002849 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Naroffcd92aeb2008-05-31 14:15:04 +00002850 // If the buffer contains preprocessor directives, we do more fine-grained
2851 // rewrites. This is intended to fix code that looks like (which occurs in
2852 // NSURL.h, for example):
2853 //
2854 // #ifdef XYZ
2855 // @interface Foo : NSObject
2856 // #else
2857 // @interface FooBar : NSObject
2858 // #endif
2859 // {
2860 // int i;
2861 // }
2862 // @end
2863 //
2864 // This clause is segregated to avoid breaking the common case.
2865 if (BufferContainsPPDirectives(startBuf, cursor)) {
Mike Stump11289f42009-09-09 15:08:12 +00002866 SourceLocation L = RCDecl ? CDecl->getSuperClassLoc() :
Steve Naroffcd92aeb2008-05-31 14:15:04 +00002867 CDecl->getClassLoc();
2868 const char *endHeader = SM->getCharacterData(L);
Chris Lattner184e65d2009-04-14 23:22:57 +00002869 endHeader += Lexer::MeasureTokenLength(L, *SM, LangOpts);
Steve Naroffcd92aeb2008-05-31 14:15:04 +00002870
Chris Lattnerf5b77512009-02-20 18:18:36 +00002871 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroffcd92aeb2008-05-31 14:15:04 +00002872 // advance to the end of the referenced protocols.
2873 while (endHeader < cursor && *endHeader != '>') endHeader++;
2874 endHeader++;
2875 }
2876 // rewrite the original header
2877 ReplaceText(LocStart, endHeader-startBuf, Result.c_str(), Result.size());
2878 } else {
2879 // rewrite the original header *without* disturbing the '{'
Steve Naroffb0e33902009-12-04 21:36:32 +00002880 ReplaceText(LocStart, cursor-startBuf, Result.c_str(), Result.size());
Steve Naroffcd92aeb2008-05-31 14:15:04 +00002881 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002882 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Naroffdde78982007-11-14 19:25:57 +00002883 Result = "\n struct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002884 Result += RCDecl->getNameAsString();
Steve Naroff9f33bd22008-03-12 21:09:20 +00002885 Result += "_IMPL ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002886 Result += RCDecl->getNameAsString();
Steve Naroffffb5f9a2008-03-12 21:22:52 +00002887 Result += "_IVARS;\n";
Mike Stump11289f42009-09-09 15:08:12 +00002888
Steve Naroffdde78982007-11-14 19:25:57 +00002889 // insert the super class structure definition.
Chris Lattner1780a852008-01-31 19:42:41 +00002890 SourceLocation OnePastCurly =
2891 LocStart.getFileLocWithOffset(cursor-startBuf+1);
2892 InsertText(OnePastCurly, Result.c_str(), Result.size());
Steve Naroffdde78982007-11-14 19:25:57 +00002893 }
2894 cursor++; // past '{'
Mike Stump11289f42009-09-09 15:08:12 +00002895
Steve Naroffdde78982007-11-14 19:25:57 +00002896 // Now comment out any visibility specifiers.
2897 while (cursor < endBuf) {
2898 if (*cursor == '@') {
2899 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattner174a8252007-11-14 22:57:51 +00002900 // Skip whitespace.
2901 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
2902 /*scan*/;
2903
Fariborz Jahanianaff228df2007-10-31 17:29:28 +00002904 // FIXME: presence of @public, etc. inside comment results in
2905 // this transformation as well, which is still correct c-code.
Steve Naroffdde78982007-11-14 19:25:57 +00002906 if (!strncmp(cursor, "public", strlen("public")) ||
2907 !strncmp(cursor, "private", strlen("private")) ||
Steve Naroffaf91b9a2008-04-04 22:34:24 +00002908 !strncmp(cursor, "package", strlen("package")) ||
Fariborz Jahanianc6225532007-11-14 22:26:25 +00002909 !strncmp(cursor, "protected", strlen("protected")))
Chris Lattner1780a852008-01-31 19:42:41 +00002910 InsertText(atLoc, "// ", 3);
Fariborz Jahanianaff228df2007-10-31 17:29:28 +00002911 }
Fariborz Jahanianc6225532007-11-14 22:26:25 +00002912 // FIXME: If there are cases where '<' is used in ivar declaration part
2913 // of user code, then scan the ivar list and use needToScanForQualifiers
2914 // for type checking.
2915 else if (*cursor == '<') {
2916 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattner1780a852008-01-31 19:42:41 +00002917 InsertText(atLoc, "/* ", 3);
Fariborz Jahanianc6225532007-11-14 22:26:25 +00002918 cursor = strchr(cursor, '>');
2919 cursor++;
2920 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattner1780a852008-01-31 19:42:41 +00002921 InsertText(atLoc, " */", 3);
Steve Naroff295570a2008-10-30 12:09:33 +00002922 } else if (*cursor == '^') { // rewrite block specifier.
2923 SourceLocation caretLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
2924 ReplaceText(caretLoc, 1, "*", 1);
Fariborz Jahanianc6225532007-11-14 22:26:25 +00002925 }
Steve Naroffdde78982007-11-14 19:25:57 +00002926 cursor++;
Fariborz Jahanianaff228df2007-10-31 17:29:28 +00002927 }
Steve Naroffdde78982007-11-14 19:25:57 +00002928 // Don't forget to add a ';'!!
Chris Lattner1780a852008-01-31 19:42:41 +00002929 InsertText(LocEnd.getFileLocWithOffset(1), ";", 1);
Steve Naroffdde78982007-11-14 19:25:57 +00002930 } else { // we don't have any instance variables - insert super struct.
Chris Lattner184e65d2009-04-14 23:22:57 +00002931 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Steve Naroffdde78982007-11-14 19:25:57 +00002932 Result += " {\n struct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002933 Result += RCDecl->getNameAsString();
Steve Naroff9f33bd22008-03-12 21:09:20 +00002934 Result += "_IMPL ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002935 Result += RCDecl->getNameAsString();
Steve Naroffffb5f9a2008-03-12 21:22:52 +00002936 Result += "_IVARS;\n};\n";
Chris Lattner9cc55f52008-01-31 19:51:04 +00002937 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00002938 }
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00002939 // Mark this struct as having been generated.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002940 if (!ObjCSynthesizedStructs.insert(CDecl))
Steve Naroff13e74872008-05-06 18:26:51 +00002941 assert(false && "struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00002942}
2943
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002944// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00002945/// class methods.
Douglas Gregor29bd76f2009-04-23 01:02:12 +00002946template<typename MethodIterator>
2947void RewriteObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
2948 MethodIterator MethodEnd,
Fariborz Jahanian3df412a2007-10-25 00:14:44 +00002949 bool IsInstanceMethod,
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00002950 const char *prefix,
Chris Lattner211f8b82007-10-25 17:07:24 +00002951 const char *ClassName,
2952 std::string &Result) {
Chris Lattner31bc07e2007-12-12 07:46:12 +00002953 if (MethodBegin == MethodEnd) return;
Mike Stump11289f42009-09-09 15:08:12 +00002954
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00002955 static bool objc_impl_method = false;
Chris Lattner31bc07e2007-12-12 07:46:12 +00002956 if (!objc_impl_method) {
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00002957 /* struct _objc_method {
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00002958 SEL _cmd;
2959 char *method_types;
2960 void *_imp;
2961 }
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00002962 */
Chris Lattner211f8b82007-10-25 17:07:24 +00002963 Result += "\nstruct _objc_method {\n";
2964 Result += "\tSEL _cmd;\n";
2965 Result += "\tchar *method_types;\n";
2966 Result += "\tvoid *_imp;\n";
2967 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00002968
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00002969 objc_impl_method = true;
Fariborz Jahanian74a1cfa2007-10-19 00:36:46 +00002970 }
Mike Stump11289f42009-09-09 15:08:12 +00002971
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00002972 // Build _objc_method_list for class's methods if needed
Mike Stump11289f42009-09-09 15:08:12 +00002973
Steve Naroffc5b9cc72008-03-11 00:12:29 +00002974 /* struct {
2975 struct _objc_method_list *next_method;
2976 int method_count;
2977 struct _objc_method method_list[];
2978 }
2979 */
Douglas Gregor29bd76f2009-04-23 01:02:12 +00002980 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
Steve Naroffc5b9cc72008-03-11 00:12:29 +00002981 Result += "\nstatic struct {\n";
2982 Result += "\tstruct _objc_method_list *next_method;\n";
2983 Result += "\tint method_count;\n";
2984 Result += "\tstruct _objc_method method_list[";
Douglas Gregor29bd76f2009-04-23 01:02:12 +00002985 Result += utostr(NumMethods);
Steve Naroffc5b9cc72008-03-11 00:12:29 +00002986 Result += "];\n} _OBJC_";
Chris Lattner31bc07e2007-12-12 07:46:12 +00002987 Result += prefix;
2988 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
2989 Result += "_METHODS_";
2990 Result += ClassName;
Steve Naroffb327e492008-03-12 17:18:30 +00002991 Result += " __attribute__ ((used, section (\"__OBJC, __";
Chris Lattner31bc07e2007-12-12 07:46:12 +00002992 Result += IsInstanceMethod ? "inst" : "cls";
2993 Result += "_meth\")))= ";
Douglas Gregor29bd76f2009-04-23 01:02:12 +00002994 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00002995
Chris Lattner31bc07e2007-12-12 07:46:12 +00002996 Result += "\t,{{(SEL)\"";
Chris Lattnere4b95692008-11-24 03:33:13 +00002997 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Chris Lattner31bc07e2007-12-12 07:46:12 +00002998 std::string MethodTypeString;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002999 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Chris Lattner31bc07e2007-12-12 07:46:12 +00003000 Result += "\", \"";
3001 Result += MethodTypeString;
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003002 Result += "\", (void *)";
Chris Lattner31bc07e2007-12-12 07:46:12 +00003003 Result += MethodInternalNames[*MethodBegin];
3004 Result += "}\n";
3005 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
3006 Result += "\t ,{(SEL)\"";
Chris Lattnere4b95692008-11-24 03:33:13 +00003007 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003008 std::string MethodTypeString;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003009 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003010 Result += "\", \"";
3011 Result += MethodTypeString;
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003012 Result += "\", (void *)";
Chris Lattner31bc07e2007-12-12 07:46:12 +00003013 Result += MethodInternalNames[*MethodBegin];
Fariborz Jahanian56338352007-11-13 21:02:00 +00003014 Result += "}\n";
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00003015 }
Chris Lattner31bc07e2007-12-12 07:46:12 +00003016 Result += "\t }\n};\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003017}
3018
Steve Naroffd9803712009-04-29 16:37:50 +00003019/// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
Chris Lattner390d39a2008-07-21 21:32:27 +00003020void RewriteObjC::
Steve Naroffd9803712009-04-29 16:37:50 +00003021RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl, const char *prefix,
3022 const char *ClassName, std::string &Result) {
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00003023 static bool objc_protocol_methods = false;
Steve Naroffd9803712009-04-29 16:37:50 +00003024
3025 // Output struct protocol_methods holder of method selector and type.
3026 if (!objc_protocol_methods && !PDecl->isForwardDecl()) {
3027 /* struct protocol_methods {
3028 SEL _cmd;
3029 char *method_types;
3030 }
3031 */
3032 Result += "\nstruct _protocol_methods {\n";
3033 Result += "\tstruct objc_selector *_cmd;\n";
3034 Result += "\tchar *method_types;\n";
3035 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003036
Steve Naroffd9803712009-04-29 16:37:50 +00003037 objc_protocol_methods = true;
3038 }
3039 // Do not synthesize the protocol more than once.
3040 if (ObjCSynthesizedProtocols.count(PDecl))
3041 return;
Mike Stump11289f42009-09-09 15:08:12 +00003042
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003043 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
3044 unsigned NumMethods = std::distance(PDecl->instmeth_begin(),
3045 PDecl->instmeth_end());
Steve Naroffd9803712009-04-29 16:37:50 +00003046 /* struct _objc_protocol_method_list {
3047 int protocol_method_count;
3048 struct protocol_methods protocols[];
3049 }
Steve Naroff251084d2008-03-12 01:06:30 +00003050 */
Steve Naroffd9803712009-04-29 16:37:50 +00003051 Result += "\nstatic struct {\n";
3052 Result += "\tint protocol_method_count;\n";
3053 Result += "\tstruct _protocol_methods protocol_methods[";
3054 Result += utostr(NumMethods);
3055 Result += "];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_";
3056 Result += PDecl->getNameAsString();
3057 Result += " __attribute__ ((used, section (\"__OBJC, __cat_inst_meth\")))= "
3058 "{\n\t" + utostr(NumMethods) + "\n";
Mike Stump11289f42009-09-09 15:08:12 +00003059
Steve Naroffd9803712009-04-29 16:37:50 +00003060 // Output instance methods declared in this protocol.
Mike Stump11289f42009-09-09 15:08:12 +00003061 for (ObjCProtocolDecl::instmeth_iterator
3062 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
Steve Naroffd9803712009-04-29 16:37:50 +00003063 I != E; ++I) {
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003064 if (I == PDecl->instmeth_begin())
Steve Naroffd9803712009-04-29 16:37:50 +00003065 Result += "\t ,{{(struct objc_selector *)\"";
3066 else
3067 Result += "\t ,{(struct objc_selector *)\"";
3068 Result += (*I)->getSelector().getAsString().c_str();
3069 std::string MethodTypeString;
3070 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
3071 Result += "\", \"";
3072 Result += MethodTypeString;
3073 Result += "\"}\n";
Chris Lattner388f6e92008-07-21 21:33:21 +00003074 }
Steve Naroffd9803712009-04-29 16:37:50 +00003075 Result += "\t }\n};\n";
3076 }
Mike Stump11289f42009-09-09 15:08:12 +00003077
Steve Naroffd9803712009-04-29 16:37:50 +00003078 // Output class methods declared in this protocol.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003079 unsigned NumMethods = std::distance(PDecl->classmeth_begin(),
3080 PDecl->classmeth_end());
Steve Naroffd9803712009-04-29 16:37:50 +00003081 if (NumMethods > 0) {
3082 /* struct _objc_protocol_method_list {
3083 int protocol_method_count;
3084 struct protocol_methods protocols[];
3085 }
3086 */
3087 Result += "\nstatic struct {\n";
3088 Result += "\tint protocol_method_count;\n";
3089 Result += "\tstruct _protocol_methods protocol_methods[";
3090 Result += utostr(NumMethods);
3091 Result += "];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
3092 Result += PDecl->getNameAsString();
3093 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
3094 "{\n\t";
3095 Result += utostr(NumMethods);
3096 Result += "\n";
Mike Stump11289f42009-09-09 15:08:12 +00003097
Steve Naroffd9803712009-04-29 16:37:50 +00003098 // Output instance methods declared in this protocol.
Mike Stump11289f42009-09-09 15:08:12 +00003099 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003100 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
Steve Naroffd9803712009-04-29 16:37:50 +00003101 I != E; ++I) {
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003102 if (I == PDecl->classmeth_begin())
Steve Naroffd9803712009-04-29 16:37:50 +00003103 Result += "\t ,{{(struct objc_selector *)\"";
3104 else
3105 Result += "\t ,{(struct objc_selector *)\"";
3106 Result += (*I)->getSelector().getAsString().c_str();
3107 std::string MethodTypeString;
3108 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
3109 Result += "\", \"";
3110 Result += MethodTypeString;
3111 Result += "\"}\n";
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00003112 }
Steve Naroffd9803712009-04-29 16:37:50 +00003113 Result += "\t }\n};\n";
3114 }
3115
3116 // Output:
3117 /* struct _objc_protocol {
3118 // Objective-C 1.0 extensions
3119 struct _objc_protocol_extension *isa;
3120 char *protocol_name;
3121 struct _objc_protocol **protocol_list;
3122 struct _objc_protocol_method_list *instance_methods;
3123 struct _objc_protocol_method_list *class_methods;
Mike Stump11289f42009-09-09 15:08:12 +00003124 };
Steve Naroffd9803712009-04-29 16:37:50 +00003125 */
3126 static bool objc_protocol = false;
3127 if (!objc_protocol) {
3128 Result += "\nstruct _objc_protocol {\n";
3129 Result += "\tstruct _objc_protocol_extension *isa;\n";
3130 Result += "\tchar *protocol_name;\n";
3131 Result += "\tstruct _objc_protocol **protocol_list;\n";
3132 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
3133 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
Chris Lattner388f6e92008-07-21 21:33:21 +00003134 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003135
Steve Naroffd9803712009-04-29 16:37:50 +00003136 objc_protocol = true;
Chris Lattner388f6e92008-07-21 21:33:21 +00003137 }
Mike Stump11289f42009-09-09 15:08:12 +00003138
Steve Naroffd9803712009-04-29 16:37:50 +00003139 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
3140 Result += PDecl->getNameAsString();
3141 Result += " __attribute__ ((used, section (\"__OBJC, __protocol\")))= "
3142 "{\n\t0, \"";
3143 Result += PDecl->getNameAsString();
3144 Result += "\", 0, ";
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003145 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
Steve Naroffd9803712009-04-29 16:37:50 +00003146 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
3147 Result += PDecl->getNameAsString();
3148 Result += ", ";
3149 }
3150 else
3151 Result += "0, ";
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003152 if (PDecl->classmeth_begin() != PDecl->classmeth_end()) {
Steve Naroffd9803712009-04-29 16:37:50 +00003153 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLASS_METHODS_";
3154 Result += PDecl->getNameAsString();
3155 Result += "\n";
3156 }
3157 else
3158 Result += "0\n";
3159 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003160
Steve Naroffd9803712009-04-29 16:37:50 +00003161 // Mark this protocol as having been generated.
3162 if (!ObjCSynthesizedProtocols.insert(PDecl))
3163 assert(false && "protocol already synthesized");
3164
3165}
3166
3167void RewriteObjC::
3168RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> &Protocols,
3169 const char *prefix, const char *ClassName,
3170 std::string &Result) {
3171 if (Protocols.empty()) return;
Mike Stump11289f42009-09-09 15:08:12 +00003172
Steve Naroffd9803712009-04-29 16:37:50 +00003173 for (unsigned i = 0; i != Protocols.size(); i++)
3174 RewriteObjCProtocolMetaData(Protocols[i], prefix, ClassName, Result);
3175
Chris Lattner388f6e92008-07-21 21:33:21 +00003176 // Output the top lovel protocol meta-data for the class.
3177 /* struct _objc_protocol_list {
3178 struct _objc_protocol_list *next;
3179 int protocol_count;
3180 struct _objc_protocol *class_protocols[];
3181 }
3182 */
3183 Result += "\nstatic struct {\n";
3184 Result += "\tstruct _objc_protocol_list *next;\n";
3185 Result += "\tint protocol_count;\n";
3186 Result += "\tstruct _objc_protocol *class_protocols[";
3187 Result += utostr(Protocols.size());
3188 Result += "];\n} _OBJC_";
3189 Result += prefix;
3190 Result += "_PROTOCOLS_";
3191 Result += ClassName;
3192 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
3193 "{\n\t0, ";
3194 Result += utostr(Protocols.size());
3195 Result += "\n";
Mike Stump11289f42009-09-09 15:08:12 +00003196
Chris Lattner388f6e92008-07-21 21:33:21 +00003197 Result += "\t,{&_OBJC_PROTOCOL_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003198 Result += Protocols[0]->getNameAsString();
Chris Lattner388f6e92008-07-21 21:33:21 +00003199 Result += " \n";
Mike Stump11289f42009-09-09 15:08:12 +00003200
Chris Lattner388f6e92008-07-21 21:33:21 +00003201 for (unsigned i = 1; i != Protocols.size(); i++) {
3202 Result += "\t ,&_OBJC_PROTOCOL_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003203 Result += Protocols[i]->getNameAsString();
Chris Lattner388f6e92008-07-21 21:33:21 +00003204 Result += "\n";
3205 }
3206 Result += "\t }\n};\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003207}
3208
Steve Naroffd9803712009-04-29 16:37:50 +00003209
Mike Stump11289f42009-09-09 15:08:12 +00003210/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003211/// implementation.
Steve Naroff1dc53ef2008-04-14 22:03:09 +00003212void RewriteObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003213 std::string &Result) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003214 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003215 // Find category declaration for this implementation.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003216 ObjCCategoryDecl *CDecl;
Mike Stump11289f42009-09-09 15:08:12 +00003217 for (CDecl = ClassDecl->getCategoryList(); CDecl;
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003218 CDecl = CDecl->getNextClassCategory())
3219 if (CDecl->getIdentifier() == IDecl->getIdentifier())
3220 break;
Mike Stump11289f42009-09-09 15:08:12 +00003221
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003222 std::string FullCategoryName = ClassDecl->getNameAsString();
Chris Lattnerb907c3f2007-12-23 01:40:15 +00003223 FullCategoryName += '_';
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003224 FullCategoryName += IDecl->getNameAsString();
Mike Stump11289f42009-09-09 15:08:12 +00003225
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003226 // Build _objc_method_list for class's instance methods if needed
Mike Stump11289f42009-09-09 15:08:12 +00003227 llvm::SmallVector<ObjCMethodDecl *, 32>
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003228 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003229
3230 // If any of our property implementations have associated getters or
3231 // setters, produce metadata for them as well.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003232 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
3233 PropEnd = IDecl->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003234 Prop != PropEnd; ++Prop) {
3235 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
3236 continue;
3237 if (!(*Prop)->getPropertyIvarDecl())
3238 continue;
3239 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
3240 if (!PD)
3241 continue;
3242 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
3243 InstanceMethods.push_back(Getter);
3244 if (PD->isReadOnly())
3245 continue;
3246 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
3247 InstanceMethods.push_back(Setter);
3248 }
3249 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
Chris Lattnerb907c3f2007-12-23 01:40:15 +00003250 true, "CATEGORY_", FullCategoryName.c_str(),
3251 Result);
Mike Stump11289f42009-09-09 15:08:12 +00003252
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003253 // Build _objc_method_list for class's class methods if needed
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003254 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnerb907c3f2007-12-23 01:40:15 +00003255 false, "CATEGORY_", FullCategoryName.c_str(),
3256 Result);
Mike Stump11289f42009-09-09 15:08:12 +00003257
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003258 // Protocols referenced in class declaration?
Fariborz Jahanian989e0392007-11-13 22:09:49 +00003259 // Null CDecl is case of a category implementation with no category interface
3260 if (CDecl)
Steve Naroffd9803712009-04-29 16:37:50 +00003261 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(), "CATEGORY",
3262 FullCategoryName.c_str(), Result);
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003263 /* struct _objc_category {
3264 char *category_name;
3265 char *class_name;
3266 struct _objc_method_list *instance_methods;
3267 struct _objc_method_list *class_methods;
3268 struct _objc_protocol_list *protocols;
3269 // Objective-C 1.0 extensions
3270 uint32_t size; // sizeof (struct _objc_category)
Mike Stump11289f42009-09-09 15:08:12 +00003271 struct _objc_property_list *instance_properties; // category's own
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003272 // @property decl.
Mike Stump11289f42009-09-09 15:08:12 +00003273 };
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003274 */
Mike Stump11289f42009-09-09 15:08:12 +00003275
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003276 static bool objc_category = false;
3277 if (!objc_category) {
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003278 Result += "\nstruct _objc_category {\n";
3279 Result += "\tchar *category_name;\n";
3280 Result += "\tchar *class_name;\n";
3281 Result += "\tstruct _objc_method_list *instance_methods;\n";
3282 Result += "\tstruct _objc_method_list *class_methods;\n";
3283 Result += "\tstruct _objc_protocol_list *protocols;\n";
Mike Stump11289f42009-09-09 15:08:12 +00003284 Result += "\tunsigned int size;\n";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003285 Result += "\tstruct _objc_property_list *instance_properties;\n";
3286 Result += "};\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003287 objc_category = true;
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00003288 }
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003289 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
3290 Result += FullCategoryName;
Steve Naroffb327e492008-03-12 17:18:30 +00003291 Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003292 Result += IDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003293 Result += "\"\n\t, \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003294 Result += ClassDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003295 Result += "\"\n";
Mike Stump11289f42009-09-09 15:08:12 +00003296
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003297 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003298 Result += "\t, (struct _objc_method_list *)"
3299 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
3300 Result += FullCategoryName;
3301 Result += "\n";
3302 }
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003303 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003304 Result += "\t, 0\n";
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003305 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003306 Result += "\t, (struct _objc_method_list *)"
3307 "&_OBJC_CATEGORY_CLASS_METHODS_";
3308 Result += FullCategoryName;
3309 Result += "\n";
3310 }
3311 else
3312 Result += "\t, 0\n";
Mike Stump11289f42009-09-09 15:08:12 +00003313
Chris Lattnerf5b77512009-02-20 18:18:36 +00003314 if (CDecl && CDecl->protocol_begin() != CDecl->protocol_end()) {
Mike Stump11289f42009-09-09 15:08:12 +00003315 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003316 Result += FullCategoryName;
3317 Result += "\n";
3318 }
3319 else
3320 Result += "\t, 0\n";
3321 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003322}
3323
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003324/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
3325/// ivar offset.
Mike Stump11289f42009-09-09 15:08:12 +00003326void RewriteObjC::SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
3327 ObjCIvarDecl *ivar,
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003328 std::string &Result) {
Steve Naroffde7d0f62008-07-16 18:22:22 +00003329 if (ivar->isBitField()) {
3330 // FIXME: The hack below doesn't work for bitfields. For now, we simply
3331 // place all bitfields at offset 0.
3332 Result += "0";
3333 } else {
3334 Result += "__OFFSETOFIVAR__(struct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003335 Result += IDecl->getNameAsString();
Steve Naroffde7d0f62008-07-16 18:22:22 +00003336 if (LangOpts.Microsoft)
3337 Result += "_IMPL";
3338 Result += ", ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003339 Result += ivar->getNameAsString();
Steve Naroffde7d0f62008-07-16 18:22:22 +00003340 Result += ")";
3341 }
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003342}
3343
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003344//===----------------------------------------------------------------------===//
3345// Meta Data Emission
3346//===----------------------------------------------------------------------===//
3347
Steve Naroff1dc53ef2008-04-14 22:03:09 +00003348void RewriteObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003349 std::string &Result) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003350 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
Mike Stump11289f42009-09-09 15:08:12 +00003351
Fariborz Jahanian96502af2007-11-26 20:59:57 +00003352 // Explictly declared @interface's are already synthesized.
Steve Naroffaac654a2009-04-20 20:09:33 +00003353 if (CDecl->isImplicitInterfaceDecl()) {
Mike Stump11289f42009-09-09 15:08:12 +00003354 // FIXME: Implementation of a class with no @interface (legacy) doese not
Fariborz Jahanian96502af2007-11-26 20:59:57 +00003355 // produce correct synthesis as yet.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003356 SynthesizeObjCInternalStruct(CDecl, Result);
Fariborz Jahanian96502af2007-11-26 20:59:57 +00003357 }
Mike Stump11289f42009-09-09 15:08:12 +00003358
Chris Lattner30d23e82007-12-12 07:56:42 +00003359 // Build _objc_ivar_list metadata for classes ivars if needed
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003360 unsigned NumIvars = !IDecl->ivar_empty()
Mike Stump11289f42009-09-09 15:08:12 +00003361 ? IDecl->ivar_size()
Chris Lattner8d1c04f2008-03-16 21:08:55 +00003362 : (CDecl ? CDecl->ivar_size() : 0);
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003363 if (NumIvars > 0) {
3364 static bool objc_ivar = false;
3365 if (!objc_ivar) {
3366 /* struct _objc_ivar {
3367 char *ivar_name;
3368 char *ivar_type;
3369 int ivar_offset;
Mike Stump11289f42009-09-09 15:08:12 +00003370 };
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003371 */
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003372 Result += "\nstruct _objc_ivar {\n";
3373 Result += "\tchar *ivar_name;\n";
3374 Result += "\tchar *ivar_type;\n";
3375 Result += "\tint ivar_offset;\n";
3376 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003377
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003378 objc_ivar = true;
3379 }
3380
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003381 /* struct {
3382 int ivar_count;
3383 struct _objc_ivar ivar_list[nIvars];
Mike Stump11289f42009-09-09 15:08:12 +00003384 };
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003385 */
Mike Stump11289f42009-09-09 15:08:12 +00003386 Result += "\nstatic struct {\n";
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003387 Result += "\tint ivar_count;\n";
3388 Result += "\tstruct _objc_ivar ivar_list[";
3389 Result += utostr(NumIvars);
3390 Result += "];\n} _OBJC_INSTANCE_VARIABLES_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003391 Result += IDecl->getNameAsString();
Steve Naroffb327e492008-03-12 17:18:30 +00003392 Result += " __attribute__ ((used, section (\"__OBJC, __instance_vars\")))= "
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003393 "{\n\t";
3394 Result += utostr(NumIvars);
3395 Result += "\n";
Mike Stump11289f42009-09-09 15:08:12 +00003396
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003397 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
Douglas Gregor5f662052009-04-23 03:23:08 +00003398 llvm::SmallVector<ObjCIvarDecl *, 8> IVars;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003399 if (!IDecl->ivar_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00003400 for (ObjCImplementationDecl::ivar_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003401 IV = IDecl->ivar_begin(), IVEnd = IDecl->ivar_end();
Douglas Gregor5f662052009-04-23 03:23:08 +00003402 IV != IVEnd; ++IV)
3403 IVars.push_back(*IV);
3404 IVI = IVars.begin();
3405 IVE = IVars.end();
Chris Lattner30d23e82007-12-12 07:56:42 +00003406 } else {
3407 IVI = CDecl->ivar_begin();
3408 IVE = CDecl->ivar_end();
3409 }
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003410 Result += "\t,{{\"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003411 Result += (*IVI)->getNameAsString();
Fariborz Jahanianbc275932007-10-29 17:16:25 +00003412 Result += "\", \"";
Steve Naroffd9803712009-04-29 16:37:50 +00003413 std::string TmpString, StrEncoding;
3414 Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
3415 QuoteDoublequotes(TmpString, StrEncoding);
Fariborz Jahanianbc275932007-10-29 17:16:25 +00003416 Result += StrEncoding;
3417 Result += "\", ";
Chris Lattner30d23e82007-12-12 07:56:42 +00003418 SynthesizeIvarOffsetComputation(IDecl, *IVI, Result);
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003419 Result += "}\n";
Chris Lattner30d23e82007-12-12 07:56:42 +00003420 for (++IVI; IVI != IVE; ++IVI) {
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003421 Result += "\t ,{\"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003422 Result += (*IVI)->getNameAsString();
Fariborz Jahanianbc275932007-10-29 17:16:25 +00003423 Result += "\", \"";
Steve Naroffd9803712009-04-29 16:37:50 +00003424 std::string TmpString, StrEncoding;
3425 Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
3426 QuoteDoublequotes(TmpString, StrEncoding);
Fariborz Jahanianbc275932007-10-29 17:16:25 +00003427 Result += StrEncoding;
3428 Result += "\", ";
Chris Lattner30d23e82007-12-12 07:56:42 +00003429 SynthesizeIvarOffsetComputation(IDecl, (*IVI), Result);
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003430 Result += "}\n";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003431 }
Mike Stump11289f42009-09-09 15:08:12 +00003432
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003433 Result += "\t }\n};\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003434 }
Mike Stump11289f42009-09-09 15:08:12 +00003435
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003436 // Build _objc_method_list for class's instance methods if needed
Mike Stump11289f42009-09-09 15:08:12 +00003437 llvm::SmallVector<ObjCMethodDecl *, 32>
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003438 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003439
3440 // If any of our property implementations have associated getters or
3441 // setters, produce metadata for them as well.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003442 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
3443 PropEnd = IDecl->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003444 Prop != PropEnd; ++Prop) {
3445 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
3446 continue;
3447 if (!(*Prop)->getPropertyIvarDecl())
3448 continue;
3449 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
3450 if (!PD)
3451 continue;
3452 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
3453 InstanceMethods.push_back(Getter);
3454 if (PD->isReadOnly())
3455 continue;
3456 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
3457 InstanceMethods.push_back(Setter);
3458 }
3459 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
Chris Lattner86d7d912008-11-24 03:54:41 +00003460 true, "", IDecl->getNameAsCString(), Result);
Mike Stump11289f42009-09-09 15:08:12 +00003461
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003462 // Build _objc_method_list for class's class methods if needed
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003463 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattner86d7d912008-11-24 03:54:41 +00003464 false, "", IDecl->getNameAsCString(), Result);
Mike Stump11289f42009-09-09 15:08:12 +00003465
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003466 // Protocols referenced in class declaration?
Steve Naroffd9803712009-04-29 16:37:50 +00003467 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(),
3468 "CLASS", CDecl->getNameAsCString(), Result);
Mike Stump11289f42009-09-09 15:08:12 +00003469
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003470 // Declaration of class/meta-class metadata
3471 /* struct _objc_class {
3472 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003473 const char *super_class_name;
3474 char *name;
3475 long version;
3476 long info;
3477 long instance_size;
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003478 struct _objc_ivar_list *ivars;
3479 struct _objc_method_list *methods;
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003480 struct objc_cache *cache;
3481 struct objc_protocol_list *protocols;
3482 const char *ivar_layout;
3483 struct _objc_class_ext *ext;
Mike Stump11289f42009-09-09 15:08:12 +00003484 };
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003485 */
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003486 static bool objc_class = false;
3487 if (!objc_class) {
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003488 Result += "\nstruct _objc_class {\n";
3489 Result += "\tstruct _objc_class *isa;\n";
3490 Result += "\tconst char *super_class_name;\n";
3491 Result += "\tchar *name;\n";
3492 Result += "\tlong version;\n";
3493 Result += "\tlong info;\n";
3494 Result += "\tlong instance_size;\n";
3495 Result += "\tstruct _objc_ivar_list *ivars;\n";
3496 Result += "\tstruct _objc_method_list *methods;\n";
3497 Result += "\tstruct objc_cache *cache;\n";
3498 Result += "\tstruct _objc_protocol_list *protocols;\n";
3499 Result += "\tconst char *ivar_layout;\n";
3500 Result += "\tstruct _objc_class_ext *ext;\n";
3501 Result += "};\n";
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003502 objc_class = true;
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003503 }
Mike Stump11289f42009-09-09 15:08:12 +00003504
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003505 // Meta-class metadata generation.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003506 ObjCInterfaceDecl *RootClass = 0;
3507 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003508 while (SuperClass) {
3509 RootClass = SuperClass;
3510 SuperClass = SuperClass->getSuperClass();
3511 }
3512 SuperClass = CDecl->getSuperClass();
Mike Stump11289f42009-09-09 15:08:12 +00003513
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003514 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003515 Result += CDecl->getNameAsString();
Steve Naroffb327e492008-03-12 17:18:30 +00003516 Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= "
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003517 "{\n\t(struct _objc_class *)\"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003518 Result += (RootClass ? RootClass->getNameAsString() : CDecl->getNameAsString());
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003519 Result += "\"";
3520
3521 if (SuperClass) {
3522 Result += ", \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003523 Result += SuperClass->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003524 Result += "\", \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003525 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003526 Result += "\"";
3527 }
3528 else {
3529 Result += ", 0, \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003530 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003531 Result += "\"";
3532 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003533 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003534 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003535 Result += ", 0,2, sizeof(struct _objc_class), 0";
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003536 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
Steve Naroff0b844f02008-03-11 18:14:26 +00003537 Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003538 Result += IDecl->getNameAsString();
Mike Stump11289f42009-09-09 15:08:12 +00003539 Result += "\n";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003540 }
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003541 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003542 Result += ", 0\n";
Chris Lattnerf5b77512009-02-20 18:18:36 +00003543 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroff251084d2008-03-12 01:06:30 +00003544 Result += "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003545 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003546 Result += ",0,0\n";
3547 }
Fariborz Jahanian486f7182007-10-24 20:54:23 +00003548 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003549 Result += "\t,0,0,0,0\n";
3550 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003551
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003552 // class metadata generation.
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003553 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003554 Result += CDecl->getNameAsString();
Steve Naroffb327e492008-03-12 17:18:30 +00003555 Result += " __attribute__ ((used, section (\"__OBJC, __class\")))= "
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003556 "{\n\t&_OBJC_METACLASS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003557 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003558 if (SuperClass) {
3559 Result += ", \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003560 Result += SuperClass->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003561 Result += "\", \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003562 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003563 Result += "\"";
3564 }
3565 else {
3566 Result += ", 0, \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003567 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003568 Result += "\"";
3569 }
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003570 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanian801b6352007-10-26 23:09:28 +00003571 Result += ", 0,1";
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003572 if (!ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian801b6352007-10-26 23:09:28 +00003573 Result += ",0";
3574 else {
3575 // class has size. Must synthesize its size.
Fariborz Jahanian63ac80e2007-11-05 17:47:33 +00003576 Result += ",sizeof(struct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003577 Result += CDecl->getNameAsString();
Steve Naroff14a07462008-03-10 23:33:22 +00003578 if (LangOpts.Microsoft)
3579 Result += "_IMPL";
Fariborz Jahanian801b6352007-10-26 23:09:28 +00003580 Result += ")";
3581 }
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003582 if (NumIvars > 0) {
Steve Naroff17978c42008-03-11 17:37:02 +00003583 Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003584 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003585 Result += "\n\t";
3586 }
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003587 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003588 Result += ",0";
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003589 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003590 Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003591 Result += CDecl->getNameAsString();
Mike Stump11289f42009-09-09 15:08:12 +00003592 Result += ", 0\n\t";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003593 }
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003594 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003595 Result += ",0,0";
Chris Lattnerf5b77512009-02-20 18:18:36 +00003596 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroff251084d2008-03-12 01:06:30 +00003597 Result += ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003598 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003599 Result += ", 0,0\n";
3600 }
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003601 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003602 Result += ",0,0,0\n";
3603 Result += "};\n";
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003604}
Fariborz Jahanianc34409c2007-10-18 22:09:03 +00003605
Fariborz Jahanian98ba6cd2007-11-13 19:21:13 +00003606/// RewriteImplementations - This routine rewrites all method implementations
3607/// and emits meta-data.
3608
Steve Narofff8cfd162008-11-13 20:07:04 +00003609void RewriteObjC::RewriteImplementations() {
Fariborz Jahanian93191af2007-10-18 19:23:00 +00003610 int ClsDefCount = ClassImplementation.size();
3611 int CatDefCount = CategoryImplementation.size();
Mike Stump11289f42009-09-09 15:08:12 +00003612
Fariborz Jahanian98ba6cd2007-11-13 19:21:13 +00003613 // Rewrite implemented methods
3614 for (int i = 0; i < ClsDefCount; i++)
3615 RewriteImplementationDecl(ClassImplementation[i]);
Mike Stump11289f42009-09-09 15:08:12 +00003616
Fariborz Jahanianc54d8462007-11-13 20:04:28 +00003617 for (int i = 0; i < CatDefCount; i++)
3618 RewriteImplementationDecl(CategoryImplementation[i]);
Steve Narofff8cfd162008-11-13 20:07:04 +00003619}
Mike Stump11289f42009-09-09 15:08:12 +00003620
Steve Narofff8cfd162008-11-13 20:07:04 +00003621void RewriteObjC::SynthesizeMetaDataIntoBuffer(std::string &Result) {
3622 int ClsDefCount = ClassImplementation.size();
3623 int CatDefCount = CategoryImplementation.size();
3624
Steve Naroff30ac2222008-05-07 21:23:49 +00003625 // This is needed for determining instance variable offsets.
Mike Stump11289f42009-09-09 15:08:12 +00003626 Result += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((int) &((TYPE *)0)->MEMBER)\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003627 // For each implemented class, write out all its meta data.
Fariborz Jahanianc34409c2007-10-18 22:09:03 +00003628 for (int i = 0; i < ClsDefCount; i++)
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003629 RewriteObjCClassMetaData(ClassImplementation[i], Result);
Mike Stump11289f42009-09-09 15:08:12 +00003630
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003631 // For each implemented category, write out all its meta data.
3632 for (int i = 0; i < CatDefCount; i++)
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003633 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
Steve Naroffd9803712009-04-29 16:37:50 +00003634
Fariborz Jahanian93191af2007-10-18 19:23:00 +00003635 // Write objc_symtab metadata
3636 /*
3637 struct _objc_symtab
3638 {
3639 long sel_ref_cnt;
3640 SEL *refs;
3641 short cls_def_cnt;
3642 short cat_def_cnt;
3643 void *defs[cls_def_cnt + cat_def_cnt];
Mike Stump11289f42009-09-09 15:08:12 +00003644 };
Fariborz Jahanian93191af2007-10-18 19:23:00 +00003645 */
Mike Stump11289f42009-09-09 15:08:12 +00003646
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003647 Result += "\nstruct _objc_symtab {\n";
3648 Result += "\tlong sel_ref_cnt;\n";
3649 Result += "\tSEL *refs;\n";
3650 Result += "\tshort cls_def_cnt;\n";
3651 Result += "\tshort cat_def_cnt;\n";
3652 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
3653 Result += "};\n\n";
Mike Stump11289f42009-09-09 15:08:12 +00003654
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003655 Result += "static struct _objc_symtab "
Steve Naroffb327e492008-03-12 17:18:30 +00003656 "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
Mike Stump11289f42009-09-09 15:08:12 +00003657 Result += "\t0, 0, " + utostr(ClsDefCount)
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003658 + ", " + utostr(CatDefCount) + "\n";
3659 for (int i = 0; i < ClsDefCount; i++) {
3660 Result += "\t,&_OBJC_CLASS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003661 Result += ClassImplementation[i]->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003662 Result += "\n";
3663 }
Mike Stump11289f42009-09-09 15:08:12 +00003664
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003665 for (int i = 0; i < CatDefCount; i++) {
3666 Result += "\t,&_OBJC_CATEGORY_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003667 Result += CategoryImplementation[i]->getClassInterface()->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003668 Result += "_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003669 Result += CategoryImplementation[i]->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003670 Result += "\n";
3671 }
Mike Stump11289f42009-09-09 15:08:12 +00003672
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003673 Result += "};\n\n";
Mike Stump11289f42009-09-09 15:08:12 +00003674
Fariborz Jahanian93191af2007-10-18 19:23:00 +00003675 // Write objc_module metadata
Mike Stump11289f42009-09-09 15:08:12 +00003676
Fariborz Jahanian93191af2007-10-18 19:23:00 +00003677 /*
3678 struct _objc_module {
3679 long version;
3680 long size;
3681 const char *name;
3682 struct _objc_symtab *symtab;
3683 }
3684 */
Mike Stump11289f42009-09-09 15:08:12 +00003685
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003686 Result += "\nstruct _objc_module {\n";
3687 Result += "\tlong version;\n";
3688 Result += "\tlong size;\n";
3689 Result += "\tconst char *name;\n";
3690 Result += "\tstruct _objc_symtab *symtab;\n";
3691 Result += "};\n\n";
3692 Result += "static struct _objc_module "
Steve Naroffb327e492008-03-12 17:18:30 +00003693 "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
Mike Stump11289f42009-09-09 15:08:12 +00003694 Result += "\t" + utostr(OBJC_ABI_VERSION) +
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003695 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003696 Result += "};\n\n";
Steve Naroff945a3b12008-03-10 20:43:59 +00003697
3698 if (LangOpts.Microsoft) {
Steve Naroffd9803712009-04-29 16:37:50 +00003699 if (ProtocolExprDecls.size()) {
3700 Result += "#pragma section(\".objc_protocol$B\",long,read,write)\n";
3701 Result += "#pragma data_seg(push, \".objc_protocol$B\")\n";
Mike Stump11289f42009-09-09 15:08:12 +00003702 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Steve Naroffd9803712009-04-29 16:37:50 +00003703 E = ProtocolExprDecls.end(); I != E; ++I) {
3704 Result += "static struct _objc_protocol *_POINTER_OBJC_PROTOCOL_";
3705 Result += (*I)->getNameAsString();
3706 Result += " = &_OBJC_PROTOCOL_";
3707 Result += (*I)->getNameAsString();
3708 Result += ";\n";
3709 }
3710 Result += "#pragma data_seg(pop)\n\n";
3711 }
Steve Naroff945a3b12008-03-10 20:43:59 +00003712 Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
Steve Naroffcab93d52008-05-07 00:06:16 +00003713 Result += "#pragma data_seg(push, \".objc_module_info$B\")\n";
Steve Naroff945a3b12008-03-10 20:43:59 +00003714 Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
3715 Result += "&_OBJC_MODULES;\n";
3716 Result += "#pragma data_seg(pop)\n\n";
3717 }
Fariborz Jahanian93191af2007-10-18 19:23:00 +00003718}
Chris Lattnera7c19fe2007-10-16 22:36:42 +00003719
Steve Naroff677ab3a2008-10-27 17:20:55 +00003720std::string RewriteObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
3721 const char *funcName,
3722 std::string Tag) {
3723 const FunctionType *AFT = CE->getFunctionType();
3724 QualType RT = AFT->getResultType();
3725 std::string StructRef = "struct " + Tag;
3726 std::string S = "static " + RT.getAsString() + " __" +
3727 funcName + "_" + "block_func_" + utostr(i);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00003728
Steve Naroff677ab3a2008-10-27 17:20:55 +00003729 BlockDecl *BD = CE->getBlockDecl();
Mike Stump11289f42009-09-09 15:08:12 +00003730
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003731 if (isa<FunctionNoProtoType>(AFT)) {
Mike Stump11289f42009-09-09 15:08:12 +00003732 // No user-supplied arguments. Still need to pass in a pointer to the
Steve Narofff26a1d42009-02-02 17:19:26 +00003733 // block (to reference imported block decl refs).
3734 S += "(" + StructRef + " *__cself)";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003735 } else if (BD->param_empty()) {
3736 S += "(" + StructRef + " *__cself)";
3737 } else {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003738 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
Steve Naroff677ab3a2008-10-27 17:20:55 +00003739 assert(FT && "SynthesizeBlockFunc: No function proto");
3740 S += '(';
3741 // first add the implicit argument.
3742 S += StructRef + " *__cself, ";
3743 std::string ParamStr;
3744 for (BlockDecl::param_iterator AI = BD->param_begin(),
3745 E = BD->param_end(); AI != E; ++AI) {
3746 if (AI != BD->param_begin()) S += ", ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003747 ParamStr = (*AI)->getNameAsString();
Douglas Gregor7de59662009-05-29 20:38:28 +00003748 (*AI)->getType().getAsStringInternal(ParamStr, Context->PrintingPolicy);
Steve Naroff677ab3a2008-10-27 17:20:55 +00003749 S += ParamStr;
3750 }
3751 if (FT->isVariadic()) {
3752 if (!BD->param_empty()) S += ", ";
3753 S += "...";
3754 }
3755 S += ')';
3756 }
3757 S += " {\n";
Mike Stump11289f42009-09-09 15:08:12 +00003758
Steve Naroff677ab3a2008-10-27 17:20:55 +00003759 // Create local declarations to avoid rewriting all closure decl ref exprs.
3760 // First, emit a declaration for all "by ref" decls.
Mike Stump11289f42009-09-09 15:08:12 +00003761 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003762 E = BlockByRefDecls.end(); I != E; ++I) {
3763 S += " ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003764 std::string Name = (*I)->getNameAsString();
Fariborz Jahanian02e07732009-12-23 02:07:37 +00003765 std::string TypeString = "struct __Block_byref_" + Name + " *";
3766 Name = TypeString + Name;
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003767 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
Mike Stump11289f42009-09-09 15:08:12 +00003768 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00003769 // Next, emit a declaration for all "by copy" declarations.
Mike Stump11289f42009-09-09 15:08:12 +00003770 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003771 E = BlockByCopyDecls.end(); I != E; ++I) {
3772 S += " ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003773 std::string Name = (*I)->getNameAsString();
Steve Naroff677ab3a2008-10-27 17:20:55 +00003774 // Handle nested closure invocation. For example:
3775 //
3776 // void (^myImportedClosure)(void);
3777 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
Mike Stump11289f42009-09-09 15:08:12 +00003778 //
Steve Naroff677ab3a2008-10-27 17:20:55 +00003779 // void (^anotherClosure)(void);
3780 // anotherClosure = ^(void) {
3781 // myImportedClosure(); // import and invoke the closure
3782 // };
3783 //
Steve Naroffa5c0db82008-12-11 21:05:33 +00003784 if (isTopLevelBlockPointerType((*I)->getType()))
Steve Naroff677ab3a2008-10-27 17:20:55 +00003785 S += "struct __block_impl *";
3786 else
Douglas Gregor7de59662009-05-29 20:38:28 +00003787 (*I)->getType().getAsStringInternal(Name, Context->PrintingPolicy);
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003788 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003789 }
3790 std::string RewrittenStr = RewrittenBlockExprs[CE];
3791 const char *cstr = RewrittenStr.c_str();
3792 while (*cstr++ != '{') ;
3793 S += cstr;
3794 S += "\n";
3795 return S;
3796}
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00003797
Steve Naroff677ab3a2008-10-27 17:20:55 +00003798std::string RewriteObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
3799 const char *funcName,
3800 std::string Tag) {
3801 std::string StructRef = "struct " + Tag;
3802 std::string S = "static void __";
Mike Stump11289f42009-09-09 15:08:12 +00003803
Steve Naroff677ab3a2008-10-27 17:20:55 +00003804 S += funcName;
3805 S += "_block_copy_" + utostr(i);
3806 S += "(" + StructRef;
3807 S += "*dst, " + StructRef;
3808 S += "*src) {";
Mike Stump11289f42009-09-09 15:08:12 +00003809 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003810 E = ImportedBlockDecls.end(); I != E; ++I) {
Steve Naroff61d879e2008-12-16 15:50:30 +00003811 S += "_Block_object_assign((void*)&dst->";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003812 S += (*I)->getNameAsString();
Steve Naroff5ac4eac2008-12-11 20:51:38 +00003813 S += ", (void*)src->";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003814 S += (*I)->getNameAsString();
Fariborz Jahaniancbdcfe82009-12-23 20:32:38 +00003815 if (BlockByRefDecls.count((*I)))
Fariborz Jahanian4bf727d2009-12-23 21:18:41 +00003816 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
Fariborz Jahaniancbdcfe82009-12-23 20:32:38 +00003817 else
Fariborz Jahanian4bf727d2009-12-23 21:18:41 +00003818 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003819 }
Fariborz Jahaniancbdcfe82009-12-23 20:32:38 +00003820 S += "}\n";
3821
Steve Naroff677ab3a2008-10-27 17:20:55 +00003822 S += "\nstatic void __";
3823 S += funcName;
3824 S += "_block_dispose_" + utostr(i);
3825 S += "(" + StructRef;
3826 S += "*src) {";
Mike Stump11289f42009-09-09 15:08:12 +00003827 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003828 E = ImportedBlockDecls.end(); I != E; ++I) {
Steve Naroff61d879e2008-12-16 15:50:30 +00003829 S += "_Block_object_dispose((void*)src->";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003830 S += (*I)->getNameAsString();
Fariborz Jahaniancbdcfe82009-12-23 20:32:38 +00003831 if (BlockByRefDecls.count((*I)))
Fariborz Jahanian4bf727d2009-12-23 21:18:41 +00003832 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
Fariborz Jahaniancbdcfe82009-12-23 20:32:38 +00003833 else
Fariborz Jahanian4bf727d2009-12-23 21:18:41 +00003834 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003835 }
Mike Stump11289f42009-09-09 15:08:12 +00003836 S += "}\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003837 return S;
3838}
3839
Steve Naroff30484702009-12-06 21:14:13 +00003840std::string RewriteObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
3841 std::string Desc) {
Steve Naroff295570a2008-10-30 12:09:33 +00003842 std::string S = "\nstruct " + Tag;
Steve Naroff677ab3a2008-10-27 17:20:55 +00003843 std::string Constructor = " " + Tag;
Mike Stump11289f42009-09-09 15:08:12 +00003844
Steve Naroff677ab3a2008-10-27 17:20:55 +00003845 S += " {\n struct __block_impl impl;\n";
Steve Naroff30484702009-12-06 21:14:13 +00003846 S += " struct " + Desc;
3847 S += "* Desc;\n";
Mike Stump11289f42009-09-09 15:08:12 +00003848
Steve Naroff30484702009-12-06 21:14:13 +00003849 Constructor += "(void *fp, "; // Invoke function pointer.
3850 Constructor += "struct " + Desc; // Descriptor pointer.
3851 Constructor += " *desc";
Mike Stump11289f42009-09-09 15:08:12 +00003852
Steve Naroff677ab3a2008-10-27 17:20:55 +00003853 if (BlockDeclRefs.size()) {
3854 // Output all "by copy" declarations.
Mike Stump11289f42009-09-09 15:08:12 +00003855 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003856 E = BlockByCopyDecls.end(); I != E; ++I) {
3857 S += " ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003858 std::string FieldName = (*I)->getNameAsString();
Steve Naroff677ab3a2008-10-27 17:20:55 +00003859 std::string ArgName = "_" + FieldName;
3860 // Handle nested closure invocation. For example:
3861 //
3862 // void (^myImportedBlock)(void);
3863 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
Mike Stump11289f42009-09-09 15:08:12 +00003864 //
Steve Naroff677ab3a2008-10-27 17:20:55 +00003865 // void (^anotherBlock)(void);
3866 // anotherBlock = ^(void) {
3867 // myImportedBlock(); // import and invoke the closure
3868 // };
3869 //
Steve Naroffa5c0db82008-12-11 21:05:33 +00003870 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00003871 S += "struct __block_impl *";
3872 Constructor += ", void *" + ArgName;
3873 } else {
Douglas Gregor7de59662009-05-29 20:38:28 +00003874 (*I)->getType().getAsStringInternal(FieldName, Context->PrintingPolicy);
3875 (*I)->getType().getAsStringInternal(ArgName, Context->PrintingPolicy);
Steve Naroff677ab3a2008-10-27 17:20:55 +00003876 Constructor += ", " + ArgName;
3877 }
3878 S += FieldName + ";\n";
3879 }
3880 // Output all "by ref" declarations.
Mike Stump11289f42009-09-09 15:08:12 +00003881 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003882 E = BlockByRefDecls.end(); I != E; ++I) {
3883 S += " ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003884 std::string FieldName = (*I)->getNameAsString();
Steve Naroff677ab3a2008-10-27 17:20:55 +00003885 std::string ArgName = "_" + FieldName;
3886 // Handle nested closure invocation. For example:
3887 //
3888 // void (^myImportedBlock)(void);
3889 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
Mike Stump11289f42009-09-09 15:08:12 +00003890 //
Steve Naroff677ab3a2008-10-27 17:20:55 +00003891 // void (^anotherBlock)(void);
3892 // anotherBlock = ^(void) {
3893 // myImportedBlock(); // import and invoke the closure
3894 // };
3895 //
Steve Naroffa5c0db82008-12-11 21:05:33 +00003896 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00003897 S += "struct __block_impl *";
3898 Constructor += ", void *" + ArgName;
3899 } else {
Fariborz Jahanian02e07732009-12-23 02:07:37 +00003900 std::string TypeString = "struct __Block_byref_" + FieldName;
3901 TypeString += " *";
3902 FieldName = TypeString + FieldName;
3903 ArgName = TypeString + ArgName;
Steve Naroff677ab3a2008-10-27 17:20:55 +00003904 Constructor += ", " + ArgName;
3905 }
3906 S += FieldName + "; // by ref\n";
3907 }
3908 // Finish writing the constructor.
Steve Naroff677ab3a2008-10-27 17:20:55 +00003909 Constructor += ", int flags=0) {\n";
Steve Naroffd9803712009-04-29 16:37:50 +00003910 if (GlobalVarDecl)
3911 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
3912 else
3913 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Steve Naroff30484702009-12-06 21:14:13 +00003914 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
Mike Stump11289f42009-09-09 15:08:12 +00003915
Steve Naroff30484702009-12-06 21:14:13 +00003916 Constructor += " Desc = desc;\n";
Mike Stump11289f42009-09-09 15:08:12 +00003917
Steve Naroff677ab3a2008-10-27 17:20:55 +00003918 // Initialize all "by copy" arguments.
Mike Stump11289f42009-09-09 15:08:12 +00003919 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003920 E = BlockByCopyDecls.end(); I != E; ++I) {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003921 std::string Name = (*I)->getNameAsString();
Steve Naroff677ab3a2008-10-27 17:20:55 +00003922 Constructor += " ";
Steve Naroffa5c0db82008-12-11 21:05:33 +00003923 if (isTopLevelBlockPointerType((*I)->getType()))
Steve Naroff677ab3a2008-10-27 17:20:55 +00003924 Constructor += Name + " = (struct __block_impl *)_";
3925 else
3926 Constructor += Name + " = _";
3927 Constructor += Name + ";\n";
3928 }
3929 // Initialize all "by ref" arguments.
Mike Stump11289f42009-09-09 15:08:12 +00003930 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003931 E = BlockByRefDecls.end(); I != E; ++I) {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003932 std::string Name = (*I)->getNameAsString();
Steve Naroff677ab3a2008-10-27 17:20:55 +00003933 Constructor += " ";
Steve Naroffa5c0db82008-12-11 21:05:33 +00003934 if (isTopLevelBlockPointerType((*I)->getType()))
Steve Naroff677ab3a2008-10-27 17:20:55 +00003935 Constructor += Name + " = (struct __block_impl *)_";
3936 else
3937 Constructor += Name + " = _";
Fariborz Jahanian02e07732009-12-23 02:07:37 +00003938 Constructor += Name + "->__forwarding;\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003939 }
3940 } else {
3941 // Finish writing the constructor.
Steve Naroff677ab3a2008-10-27 17:20:55 +00003942 Constructor += ", int flags=0) {\n";
Steve Naroffd9803712009-04-29 16:37:50 +00003943 if (GlobalVarDecl)
3944 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
3945 else
3946 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Steve Naroff30484702009-12-06 21:14:13 +00003947 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3948 Constructor += " Desc = desc;\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003949 }
3950 Constructor += " ";
3951 Constructor += "}\n";
3952 S += Constructor;
3953 S += "};\n";
3954 return S;
3955}
3956
Steve Naroff30484702009-12-06 21:14:13 +00003957std::string RewriteObjC::SynthesizeBlockDescriptor(std::string DescTag,
3958 std::string ImplTag, int i,
3959 const char *FunName,
3960 unsigned hasCopy) {
3961 std::string S = "\nstatic struct " + DescTag;
3962
3963 S += " {\n unsigned long reserved;\n";
3964 S += " unsigned long Block_size;\n";
3965 if (hasCopy) {
Fariborz Jahaniane175eeb2009-12-21 23:31:42 +00003966 S += " void (*copy)(struct ";
3967 S += ImplTag; S += "*, struct ";
3968 S += ImplTag; S += "*);\n";
3969
3970 S += " void (*dispose)(struct ";
3971 S += ImplTag; S += "*);\n";
Steve Naroff30484702009-12-06 21:14:13 +00003972 }
3973 S += "} ";
3974
3975 S += DescTag + "_DATA = { 0, sizeof(struct ";
3976 S += ImplTag + ")";
3977 if (hasCopy) {
3978 S += ", __" + std::string(FunName) + "_block_copy_" + utostr(i);
3979 S += ", __" + std::string(FunName) + "_block_dispose_" + utostr(i);
3980 }
3981 S += "};\n";
3982 return S;
3983}
3984
Steve Naroff677ab3a2008-10-27 17:20:55 +00003985void RewriteObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
3986 const char *FunName) {
3987 // Insert closures that were part of the function.
3988 for (unsigned i = 0; i < Blocks.size(); i++) {
3989
3990 CollectBlockDeclRefInfo(Blocks[i]);
3991
Steve Naroff30484702009-12-06 21:14:13 +00003992 std::string ImplTag = "__" + std::string(FunName) + "_block_impl_" + utostr(i);
3993 std::string DescTag = "__" + std::string(FunName) + "_block_desc_" + utostr(i);
Mike Stump11289f42009-09-09 15:08:12 +00003994
Steve Naroff30484702009-12-06 21:14:13 +00003995 std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
Steve Naroff677ab3a2008-10-27 17:20:55 +00003996
3997 InsertText(FunLocStart, CI.c_str(), CI.size());
3998
Steve Naroff30484702009-12-06 21:14:13 +00003999 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
Mike Stump11289f42009-09-09 15:08:12 +00004000
Steve Naroff677ab3a2008-10-27 17:20:55 +00004001 InsertText(FunLocStart, CF.c_str(), CF.size());
4002
4003 if (ImportedBlockDecls.size()) {
Steve Naroff30484702009-12-06 21:14:13 +00004004 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004005 InsertText(FunLocStart, HF.c_str(), HF.size());
4006 }
Steve Naroff30484702009-12-06 21:14:13 +00004007 std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
4008 ImportedBlockDecls.size() > 0);
4009 InsertText(FunLocStart, BD.c_str(), BD.size());
Mike Stump11289f42009-09-09 15:08:12 +00004010
Steve Naroff677ab3a2008-10-27 17:20:55 +00004011 BlockDeclRefs.clear();
4012 BlockByRefDecls.clear();
4013 BlockByCopyDecls.clear();
4014 BlockCallExprs.clear();
4015 ImportedBlockDecls.clear();
4016 }
4017 Blocks.clear();
4018 RewrittenBlockExprs.clear();
4019}
4020
4021void RewriteObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
4022 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
Chris Lattner86d7d912008-11-24 03:54:41 +00004023 const char *FuncName = FD->getNameAsCString();
Mike Stump11289f42009-09-09 15:08:12 +00004024
Steve Naroff677ab3a2008-10-27 17:20:55 +00004025 SynthesizeBlockLiterals(FunLocStart, FuncName);
4026}
4027
4028void RewriteObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
Steve Naroff295570a2008-10-30 12:09:33 +00004029 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
4030 //SourceLocation FunLocStart = MD->getLocStart();
4031 // FIXME: This hack works around a bug in Rewrite.InsertText().
4032 SourceLocation FunLocStart = MD->getLocStart().getFileLocWithOffset(-1);
Chris Lattnere4b95692008-11-24 03:33:13 +00004033 std::string FuncName = MD->getSelector().getAsString();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004034 // Convert colons to underscores.
4035 std::string::size_type loc = 0;
4036 while ((loc = FuncName.find(":", loc)) != std::string::npos)
4037 FuncName.replace(loc, 1, "_");
Mike Stump11289f42009-09-09 15:08:12 +00004038
Steve Naroff677ab3a2008-10-27 17:20:55 +00004039 SynthesizeBlockLiterals(FunLocStart, FuncName.c_str());
4040}
4041
4042void RewriteObjC::GetBlockDeclRefExprs(Stmt *S) {
4043 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4044 CI != E; ++CI)
4045 if (*CI) {
4046 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
4047 GetBlockDeclRefExprs(CBE->getBody());
4048 else
4049 GetBlockDeclRefExprs(*CI);
4050 }
4051 // Handle specific things.
4052 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S))
4053 // FIXME: Handle enums.
4054 if (!isa<FunctionDecl>(CDRE->getDecl()))
4055 BlockDeclRefs.push_back(CDRE);
4056 return;
4057}
4058
4059void RewriteObjC::GetBlockCallExprs(Stmt *S) {
4060 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4061 CI != E; ++CI)
4062 if (*CI) {
4063 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
4064 GetBlockCallExprs(CBE->getBody());
4065 else
4066 GetBlockCallExprs(*CI);
4067 }
Mike Stump11289f42009-09-09 15:08:12 +00004068
Steve Naroff677ab3a2008-10-27 17:20:55 +00004069 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
4070 if (CE->getCallee()->getType()->isBlockPointerType()) {
4071 BlockCallExprs[dyn_cast<BlockDeclRefExpr>(CE->getCallee())] = CE;
4072 }
4073 }
4074 return;
4075}
4076
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004077Stmt *RewriteObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00004078 // Navigate to relevant type information.
Steve Naroff677ab3a2008-10-27 17:20:55 +00004079 const BlockPointerType *CPT = 0;
Mike Stump11289f42009-09-09 15:08:12 +00004080
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004081 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004082 CPT = DRE->getType()->getAs<BlockPointerType>();
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004083 } else if (const BlockDeclRefExpr *CDRE =
4084 dyn_cast<BlockDeclRefExpr>(BlockExp)) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004085 CPT = CDRE->getType()->getAs<BlockPointerType>();
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004086 } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004087 CPT = MExpr->getType()->getAs<BlockPointerType>();
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004088 }
4089 else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
4090 return SynthesizeBlockCall(Exp, PRE->getSubExpr());
4091 }
4092 else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
4093 CPT = IEXPR->getType()->getAs<BlockPointerType>();
4094 else if (const ConditionalOperator *CEXPR =
4095 dyn_cast<ConditionalOperator>(BlockExp)) {
4096 Expr *LHSExp = CEXPR->getLHS();
4097 Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
4098 Expr *RHSExp = CEXPR->getRHS();
4099 Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
4100 Expr *CONDExp = CEXPR->getCond();
4101 ConditionalOperator *CondExpr =
4102 new (Context) ConditionalOperator(CONDExp,
4103 SourceLocation(), cast<Expr>(LHSStmt),
4104 SourceLocation(), cast<Expr>(RHSStmt),
4105 Exp->getType());
4106 return CondExpr;
Fariborz Jahanian6ab7ed42009-12-18 01:15:21 +00004107 } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
4108 CPT = IRE->getType()->getAs<BlockPointerType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004109 } else {
4110 assert(1 && "RewriteBlockClass: Bad type");
4111 }
4112 assert(CPT && "RewriteBlockClass: Bad type");
John McCall9dd450b2009-09-21 23:43:11 +00004113 const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004114 assert(FT && "RewriteBlockClass: Bad type");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004115 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004116 // FTP will be null for closures that don't take arguments.
Mike Stump11289f42009-09-09 15:08:12 +00004117
Steve Naroff350b6652008-10-30 10:07:53 +00004118 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
4119 SourceLocation(),
4120 &Context->Idents.get("__block_impl"));
4121 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
Steve Naroff677ab3a2008-10-27 17:20:55 +00004122
Steve Naroff350b6652008-10-30 10:07:53 +00004123 // Generate a funky cast.
4124 llvm::SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00004125
Steve Naroff350b6652008-10-30 10:07:53 +00004126 // Push the block argument type.
4127 ArgTypes.push_back(PtrBlock);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004128 if (FTP) {
Mike Stump11289f42009-09-09 15:08:12 +00004129 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroff350b6652008-10-30 10:07:53 +00004130 E = FTP->arg_type_end(); I && (I != E); ++I) {
4131 QualType t = *I;
4132 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Steve Naroffa5c0db82008-12-11 21:05:33 +00004133 if (isTopLevelBlockPointerType(t)) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004134 const BlockPointerType *BPT = t->getAs<BlockPointerType>();
Steve Naroff350b6652008-10-30 10:07:53 +00004135 t = Context->getPointerType(BPT->getPointeeType());
4136 }
4137 ArgTypes.push_back(t);
4138 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00004139 }
Steve Naroff350b6652008-10-30 10:07:53 +00004140 // Now do the pointer to function cast.
Mike Stump11289f42009-09-09 15:08:12 +00004141 QualType PtrToFuncCastType = Context->getFunctionType(Exp->getType(),
Steve Naroff350b6652008-10-30 10:07:53 +00004142 &ArgTypes[0], ArgTypes.size(), false/*no variadic*/, 0);
Mike Stump11289f42009-09-09 15:08:12 +00004143
Steve Naroff350b6652008-10-30 10:07:53 +00004144 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
Mike Stump11289f42009-09-09 15:08:12 +00004145
4146 CastExpr *BlkCast = new (Context) CStyleCastExpr(PtrBlock,
Anders Carlssona2615922009-07-31 00:48:10 +00004147 CastExpr::CK_Unknown,
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004148 const_cast<Expr*>(BlockExp),
Ted Kremenek5a201952009-02-07 01:47:29 +00004149 PtrBlock, SourceLocation(),
4150 SourceLocation());
Steve Naroff350b6652008-10-30 10:07:53 +00004151 // Don't forget the parens to enforce the proper binding.
Ted Kremenek5a201952009-02-07 01:47:29 +00004152 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4153 BlkCast);
Steve Naroff350b6652008-10-30 10:07:53 +00004154 //PE->dump();
Mike Stump11289f42009-09-09 15:08:12 +00004155
Douglas Gregor91f84212008-12-11 16:49:14 +00004156 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00004157 &Context->Idents.get("FuncPtr"), Context->VoidPtrTy, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00004158 /*BitWidth=*/0, /*Mutable=*/true);
Ted Kremenek5a201952009-02-07 01:47:29 +00004159 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
4160 FD->getType());
Mike Stump11289f42009-09-09 15:08:12 +00004161
Anders Carlssona2615922009-07-31 00:48:10 +00004162 CastExpr *FunkCast = new (Context) CStyleCastExpr(PtrToFuncCastType,
4163 CastExpr::CK_Unknown, ME,
Ted Kremenek5a201952009-02-07 01:47:29 +00004164 PtrToFuncCastType,
4165 SourceLocation(),
4166 SourceLocation());
4167 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
Mike Stump11289f42009-09-09 15:08:12 +00004168
Steve Naroff350b6652008-10-30 10:07:53 +00004169 llvm::SmallVector<Expr*, 8> BlkExprs;
4170 // Add the implicit argument.
4171 BlkExprs.push_back(BlkCast);
4172 // Add the user arguments.
Mike Stump11289f42009-09-09 15:08:12 +00004173 for (CallExpr::arg_iterator I = Exp->arg_begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00004174 E = Exp->arg_end(); I != E; ++I) {
Steve Naroff350b6652008-10-30 10:07:53 +00004175 BlkExprs.push_back(*I);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004176 }
Ted Kremenekd7b4f402009-02-09 20:51:47 +00004177 CallExpr *CE = new (Context) CallExpr(*Context, PE, &BlkExprs[0],
4178 BlkExprs.size(),
Ted Kremenek5a201952009-02-07 01:47:29 +00004179 Exp->getType(), SourceLocation());
Steve Naroff350b6652008-10-30 10:07:53 +00004180 return CE;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004181}
4182
4183void RewriteObjC::RewriteBlockCall(CallExpr *Exp) {
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004184 Stmt *BlockCall = SynthesizeBlockCall(Exp, Exp->getCallee());
Steve Naroff350b6652008-10-30 10:07:53 +00004185 ReplaceStmt(Exp, BlockCall);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004186}
4187
Steve Naroffd9803712009-04-29 16:37:50 +00004188// We need to return the rewritten expression to handle cases where the
4189// BlockDeclRefExpr is embedded in another expression being rewritten.
4190// For example:
4191//
4192// int main() {
4193// __block Foo *f;
4194// __block int i;
Mike Stump11289f42009-09-09 15:08:12 +00004195//
Steve Naroffd9803712009-04-29 16:37:50 +00004196// void (^myblock)() = ^() {
4197// [f test]; // f is a BlockDeclRefExpr embedded in a message (which is being rewritten).
4198// i = 77;
4199// };
4200//}
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004201Stmt *RewriteObjC::RewriteBlockDeclRefExpr(Expr *DeclRefExp) {
Fariborz Jahanian25c07fa2009-12-23 19:26:34 +00004202 // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004203 // for each DeclRefExp where BYREFVAR is name of the variable.
4204 ValueDecl *VD;
4205 bool isArrow = true;
4206 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(DeclRefExp))
4207 VD = BDRE->getDecl();
4208 else {
4209 VD = cast<DeclRefExpr>(DeclRefExp)->getDecl();
4210 isArrow = false;
4211 }
4212
Fariborz Jahanian7df39802009-12-23 19:22:33 +00004213 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4214 &Context->Idents.get("__forwarding"),
4215 Context->VoidPtrTy, 0,
4216 /*BitWidth=*/0, /*Mutable=*/true);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004217 MemberExpr *ME = new (Context) MemberExpr(DeclRefExp, isArrow,
4218 FD, SourceLocation(),
Fariborz Jahanian7df39802009-12-23 19:22:33 +00004219 FD->getType());
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004220
4221 const char *Name = VD->getNameAsCString();
Fariborz Jahanian7df39802009-12-23 19:22:33 +00004222 FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4223 &Context->Idents.get(Name),
4224 Context->VoidPtrTy, 0,
4225 /*BitWidth=*/0, /*Mutable=*/true);
4226 ME = new (Context) MemberExpr(ME, true, FD, SourceLocation(),
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004227 DeclRefExp->getType());
Fariborz Jahanian7df39802009-12-23 19:22:33 +00004228
4229
4230
Steve Narofff26a1d42009-02-02 17:19:26 +00004231 // Need parens to enforce precedence.
Fariborz Jahanian7df39802009-12-23 19:22:33 +00004232 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4233 ME);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004234 ReplaceStmt(DeclRefExp, PE);
Steve Naroffd9803712009-04-29 16:37:50 +00004235 return PE;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004236}
4237
Steve Naroffc989a7b2008-11-03 23:29:32 +00004238void RewriteObjC::RewriteCastExpr(CStyleCastExpr *CE) {
4239 SourceLocation LocStart = CE->getLParenLoc();
4240 SourceLocation LocEnd = CE->getRParenLoc();
Steve Narofff4b992a2008-10-28 20:29:00 +00004241
4242 // Need to avoid trying to rewrite synthesized casts.
4243 if (LocStart.isInvalid())
4244 return;
Steve Naroff3e7ced12008-11-03 11:20:24 +00004245 // Need to avoid trying to rewrite casts contained in macros.
4246 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
4247 return;
Mike Stump11289f42009-09-09 15:08:12 +00004248
Steve Naroff677ab3a2008-10-27 17:20:55 +00004249 const char *startBuf = SM->getCharacterData(LocStart);
4250 const char *endBuf = SM->getCharacterData(LocEnd);
Mike Stump11289f42009-09-09 15:08:12 +00004251
Steve Naroff677ab3a2008-10-27 17:20:55 +00004252 // advance the location to startArgList.
4253 const char *argPtr = startBuf;
Mike Stump11289f42009-09-09 15:08:12 +00004254
Steve Naroff677ab3a2008-10-27 17:20:55 +00004255 while (*argPtr++ && (argPtr < endBuf)) {
4256 switch (*argPtr) {
Mike Stump11289f42009-09-09 15:08:12 +00004257 case '^':
Steve Naroff677ab3a2008-10-27 17:20:55 +00004258 // Replace the '^' with '*'.
4259 LocStart = LocStart.getFileLocWithOffset(argPtr-startBuf);
4260 ReplaceText(LocStart, 1, "*", 1);
4261 break;
4262 }
4263 }
4264 return;
4265}
4266
4267void RewriteObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
4268 SourceLocation DeclLoc = FD->getLocation();
4269 unsigned parenCount = 0;
Mike Stump11289f42009-09-09 15:08:12 +00004270
Steve Naroff677ab3a2008-10-27 17:20:55 +00004271 // We have 1 or more arguments that have closure pointers.
4272 const char *startBuf = SM->getCharacterData(DeclLoc);
4273 const char *startArgList = strchr(startBuf, '(');
Mike Stump11289f42009-09-09 15:08:12 +00004274
Steve Naroff677ab3a2008-10-27 17:20:55 +00004275 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
Mike Stump11289f42009-09-09 15:08:12 +00004276
Steve Naroff677ab3a2008-10-27 17:20:55 +00004277 parenCount++;
4278 // advance the location to startArgList.
4279 DeclLoc = DeclLoc.getFileLocWithOffset(startArgList-startBuf);
4280 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
Mike Stump11289f42009-09-09 15:08:12 +00004281
Steve Naroff677ab3a2008-10-27 17:20:55 +00004282 const char *argPtr = startArgList;
Mike Stump11289f42009-09-09 15:08:12 +00004283
Steve Naroff677ab3a2008-10-27 17:20:55 +00004284 while (*argPtr++ && parenCount) {
4285 switch (*argPtr) {
Mike Stump11289f42009-09-09 15:08:12 +00004286 case '^':
Steve Naroff677ab3a2008-10-27 17:20:55 +00004287 // Replace the '^' with '*'.
4288 DeclLoc = DeclLoc.getFileLocWithOffset(argPtr-startArgList);
4289 ReplaceText(DeclLoc, 1, "*", 1);
4290 break;
Mike Stump11289f42009-09-09 15:08:12 +00004291 case '(':
4292 parenCount++;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004293 break;
Mike Stump11289f42009-09-09 15:08:12 +00004294 case ')':
Steve Naroff677ab3a2008-10-27 17:20:55 +00004295 parenCount--;
4296 break;
4297 }
4298 }
4299 return;
4300}
4301
4302bool RewriteObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004303 const FunctionProtoType *FTP;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004304 const PointerType *PT = QT->getAs<PointerType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004305 if (PT) {
John McCall9dd450b2009-09-21 23:43:11 +00004306 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004307 } else {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004308 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004309 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
John McCall9dd450b2009-09-21 23:43:11 +00004310 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004311 }
4312 if (FTP) {
Mike Stump11289f42009-09-09 15:08:12 +00004313 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00004314 E = FTP->arg_type_end(); I != E; ++I)
Steve Naroffa5c0db82008-12-11 21:05:33 +00004315 if (isTopLevelBlockPointerType(*I))
Steve Naroff677ab3a2008-10-27 17:20:55 +00004316 return true;
4317 }
4318 return false;
4319}
4320
Ted Kremenek5a201952009-02-07 01:47:29 +00004321void RewriteObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
4322 const char *&RParen) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00004323 const char *argPtr = strchr(Name, '(');
4324 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
Mike Stump11289f42009-09-09 15:08:12 +00004325
Steve Naroff677ab3a2008-10-27 17:20:55 +00004326 LParen = argPtr; // output the start.
4327 argPtr++; // skip past the left paren.
4328 unsigned parenCount = 1;
Mike Stump11289f42009-09-09 15:08:12 +00004329
Steve Naroff677ab3a2008-10-27 17:20:55 +00004330 while (*argPtr && parenCount) {
4331 switch (*argPtr) {
4332 case '(': parenCount++; break;
4333 case ')': parenCount--; break;
4334 default: break;
4335 }
4336 if (parenCount) argPtr++;
4337 }
4338 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
4339 RParen = argPtr; // output the end
4340}
4341
4342void RewriteObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
4343 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4344 RewriteBlockPointerFunctionArgs(FD);
4345 return;
Mike Stump11289f42009-09-09 15:08:12 +00004346 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00004347 // Handle Variables and Typedefs.
4348 SourceLocation DeclLoc = ND->getLocation();
4349 QualType DeclT;
4350 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
4351 DeclT = VD->getType();
4352 else if (TypedefDecl *TDD = dyn_cast<TypedefDecl>(ND))
4353 DeclT = TDD->getUnderlyingType();
4354 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
4355 DeclT = FD->getType();
Mike Stump11289f42009-09-09 15:08:12 +00004356 else
Steve Naroff677ab3a2008-10-27 17:20:55 +00004357 assert(0 && "RewriteBlockPointerDecl(): Decl type not yet handled");
Mike Stump11289f42009-09-09 15:08:12 +00004358
Steve Naroff677ab3a2008-10-27 17:20:55 +00004359 const char *startBuf = SM->getCharacterData(DeclLoc);
4360 const char *endBuf = startBuf;
4361 // scan backward (from the decl location) for the end of the previous decl.
4362 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
4363 startBuf--;
Mike Stump11289f42009-09-09 15:08:12 +00004364
Steve Naroff677ab3a2008-10-27 17:20:55 +00004365 // *startBuf != '^' if we are dealing with a pointer to function that
4366 // may take block argument types (which will be handled below).
4367 if (*startBuf == '^') {
4368 // Replace the '^' with '*', computing a negative offset.
4369 DeclLoc = DeclLoc.getFileLocWithOffset(startBuf-endBuf);
4370 ReplaceText(DeclLoc, 1, "*", 1);
4371 }
4372 if (PointerTypeTakesAnyBlockArguments(DeclT)) {
4373 // Replace the '^' with '*' for arguments.
4374 DeclLoc = ND->getLocation();
4375 startBuf = SM->getCharacterData(DeclLoc);
4376 const char *argListBegin, *argListEnd;
4377 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
4378 while (argListBegin < argListEnd) {
4379 if (*argListBegin == '^') {
4380 SourceLocation CaretLoc = DeclLoc.getFileLocWithOffset(argListBegin-startBuf);
4381 ReplaceText(CaretLoc, 1, "*", 1);
4382 }
4383 argListBegin++;
4384 }
4385 }
4386 return;
4387}
4388
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004389
4390/// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
4391/// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
4392/// struct Block_byref_id_object *src) {
4393/// _Block_object_assign (&_dest->object, _src->object,
4394/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4395/// [|BLOCK_FIELD_IS_WEAK]) // object
4396/// _Block_object_assign(&_dest->object, _src->object,
4397/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4398/// [|BLOCK_FIELD_IS_WEAK]) // block
4399/// }
4400/// And:
4401/// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
4402/// _Block_object_dispose(_src->object,
4403/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4404/// [|BLOCK_FIELD_IS_WEAK]) // object
4405/// _Block_object_dispose(_src->object,
4406/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4407/// [|BLOCK_FIELD_IS_WEAK]) // block
4408/// }
4409
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004410std::string RewriteObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
4411 int flag) {
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004412 std::string S;
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004413 if (CopyDestroyCache.count(flag) > 0)
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004414 return S;
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004415 CopyDestroyCache.insert(flag);
4416 S = "static void __Block_byref_id_object_copy_";
4417 S += utostr(flag);
4418 S += "(void *dst, void *src) {\n";
4419
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004420 // offset into the object pointer is computed as:
4421 // void * + void* + int + int + void* + void *
4422 unsigned IntSize =
4423 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
4424 unsigned VoidPtrSize =
4425 static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
4426
4427 unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/8;
4428 S += " _Block_object_assign((char*)dst + ";
4429 S += utostr(offset);
4430 S += ", *(void * *) ((char*)src + ";
4431 S += utostr(offset);
4432 S += "), ";
4433 S += utostr(flag);
4434 S += ");\n}\n";
4435
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004436 S += "static void __Block_byref_id_object_dispose_";
4437 S += utostr(flag);
4438 S += "(void *src) {\n";
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004439 S += " _Block_object_dispose(*(void * *) ((char*)src + ";
4440 S += utostr(offset);
4441 S += "), ";
4442 S += utostr(flag);
4443 S += ");\n}\n";
4444 return S;
4445}
4446
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004447/// RewriteByRefVar - For each __block typex ND variable this routine transforms
4448/// the declaration into:
4449/// struct __Block_byref_ND {
4450/// void *__isa; // NULL for everything except __weak pointers
4451/// struct __Block_byref_ND *__forwarding;
4452/// int32_t __flags;
4453/// int32_t __size;
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004454/// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
4455/// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004456/// typex ND;
4457/// };
4458///
4459/// It then replaces declaration of ND variable with:
4460/// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
4461/// __size=sizeof(struct __Block_byref_ND),
4462/// ND=initializer-if-any};
4463///
4464///
4465void RewriteObjC::RewriteByRefVar(VarDecl *ND) {
Fariborz Jahanian7fac6552010-01-05 19:21:35 +00004466 int flag = 0;
4467 int isa = 0;
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004468 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
4469 const char *startBuf = SM->getCharacterData(DeclLoc);
Fariborz Jahanian92368a12009-12-30 20:38:08 +00004470 SourceLocation X = ND->getLocEnd();
4471 X = SM->getInstantiationLoc(X);
4472 const char *endBuf = SM->getCharacterData(X);
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004473 std::string Name(ND->getNameAsString());
4474 std::string ByrefType = "struct __Block_byref_";
4475 ByrefType += Name;
4476 ByrefType += " {\n";
4477 ByrefType += " void *__isa;\n";
4478 ByrefType += " struct __Block_byref_" + Name + " *__forwarding;\n";
4479 ByrefType += " int __flags;\n";
4480 ByrefType += " int __size;\n";
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004481 // Add void *__Block_byref_id_object_copy;
4482 // void *__Block_byref_id_object_dispose; if needed.
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004483 QualType Ty = ND->getType();
4484 bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty);
4485 if (HasCopyAndDispose) {
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004486 ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
4487 ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004488 }
4489
4490 Ty.getAsStringInternal(Name, Context->PrintingPolicy);
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004491 ByrefType += " " + Name + ";\n";
4492 ByrefType += "};\n";
4493 // Insert this type in global scope. It is needed by helper function.
4494 assert(CurFunctionDef && "RewriteByRefVar - CurFunctionDef is null");
4495 SourceLocation FunLocStart = CurFunctionDef->getTypeSpecStartLoc();
4496 InsertText(FunLocStart, ByrefType.c_str(), ByrefType.size());
Fariborz Jahanian7fac6552010-01-05 19:21:35 +00004497 if (Ty.isObjCGCWeak()) {
4498 flag |= BLOCK_FIELD_IS_WEAK;
4499 isa = 1;
4500 }
4501
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004502 if (HasCopyAndDispose) {
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004503 flag = BLOCK_BYREF_CALLER;
4504 QualType Ty = ND->getType();
4505 // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
4506 if (Ty->isBlockPointerType())
4507 flag |= BLOCK_FIELD_IS_BLOCK;
4508 else
4509 flag |= BLOCK_FIELD_IS_OBJECT;
4510 std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004511 if (!HF.empty())
4512 InsertText(FunLocStart, HF.c_str(), HF.size());
4513 }
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004514
4515 // struct __Block_byref_ND ND =
4516 // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
4517 // initializer-if-any};
4518 bool hasInit = (ND->getInit() != 0);
Fariborz Jahanianf7945432010-01-05 18:15:57 +00004519 unsigned flags = 0;
4520 if (HasCopyAndDispose)
4521 flags |= BLOCK_HAS_COPY_DISPOSE;
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004522 Name = ND->getNameAsString();
4523 ByrefType = "struct __Block_byref_" + Name;
4524 if (!hasInit) {
Fariborz Jahanian7fac6552010-01-05 19:21:35 +00004525 ByrefType += " " + Name + " = {(void*)";
4526 ByrefType += utostr(isa);
4527 ByrefType += ", &" + Name + ", ";
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004528 ByrefType += utostr(flags);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004529 ByrefType += ", ";
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004530 ByrefType += "sizeof(struct __Block_byref_" + Name + ")";
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004531 if (HasCopyAndDispose) {
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004532 ByrefType += ", __Block_byref_id_object_copy_";
4533 ByrefType += utostr(flag);
4534 ByrefType += ", __Block_byref_id_object_dispose_";
4535 ByrefType += utostr(flag);
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004536 }
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004537 ByrefType += "};\n";
4538 ReplaceText(DeclLoc, endBuf-startBuf+Name.size(),
4539 ByrefType.c_str(), ByrefType.size());
4540 }
4541 else {
4542 SourceLocation startLoc = ND->getInit()->getLocStart();
4543 ByrefType += " " + Name;
4544 ReplaceText(DeclLoc, endBuf-startBuf,
4545 ByrefType.c_str(), ByrefType.size());
Fariborz Jahanian7fac6552010-01-05 19:21:35 +00004546 ByrefType = " = {(void*)";
4547 ByrefType += utostr(isa);
4548 ByrefType += ", &" + Name + ", ";
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004549 ByrefType += utostr(flags);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004550 ByrefType += ", ";
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004551 ByrefType += "sizeof(struct __Block_byref_" + Name + "), ";
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004552 if (HasCopyAndDispose) {
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004553 ByrefType += "__Block_byref_id_object_copy_";
4554 ByrefType += utostr(flag);
4555 ByrefType += ", __Block_byref_id_object_dispose_";
4556 ByrefType += utostr(flag);
4557 ByrefType += ", ";
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004558 }
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004559 InsertText(startLoc, ByrefType.c_str(), ByrefType.size());
Steve Naroff13468372009-12-23 17:24:33 +00004560
4561 // Complete the newly synthesized compound expression by inserting a right
4562 // curly brace before the end of the declaration.
4563 // FIXME: This approach avoids rewriting the initializer expression. It
4564 // also assumes there is only one declarator. For example, the following
4565 // isn't currently supported by this routine (in general):
4566 //
4567 // double __block BYREFVAR = 1.34, BYREFVAR2 = 1.37;
4568 //
4569 const char *startBuf = SM->getCharacterData(startLoc);
4570 const char *semiBuf = strchr(startBuf, ';');
4571 assert((*semiBuf == ';') && "RewriteByRefVar: can't find ';'");
4572 SourceLocation semiLoc =
4573 startLoc.getFileLocWithOffset(semiBuf-startBuf);
4574
4575 InsertText(semiLoc, "}", 1);
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004576 }
Fariborz Jahanian81203462009-12-22 00:48:54 +00004577 return;
4578}
4579
Mike Stump11289f42009-09-09 15:08:12 +00004580void RewriteObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00004581 // Add initializers for any closure decl refs.
4582 GetBlockDeclRefExprs(Exp->getBody());
4583 if (BlockDeclRefs.size()) {
4584 // Unique all "by copy" declarations.
4585 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
4586 if (!BlockDeclRefs[i]->isByRef())
4587 BlockByCopyDecls.insert(BlockDeclRefs[i]->getDecl());
4588 // Unique all "by ref" declarations.
4589 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
4590 if (BlockDeclRefs[i]->isByRef()) {
4591 BlockByRefDecls.insert(BlockDeclRefs[i]->getDecl());
4592 }
4593 // Find any imported blocks...they will need special attention.
4594 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
Fariborz Jahaniane175eeb2009-12-21 23:31:42 +00004595 if (BlockDeclRefs[i]->isByRef() ||
4596 BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
4597 BlockDeclRefs[i]->getType()->isBlockPointerType()) {
Steve Naroff832d8902008-11-13 17:40:07 +00004598 GetBlockCallExprs(BlockDeclRefs[i]);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004599 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
4600 }
4601 }
4602}
4603
Steve Narofff4b992a2008-10-28 20:29:00 +00004604FunctionDecl *RewriteObjC::SynthBlockInitFunctionDecl(const char *name) {
4605 IdentifierInfo *ID = &Context->Idents.get(name);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004606 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
Mike Stump11289f42009-09-09 15:08:12 +00004607 return FunctionDecl::Create(*Context, TUDecl,SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00004608 ID, FType, 0, FunctionDecl::Extern, false,
Douglas Gregor739ef0c2009-02-25 16:33:18 +00004609 false);
Steve Narofff4b992a2008-10-28 20:29:00 +00004610}
4611
Steve Naroffd8907b72008-10-29 18:15:37 +00004612Stmt *RewriteObjC::SynthBlockInitExpr(BlockExpr *Exp) {
Steve Narofff4b992a2008-10-28 20:29:00 +00004613 Blocks.push_back(Exp);
4614
4615 CollectBlockDeclRefInfo(Exp);
4616 std::string FuncName;
Mike Stump11289f42009-09-09 15:08:12 +00004617
Steve Narofff4b992a2008-10-28 20:29:00 +00004618 if (CurFunctionDef)
Chris Lattnere4b95692008-11-24 03:33:13 +00004619 FuncName = CurFunctionDef->getNameAsString();
Steve Narofff4b992a2008-10-28 20:29:00 +00004620 else if (CurMethodDef) {
Chris Lattnere4b95692008-11-24 03:33:13 +00004621 FuncName = CurMethodDef->getSelector().getAsString();
Steve Narofff4b992a2008-10-28 20:29:00 +00004622 // Convert colons to underscores.
4623 std::string::size_type loc = 0;
4624 while ((loc = FuncName.find(":", loc)) != std::string::npos)
4625 FuncName.replace(loc, 1, "_");
Steve Naroffd8907b72008-10-29 18:15:37 +00004626 } else if (GlobalVarDecl)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004627 FuncName = std::string(GlobalVarDecl->getNameAsString());
Mike Stump11289f42009-09-09 15:08:12 +00004628
Steve Narofff4b992a2008-10-28 20:29:00 +00004629 std::string BlockNumber = utostr(Blocks.size()-1);
Mike Stump11289f42009-09-09 15:08:12 +00004630
Steve Narofff4b992a2008-10-28 20:29:00 +00004631 std::string Tag = "__" + FuncName + "_block_impl_" + BlockNumber;
4632 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
Mike Stump11289f42009-09-09 15:08:12 +00004633
Steve Narofff4b992a2008-10-28 20:29:00 +00004634 // Get a pointer to the function type so we can cast appropriately.
4635 QualType FType = Context->getPointerType(QualType(Exp->getFunctionType(),0));
4636
4637 FunctionDecl *FD;
4638 Expr *NewRep;
Mike Stump11289f42009-09-09 15:08:12 +00004639
Steve Narofff4b992a2008-10-28 20:29:00 +00004640 // Simulate a contructor call...
4641 FD = SynthBlockInitFunctionDecl(Tag.c_str());
Ted Kremenek5a201952009-02-07 01:47:29 +00004642 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, FType, SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00004643
Steve Narofff4b992a2008-10-28 20:29:00 +00004644 llvm::SmallVector<Expr*, 4> InitExprs;
Mike Stump11289f42009-09-09 15:08:12 +00004645
Steve Naroffe2514232008-10-29 21:23:59 +00004646 // Initialize the block function.
Steve Narofff4b992a2008-10-28 20:29:00 +00004647 FD = SynthBlockInitFunctionDecl(Func.c_str());
Ted Kremenek5a201952009-02-07 01:47:29 +00004648 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, FD->getType(),
4649 SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00004650 CastExpr *castExpr = new (Context) CStyleCastExpr(Context->VoidPtrTy,
4651 CastExpr::CK_Unknown, Arg,
Ted Kremenek5a201952009-02-07 01:47:29 +00004652 Context->VoidPtrTy, SourceLocation(),
4653 SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00004654 InitExprs.push_back(castExpr);
4655
Steve Naroff30484702009-12-06 21:14:13 +00004656 // Initialize the block descriptor.
4657 std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
Mike Stump11289f42009-09-09 15:08:12 +00004658
Steve Naroff30484702009-12-06 21:14:13 +00004659 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
4660 &Context->Idents.get(DescData.c_str()),
4661 Context->VoidPtrTy, 0,
4662 VarDecl::Static);
4663 UnaryOperator *DescRefExpr = new (Context) UnaryOperator(
4664 new (Context) DeclRefExpr(NewVD,
4665 Context->VoidPtrTy, SourceLocation()),
4666 UnaryOperator::AddrOf,
4667 Context->getPointerType(Context->VoidPtrTy),
4668 SourceLocation());
4669 InitExprs.push_back(DescRefExpr);
4670
Steve Narofff4b992a2008-10-28 20:29:00 +00004671 // Add initializers for any closure decl refs.
4672 if (BlockDeclRefs.size()) {
Steve Naroffe2514232008-10-29 21:23:59 +00004673 Expr *Exp;
Steve Narofff4b992a2008-10-28 20:29:00 +00004674 // Output all "by copy" declarations.
Mike Stump11289f42009-09-09 15:08:12 +00004675 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Narofff4b992a2008-10-28 20:29:00 +00004676 E = BlockByCopyDecls.end(); I != E; ++I) {
Steve Narofff4b992a2008-10-28 20:29:00 +00004677 if (isObjCType((*I)->getType())) {
Steve Naroffe2514232008-10-29 21:23:59 +00004678 // FIXME: Conform to ABI ([[obj retain] autorelease]).
Chris Lattner86d7d912008-11-24 03:54:41 +00004679 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek5a201952009-02-07 01:47:29 +00004680 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
Steve Naroffa5c0db82008-12-11 21:05:33 +00004681 } else if (isTopLevelBlockPointerType((*I)->getType())) {
Chris Lattner86d7d912008-11-24 03:54:41 +00004682 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek5a201952009-02-07 01:47:29 +00004683 Arg = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00004684 Exp = new (Context) CStyleCastExpr(Context->VoidPtrTy,
4685 CastExpr::CK_Unknown, Arg,
4686 Context->VoidPtrTy,
Anders Carlssona2615922009-07-31 00:48:10 +00004687 SourceLocation(),
Ted Kremenek5a201952009-02-07 01:47:29 +00004688 SourceLocation());
Steve Narofff4b992a2008-10-28 20:29:00 +00004689 } else {
Chris Lattner86d7d912008-11-24 03:54:41 +00004690 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek5a201952009-02-07 01:47:29 +00004691 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
Steve Narofff4b992a2008-10-28 20:29:00 +00004692 }
Mike Stump11289f42009-09-09 15:08:12 +00004693 InitExprs.push_back(Exp);
Steve Narofff4b992a2008-10-28 20:29:00 +00004694 }
4695 // Output all "by ref" declarations.
Mike Stump11289f42009-09-09 15:08:12 +00004696 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Narofff4b992a2008-10-28 20:29:00 +00004697 E = BlockByRefDecls.end(); I != E; ++I) {
Chris Lattner86d7d912008-11-24 03:54:41 +00004698 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek5a201952009-02-07 01:47:29 +00004699 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
4700 Exp = new (Context) UnaryOperator(Exp, UnaryOperator::AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00004701 Context->getPointerType(Exp->getType()),
Steve Naroffe2514232008-10-29 21:23:59 +00004702 SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00004703 InitExprs.push_back(Exp);
Steve Narofff4b992a2008-10-28 20:29:00 +00004704 }
4705 }
Fariborz Jahanian65e6bd62009-12-23 21:52:32 +00004706 if (ImportedBlockDecls.size()) {
4707 // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
4708 int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
Steve Naroff30484702009-12-06 21:14:13 +00004709 unsigned IntSize =
4710 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Fariborz Jahanian65e6bd62009-12-23 21:52:32 +00004711 Expr *FlagExp = new (Context) IntegerLiteral(llvm::APInt(IntSize, flag),
4712 Context->IntTy, SourceLocation());
4713 InitExprs.push_back(FlagExp);
Steve Naroff30484702009-12-06 21:14:13 +00004714 }
Ted Kremenekd7b4f402009-02-09 20:51:47 +00004715 NewRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0], InitExprs.size(),
4716 FType, SourceLocation());
Ted Kremenek5a201952009-02-07 01:47:29 +00004717 NewRep = new (Context) UnaryOperator(NewRep, UnaryOperator::AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00004718 Context->getPointerType(NewRep->getType()),
Steve Narofff4b992a2008-10-28 20:29:00 +00004719 SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00004720 NewRep = new (Context) CStyleCastExpr(FType, CastExpr::CK_Unknown, NewRep,
Anders Carlssona2615922009-07-31 00:48:10 +00004721 FType, SourceLocation(),
Ted Kremenek5a201952009-02-07 01:47:29 +00004722 SourceLocation());
Steve Narofff4b992a2008-10-28 20:29:00 +00004723 BlockDeclRefs.clear();
4724 BlockByRefDecls.clear();
4725 BlockByCopyDecls.clear();
4726 ImportedBlockDecls.clear();
4727 return NewRep;
4728}
4729
4730//===----------------------------------------------------------------------===//
4731// Function Body / Expression rewriting
4732//===----------------------------------------------------------------------===//
4733
Steve Naroff4588d0f2008-12-04 16:24:46 +00004734// This is run as a first "pass" prior to RewriteFunctionBodyOrGlobalInitializer().
4735// The allows the main rewrite loop to associate all ObjCPropertyRefExprs with
4736// their respective BinaryOperator. Without this knowledge, we'd need to rewrite
4737// the ObjCPropertyRefExpr twice (once as a getter, and later as a setter).
4738// Since the rewriter isn't capable of rewriting rewritten code, it's important
4739// we get this right.
4740void RewriteObjC::CollectPropertySetters(Stmt *S) {
4741 // Perform a bottom up traversal of all children.
4742 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4743 CI != E; ++CI)
4744 if (*CI)
4745 CollectPropertySetters(*CI);
4746
4747 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(S)) {
4748 if (BinOp->isAssignmentOp()) {
4749 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(BinOp->getLHS()))
4750 PropSetters[PRE] = BinOp;
4751 }
4752 }
4753}
4754
Steve Narofff4b992a2008-10-28 20:29:00 +00004755Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
Mike Stump11289f42009-09-09 15:08:12 +00004756 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofff4b992a2008-10-28 20:29:00 +00004757 isa<DoStmt>(S) || isa<ForStmt>(S))
4758 Stmts.push_back(S);
4759 else if (isa<ObjCForCollectionStmt>(S)) {
4760 Stmts.push_back(S);
Anders Carlsson3caa2b42009-12-22 06:13:42 +00004761 ++BcLabelCount;
4762 ObjCBcLabelNo.push_back(BcLabelCount);
Steve Narofff4b992a2008-10-28 20:29:00 +00004763 }
Mike Stump11289f42009-09-09 15:08:12 +00004764
Steve Narofff4b992a2008-10-28 20:29:00 +00004765 SourceRange OrigStmtRange = S->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00004766
Steve Narofff4b992a2008-10-28 20:29:00 +00004767 // Perform a bottom up rewrite of all children.
4768 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4769 CI != E; ++CI)
4770 if (*CI) {
4771 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(*CI);
Mike Stump11289f42009-09-09 15:08:12 +00004772 if (newStmt)
Steve Narofff4b992a2008-10-28 20:29:00 +00004773 *CI = newStmt;
4774 }
Mike Stump11289f42009-09-09 15:08:12 +00004775
Steve Narofff4b992a2008-10-28 20:29:00 +00004776 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
4777 // Rewrite the block body in place.
4778 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
Mike Stump11289f42009-09-09 15:08:12 +00004779
Steve Narofff4b992a2008-10-28 20:29:00 +00004780 // Now we snarf the rewritten text and stash it away for later use.
Steve Naroffd8907b72008-10-29 18:15:37 +00004781 std::string Str = Rewrite.getRewritenText(BE->getSourceRange());
4782 RewrittenBlockExprs[BE] = Str;
Mike Stump11289f42009-09-09 15:08:12 +00004783
Steve Narofff4b992a2008-10-28 20:29:00 +00004784 Stmt *blockTranscribed = SynthBlockInitExpr(BE);
4785 //blockTranscribed->dump();
Steve Naroffd8907b72008-10-29 18:15:37 +00004786 ReplaceStmt(S, blockTranscribed);
Steve Narofff4b992a2008-10-28 20:29:00 +00004787 return blockTranscribed;
4788 }
4789 // Handle specific things.
4790 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
4791 return RewriteAtEncode(AtEncode);
Mike Stump11289f42009-09-09 15:08:12 +00004792
Steve Narofff4b992a2008-10-28 20:29:00 +00004793 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S))
4794 return RewriteObjCIvarRefExpr(IvarRefExpr, OrigStmtRange.getBegin());
4795
Steve Naroff4588d0f2008-12-04 16:24:46 +00004796 if (ObjCPropertyRefExpr *PropRefExpr = dyn_cast<ObjCPropertyRefExpr>(S)) {
4797 BinaryOperator *BinOp = PropSetters[PropRefExpr];
4798 if (BinOp) {
4799 // Because the rewriter doesn't allow us to rewrite rewritten code,
4800 // we need to rewrite the right hand side prior to rewriting the setter.
Steve Naroff08628db2008-12-09 12:56:34 +00004801 DisableReplaceStmt = true;
4802 // Save the source range. Even if we disable the replacement, the
4803 // rewritten node will have been inserted into the tree. If the synthesized
4804 // node is at the 'end', the rewriter will fail. Consider this:
Mike Stump11289f42009-09-09 15:08:12 +00004805 // self.errorHandler = handler ? handler :
Steve Naroff08628db2008-12-09 12:56:34 +00004806 // ^(NSURL *errorURL, NSError *error) { return (BOOL)1; };
4807 SourceRange SrcRange = BinOp->getSourceRange();
Steve Naroff4588d0f2008-12-04 16:24:46 +00004808 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(BinOp->getRHS());
Steve Naroff08628db2008-12-09 12:56:34 +00004809 DisableReplaceStmt = false;
Steve Naroff22216db2008-12-04 23:50:32 +00004810 //
4811 // Unlike the main iterator, we explicily avoid changing 'BinOp'. If
4812 // we changed the RHS of BinOp, the rewriter would fail (since it needs
4813 // to see the original expression). Consider this example:
4814 //
4815 // Foo *obj1, *obj2;
4816 //
4817 // obj1.i = [obj2 rrrr];
4818 //
4819 // 'BinOp' for the previous expression looks like:
4820 //
4821 // (BinaryOperator 0x231ccf0 'int' '='
4822 // (ObjCPropertyRefExpr 0x231cc70 'int' Kind=PropertyRef Property="i"
4823 // (DeclRefExpr 0x231cc50 'Foo *' Var='obj1' 0x231cbb0))
4824 // (ObjCMessageExpr 0x231ccb0 'int' selector=rrrr
4825 // (DeclRefExpr 0x231cc90 'Foo *' Var='obj2' 0x231cbe0)))
4826 //
4827 // 'newStmt' represents the rewritten message expression. For example:
4828 //
4829 // (CallExpr 0x231d300 'id':'struct objc_object *'
4830 // (ParenExpr 0x231d2e0 'int (*)(id, SEL)'
4831 // (CStyleCastExpr 0x231d2c0 'int (*)(id, SEL)'
4832 // (CStyleCastExpr 0x231d220 'void *'
4833 // (DeclRefExpr 0x231d200 'id (id, SEL, ...)' FunctionDecl='objc_msgSend' 0x231cdc0))))
4834 //
4835 // Note that 'newStmt' is passed to RewritePropertySetter so that it
4836 // can be used as the setter argument. ReplaceStmt() will still 'see'
4837 // the original RHS (since we haven't altered BinOp).
4838 //
Mike Stump11289f42009-09-09 15:08:12 +00004839 // This implies the Rewrite* routines can no longer delete the original
Steve Naroff22216db2008-12-04 23:50:32 +00004840 // node. As a result, we now leak the original AST nodes.
4841 //
Steve Naroff08628db2008-12-09 12:56:34 +00004842 return RewritePropertySetter(BinOp, dyn_cast<Expr>(newStmt), SrcRange);
Steve Naroff4588d0f2008-12-04 16:24:46 +00004843 } else {
4844 return RewritePropertyGetter(PropRefExpr);
Steve Narofff326f402008-12-03 00:56:33 +00004845 }
4846 }
Steve Narofff4b992a2008-10-28 20:29:00 +00004847 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
4848 return RewriteAtSelector(AtSelector);
Mike Stump11289f42009-09-09 15:08:12 +00004849
Steve Narofff4b992a2008-10-28 20:29:00 +00004850 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
4851 return RewriteObjCStringLiteral(AtString);
Mike Stump11289f42009-09-09 15:08:12 +00004852
Steve Narofff4b992a2008-10-28 20:29:00 +00004853 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
Steve Naroff4588d0f2008-12-04 16:24:46 +00004854#if 0
Steve Narofff4b992a2008-10-28 20:29:00 +00004855 // Before we rewrite it, put the original message expression in a comment.
4856 SourceLocation startLoc = MessExpr->getLocStart();
4857 SourceLocation endLoc = MessExpr->getLocEnd();
Mike Stump11289f42009-09-09 15:08:12 +00004858
Steve Narofff4b992a2008-10-28 20:29:00 +00004859 const char *startBuf = SM->getCharacterData(startLoc);
4860 const char *endBuf = SM->getCharacterData(endLoc);
Mike Stump11289f42009-09-09 15:08:12 +00004861
Steve Narofff4b992a2008-10-28 20:29:00 +00004862 std::string messString;
4863 messString += "// ";
4864 messString.append(startBuf, endBuf-startBuf+1);
4865 messString += "\n";
Mike Stump11289f42009-09-09 15:08:12 +00004866
4867 // FIXME: Missing definition of
Steve Narofff4b992a2008-10-28 20:29:00 +00004868 // InsertText(clang::SourceLocation, char const*, unsigned int).
4869 // InsertText(startLoc, messString.c_str(), messString.size());
4870 // Tried this, but it didn't work either...
4871 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroff4588d0f2008-12-04 16:24:46 +00004872#endif
Steve Narofff4b992a2008-10-28 20:29:00 +00004873 return RewriteMessageExpr(MessExpr);
4874 }
Mike Stump11289f42009-09-09 15:08:12 +00004875
Steve Narofff4b992a2008-10-28 20:29:00 +00004876 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
4877 return RewriteObjCTryStmt(StmtTry);
4878
4879 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
4880 return RewriteObjCSynchronizedStmt(StmtTry);
4881
4882 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
4883 return RewriteObjCThrowStmt(StmtThrow);
Mike Stump11289f42009-09-09 15:08:12 +00004884
Steve Narofff4b992a2008-10-28 20:29:00 +00004885 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
4886 return RewriteObjCProtocolExpr(ProtocolExp);
Mike Stump11289f42009-09-09 15:08:12 +00004887
4888 if (ObjCForCollectionStmt *StmtForCollection =
Steve Narofff4b992a2008-10-28 20:29:00 +00004889 dyn_cast<ObjCForCollectionStmt>(S))
Mike Stump11289f42009-09-09 15:08:12 +00004890 return RewriteObjCForCollectionStmt(StmtForCollection,
Steve Narofff4b992a2008-10-28 20:29:00 +00004891 OrigStmtRange.getEnd());
4892 if (BreakStmt *StmtBreakStmt =
4893 dyn_cast<BreakStmt>(S))
4894 return RewriteBreakStmt(StmtBreakStmt);
4895 if (ContinueStmt *StmtContinueStmt =
4896 dyn_cast<ContinueStmt>(S))
4897 return RewriteContinueStmt(StmtContinueStmt);
Mike Stump11289f42009-09-09 15:08:12 +00004898
4899 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
Steve Narofff4b992a2008-10-28 20:29:00 +00004900 // and cast exprs.
4901 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
4902 // FIXME: What we're doing here is modifying the type-specifier that
4903 // precedes the first Decl. In the future the DeclGroup should have
Mike Stump11289f42009-09-09 15:08:12 +00004904 // a separate type-specifier that we can rewrite.
Steve Naroffe70a52a2009-12-05 15:55:59 +00004905 // NOTE: We need to avoid rewriting the DeclStmt if it is within
4906 // the context of an ObjCForCollectionStmt. For example:
4907 // NSArray *someArray;
4908 // for (id <FooProtocol> index in someArray) ;
4909 // This is because RewriteObjCForCollectionStmt() does textual rewriting
4910 // and it depends on the original text locations/positions.
Benjamin Krameracc5fa12009-12-05 22:16:51 +00004911 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
Steve Naroffe70a52a2009-12-05 15:55:59 +00004912 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
Mike Stump11289f42009-09-09 15:08:12 +00004913
Steve Narofff4b992a2008-10-28 20:29:00 +00004914 // Blocks rewrite rules.
4915 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
4916 DI != DE; ++DI) {
Douglas Gregor6e6ad602009-01-20 01:17:11 +00004917 Decl *SD = *DI;
Steve Narofff4b992a2008-10-28 20:29:00 +00004918 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
Steve Naroffa5c0db82008-12-11 21:05:33 +00004919 if (isTopLevelBlockPointerType(ND->getType()))
Steve Narofff4b992a2008-10-28 20:29:00 +00004920 RewriteBlockPointerDecl(ND);
Mike Stump11289f42009-09-09 15:08:12 +00004921 else if (ND->getType()->isFunctionPointerType())
Steve Narofff4b992a2008-10-28 20:29:00 +00004922 CheckFunctionPointerDecl(ND->getType(), ND);
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004923 if (VarDecl *VD = dyn_cast<VarDecl>(SD))
4924 if (VD->hasAttr<BlocksAttr>())
4925 RewriteByRefVar(VD);
Steve Narofff4b992a2008-10-28 20:29:00 +00004926 }
4927 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(SD)) {
Steve Naroffa5c0db82008-12-11 21:05:33 +00004928 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofff4b992a2008-10-28 20:29:00 +00004929 RewriteBlockPointerDecl(TD);
Mike Stump11289f42009-09-09 15:08:12 +00004930 else if (TD->getUnderlyingType()->isFunctionPointerType())
Steve Narofff4b992a2008-10-28 20:29:00 +00004931 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
4932 }
4933 }
4934 }
Mike Stump11289f42009-09-09 15:08:12 +00004935
Steve Narofff4b992a2008-10-28 20:29:00 +00004936 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
4937 RewriteObjCQualifiedInterfaceTypes(CE);
Mike Stump11289f42009-09-09 15:08:12 +00004938
4939 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofff4b992a2008-10-28 20:29:00 +00004940 isa<DoStmt>(S) || isa<ForStmt>(S)) {
4941 assert(!Stmts.empty() && "Statement stack is empty");
Mike Stump11289f42009-09-09 15:08:12 +00004942 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
4943 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
Steve Narofff4b992a2008-10-28 20:29:00 +00004944 && "Statement stack mismatch");
4945 Stmts.pop_back();
4946 }
4947 // Handle blocks rewriting.
4948 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(S)) {
4949 if (BDRE->isByRef())
Steve Naroffd9803712009-04-29 16:37:50 +00004950 return RewriteBlockDeclRefExpr(BDRE);
Steve Narofff4b992a2008-10-28 20:29:00 +00004951 }
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004952 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4953 ValueDecl *VD = DRE->getDecl();
4954 if (VD->hasAttr<BlocksAttr>())
4955 return RewriteBlockDeclRefExpr(DRE);
4956 }
4957
Steve Narofff4b992a2008-10-28 20:29:00 +00004958 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
Steve Naroff350b6652008-10-30 10:07:53 +00004959 if (CE->getCallee()->getType()->isBlockPointerType()) {
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004960 Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
Steve Naroff350b6652008-10-30 10:07:53 +00004961 ReplaceStmt(S, BlockCall);
4962 return BlockCall;
4963 }
Steve Narofff4b992a2008-10-28 20:29:00 +00004964 }
Steve Naroffc989a7b2008-11-03 23:29:32 +00004965 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
Steve Narofff4b992a2008-10-28 20:29:00 +00004966 RewriteCastExpr(CE);
4967 }
4968#if 0
4969 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
Ted Kremenek5a201952009-02-07 01:47:29 +00004970 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(), ICE->getSubExpr(), SourceLocation());
Steve Narofff4b992a2008-10-28 20:29:00 +00004971 // Get the new text.
4972 std::string SStr;
4973 llvm::raw_string_ostream Buf(SStr);
Eli Friedman0905f142009-05-30 05:19:26 +00004974 Replacement->printPretty(Buf, *Context);
Steve Narofff4b992a2008-10-28 20:29:00 +00004975 const std::string &Str = Buf.str();
4976
4977 printf("CAST = %s\n", &Str[0]);
4978 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
4979 delete S;
4980 return Replacement;
4981 }
4982#endif
4983 // Return this stmt unmodified.
4984 return S;
4985}
4986
Steve Naroffe70a52a2009-12-05 15:55:59 +00004987void RewriteObjC::RewriteRecordBody(RecordDecl *RD) {
4988 for (RecordDecl::field_iterator i = RD->field_begin(),
4989 e = RD->field_end(); i != e; ++i) {
4990 FieldDecl *FD = *i;
4991 if (isTopLevelBlockPointerType(FD->getType()))
4992 RewriteBlockPointerDecl(FD);
4993 if (FD->getType()->isObjCQualifiedIdType() ||
4994 FD->getType()->isObjCQualifiedInterfaceType())
4995 RewriteObjCQualifiedInterfaceTypes(FD);
4996 }
4997}
4998
Steve Narofff4b992a2008-10-28 20:29:00 +00004999/// HandleDeclInMainFile - This is called for each top-level decl defined in the
5000/// main file of the input.
5001void RewriteObjC::HandleDeclInMainFile(Decl *D) {
5002 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroffb1368882008-12-17 00:20:22 +00005003 if (FD->isOverloadedOperator())
5004 return;
Mike Stump11289f42009-09-09 15:08:12 +00005005
Steve Narofff4b992a2008-10-28 20:29:00 +00005006 // Since function prototypes don't have ParmDecl's, we check the function
5007 // prototype. This enables us to rewrite function declarations and
5008 // definitions using the same code.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005009 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
Steve Narofff4b992a2008-10-28 20:29:00 +00005010
Sebastian Redla7b98a72009-04-26 20:35:05 +00005011 // FIXME: If this should support Obj-C++, support CXXTryStmt
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00005012 if (CompoundStmt *Body = FD->getCompoundBody()) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005013 CurFunctionDef = FD;
Steve Naroff4588d0f2008-12-04 16:24:46 +00005014 CollectPropertySetters(Body);
Steve Naroff1042ff32008-12-08 16:43:47 +00005015 CurrentBody = Body;
Ted Kremenek73980592009-03-12 18:33:24 +00005016 Body =
5017 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5018 FD->setBody(Body);
Steve Naroff1042ff32008-12-08 16:43:47 +00005019 CurrentBody = 0;
5020 if (PropParentMap) {
5021 delete PropParentMap;
5022 PropParentMap = 0;
5023 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005024 // This synthesizes and inserts the block "impl" struct, invoke function,
5025 // and any copy/dispose helper functions.
5026 InsertBlockLiteralsWithinFunction(FD);
5027 CurFunctionDef = 0;
Mike Stump11289f42009-09-09 15:08:12 +00005028 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005029 return;
5030 }
5031 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00005032 if (CompoundStmt *Body = MD->getCompoundBody()) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005033 CurMethodDef = MD;
Steve Naroff4588d0f2008-12-04 16:24:46 +00005034 CollectPropertySetters(Body);
Steve Naroff1042ff32008-12-08 16:43:47 +00005035 CurrentBody = Body;
Ted Kremenek73980592009-03-12 18:33:24 +00005036 Body =
5037 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5038 MD->setBody(Body);
Steve Naroff1042ff32008-12-08 16:43:47 +00005039 CurrentBody = 0;
5040 if (PropParentMap) {
5041 delete PropParentMap;
5042 PropParentMap = 0;
5043 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005044 InsertBlockLiteralsWithinMethod(MD);
5045 CurMethodDef = 0;
5046 }
5047 }
5048 if (ObjCImplementationDecl *CI = dyn_cast<ObjCImplementationDecl>(D))
5049 ClassImplementation.push_back(CI);
5050 else if (ObjCCategoryImplDecl *CI = dyn_cast<ObjCCategoryImplDecl>(D))
5051 CategoryImplementation.push_back(CI);
5052 else if (ObjCClassDecl *CD = dyn_cast<ObjCClassDecl>(D))
5053 RewriteForwardClassDecl(CD);
5054 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
5055 RewriteObjCQualifiedInterfaceTypes(VD);
Steve Naroffa5c0db82008-12-11 21:05:33 +00005056 if (isTopLevelBlockPointerType(VD->getType()))
Steve Narofff4b992a2008-10-28 20:29:00 +00005057 RewriteBlockPointerDecl(VD);
Steve Naroffd8907b72008-10-29 18:15:37 +00005058 else if (VD->getType()->isFunctionPointerType()) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005059 CheckFunctionPointerDecl(VD->getType(), VD);
5060 if (VD->getInit()) {
Steve Naroffc989a7b2008-11-03 23:29:32 +00005061 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005062 RewriteCastExpr(CE);
5063 }
5064 }
Steve Naroffe70a52a2009-12-05 15:55:59 +00005065 } else if (VD->getType()->isRecordType()) {
5066 RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
5067 if (RD->isDefinition())
5068 RewriteRecordBody(RD);
Steve Narofff4b992a2008-10-28 20:29:00 +00005069 }
Steve Naroffd8907b72008-10-29 18:15:37 +00005070 if (VD->getInit()) {
5071 GlobalVarDecl = VD;
Steve Naroff4588d0f2008-12-04 16:24:46 +00005072 CollectPropertySetters(VD->getInit());
Steve Naroff1042ff32008-12-08 16:43:47 +00005073 CurrentBody = VD->getInit();
Steve Naroffd8907b72008-10-29 18:15:37 +00005074 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
Steve Naroff1042ff32008-12-08 16:43:47 +00005075 CurrentBody = 0;
5076 if (PropParentMap) {
5077 delete PropParentMap;
5078 PropParentMap = 0;
5079 }
Mike Stump11289f42009-09-09 15:08:12 +00005080 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(),
Chris Lattner86d7d912008-11-24 03:54:41 +00005081 VD->getNameAsCString());
Steve Naroffd8907b72008-10-29 18:15:37 +00005082 GlobalVarDecl = 0;
5083
5084 // This is needed for blocks.
Steve Naroffc989a7b2008-11-03 23:29:32 +00005085 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Naroffd8907b72008-10-29 18:15:37 +00005086 RewriteCastExpr(CE);
5087 }
5088 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005089 return;
5090 }
5091 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(D)) {
Steve Naroffa5c0db82008-12-11 21:05:33 +00005092 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofff4b992a2008-10-28 20:29:00 +00005093 RewriteBlockPointerDecl(TD);
Mike Stump11289f42009-09-09 15:08:12 +00005094 else if (TD->getUnderlyingType()->isFunctionPointerType())
Steve Narofff4b992a2008-10-28 20:29:00 +00005095 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
Steve Naroffe70a52a2009-12-05 15:55:59 +00005096 else if (TD->getUnderlyingType()->isRecordType()) {
5097 RecordDecl *RD = TD->getUnderlyingType()->getAs<RecordType>()->getDecl();
5098 if (RD->isDefinition())
5099 RewriteRecordBody(RD);
5100 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005101 return;
5102 }
5103 if (RecordDecl *RD = dyn_cast<RecordDecl>(D)) {
Steve Naroffe70a52a2009-12-05 15:55:59 +00005104 if (RD->isDefinition())
5105 RewriteRecordBody(RD);
Steve Narofff4b992a2008-10-28 20:29:00 +00005106 return;
5107 }
5108 // Nothing yet.
5109}
5110
Chris Lattnercf169832009-03-28 04:11:33 +00005111void RewriteObjC::HandleTranslationUnit(ASTContext &C) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005112 // Get the top-level buffer that this corresponds to.
Mike Stump11289f42009-09-09 15:08:12 +00005113
Steve Narofff4b992a2008-10-28 20:29:00 +00005114 // Rewrite tabs if we care.
5115 //RewriteTabs();
Mike Stump11289f42009-09-09 15:08:12 +00005116
Steve Narofff4b992a2008-10-28 20:29:00 +00005117 if (Diags.hasErrorOccurred())
5118 return;
Mike Stump11289f42009-09-09 15:08:12 +00005119
Steve Narofff4b992a2008-10-28 20:29:00 +00005120 RewriteInclude();
Mike Stump11289f42009-09-09 15:08:12 +00005121
Steve Naroffd9803712009-04-29 16:37:50 +00005122 // Here's a great place to add any extra declarations that may be needed.
5123 // Write out meta data for each @protocol(<expr>).
Mike Stump11289f42009-09-09 15:08:12 +00005124 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Steve Naroffd9803712009-04-29 16:37:50 +00005125 E = ProtocolExprDecls.end(); I != E; ++I)
5126 RewriteObjCProtocolMetaData(*I, "", "", Preamble);
5127
Mike Stump11289f42009-09-09 15:08:12 +00005128 InsertText(SM->getLocForStartOfFile(MainFileID),
Steve Narofff4b992a2008-10-28 20:29:00 +00005129 Preamble.c_str(), Preamble.size(), false);
Steve Naroff2a2a41f2008-11-14 14:10:01 +00005130 if (ClassImplementation.size() || CategoryImplementation.size())
5131 RewriteImplementations();
Steve Naroffd9803712009-04-29 16:37:50 +00005132
Steve Narofff4b992a2008-10-28 20:29:00 +00005133 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
5134 // we are done.
Mike Stump11289f42009-09-09 15:08:12 +00005135 if (const RewriteBuffer *RewriteBuf =
Steve Narofff4b992a2008-10-28 20:29:00 +00005136 Rewrite.getRewriteBufferFor(MainFileID)) {
5137 //printf("Changed:\n");
5138 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
5139 } else {
5140 fprintf(stderr, "No changes\n");
5141 }
Steve Narofff8cfd162008-11-13 20:07:04 +00005142
Steve Naroffd9803712009-04-29 16:37:50 +00005143 if (ClassImplementation.size() || CategoryImplementation.size() ||
5144 ProtocolExprDecls.size()) {
Steve Naroff2a2a41f2008-11-14 14:10:01 +00005145 // Rewrite Objective-c meta data*
5146 std::string ResultStr;
5147 SynthesizeMetaDataIntoBuffer(ResultStr);
5148 // Emit metadata.
5149 *OutFile << ResultStr;
5150 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005151 OutFile->flush();
5152}
5153