blob: 28f79aa10adfcbcc641312d8b319dd75b78d7cae [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;
Fariborz Jahanianbc6811c2010-01-07 22:51:18 +0000117 bool objc_impl_method;
Eli Friedmanf22439a2009-05-18 22:39:16 +0000118
Steve Naroff00a31762008-03-27 22:29:16 +0000119 std::string Preamble;
Steve Naroff677ab3a2008-10-27 17:20:55 +0000120
121 // Block expressions.
122 llvm::SmallVector<BlockExpr *, 32> Blocks;
123 llvm::SmallVector<BlockDeclRefExpr *, 32> BlockDeclRefs;
124 llvm::DenseMap<BlockDeclRefExpr *, CallExpr *> BlockCallExprs;
Mike Stump11289f42009-09-09 15:08:12 +0000125
Steve Naroff677ab3a2008-10-27 17:20:55 +0000126 // Block related declarations.
127 llvm::SmallPtrSet<ValueDecl *, 8> BlockByCopyDecls;
128 llvm::SmallPtrSet<ValueDecl *, 8> BlockByRefDecls;
129 llvm::SmallPtrSet<ValueDecl *, 8> ImportedBlockDecls;
130
131 llvm::DenseMap<BlockExpr *, std::string> RewrittenBlockExprs;
132
Steve Naroff4588d0f2008-12-04 16:24:46 +0000133 // This maps a property to it's assignment statement.
134 llvm::DenseMap<ObjCPropertyRefExpr *, BinaryOperator *> PropSetters;
Steve Naroff1042ff32008-12-08 16:43:47 +0000135 // This maps a property to it's synthesied message expression.
136 // This allows us to rewrite chained getters (e.g. o.a.b.c).
137 llvm::DenseMap<ObjCPropertyRefExpr *, Stmt *> PropGetters;
Mike Stump11289f42009-09-09 15:08:12 +0000138
Steve Naroff22216db2008-12-04 23:50:32 +0000139 // This maps an original source AST to it's rewritten form. This allows
140 // us to avoid rewriting the same node twice (which is very uncommon).
141 // This is needed to support some of the exotic property rewriting.
142 llvm::DenseMap<Stmt *, Stmt *> ReplacedNodes;
Steve Narofff326f402008-12-03 00:56:33 +0000143
Steve Naroff677ab3a2008-10-27 17:20:55 +0000144 FunctionDecl *CurFunctionDef;
Steve Naroffd8907b72008-10-29 18:15:37 +0000145 VarDecl *GlobalVarDecl;
Mike Stump11289f42009-09-09 15:08:12 +0000146
Steve Naroff08628db2008-12-09 12:56:34 +0000147 bool DisableReplaceStmt;
Mike Stump11289f42009-09-09 15:08:12 +0000148
Fariborz Jahanian93191af2007-10-18 19:23:00 +0000149 static const int OBJC_ABI_VERSION =7 ;
Chris Lattnere99c8322007-10-11 00:43:27 +0000150 public:
Ted Kremenek380df932008-05-31 20:11:04 +0000151 virtual void Initialize(ASTContext &context);
152
Chris Lattner3c799d72007-10-24 17:06:59 +0000153 // Top Level Driver code.
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000154 virtual void HandleTopLevelDecl(DeclGroupRef D) {
155 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I)
156 HandleTopLevelSingleDecl(*I);
157 }
158 void HandleTopLevelSingleDecl(Decl *D);
Chris Lattner0bd1c972007-10-16 21:07:07 +0000159 void HandleDeclInMainFile(Decl *D);
Eli Friedman94cf21e2009-05-18 22:20:00 +0000160 RewriteObjC(std::string inFile, llvm::raw_ostream *OS,
Eli Friedmanf22439a2009-05-18 22:39:16 +0000161 Diagnostic &D, const LangOptions &LOpts,
162 bool silenceMacroWarn);
Ted Kremenek6231e7e2008-08-08 04:15:52 +0000163
164 ~RewriteObjC() {}
Mike Stump11289f42009-09-09 15:08:12 +0000165
Chris Lattnercf169832009-03-28 04:11:33 +0000166 virtual void HandleTranslationUnit(ASTContext &C);
Mike Stump11289f42009-09-09 15:08:12 +0000167
Chris Lattner2e0d2602008-01-31 19:37:57 +0000168 void ReplaceStmt(Stmt *Old, Stmt *New) {
Steve Naroff22216db2008-12-04 23:50:32 +0000169 Stmt *ReplacingStmt = ReplacedNodes[Old];
Mike Stump11289f42009-09-09 15:08:12 +0000170
Steve Naroff22216db2008-12-04 23:50:32 +0000171 if (ReplacingStmt)
172 return; // We can't rewrite the same node twice.
Chris Lattner2e0d2602008-01-31 19:37:57 +0000173
Steve Naroff08628db2008-12-09 12:56:34 +0000174 if (DisableReplaceStmt)
175 return; // Used when rewriting the assignment of a property setter.
176
Steve Naroff22216db2008-12-04 23:50:32 +0000177 // If replacement succeeded or warning disabled return with no warning.
178 if (!Rewrite.ReplaceStmt(Old, New)) {
179 ReplacedNodes[Old] = New;
180 return;
181 }
182 if (SilenceRewriteMacroWarning)
183 return;
Chris Lattner8488c822008-11-18 07:04:44 +0000184 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
185 << Old->getSourceRange();
Chris Lattner2e0d2602008-01-31 19:37:57 +0000186 }
Steve Naroff08628db2008-12-09 12:56:34 +0000187
188 void ReplaceStmtWithRange(Stmt *Old, Stmt *New, SourceRange SrcRange) {
189 // Measaure the old text.
190 int Size = Rewrite.getRangeSize(SrcRange);
191 if (Size == -1) {
192 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
193 << Old->getSourceRange();
194 return;
195 }
196 // Get the new text.
197 std::string SStr;
198 llvm::raw_string_ostream S(SStr);
Chris Lattnerc61089a2009-06-30 01:26:17 +0000199 New->printPretty(S, *Context, 0, PrintingPolicy(LangOpts));
Steve Naroff08628db2008-12-09 12:56:34 +0000200 const std::string &Str = S.str();
201
202 // If replacement succeeded or warning disabled return with no warning.
Daniel Dunbardec484a2009-08-19 19:10:30 +0000203 if (!Rewrite.ReplaceText(SrcRange.getBegin(), Size, Str)) {
Steve Naroff08628db2008-12-09 12:56:34 +0000204 ReplacedNodes[Old] = New;
205 return;
206 }
207 if (SilenceRewriteMacroWarning)
208 return;
209 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
210 << Old->getSourceRange();
211 }
212
Steve Naroff00a31762008-03-27 22:29:16 +0000213 void InsertText(SourceLocation Loc, const char *StrData, unsigned StrLen,
214 bool InsertAfter = true) {
Chris Lattner9cc55f52008-01-31 19:51:04 +0000215 // If insertion succeeded or warning disabled return with no warning.
Daniel Dunbardec484a2009-08-19 19:10:30 +0000216 if (!Rewrite.InsertText(Loc, llvm::StringRef(StrData, StrLen),
217 InsertAfter) ||
Chris Lattner1780a852008-01-31 19:42:41 +0000218 SilenceRewriteMacroWarning)
219 return;
Mike Stump11289f42009-09-09 15:08:12 +0000220
Chris Lattner1780a852008-01-31 19:42:41 +0000221 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
222 }
Mike Stump11289f42009-09-09 15:08:12 +0000223
Chris Lattner9cc55f52008-01-31 19:51:04 +0000224 void RemoveText(SourceLocation Loc, unsigned StrLen) {
225 // If removal succeeded or warning disabled return with no warning.
226 if (!Rewrite.RemoveText(Loc, StrLen) || SilenceRewriteMacroWarning)
227 return;
Mike Stump11289f42009-09-09 15:08:12 +0000228
Chris Lattner9cc55f52008-01-31 19:51:04 +0000229 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
230 }
Chris Lattner3c799d72007-10-24 17:06:59 +0000231
Chris Lattner9cc55f52008-01-31 19:51:04 +0000232 void ReplaceText(SourceLocation Start, unsigned OrigLength,
233 const char *NewStr, unsigned NewLength) {
234 // If removal succeeded or warning disabled return with no warning.
Daniel Dunbardec484a2009-08-19 19:10:30 +0000235 if (!Rewrite.ReplaceText(Start, OrigLength,
236 llvm::StringRef(NewStr, NewLength)) ||
Chris Lattner9cc55f52008-01-31 19:51:04 +0000237 SilenceRewriteMacroWarning)
238 return;
Mike Stump11289f42009-09-09 15:08:12 +0000239
Chris Lattner9cc55f52008-01-31 19:51:04 +0000240 Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
241 }
Mike Stump11289f42009-09-09 15:08:12 +0000242
Chris Lattner3c799d72007-10-24 17:06:59 +0000243 // Syntactic Rewriting.
Steve Narofff36987c2007-11-04 22:37:50 +0000244 void RewritePrologue(SourceLocation Loc);
Fariborz Jahanian80258362008-01-19 00:30:35 +0000245 void RewriteInclude();
Chris Lattner3c799d72007-10-24 17:06:59 +0000246 void RewriteTabs();
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000247 void RewriteForwardClassDecl(ObjCClassDecl *Dcl);
Steve Naroffc038b3a2008-12-02 17:36:43 +0000248 void RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
249 ObjCImplementationDecl *IMD,
250 ObjCCategoryImplDecl *CID);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000251 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
Douglas Gregor6e6ad602009-01-20 01:17:11 +0000252 void RewriteImplementationDecl(Decl *Dcl);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000253 void RewriteObjCMethodDecl(ObjCMethodDecl *MDecl, std::string &ResultStr);
254 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
255 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
256 void RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *Dcl);
257 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
Steve Naroff0c0f5ba2009-01-11 01:06:09 +0000258 void RewriteProperty(ObjCPropertyDecl *prop);
Steve Naroff5cdcd9b2007-10-30 23:14:51 +0000259 void RewriteFunctionDecl(FunctionDecl *FD);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000260 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
Steve Naroff873bd842008-07-29 18:15:38 +0000261 void RewriteObjCQualifiedInterfaceTypes(Expr *E);
Steve Naroff50d42052007-11-01 13:24:47 +0000262 bool needToScanForQualifiers(QualType T);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000263 ObjCInterfaceDecl *isSuperReceiver(Expr *recExpr);
Steve Naroff7fa2f042007-11-15 10:28:18 +0000264 QualType getSuperStructType();
Steve Naroffce8e8862008-03-15 00:55:56 +0000265 QualType getConstantStringStructType();
Steve Naroffcd92aeb2008-05-31 14:15:04 +0000266 bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf);
Mike Stump11289f42009-09-09 15:08:12 +0000267
Chris Lattner3c799d72007-10-24 17:06:59 +0000268 // Expression Rewriting.
Steve Naroff20113382007-11-09 15:20:18 +0000269 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
Steve Naroff4588d0f2008-12-04 16:24:46 +0000270 void CollectPropertySetters(Stmt *S);
Mike Stump11289f42009-09-09 15:08:12 +0000271
Steve Naroff1042ff32008-12-08 16:43:47 +0000272 Stmt *CurrentBody;
273 ParentMap *PropParentMap; // created lazily.
Mike Stump11289f42009-09-09 15:08:12 +0000274
Chris Lattner69534692007-10-24 16:57:36 +0000275 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
Chris Lattner37f5b7d2008-05-23 20:40:52 +0000276 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV, SourceLocation OrigStart);
Steve Naroff4588d0f2008-12-04 16:24:46 +0000277 Stmt *RewritePropertyGetter(ObjCPropertyRefExpr *PropRefExpr);
Mike Stump11289f42009-09-09 15:08:12 +0000278 Stmt *RewritePropertySetter(BinaryOperator *BinOp, Expr *newStmt,
Steve Naroff08628db2008-12-09 12:56:34 +0000279 SourceRange SrcRange);
Steve Naroffe4f9b232007-11-05 14:50:49 +0000280 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
Chris Lattner69534692007-10-24 16:57:36 +0000281 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroffa397efd2007-11-03 11:27:19 +0000282 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian33c0e812007-12-07 18:47:10 +0000283 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Steve Naroffec60b432009-12-05 21:43:12 +0000284 void WarnAboutReturnGotoStmts(Stmt *S);
285 void HasReturnStmts(Stmt *S, bool &hasReturns);
286 void RewriteTryReturnStmts(Stmt *S);
287 void RewriteSyncReturnStmts(Stmt *S, std::string buf);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000288 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
Fariborz Jahanian284011b2008-01-29 22:59:37 +0000289 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000290 Stmt *RewriteObjCCatchStmt(ObjCAtCatchStmt *S);
291 Stmt *RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S);
292 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
Chris Lattnera779d692008-01-31 05:10:40 +0000293 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
294 SourceLocation OrigEnd);
Mike Stump11289f42009-09-09 15:08:12 +0000295 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
Steve Naroff574440f2007-10-24 22:48:43 +0000296 Expr **args, unsigned nargs);
Fariborz Jahanian965a8962008-01-08 22:06:28 +0000297 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp);
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +0000298 Stmt *RewriteBreakStmt(BreakStmt *S);
299 Stmt *RewriteContinueStmt(ContinueStmt *S);
Fariborz Jahanian965a8962008-01-08 22:06:28 +0000300 void SynthCountByEnumWithState(std::string &buf);
Mike Stump11289f42009-09-09 15:08:12 +0000301
Steve Naroff5cdcd9b2007-10-30 23:14:51 +0000302 void SynthMsgSendFunctionDecl();
Steve Naroff7fa2f042007-11-15 10:28:18 +0000303 void SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +0000304 void SynthMsgSendStretFunctionDecl();
Fariborz Jahanian4f76f222007-12-03 21:26:48 +0000305 void SynthMsgSendFpretFunctionDecl();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +0000306 void SynthMsgSendSuperStretFunctionDecl();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +0000307 void SynthGetClassFunctionDecl();
Steve Naroffb2f8ff12007-12-07 03:50:46 +0000308 void SynthGetMetaClassFunctionDecl();
Fariborz Jahanian31e18502007-12-04 21:47:40 +0000309 void SynthSelGetUidFunctionDecl();
Steve Naroff17978c42008-03-11 17:37:02 +0000310 void SynthSuperContructorFunctionDecl();
Mike Stump11289f42009-09-09 15:08:12 +0000311
Chris Lattner3c799d72007-10-24 17:06:59 +0000312 // Metadata emission.
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000313 void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanian51f21822007-10-25 20:55:25 +0000314 std::string &Result);
Mike Stump11289f42009-09-09 15:08:12 +0000315
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000316 void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
Fariborz Jahanian51f21822007-10-25 20:55:25 +0000317 std::string &Result);
Mike Stump11289f42009-09-09 15:08:12 +0000318
Douglas Gregor29bd76f2009-04-23 01:02:12 +0000319 template<typename MethodIterator>
320 void RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
321 MethodIterator MethodEnd,
Fariborz Jahanian3df412a2007-10-25 00:14:44 +0000322 bool IsInstanceMethod,
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +0000323 const char *prefix,
Chris Lattner211f8b82007-10-25 17:07:24 +0000324 const char *ClassName,
325 std::string &Result);
Mike Stump11289f42009-09-09 15:08:12 +0000326
Steve Naroffd9803712009-04-29 16:37:50 +0000327 void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
328 const char *prefix,
329 const char *ClassName,
330 std::string &Result);
331 void RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> &Prots,
Mike Stump11289f42009-09-09 15:08:12 +0000332 const char *prefix,
Steve Naroffd9803712009-04-29 16:37:50 +0000333 const char *ClassName,
334 std::string &Result);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000335 void SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian99e96b02007-10-26 19:46:17 +0000336 std::string &Result);
Mike Stump11289f42009-09-09 15:08:12 +0000337 void SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
338 ObjCIvarDecl *ivar,
Fariborz Jahanian99e96b02007-10-26 19:46:17 +0000339 std::string &Result);
Steve Narofff8cfd162008-11-13 20:07:04 +0000340 void RewriteImplementations();
341 void SynthesizeMetaDataIntoBuffer(std::string &Result);
Mike Stump11289f42009-09-09 15:08:12 +0000342
Steve Naroff677ab3a2008-10-27 17:20:55 +0000343 // Block rewriting.
Mike Stump11289f42009-09-09 15:08:12 +0000344 void RewriteBlocksInFunctionProtoType(QualType funcType, NamedDecl *D);
Steve Naroff677ab3a2008-10-27 17:20:55 +0000345 void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
Mike Stump11289f42009-09-09 15:08:12 +0000346
Steve Naroff677ab3a2008-10-27 17:20:55 +0000347 void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
348 void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
Mike Stump11289f42009-09-09 15:08:12 +0000349
350 // Block specific rewrite rules.
Steve Naroff677ab3a2008-10-27 17:20:55 +0000351 void RewriteBlockCall(CallExpr *Exp);
352 void RewriteBlockPointerDecl(NamedDecl *VD);
Fariborz Jahanian02e07732009-12-23 02:07:37 +0000353 void RewriteByRefVar(VarDecl *VD);
Fariborz Jahaniane3891582010-01-05 18:04:40 +0000354 std::string SynthesizeByrefCopyDestroyHelper(VarDecl *VD, int flag);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +0000355 Stmt *RewriteBlockDeclRefExpr(Expr *VD);
Steve Naroff677ab3a2008-10-27 17:20:55 +0000356 void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
Mike Stump11289f42009-09-09 15:08:12 +0000357
358 std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
Steve Naroff677ab3a2008-10-27 17:20:55 +0000359 const char *funcName, std::string Tag);
Mike Stump11289f42009-09-09 15:08:12 +0000360 std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
Steve Naroff677ab3a2008-10-27 17:20:55 +0000361 const char *funcName, std::string Tag);
Steve Naroff30484702009-12-06 21:14:13 +0000362 std::string SynthesizeBlockImpl(BlockExpr *CE,
363 std::string Tag, std::string Desc);
364 std::string SynthesizeBlockDescriptor(std::string DescTag,
365 std::string ImplTag,
366 int i, const char *funcName,
367 unsigned hasCopy);
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +0000368 Stmt *SynthesizeBlockCall(CallExpr *Exp, const Expr* BlockExp);
Steve Naroff677ab3a2008-10-27 17:20:55 +0000369 void SynthesizeBlockLiterals(SourceLocation FunLocStart,
370 const char *FunName);
Steve Naroffe70a52a2009-12-05 15:55:59 +0000371 void RewriteRecordBody(RecordDecl *RD);
Mike Stump11289f42009-09-09 15:08:12 +0000372
Steve Naroff677ab3a2008-10-27 17:20:55 +0000373 void CollectBlockDeclRefInfo(BlockExpr *Exp);
374 void GetBlockCallExprs(Stmt *S);
375 void GetBlockDeclRefExprs(Stmt *S);
Mike Stump11289f42009-09-09 15:08:12 +0000376
Steve Naroff677ab3a2008-10-27 17:20:55 +0000377 // We avoid calling Type::isBlockPointerType(), since it operates on the
378 // canonical type. We only care if the top-level type is a closure pointer.
Ted Kremenek5a201952009-02-07 01:47:29 +0000379 bool isTopLevelBlockPointerType(QualType T) {
380 return isa<BlockPointerType>(T);
381 }
Mike Stump11289f42009-09-09 15:08:12 +0000382
Steve Naroff677ab3a2008-10-27 17:20:55 +0000383 // FIXME: This predicate seems like it would be useful to add to ASTContext.
384 bool isObjCType(QualType T) {
385 if (!LangOpts.ObjC1 && !LangOpts.ObjC2)
386 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000387
Steve Naroff677ab3a2008-10-27 17:20:55 +0000388 QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +0000389
Steve Naroff677ab3a2008-10-27 17:20:55 +0000390 if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
391 OCT == Context->getCanonicalType(Context->getObjCClassType()))
392 return true;
Mike Stump11289f42009-09-09 15:08:12 +0000393
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000394 if (const PointerType *PT = OCT->getAs<PointerType>()) {
Mike Stump11289f42009-09-09 15:08:12 +0000395 if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
Steve Narofffb4330f2009-06-17 22:40:22 +0000396 PT->getPointeeType()->isObjCQualifiedIdType())
Steve Naroff677ab3a2008-10-27 17:20:55 +0000397 return true;
398 }
399 return false;
400 }
401 bool PointerTypeTakesAnyBlockArguments(QualType QT);
Ted Kremenek5a201952009-02-07 01:47:29 +0000402 void GetExtentOfArgList(const char *Name, const char *&LParen,
403 const char *&RParen);
Steve Naroffc989a7b2008-11-03 23:29:32 +0000404 void RewriteCastExpr(CStyleCastExpr *CE);
Mike Stump11289f42009-09-09 15:08:12 +0000405
Steve Narofff4b992a2008-10-28 20:29:00 +0000406 FunctionDecl *SynthBlockInitFunctionDecl(const char *name);
Steve Naroffd8907b72008-10-29 18:15:37 +0000407 Stmt *SynthBlockInitExpr(BlockExpr *Exp);
Mike Stump11289f42009-09-09 15:08:12 +0000408
Steve Naroffd9803712009-04-29 16:37:50 +0000409 void QuoteDoublequotes(std::string &From, std::string &To) {
Mike Stump11289f42009-09-09 15:08:12 +0000410 for (unsigned i = 0; i < From.length(); i++) {
Steve Naroffd9803712009-04-29 16:37:50 +0000411 if (From[i] == '"')
412 To += "\\\"";
413 else
414 To += From[i];
415 }
416 }
Chris Lattnere99c8322007-10-11 00:43:27 +0000417 };
418}
419
Mike Stump11289f42009-09-09 15:08:12 +0000420void RewriteObjC::RewriteBlocksInFunctionProtoType(QualType funcType,
421 NamedDecl *D) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000422 if (FunctionProtoType *fproto = dyn_cast<FunctionProtoType>(funcType)) {
Mike Stump11289f42009-09-09 15:08:12 +0000423 for (FunctionProtoType::arg_type_iterator I = fproto->arg_type_begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +0000424 E = fproto->arg_type_end(); I && (I != E); ++I)
Steve Naroffa5c0db82008-12-11 21:05:33 +0000425 if (isTopLevelBlockPointerType(*I)) {
Steve Naroff677ab3a2008-10-27 17:20:55 +0000426 // All the args are checked/rewritten. Don't call twice!
427 RewriteBlockPointerDecl(D);
428 break;
429 }
430 }
431}
432
433void RewriteObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000434 const PointerType *PT = funcType->getAs<PointerType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +0000435 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000436 RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND);
Steve Naroff677ab3a2008-10-27 17:20:55 +0000437}
438
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000439static bool IsHeaderFile(const std::string &Filename) {
440 std::string::size_type DotPos = Filename.rfind('.');
Mike Stump11289f42009-09-09 15:08:12 +0000441
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000442 if (DotPos == std::string::npos) {
443 // no file extension
Mike Stump11289f42009-09-09 15:08:12 +0000444 return false;
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000445 }
Mike Stump11289f42009-09-09 15:08:12 +0000446
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000447 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
448 // C header: .h
449 // C++ header: .hh or .H;
450 return Ext == "h" || Ext == "hh" || Ext == "H";
Mike Stump11289f42009-09-09 15:08:12 +0000451}
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000452
Eli Friedman94cf21e2009-05-18 22:20:00 +0000453RewriteObjC::RewriteObjC(std::string inFile, llvm::raw_ostream* OS,
Eli Friedmanf22439a2009-05-18 22:39:16 +0000454 Diagnostic &D, const LangOptions &LOpts,
455 bool silenceMacroWarn)
456 : Diags(D), LangOpts(LOpts), InFileName(inFile), OutFile(OS),
457 SilenceRewriteMacroWarning(silenceMacroWarn) {
Steve Narofff9e7c902008-03-28 22:26:09 +0000458 IsHeader = IsHeaderFile(inFile);
Mike Stump11289f42009-09-09 15:08:12 +0000459 RewriteFailedDiag = Diags.getCustomDiagID(Diagnostic::Warning,
Steve Narofff9e7c902008-03-28 22:26:09 +0000460 "rewriting sub-expression within a macro (may not be correct)");
Mike Stump11289f42009-09-09 15:08:12 +0000461 TryFinallyContainsReturnDiag = Diags.getCustomDiagID(Diagnostic::Warning,
Ted Kremenek5a201952009-02-07 01:47:29 +0000462 "rewriter doesn't support user-specified control flow semantics "
463 "for @try/@finally (code may not execute properly)");
Steve Narofff9e7c902008-03-28 22:26:09 +0000464}
465
Eli Friedmana63ab2d2009-05-18 22:29:17 +0000466ASTConsumer *clang::CreateObjCRewriter(const std::string& InFile,
467 llvm::raw_ostream* OS,
Mike Stump11289f42009-09-09 15:08:12 +0000468 Diagnostic &Diags,
Eli Friedmanf22439a2009-05-18 22:39:16 +0000469 const LangOptions &LOpts,
470 bool SilenceRewriteMacroWarning) {
471 return new RewriteObjC(InFile, OS, Diags, LOpts, SilenceRewriteMacroWarning);
Chris Lattnere9c810c2007-11-30 22:25:36 +0000472}
Chris Lattnere99c8322007-10-11 00:43:27 +0000473
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000474void RewriteObjC::Initialize(ASTContext &context) {
Chris Lattner187f6262008-01-31 19:38:44 +0000475 Context = &context;
476 SM = &Context->getSourceManager();
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +0000477 TUDecl = Context->getTranslationUnitDecl();
Chris Lattner187f6262008-01-31 19:38:44 +0000478 MsgSendFunctionDecl = 0;
479 MsgSendSuperFunctionDecl = 0;
480 MsgSendStretFunctionDecl = 0;
481 MsgSendSuperStretFunctionDecl = 0;
482 MsgSendFpretFunctionDecl = 0;
483 GetClassFunctionDecl = 0;
484 GetMetaClassFunctionDecl = 0;
485 SelGetUidFunctionDecl = 0;
486 CFStringFunctionDecl = 0;
Chris Lattner187f6262008-01-31 19:38:44 +0000487 ConstantStringClassReference = 0;
488 NSStringRecord = 0;
Steve Naroff677ab3a2008-10-27 17:20:55 +0000489 CurMethodDef = 0;
490 CurFunctionDef = 0;
Steve Naroff08628db2008-12-09 12:56:34 +0000491 GlobalVarDecl = 0;
Chris Lattner187f6262008-01-31 19:38:44 +0000492 SuperStructDecl = 0;
Steve Naroffd9803712009-04-29 16:37:50 +0000493 ProtocolTypeDecl = 0;
Steve Naroff60a9ef62008-03-27 22:59:54 +0000494 ConstantStringDecl = 0;
Chris Lattner187f6262008-01-31 19:38:44 +0000495 BcLabelCount = 0;
Steve Naroff17978c42008-03-11 17:37:02 +0000496 SuperContructorFunctionDecl = 0;
Steve Naroffce8e8862008-03-15 00:55:56 +0000497 NumObjCStringLiterals = 0;
Steve Narofff1ab6002008-12-08 20:01:41 +0000498 PropParentMap = 0;
499 CurrentBody = 0;
Steve Naroff08628db2008-12-09 12:56:34 +0000500 DisableReplaceStmt = false;
Fariborz Jahanianbc6811c2010-01-07 22:51:18 +0000501 objc_impl_method = false;
Mike Stump11289f42009-09-09 15:08:12 +0000502
Chris Lattner187f6262008-01-31 19:38:44 +0000503 // Get the ID and start/end of the main file.
504 MainFileID = SM->getMainFileID();
505 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
506 MainFileStart = MainBuf->getBufferStart();
507 MainFileEnd = MainBuf->getBufferEnd();
Mike Stump11289f42009-09-09 15:08:12 +0000508
Chris Lattner184e65d2009-04-14 23:22:57 +0000509 Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOptions());
Mike Stump11289f42009-09-09 15:08:12 +0000510
Chris Lattner187f6262008-01-31 19:38:44 +0000511 // declaring objc_selector outside the parameter list removes a silly
512 // scope related warning...
Steve Naroff00a31762008-03-27 22:29:16 +0000513 if (IsHeader)
Steve Narofffcc6fd52009-02-03 20:39:18 +0000514 Preamble = "#pragma once\n";
Steve Naroff00a31762008-03-27 22:29:16 +0000515 Preamble += "struct objc_selector; struct objc_class;\n";
Steve Naroff6ab6dc72008-12-23 20:11:22 +0000516 Preamble += "struct __rw_objc_super { struct objc_object *object; ";
Steve Naroff00a31762008-03-27 22:29:16 +0000517 Preamble += "struct objc_object *superClass; ";
Steve Naroff17978c42008-03-11 17:37:02 +0000518 if (LangOpts.Microsoft) {
519 // Add a constructor for creating temporary objects.
Ted Kremenek5a201952009-02-07 01:47:29 +0000520 Preamble += "__rw_objc_super(struct objc_object *o, struct objc_object *s) "
521 ": ";
Steve Naroff00a31762008-03-27 22:29:16 +0000522 Preamble += "object(o), superClass(s) {} ";
Steve Naroff17978c42008-03-11 17:37:02 +0000523 }
Steve Naroff00a31762008-03-27 22:29:16 +0000524 Preamble += "};\n";
Steve Naroff00a31762008-03-27 22:29:16 +0000525 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
526 Preamble += "typedef struct objc_object Protocol;\n";
527 Preamble += "#define _REWRITER_typedef_Protocol\n";
528 Preamble += "#endif\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000529 if (LangOpts.Microsoft) {
530 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
531 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
532 } else
533 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
534 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend";
Steve Naroff00a31762008-03-27 22:29:16 +0000535 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000536 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper";
Steve Naroff00a31762008-03-27 22:29:16 +0000537 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000538 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend_stret";
Steve Naroff00a31762008-03-27 22:29:16 +0000539 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000540 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper_stret";
Steve Naroff00a31762008-03-27 22:29:16 +0000541 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000542 Preamble += "__OBJC_RW_DLLIMPORT double objc_msgSend_fpret";
Steve Naroff00a31762008-03-27 22:29:16 +0000543 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000544 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getClass";
Steve Naroff00a31762008-03-27 22:29:16 +0000545 Preamble += "(const char *);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000546 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getMetaClass";
Steve Naroff00a31762008-03-27 22:29:16 +0000547 Preamble += "(const char *);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000548 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw(struct objc_object *);\n";
549 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_enter(void *);\n";
550 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_exit(void *);\n";
551 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_exception_extract(void *);\n";
552 Preamble += "__OBJC_RW_DLLIMPORT int objc_exception_match";
Steve Naroffd30f8c52008-05-09 21:17:56 +0000553 Preamble += "(struct objc_class *, struct objc_object *);\n";
Steve Naroff8dd15252008-07-16 18:58:11 +0000554 // @synchronized hooks.
Steve Narofff122ff02008-12-08 17:30:33 +0000555 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_enter(struct objc_object *);\n";
556 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_exit(struct objc_object *);\n";
557 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
Steve Naroff00a31762008-03-27 22:29:16 +0000558 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
559 Preamble += "struct __objcFastEnumerationState {\n\t";
560 Preamble += "unsigned long state;\n\t";
Steve Naroff4dbab8a2008-04-04 22:58:22 +0000561 Preamble += "void **itemsPtr;\n\t";
Steve Naroff00a31762008-03-27 22:29:16 +0000562 Preamble += "unsigned long *mutationsPtr;\n\t";
563 Preamble += "unsigned long extra[5];\n};\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000564 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
Steve Naroff00a31762008-03-27 22:29:16 +0000565 Preamble += "#define __FASTENUMERATIONSTATE\n";
566 Preamble += "#endif\n";
567 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
568 Preamble += "struct __NSConstantStringImpl {\n";
569 Preamble += " int *isa;\n";
570 Preamble += " int flags;\n";
571 Preamble += " char *str;\n";
572 Preamble += " long length;\n";
573 Preamble += "};\n";
Steve Naroffdd514e02008-08-05 20:04:48 +0000574 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
575 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
576 Preamble += "#else\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000577 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
Steve Naroffdd514e02008-08-05 20:04:48 +0000578 Preamble += "#endif\n";
Steve Naroff00a31762008-03-27 22:29:16 +0000579 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
580 Preamble += "#endif\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +0000581 // Blocks preamble.
582 Preamble += "#ifndef BLOCK_IMPL\n";
583 Preamble += "#define BLOCK_IMPL\n";
584 Preamble += "struct __block_impl {\n";
585 Preamble += " void *isa;\n";
586 Preamble += " int Flags;\n";
Steve Naroff30484702009-12-06 21:14:13 +0000587 Preamble += " int Reserved;\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +0000588 Preamble += " void *FuncPtr;\n";
589 Preamble += "};\n";
Steve Naroff61d879e2008-12-16 15:50:30 +0000590 Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
Steve Naroff287a2bf2009-12-06 01:52:22 +0000591 Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n";
Steve Naroff2b3843d2009-12-06 01:33:56 +0000592 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_assign(void *, const void *, const int);\n";
593 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
594 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
595 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
596 Preamble += "#else\n";
Steve Naroff7bf01ea2010-01-05 18:09:31 +0000597 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n";
598 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n";
Steve Naroff2b3843d2009-12-06 01:33:56 +0000599 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
600 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
601 Preamble += "#endif\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +0000602 Preamble += "#endif\n";
Steve Naroffcb04e882008-10-27 18:50:14 +0000603 if (LangOpts.Microsoft) {
Steve Narofff122ff02008-12-08 17:30:33 +0000604 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
605 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
Steve Naroffcb04e882008-10-27 18:50:14 +0000606 Preamble += "#define __attribute__(X)\n";
607 }
Fariborz Jahanian7fac6552010-01-05 19:21:35 +0000608 else {
Fariborz Jahanian02e07732009-12-23 02:07:37 +0000609 Preamble += "#define __block\n";
Fariborz Jahanian7fac6552010-01-05 19:21:35 +0000610 Preamble += "#define __weak\n";
611 }
Chris Lattner187f6262008-01-31 19:38:44 +0000612}
613
614
Chris Lattner3c799d72007-10-24 17:06:59 +0000615//===----------------------------------------------------------------------===//
616// Top Level Driver Code
617//===----------------------------------------------------------------------===//
618
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000619void RewriteObjC::HandleTopLevelSingleDecl(Decl *D) {
Chris Lattner0bd1c972007-10-16 21:07:07 +0000620 // Two cases: either the decl could be in the main file, or it could be in a
621 // #included file. If the former, rewrite it now. If the later, check to see
622 // if we rewrote the #include/#import.
623 SourceLocation Loc = D->getLocation();
Chris Lattner8a425862009-01-16 07:36:28 +0000624 Loc = SM->getInstantiationLoc(Loc);
Mike Stump11289f42009-09-09 15:08:12 +0000625
Chris Lattner0bd1c972007-10-16 21:07:07 +0000626 // If this is for a builtin, ignore it.
627 if (Loc.isInvalid()) return;
628
Steve Naroffdb1ab1c2007-10-23 23:50:29 +0000629 // Look for built-in declarations that we need to refer during the rewrite.
630 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +0000631 RewriteFunctionDecl(FD);
Steve Naroff08899ff2008-04-15 22:42:06 +0000632 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
Steve Naroffa397efd2007-11-03 11:27:19 +0000633 // declared in <Foundation/NSString.h>
Chris Lattner86d7d912008-11-24 03:54:41 +0000634 if (strcmp(FVD->getNameAsCString(), "_NSConstantStringClassReference") == 0) {
Steve Naroffa397efd2007-11-03 11:27:19 +0000635 ConstantStringClassReference = FVD;
636 return;
637 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000638 } else if (ObjCInterfaceDecl *MD = dyn_cast<ObjCInterfaceDecl>(D)) {
Steve Naroff161a92b2007-10-26 20:53:56 +0000639 RewriteInterfaceDecl(MD);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000640 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
Steve Naroff5448cf62007-10-30 13:30:57 +0000641 RewriteCategoryDecl(CD);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000642 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
Steve Narofff921385f2007-10-30 16:42:30 +0000643 RewriteProtocolDecl(PD);
Mike Stump11289f42009-09-09 15:08:12 +0000644 } else if (ObjCForwardProtocolDecl *FP =
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000645 dyn_cast<ObjCForwardProtocolDecl>(D)){
Fariborz Jahanianda6165c2007-11-14 00:42:16 +0000646 RewriteForwardProtocolDecl(FP);
Douglas Gregorc25d7a72009-01-09 00:49:46 +0000647 } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) {
648 // Recurse into linkage specifications
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000649 for (DeclContext::decl_iterator DI = LSD->decls_begin(),
650 DIEnd = LSD->decls_end();
Douglas Gregorc25d7a72009-01-09 00:49:46 +0000651 DI != DIEnd; ++DI)
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000652 HandleTopLevelSingleDecl(*DI);
Steve Naroffdb1ab1c2007-10-23 23:50:29 +0000653 }
Chris Lattner3c799d72007-10-24 17:06:59 +0000654 // If we have a decl in the main file, see if we should rewrite it.
Ted Kremenekd61ed3b2008-04-14 21:24:13 +0000655 if (SM->isFromMainFile(Loc))
Chris Lattner0bd1c972007-10-16 21:07:07 +0000656 return HandleDeclInMainFile(D);
Chris Lattner0bd1c972007-10-16 21:07:07 +0000657}
658
Chris Lattner3c799d72007-10-24 17:06:59 +0000659//===----------------------------------------------------------------------===//
660// Syntactic (non-AST) Rewriting Code
661//===----------------------------------------------------------------------===//
662
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000663void RewriteObjC::RewriteInclude() {
Chris Lattnerd32480d2009-01-17 06:22:33 +0000664 SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID);
Fariborz Jahanian80258362008-01-19 00:30:35 +0000665 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
666 const char *MainBufStart = MainBuf.first;
667 const char *MainBufEnd = MainBuf.second;
668 size_t ImportLen = strlen("import");
669 size_t IncludeLen = strlen("include");
Mike Stump11289f42009-09-09 15:08:12 +0000670
Fariborz Jahanian137d6932008-01-19 01:03:17 +0000671 // Loop over the whole file, looking for includes.
Fariborz Jahanian80258362008-01-19 00:30:35 +0000672 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
673 if (*BufPtr == '#') {
674 if (++BufPtr == MainBufEnd)
675 return;
676 while (*BufPtr == ' ' || *BufPtr == '\t')
677 if (++BufPtr == MainBufEnd)
678 return;
679 if (!strncmp(BufPtr, "import", ImportLen)) {
680 // replace import with include
Mike Stump11289f42009-09-09 15:08:12 +0000681 SourceLocation ImportLoc =
Fariborz Jahanian80258362008-01-19 00:30:35 +0000682 LocStart.getFileLocWithOffset(BufPtr-MainBufStart);
Chris Lattner9cc55f52008-01-31 19:51:04 +0000683 ReplaceText(ImportLoc, ImportLen, "include", IncludeLen);
Fariborz Jahanian80258362008-01-19 00:30:35 +0000684 BufPtr += ImportLen;
685 }
686 }
687 }
Chris Lattner0bd1c972007-10-16 21:07:07 +0000688}
689
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000690void RewriteObjC::RewriteTabs() {
Chris Lattner3c799d72007-10-24 17:06:59 +0000691 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
692 const char *MainBufStart = MainBuf.first;
693 const char *MainBufEnd = MainBuf.second;
Mike Stump11289f42009-09-09 15:08:12 +0000694
Chris Lattner3c799d72007-10-24 17:06:59 +0000695 // Loop over the whole file, looking for tabs.
696 for (const char *BufPtr = MainBufStart; BufPtr != MainBufEnd; ++BufPtr) {
697 if (*BufPtr != '\t')
698 continue;
Mike Stump11289f42009-09-09 15:08:12 +0000699
Chris Lattner3c799d72007-10-24 17:06:59 +0000700 // Okay, we found a tab. This tab will turn into at least one character,
701 // but it depends on which 'virtual column' it is in. Compute that now.
702 unsigned VCol = 0;
703 while (BufPtr-VCol != MainBufStart && BufPtr[-VCol-1] != '\t' &&
704 BufPtr[-VCol-1] != '\n' && BufPtr[-VCol-1] != '\r')
705 ++VCol;
Mike Stump11289f42009-09-09 15:08:12 +0000706
Chris Lattner3c799d72007-10-24 17:06:59 +0000707 // Okay, now that we know the virtual column, we know how many spaces to
708 // insert. We assume 8-character tab-stops.
709 unsigned Spaces = 8-(VCol & 7);
Mike Stump11289f42009-09-09 15:08:12 +0000710
Chris Lattner3c799d72007-10-24 17:06:59 +0000711 // Get the location of the tab.
Chris Lattnerd32480d2009-01-17 06:22:33 +0000712 SourceLocation TabLoc = SM->getLocForStartOfFile(MainFileID);
713 TabLoc = TabLoc.getFileLocWithOffset(BufPtr-MainBufStart);
Mike Stump11289f42009-09-09 15:08:12 +0000714
Chris Lattner3c799d72007-10-24 17:06:59 +0000715 // Rewrite the single tab character into a sequence of spaces.
Chris Lattner9cc55f52008-01-31 19:51:04 +0000716 ReplaceText(TabLoc, 1, " ", Spaces);
Chris Lattner3c799d72007-10-24 17:06:59 +0000717 }
Chris Lattner16a0de42007-10-11 18:38:32 +0000718}
719
Steve Naroff9af94912008-12-02 15:48:25 +0000720static std::string getIvarAccessString(ObjCInterfaceDecl *ClassDecl,
721 ObjCIvarDecl *OID) {
722 std::string S;
723 S = "((struct ";
724 S += ClassDecl->getIdentifier()->getName();
725 S += "_IMPL *)self)->";
Daniel Dunbar70e7ead2009-10-18 20:26:27 +0000726 S += OID->getName();
Steve Naroff9af94912008-12-02 15:48:25 +0000727 return S;
728}
729
Steve Naroffc038b3a2008-12-02 17:36:43 +0000730void RewriteObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
731 ObjCImplementationDecl *IMD,
732 ObjCCategoryImplDecl *CID) {
Steve Naroffe1908e32008-12-01 20:33:01 +0000733 SourceLocation startLoc = PID->getLocStart();
734 InsertText(startLoc, "// ", 3);
Steve Naroff9af94912008-12-02 15:48:25 +0000735 const char *startBuf = SM->getCharacterData(startLoc);
736 assert((*startBuf == '@') && "bogus @synthesize location");
737 const char *semiBuf = strchr(startBuf, ';');
738 assert((*semiBuf == ';') && "@synthesize: can't find ';'");
Ted Kremenek5a201952009-02-07 01:47:29 +0000739 SourceLocation onePastSemiLoc =
740 startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
Steve Naroff9af94912008-12-02 15:48:25 +0000741
742 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
743 return; // FIXME: is this correct?
Mike Stump11289f42009-09-09 15:08:12 +0000744
Steve Naroff9af94912008-12-02 15:48:25 +0000745 // Generate the 'getter' function.
Steve Naroff9af94912008-12-02 15:48:25 +0000746 ObjCPropertyDecl *PD = PID->getPropertyDecl();
Steve Naroff9af94912008-12-02 15:48:25 +0000747 ObjCInterfaceDecl *ClassDecl = PD->getGetterMethodDecl()->getClassInterface();
Steve Naroff9af94912008-12-02 15:48:25 +0000748 ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
Mike Stump11289f42009-09-09 15:08:12 +0000749
Steve Naroff003d00e2008-12-02 16:05:55 +0000750 if (!OID)
751 return;
Mike Stump11289f42009-09-09 15:08:12 +0000752
Steve Naroff003d00e2008-12-02 16:05:55 +0000753 std::string Getr;
754 RewriteObjCMethodDecl(PD->getGetterMethodDecl(), Getr);
755 Getr += "{ ";
756 // Synthesize an explicit cast to gain access to the ivar.
Mike Stump11289f42009-09-09 15:08:12 +0000757 // FIXME: deal with code generation implications for various property
758 // attributes (copy, retain, nonatomic).
Steve Naroff06297042008-12-02 17:54:50 +0000759 // See objc-act.c:objc_synthesize_new_getter() for details.
Steve Naroff003d00e2008-12-02 16:05:55 +0000760 Getr += "return " + getIvarAccessString(ClassDecl, OID);
761 Getr += "; }";
Steve Naroff9af94912008-12-02 15:48:25 +0000762 InsertText(onePastSemiLoc, Getr.c_str(), Getr.size());
Steve Naroff9af94912008-12-02 15:48:25 +0000763 if (PD->isReadOnly())
764 return;
Mike Stump11289f42009-09-09 15:08:12 +0000765
Steve Naroff9af94912008-12-02 15:48:25 +0000766 // Generate the 'setter' function.
767 std::string Setr;
768 RewriteObjCMethodDecl(PD->getSetterMethodDecl(), Setr);
Steve Naroff9af94912008-12-02 15:48:25 +0000769 Setr += "{ ";
Steve Naroff003d00e2008-12-02 16:05:55 +0000770 // Synthesize an explicit cast to initialize the ivar.
Mike Stump11289f42009-09-09 15:08:12 +0000771 // FIXME: deal with code generation implications for various property
772 // attributes (copy, retain, nonatomic).
Steve Narofff326f402008-12-03 00:56:33 +0000773 // See objc-act.c:objc_synthesize_new_setter() for details.
Steve Naroff003d00e2008-12-02 16:05:55 +0000774 Setr += getIvarAccessString(ClassDecl, OID) + " = ";
Steve Naroff1fa7bd12008-12-11 19:29:16 +0000775 Setr += PD->getNameAsCString();
Steve Naroff003d00e2008-12-02 16:05:55 +0000776 Setr += "; }";
Steve Naroff9af94912008-12-02 15:48:25 +0000777 InsertText(onePastSemiLoc, Setr.c_str(), Setr.size());
Steve Naroffe1908e32008-12-01 20:33:01 +0000778}
Chris Lattner16a0de42007-10-11 18:38:32 +0000779
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000780void RewriteObjC::RewriteForwardClassDecl(ObjCClassDecl *ClassDecl) {
Chris Lattner3c799d72007-10-24 17:06:59 +0000781 // Get the start location and compute the semi location.
782 SourceLocation startLoc = ClassDecl->getLocation();
783 const char *startBuf = SM->getCharacterData(startLoc);
784 const char *semiPtr = strchr(startBuf, ';');
Mike Stump11289f42009-09-09 15:08:12 +0000785
Chris Lattner3c799d72007-10-24 17:06:59 +0000786 // Translate to typedef's that forward reference structs with the same name
787 // as the class. As a convenience, we include the original declaration
788 // as a comment.
789 std::string typedefString;
790 typedefString += "// ";
Steve Naroff574440f2007-10-24 22:48:43 +0000791 typedefString.append(startBuf, semiPtr-startBuf+1);
792 typedefString += "\n";
Chris Lattner9ee23b72009-02-20 18:04:31 +0000793 for (ObjCClassDecl::iterator I = ClassDecl->begin(), E = ClassDecl->end();
794 I != E; ++I) {
Ted Kremenek9b124e12009-11-18 00:28:11 +0000795 ObjCInterfaceDecl *ForwardDecl = I->getInterface();
Steve Naroff1b232132007-11-09 12:50:28 +0000796 typedefString += "#ifndef _REWRITER_typedef_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000797 typedefString += ForwardDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +0000798 typedefString += "\n";
799 typedefString += "#define _REWRITER_typedef_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000800 typedefString += ForwardDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +0000801 typedefString += "\n";
Steve Naroff98eb8d12007-11-05 14:36:37 +0000802 typedefString += "typedef struct objc_object ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000803 typedefString += ForwardDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +0000804 typedefString += ";\n#endif\n";
Steve Naroff574440f2007-10-24 22:48:43 +0000805 }
Mike Stump11289f42009-09-09 15:08:12 +0000806
Steve Naroff574440f2007-10-24 22:48:43 +0000807 // Replace the @class with typedefs corresponding to the classes.
Mike Stump11289f42009-09-09 15:08:12 +0000808 ReplaceText(startLoc, semiPtr-startBuf+1,
Chris Lattner9cc55f52008-01-31 19:51:04 +0000809 typedefString.c_str(), typedefString.size());
Chris Lattner3c799d72007-10-24 17:06:59 +0000810}
811
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000812void RewriteObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
Steve Naroff3ce37a62007-12-14 23:37:57 +0000813 SourceLocation LocStart = Method->getLocStart();
814 SourceLocation LocEnd = Method->getLocEnd();
Mike Stump11289f42009-09-09 15:08:12 +0000815
Chris Lattner88ea93e2009-02-04 01:06:56 +0000816 if (SM->getInstantiationLineNumber(LocEnd) >
817 SM->getInstantiationLineNumber(LocStart)) {
Steve Naroffe020fa12008-10-21 13:37:27 +0000818 InsertText(LocStart, "#if 0\n", 6);
819 ReplaceText(LocEnd, 1, ";\n#endif\n", 9);
Steve Naroff3ce37a62007-12-14 23:37:57 +0000820 } else {
Chris Lattner1780a852008-01-31 19:42:41 +0000821 InsertText(LocStart, "// ", 3);
Steve Naroff5448cf62007-10-30 13:30:57 +0000822 }
823}
824
Mike Stump11289f42009-09-09 15:08:12 +0000825void RewriteObjC::RewriteProperty(ObjCPropertyDecl *prop) {
Steve Naroff0c0f5ba2009-01-11 01:06:09 +0000826 SourceLocation Loc = prop->getLocation();
Mike Stump11289f42009-09-09 15:08:12 +0000827
Steve Naroff0c0f5ba2009-01-11 01:06:09 +0000828 ReplaceText(Loc, 0, "// ", 3);
Mike Stump11289f42009-09-09 15:08:12 +0000829
Steve Naroff0c0f5ba2009-01-11 01:06:09 +0000830 // FIXME: handle properties that are declared across multiple lines.
Fariborz Jahaniane8a30162007-11-07 00:09:37 +0000831}
832
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000833void RewriteObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
Steve Naroff5448cf62007-10-30 13:30:57 +0000834 SourceLocation LocStart = CatDecl->getLocStart();
Mike Stump11289f42009-09-09 15:08:12 +0000835
Steve Naroff5448cf62007-10-30 13:30:57 +0000836 // FIXME: handle category headers that are declared across multiple lines.
Chris Lattner9cc55f52008-01-31 19:51:04 +0000837 ReplaceText(LocStart, 0, "// ", 3);
Mike Stump11289f42009-09-09 15:08:12 +0000838
839 for (ObjCCategoryDecl::instmeth_iterator
840 I = CatDecl->instmeth_begin(), E = CatDecl->instmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000841 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +0000842 RewriteMethodDeclaration(*I);
Mike Stump11289f42009-09-09 15:08:12 +0000843 for (ObjCCategoryDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000844 I = CatDecl->classmeth_begin(), E = CatDecl->classmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000845 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +0000846 RewriteMethodDeclaration(*I);
847
Steve Naroff5448cf62007-10-30 13:30:57 +0000848 // Lastly, comment out the @end.
Ted Kremenekc7c64312010-01-07 01:20:12 +0000849 ReplaceText(CatDecl->getAtEndRange().getBegin(), 0, "// ", 3);
Steve Naroff5448cf62007-10-30 13:30:57 +0000850}
851
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000852void RewriteObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
Fariborz Jahanianfe38ba22007-11-14 01:37:46 +0000853 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
Mike Stump11289f42009-09-09 15:08:12 +0000854
Steve Narofff921385f2007-10-30 16:42:30 +0000855 SourceLocation LocStart = PDecl->getLocStart();
Mike Stump11289f42009-09-09 15:08:12 +0000856
Steve Narofff921385f2007-10-30 16:42:30 +0000857 // FIXME: handle protocol headers that are declared across multiple lines.
Chris Lattner9cc55f52008-01-31 19:51:04 +0000858 ReplaceText(LocStart, 0, "// ", 3);
Mike Stump11289f42009-09-09 15:08:12 +0000859
860 for (ObjCProtocolDecl::instmeth_iterator
861 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000862 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +0000863 RewriteMethodDeclaration(*I);
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000864 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000865 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000866 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +0000867 RewriteMethodDeclaration(*I);
868
Steve Narofff921385f2007-10-30 16:42:30 +0000869 // Lastly, comment out the @end.
Ted Kremenekc7c64312010-01-07 01:20:12 +0000870 SourceLocation LocEnd = PDecl->getAtEndRange().getBegin();
Chris Lattner9cc55f52008-01-31 19:51:04 +0000871 ReplaceText(LocEnd, 0, "// ", 3);
Steve Naroffa509f042007-11-14 15:03:57 +0000872
Fariborz Jahanianfe38ba22007-11-14 01:37:46 +0000873 // Must comment out @optional/@required
874 const char *startBuf = SM->getCharacterData(LocStart);
875 const char *endBuf = SM->getCharacterData(LocEnd);
876 for (const char *p = startBuf; p < endBuf; p++) {
877 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
878 std::string CommentedOptional = "/* @optional */";
Steve Naroffa509f042007-11-14 15:03:57 +0000879 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattner9cc55f52008-01-31 19:51:04 +0000880 ReplaceText(OptionalLoc, strlen("@optional"),
881 CommentedOptional.c_str(), CommentedOptional.size());
Mike Stump11289f42009-09-09 15:08:12 +0000882
Fariborz Jahanianfe38ba22007-11-14 01:37:46 +0000883 }
884 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
885 std::string CommentedRequired = "/* @required */";
Steve Naroffa509f042007-11-14 15:03:57 +0000886 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattner9cc55f52008-01-31 19:51:04 +0000887 ReplaceText(OptionalLoc, strlen("@required"),
888 CommentedRequired.c_str(), CommentedRequired.size());
Mike Stump11289f42009-09-09 15:08:12 +0000889
Fariborz Jahanianfe38ba22007-11-14 01:37:46 +0000890 }
891 }
Steve Narofff921385f2007-10-30 16:42:30 +0000892}
893
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000894void RewriteObjC::RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *PDecl) {
Fariborz Jahanianda6165c2007-11-14 00:42:16 +0000895 SourceLocation LocStart = PDecl->getLocation();
Steve Naroffc17b0562007-11-14 03:37:28 +0000896 if (LocStart.isInvalid())
897 assert(false && "Invalid SourceLocation");
Fariborz Jahanianda6165c2007-11-14 00:42:16 +0000898 // FIXME: handle forward protocol that are declared across multiple lines.
Chris Lattner9cc55f52008-01-31 19:51:04 +0000899 ReplaceText(LocStart, 0, "// ", 3);
Fariborz Jahanianda6165c2007-11-14 00:42:16 +0000900}
901
Mike Stump11289f42009-09-09 15:08:12 +0000902void RewriteObjC::RewriteObjCMethodDecl(ObjCMethodDecl *OMD,
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000903 std::string &ResultStr) {
Steve Naroff295570a2008-10-30 12:09:33 +0000904 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
Steve Naroffb067bbd2008-07-16 14:40:40 +0000905 const FunctionType *FPRetType = 0;
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000906 ResultStr += "\nstatic ";
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000907 if (OMD->getResultType()->isObjCQualifiedIdType())
Fariborz Jahanian24cb52c2007-12-17 21:03:50 +0000908 ResultStr += "id";
Steve Naroff1fa7bd12008-12-11 19:29:16 +0000909 else if (OMD->getResultType()->isFunctionPointerType() ||
910 OMD->getResultType()->isBlockPointerType()) {
Steve Naroffb067bbd2008-07-16 14:40:40 +0000911 // needs special handling, since pointer-to-functions have special
912 // syntax (where a decaration models use).
913 QualType retType = OMD->getResultType();
Steve Naroff1fa7bd12008-12-11 19:29:16 +0000914 QualType PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000915 if (const PointerType* PT = retType->getAs<PointerType>())
Steve Naroff1fa7bd12008-12-11 19:29:16 +0000916 PointeeTy = PT->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000917 else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>())
Steve Naroff1fa7bd12008-12-11 19:29:16 +0000918 PointeeTy = BPT->getPointeeType();
John McCall9dd450b2009-09-21 23:43:11 +0000919 if ((FPRetType = PointeeTy->getAs<FunctionType>())) {
Steve Naroff1fa7bd12008-12-11 19:29:16 +0000920 ResultStr += FPRetType->getResultType().getAsString();
921 ResultStr += "(*";
Steve Naroffb067bbd2008-07-16 14:40:40 +0000922 }
923 } else
Fariborz Jahanian24cb52c2007-12-17 21:03:50 +0000924 ResultStr += OMD->getResultType().getAsString();
Fariborz Jahanian7262fca2008-01-10 01:39:52 +0000925 ResultStr += " ";
Mike Stump11289f42009-09-09 15:08:12 +0000926
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000927 // Unique method name
Fariborz Jahanian56338352007-11-13 21:02:00 +0000928 std::string NameStr;
Mike Stump11289f42009-09-09 15:08:12 +0000929
Douglas Gregorffca3a22009-01-09 17:18:27 +0000930 if (OMD->isInstanceMethod())
Fariborz Jahanian56338352007-11-13 21:02:00 +0000931 NameStr += "_I_";
932 else
933 NameStr += "_C_";
Mike Stump11289f42009-09-09 15:08:12 +0000934
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000935 NameStr += OMD->getClassInterface()->getNameAsString();
Fariborz Jahanian56338352007-11-13 21:02:00 +0000936 NameStr += "_";
Mike Stump11289f42009-09-09 15:08:12 +0000937
938 if (ObjCCategoryImplDecl *CID =
Steve Naroff11b387f2009-01-08 19:41:02 +0000939 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000940 NameStr += CID->getNameAsString();
Fariborz Jahanian56338352007-11-13 21:02:00 +0000941 NameStr += "_";
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000942 }
Mike Stump11289f42009-09-09 15:08:12 +0000943 // Append selector names, replacing ':' with '_'
Chris Lattnere4b95692008-11-24 03:33:13 +0000944 {
945 std::string selString = OMD->getSelector().getAsString();
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000946 int len = selString.size();
947 for (int i = 0; i < len; i++)
948 if (selString[i] == ':')
949 selString[i] = '_';
Fariborz Jahanian56338352007-11-13 21:02:00 +0000950 NameStr += selString;
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000951 }
Fariborz Jahanian56338352007-11-13 21:02:00 +0000952 // Remember this name for metadata emission
953 MethodInternalNames[OMD] = NameStr;
954 ResultStr += NameStr;
Mike Stump11289f42009-09-09 15:08:12 +0000955
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000956 // Rewrite arguments
957 ResultStr += "(";
Mike Stump11289f42009-09-09 15:08:12 +0000958
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000959 // invisible arguments
Douglas Gregorffca3a22009-01-09 17:18:27 +0000960 if (OMD->isInstanceMethod()) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000961 QualType selfTy = Context->getObjCInterfaceType(OMD->getClassInterface());
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000962 selfTy = Context->getPointerType(selfTy);
Steve Naroffdc5b6b22008-03-12 00:25:36 +0000963 if (!LangOpts.Microsoft) {
964 if (ObjCSynthesizedStructs.count(OMD->getClassInterface()))
965 ResultStr += "struct ";
966 }
967 // When rewriting for Microsoft, explicitly omit the structure name.
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000968 ResultStr += OMD->getClassInterface()->getNameAsString();
Steve Naroffa1e115e2008-03-10 23:16:54 +0000969 ResultStr += " *";
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000970 }
971 else
Steve Naroffd9803712009-04-29 16:37:50 +0000972 ResultStr += Context->getObjCClassType().getAsString();
Mike Stump11289f42009-09-09 15:08:12 +0000973
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000974 ResultStr += " self, ";
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000975 ResultStr += Context->getObjCSelType().getAsString();
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000976 ResultStr += " _cmd";
Mike Stump11289f42009-09-09 15:08:12 +0000977
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000978 // Method arguments.
Chris Lattnera4997152009-02-20 18:43:26 +0000979 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
980 E = OMD->param_end(); PI != E; ++PI) {
981 ParmVarDecl *PDecl = *PI;
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000982 ResultStr += ", ";
Steve Naroffdcdcdcd2008-04-18 21:13:19 +0000983 if (PDecl->getType()->isObjCQualifiedIdType()) {
984 ResultStr += "id ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000985 ResultStr += PDecl->getNameAsString();
Steve Naroffdcdcdcd2008-04-18 21:13:19 +0000986 } else {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000987 std::string Name = PDecl->getNameAsString();
Steve Naroffa5c0db82008-12-11 21:05:33 +0000988 if (isTopLevelBlockPointerType(PDecl->getType())) {
Steve Naroff44df6a22008-10-30 14:45:29 +0000989 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000990 const BlockPointerType *BPT = PDecl->getType()->getAs<BlockPointerType>();
Douglas Gregor7de59662009-05-29 20:38:28 +0000991 Context->getPointerType(BPT->getPointeeType()).getAsStringInternal(Name,
992 Context->PrintingPolicy);
Steve Naroff44df6a22008-10-30 14:45:29 +0000993 } else
Douglas Gregor7de59662009-05-29 20:38:28 +0000994 PDecl->getType().getAsStringInternal(Name, Context->PrintingPolicy);
Steve Naroffdcdcdcd2008-04-18 21:13:19 +0000995 ResultStr += Name;
996 }
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000997 }
Fariborz Jahanianeab81cd2008-01-21 20:14:23 +0000998 if (OMD->isVariadic())
999 ResultStr += ", ...";
Fariborz Jahanian7262fca2008-01-10 01:39:52 +00001000 ResultStr += ") ";
Mike Stump11289f42009-09-09 15:08:12 +00001001
Steve Naroffb067bbd2008-07-16 14:40:40 +00001002 if (FPRetType) {
1003 ResultStr += ")"; // close the precedence "scope" for "*".
Mike Stump11289f42009-09-09 15:08:12 +00001004
Steve Naroffb067bbd2008-07-16 14:40:40 +00001005 // Now, emit the argument types (if any).
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001006 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
Steve Naroffb067bbd2008-07-16 14:40:40 +00001007 ResultStr += "(";
1008 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
1009 if (i) ResultStr += ", ";
1010 std::string ParamStr = FT->getArgType(i).getAsString();
1011 ResultStr += ParamStr;
1012 }
1013 if (FT->isVariadic()) {
1014 if (FT->getNumArgs()) ResultStr += ", ";
1015 ResultStr += "...";
1016 }
1017 ResultStr += ")";
1018 } else {
1019 ResultStr += "()";
1020 }
1021 }
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001022}
Douglas Gregor6e6ad602009-01-20 01:17:11 +00001023void RewriteObjC::RewriteImplementationDecl(Decl *OID) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001024 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
1025 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
Mike Stump11289f42009-09-09 15:08:12 +00001026
Fariborz Jahanianc54d8462007-11-13 20:04:28 +00001027 if (IMD)
Chris Lattner1780a852008-01-31 19:42:41 +00001028 InsertText(IMD->getLocStart(), "// ", 3);
Fariborz Jahanianc54d8462007-11-13 20:04:28 +00001029 else
Chris Lattner1780a852008-01-31 19:42:41 +00001030 InsertText(CID->getLocStart(), "// ", 3);
Mike Stump11289f42009-09-09 15:08:12 +00001031
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001032 for (ObjCCategoryImplDecl::instmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001033 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
1034 E = IMD ? IMD->instmeth_end() : CID->instmeth_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00001035 I != E; ++I) {
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001036 std::string ResultStr;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001037 ObjCMethodDecl *OMD = *I;
1038 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001039 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00001040 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Sebastian Redla7b98a72009-04-26 20:35:05 +00001041
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001042 const char *startBuf = SM->getCharacterData(LocStart);
1043 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattner9cc55f52008-01-31 19:51:04 +00001044 ReplaceText(LocStart, endBuf-startBuf,
1045 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001046 }
Mike Stump11289f42009-09-09 15:08:12 +00001047
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001048 for (ObjCCategoryImplDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001049 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
1050 E = IMD ? IMD->classmeth_end() : CID->classmeth_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00001051 I != E; ++I) {
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001052 std::string ResultStr;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001053 ObjCMethodDecl *OMD = *I;
1054 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001055 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00001056 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Mike Stump11289f42009-09-09 15:08:12 +00001057
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001058 const char *startBuf = SM->getCharacterData(LocStart);
1059 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattner9cc55f52008-01-31 19:51:04 +00001060 ReplaceText(LocStart, endBuf-startBuf,
Mike Stump11289f42009-09-09 15:08:12 +00001061 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001062 }
Steve Naroffe1908e32008-12-01 20:33:01 +00001063 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001064 I = IMD ? IMD->propimpl_begin() : CID->propimpl_begin(),
Mike Stump11289f42009-09-09 15:08:12 +00001065 E = IMD ? IMD->propimpl_end() : CID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00001066 I != E; ++I) {
Steve Naroffc038b3a2008-12-02 17:36:43 +00001067 RewritePropertyImplDecl(*I, IMD, CID);
Steve Naroffe1908e32008-12-01 20:33:01 +00001068 }
1069
Fariborz Jahanianc54d8462007-11-13 20:04:28 +00001070 if (IMD)
Chris Lattner1780a852008-01-31 19:42:41 +00001071 InsertText(IMD->getLocEnd(), "// ", 3);
Fariborz Jahanianc54d8462007-11-13 20:04:28 +00001072 else
Mike Stump11289f42009-09-09 15:08:12 +00001073 InsertText(CID->getLocEnd(), "// ", 3);
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001074}
1075
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001076void RewriteObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Steve Naroffc5484042007-10-30 02:23:23 +00001077 std::string ResultStr;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001078 if (!ObjCForwardDecls.count(ClassDecl)) {
Steve Naroff2f55b982007-11-01 03:35:41 +00001079 // we haven't seen a forward decl - generate a typedef.
Steve Naroff03f27672007-11-14 23:02:56 +00001080 ResultStr = "#ifndef _REWRITER_typedef_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001081 ResultStr += ClassDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +00001082 ResultStr += "\n";
1083 ResultStr += "#define _REWRITER_typedef_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001084 ResultStr += ClassDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +00001085 ResultStr += "\n";
Steve Naroffa1e115e2008-03-10 23:16:54 +00001086 ResultStr += "typedef struct objc_object ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001087 ResultStr += ClassDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +00001088 ResultStr += ";\n#endif\n";
Steve Naroff2f55b982007-11-01 03:35:41 +00001089 // Mark this typedef as having been generated.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001090 ObjCForwardDecls.insert(ClassDecl);
Steve Naroff2f55b982007-11-01 03:35:41 +00001091 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001092 SynthesizeObjCInternalStruct(ClassDecl, ResultStr);
Mike Stump11289f42009-09-09 15:08:12 +00001093
1094 for (ObjCInterfaceDecl::prop_iterator I = ClassDecl->prop_begin(),
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001095 E = ClassDecl->prop_end(); I != E; ++I)
Steve Naroff0c0f5ba2009-01-11 01:06:09 +00001096 RewriteProperty(*I);
Mike Stump11289f42009-09-09 15:08:12 +00001097 for (ObjCInterfaceDecl::instmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001098 I = ClassDecl->instmeth_begin(), E = ClassDecl->instmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +00001099 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +00001100 RewriteMethodDeclaration(*I);
Mike Stump11289f42009-09-09 15:08:12 +00001101 for (ObjCInterfaceDecl::classmeth_iterator
1102 I = ClassDecl->classmeth_begin(), E = ClassDecl->classmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +00001103 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +00001104 RewriteMethodDeclaration(*I);
1105
Steve Naroff4cd61ac2007-10-30 03:43:13 +00001106 // Lastly, comment out the @end.
Ted Kremenekc7c64312010-01-07 01:20:12 +00001107 ReplaceText(ClassDecl->getAtEndRange().getBegin(), 0, "// ", 3);
Steve Naroff161a92b2007-10-26 20:53:56 +00001108}
1109
Steve Naroff08628db2008-12-09 12:56:34 +00001110Stmt *RewriteObjC::RewritePropertySetter(BinaryOperator *BinOp, Expr *newStmt,
1111 SourceRange SrcRange) {
Steve Naroff4588d0f2008-12-04 16:24:46 +00001112 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr.
1113 // This allows us to reuse all the fun and games in SynthMessageExpr().
1114 ObjCPropertyRefExpr *PropRefExpr = dyn_cast<ObjCPropertyRefExpr>(BinOp->getLHS());
1115 ObjCMessageExpr *MsgExpr;
1116 ObjCPropertyDecl *PDecl = PropRefExpr->getProperty();
1117 llvm::SmallVector<Expr *, 1> ExprVec;
1118 ExprVec.push_back(newStmt);
Mike Stump11289f42009-09-09 15:08:12 +00001119
Steve Naroff1042ff32008-12-08 16:43:47 +00001120 Stmt *Receiver = PropRefExpr->getBase();
1121 ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(Receiver);
1122 if (PRE && PropGetters[PRE]) {
1123 // This allows us to handle chain/nested property getters.
1124 Receiver = PropGetters[PRE];
1125 }
Mike Stump11289f42009-09-09 15:08:12 +00001126 MsgExpr = new (Context) ObjCMessageExpr(dyn_cast<Expr>(Receiver),
1127 PDecl->getSetterName(), PDecl->getType(),
1128 PDecl->getSetterMethodDecl(),
1129 SourceLocation(), SourceLocation(),
Steve Naroff4588d0f2008-12-04 16:24:46 +00001130 &ExprVec[0], 1);
1131 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr);
Mike Stump11289f42009-09-09 15:08:12 +00001132
Steve Naroff4588d0f2008-12-04 16:24:46 +00001133 // Now do the actual rewrite.
Steve Naroff08628db2008-12-09 12:56:34 +00001134 ReplaceStmtWithRange(BinOp, ReplacingStmt, SrcRange);
Steve Naroffdf705772008-12-10 14:53:27 +00001135 //delete BinOp;
Ted Kremenek5a201952009-02-07 01:47:29 +00001136 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1137 // to things that stay around.
1138 Context->Deallocate(MsgExpr);
Steve Naroff4588d0f2008-12-04 16:24:46 +00001139 return ReplacingStmt;
Steve Narofff326f402008-12-03 00:56:33 +00001140}
1141
Steve Naroff4588d0f2008-12-04 16:24:46 +00001142Stmt *RewriteObjC::RewritePropertyGetter(ObjCPropertyRefExpr *PropRefExpr) {
Steve Narofff326f402008-12-03 00:56:33 +00001143 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr.
1144 // This allows us to reuse all the fun and games in SynthMessageExpr().
1145 ObjCMessageExpr *MsgExpr;
1146 ObjCPropertyDecl *PDecl = PropRefExpr->getProperty();
Mike Stump11289f42009-09-09 15:08:12 +00001147
Steve Naroff1042ff32008-12-08 16:43:47 +00001148 Stmt *Receiver = PropRefExpr->getBase();
Mike Stump11289f42009-09-09 15:08:12 +00001149
Steve Naroff1042ff32008-12-08 16:43:47 +00001150 ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(Receiver);
1151 if (PRE && PropGetters[PRE]) {
1152 // This allows us to handle chain/nested property getters.
1153 Receiver = PropGetters[PRE];
1154 }
Mike Stump11289f42009-09-09 15:08:12 +00001155 MsgExpr = new (Context) ObjCMessageExpr(dyn_cast<Expr>(Receiver),
1156 PDecl->getGetterName(), PDecl->getType(),
1157 PDecl->getGetterMethodDecl(),
1158 SourceLocation(), SourceLocation(),
Steve Narofff326f402008-12-03 00:56:33 +00001159 0, 0);
1160
Steve Naroff22216db2008-12-04 23:50:32 +00001161 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr);
Steve Naroff1042ff32008-12-08 16:43:47 +00001162
1163 if (!PropParentMap)
1164 PropParentMap = new ParentMap(CurrentBody);
1165
1166 Stmt *Parent = PropParentMap->getParent(PropRefExpr);
1167 if (Parent && isa<ObjCPropertyRefExpr>(Parent)) {
1168 // We stash away the ReplacingStmt since actually doing the
1169 // replacement/rewrite won't work for nested getters (e.g. obj.p.i)
1170 PropGetters[PropRefExpr] = ReplacingStmt;
Ted Kremenek5a201952009-02-07 01:47:29 +00001171 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1172 // to things that stay around.
1173 Context->Deallocate(MsgExpr);
Steve Naroff1042ff32008-12-08 16:43:47 +00001174 return PropRefExpr; // return the original...
1175 } else {
1176 ReplaceStmt(PropRefExpr, ReplacingStmt);
Mike Stump11289f42009-09-09 15:08:12 +00001177 // delete PropRefExpr; elsewhere...
Ted Kremenek5a201952009-02-07 01:47:29 +00001178 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1179 // to things that stay around.
1180 Context->Deallocate(MsgExpr);
Steve Naroff1042ff32008-12-08 16:43:47 +00001181 return ReplacingStmt;
1182 }
Steve Narofff326f402008-12-03 00:56:33 +00001183}
1184
Mike Stump11289f42009-09-09 15:08:12 +00001185Stmt *RewriteObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV,
Chris Lattner37f5b7d2008-05-23 20:40:52 +00001186 SourceLocation OrigStart) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001187 ObjCIvarDecl *D = IV->getDecl();
Fariborz Jahanian0f3aecf2010-01-07 18:18:32 +00001188 const Expr *BaseExpr = IV->getBase();
Steve Naroff677ab3a2008-10-27 17:20:55 +00001189 if (CurMethodDef) {
Fariborz Jahanian14442302010-01-07 22:15:31 +00001190 if (IV->isArrow() && isa<DeclRefExpr>(BaseExpr)) {
Ted Kremenek5a201952009-02-07 01:47:29 +00001191 ObjCInterfaceType *iFaceDecl =
Fariborz Jahanian0f3aecf2010-01-07 18:18:32 +00001192 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
Steve Naroffb1c02372008-05-08 17:52:16 +00001193 // lookup which class implements the instance variable.
1194 ObjCInterfaceDecl *clsDeclared = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001195 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
Douglas Gregorbcced4e2009-04-09 21:40:53 +00001196 clsDeclared);
Steve Naroffb1c02372008-05-08 17:52:16 +00001197 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
Mike Stump11289f42009-09-09 15:08:12 +00001198
Steve Naroffb1c02372008-05-08 17:52:16 +00001199 // Synthesize an explicit cast to gain access to the ivar.
1200 std::string RecName = clsDeclared->getIdentifier()->getName();
1201 RecName += "_IMPL";
1202 IdentifierInfo *II = &Context->Idents.get(RecName.c_str());
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00001203 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Ted Kremenek47923c72008-09-05 01:34:33 +00001204 SourceLocation(), II);
Steve Naroffb1c02372008-05-08 17:52:16 +00001205 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1206 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
Mike Stump11289f42009-09-09 15:08:12 +00001207 CastExpr *castExpr = new (Context) CStyleCastExpr(castT,
Anders Carlssona2615922009-07-31 00:48:10 +00001208 CastExpr::CK_Unknown,
1209 IV->getBase(),
1210 castT,SourceLocation(),
1211 SourceLocation());
Steve Naroffb1c02372008-05-08 17:52:16 +00001212 // Don't forget the parens to enforce the proper binding.
Ted Kremenek5a201952009-02-07 01:47:29 +00001213 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
1214 IV->getBase()->getLocEnd(),
1215 castExpr);
Mike Stump11289f42009-09-09 15:08:12 +00001216 if (IV->isFreeIvar() &&
Steve Naroff677ab3a2008-10-27 17:20:55 +00001217 CurMethodDef->getClassInterface() == iFaceDecl->getDecl()) {
Ted Kremenek5a201952009-02-07 01:47:29 +00001218 MemberExpr *ME = new (Context) MemberExpr(PE, true, D,
1219 IV->getLocation(),
1220 D->getType());
Steve Naroffb1c02372008-05-08 17:52:16 +00001221 ReplaceStmt(IV, ME);
Steve Naroff22216db2008-12-04 23:50:32 +00001222 // delete IV; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroffb1c02372008-05-08 17:52:16 +00001223 return ME;
Steve Naroff05caa482007-11-15 11:33:00 +00001224 }
Mike Stump11289f42009-09-09 15:08:12 +00001225
Chris Lattner37f5b7d2008-05-23 20:40:52 +00001226 ReplaceStmt(IV->getBase(), PE);
1227 // Cannot delete IV->getBase(), since PE points to it.
1228 // Replace the old base with the cast. This is important when doing
1229 // embedded rewrites. For example, [newInv->_container addObject:0].
Mike Stump11289f42009-09-09 15:08:12 +00001230 IV->setBase(PE);
Chris Lattner37f5b7d2008-05-23 20:40:52 +00001231 return IV;
Steve Naroff05caa482007-11-15 11:33:00 +00001232 }
Steve Naroff24840f62008-04-18 21:55:08 +00001233 } else { // we are outside a method.
Steve Naroff29ce4e52008-05-06 23:20:07 +00001234 assert(!IV->isFreeIvar() && "Cannot have a free standing ivar outside a method");
Mike Stump11289f42009-09-09 15:08:12 +00001235
Steve Naroff29ce4e52008-05-06 23:20:07 +00001236 // Explicit ivar refs need to have a cast inserted.
1237 // FIXME: consider sharing some of this code with the code above.
Fariborz Jahanian9146e442010-01-11 17:50:35 +00001238 if (IV->isArrow()) {
1239 ObjCInterfaceType *iFaceDecl =
1240 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
Steve Naroff29ce4e52008-05-06 23:20:07 +00001241 // lookup which class implements the instance variable.
1242 ObjCInterfaceDecl *clsDeclared = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001243 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
Douglas Gregorbcced4e2009-04-09 21:40:53 +00001244 clsDeclared);
Steve Naroff29ce4e52008-05-06 23:20:07 +00001245 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
Mike Stump11289f42009-09-09 15:08:12 +00001246
Steve Naroff29ce4e52008-05-06 23:20:07 +00001247 // Synthesize an explicit cast to gain access to the ivar.
1248 std::string RecName = clsDeclared->getIdentifier()->getName();
1249 RecName += "_IMPL";
1250 IdentifierInfo *II = &Context->Idents.get(RecName.c_str());
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00001251 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Ted Kremenek47923c72008-09-05 01:34:33 +00001252 SourceLocation(), II);
Steve Naroff29ce4e52008-05-06 23:20:07 +00001253 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1254 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
Mike Stump11289f42009-09-09 15:08:12 +00001255 CastExpr *castExpr = new (Context) CStyleCastExpr(castT,
Anders Carlssona2615922009-07-31 00:48:10 +00001256 CastExpr::CK_Unknown,
1257 IV->getBase(),
Ted Kremenek5a201952009-02-07 01:47:29 +00001258 castT, SourceLocation(),
1259 SourceLocation());
Steve Naroff29ce4e52008-05-06 23:20:07 +00001260 // Don't forget the parens to enforce the proper binding.
Ted Kremenek5a201952009-02-07 01:47:29 +00001261 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
Chris Lattner34873d22008-05-28 16:38:23 +00001262 IV->getBase()->getLocEnd(), castExpr);
Steve Naroff29ce4e52008-05-06 23:20:07 +00001263 ReplaceStmt(IV->getBase(), PE);
1264 // Cannot delete IV->getBase(), since PE points to it.
1265 // Replace the old base with the cast. This is important when doing
1266 // embedded rewrites. For example, [newInv->_container addObject:0].
Mike Stump11289f42009-09-09 15:08:12 +00001267 IV->setBase(PE);
Steve Naroff29ce4e52008-05-06 23:20:07 +00001268 return IV;
1269 }
Steve Naroff05caa482007-11-15 11:33:00 +00001270 }
Steve Naroff24840f62008-04-18 21:55:08 +00001271 return IV;
Steve Narofff60782b2007-11-15 02:58:25 +00001272}
1273
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001274/// SynthCountByEnumWithState - To print:
1275/// ((unsigned int (*)
1276/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump11289f42009-09-09 15:08:12 +00001277/// (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001278/// sel_registerName(
Mike Stump11289f42009-09-09 15:08:12 +00001279/// "countByEnumeratingWithState:objects:count:"),
1280/// &enumState,
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001281/// (id *)items, (unsigned int)16)
1282///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001283void RewriteObjC::SynthCountByEnumWithState(std::string &buf) {
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001284 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1285 "id *, unsigned int))(void *)objc_msgSend)";
1286 buf += "\n\t\t";
1287 buf += "((id)l_collection,\n\t\t";
1288 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1289 buf += "\n\t\t";
1290 buf += "&enumState, "
1291 "(id *)items, (unsigned int)16)";
1292}
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001293
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001294/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1295/// statement to exit to its outer synthesized loop.
1296///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001297Stmt *RewriteObjC::RewriteBreakStmt(BreakStmt *S) {
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001298 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1299 return S;
1300 // replace break with goto __break_label
1301 std::string buf;
Mike Stump11289f42009-09-09 15:08:12 +00001302
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001303 SourceLocation startLoc = S->getLocStart();
1304 buf = "goto __break_label_";
1305 buf += utostr(ObjCBcLabelNo.back());
Chris Lattner9cc55f52008-01-31 19:51:04 +00001306 ReplaceText(startLoc, strlen("break"), buf.c_str(), buf.size());
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001307
1308 return 0;
1309}
1310
1311/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1312/// statement to continue with its inner synthesized loop.
1313///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001314Stmt *RewriteObjC::RewriteContinueStmt(ContinueStmt *S) {
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001315 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1316 return S;
1317 // replace continue with goto __continue_label
1318 std::string buf;
Mike Stump11289f42009-09-09 15:08:12 +00001319
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001320 SourceLocation startLoc = S->getLocStart();
1321 buf = "goto __continue_label_";
1322 buf += utostr(ObjCBcLabelNo.back());
Chris Lattner9cc55f52008-01-31 19:51:04 +00001323 ReplaceText(startLoc, strlen("continue"), buf.c_str(), buf.size());
Mike Stump11289f42009-09-09 15:08:12 +00001324
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001325 return 0;
1326}
1327
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001328/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001329/// It rewrites:
1330/// for ( type elem in collection) { stmts; }
Mike Stump11289f42009-09-09 15:08:12 +00001331
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001332/// Into:
1333/// {
Mike Stump11289f42009-09-09 15:08:12 +00001334/// type elem;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001335/// struct __objcFastEnumerationState enumState = { 0 };
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001336/// id items[16];
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001337/// id l_collection = (id)collection;
Mike Stump11289f42009-09-09 15:08:12 +00001338/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001339/// objects:items count:16];
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001340/// if (limit) {
1341/// unsigned long startMutations = *enumState.mutationsPtr;
1342/// do {
1343/// unsigned long counter = 0;
1344/// do {
Mike Stump11289f42009-09-09 15:08:12 +00001345/// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001346/// objc_enumerationMutation(l_collection);
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001347/// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001348/// stmts;
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001349/// __continue_label: ;
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001350/// } while (counter < limit);
Mike Stump11289f42009-09-09 15:08:12 +00001351/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001352/// objects:items count:16]);
1353/// elem = nil;
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001354/// __break_label: ;
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001355/// }
1356/// else
1357/// elem = nil;
1358/// }
1359///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001360Stmt *RewriteObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
Chris Lattnera779d692008-01-31 05:10:40 +00001361 SourceLocation OrigEnd) {
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001362 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
Mike Stump11289f42009-09-09 15:08:12 +00001363 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001364 "ObjCForCollectionStmt Statement stack mismatch");
Mike Stump11289f42009-09-09 15:08:12 +00001365 assert(!ObjCBcLabelNo.empty() &&
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001366 "ObjCForCollectionStmt - Label No stack empty");
Mike Stump11289f42009-09-09 15:08:12 +00001367
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001368 SourceLocation startLoc = S->getLocStart();
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001369 const char *startBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001370 const char *elementName;
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001371 std::string elementTypeAsString;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001372 std::string buf;
1373 buf = "\n{\n\t";
1374 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1375 // type elem;
Chris Lattner529efc72009-03-28 06:33:19 +00001376 NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
Ted Kremenek292b3842008-10-06 22:16:13 +00001377 QualType ElementType = cast<ValueDecl>(D)->getType();
Steve Naroff3ce3af22009-12-04 21:18:19 +00001378 if (ElementType->isObjCQualifiedIdType() ||
1379 ElementType->isObjCQualifiedInterfaceType())
1380 // Simply use 'id' for all qualified types.
1381 elementTypeAsString = "id";
1382 else
1383 elementTypeAsString = ElementType.getAsString();
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001384 buf += elementTypeAsString;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001385 buf += " ";
Chris Lattner86d7d912008-11-24 03:54:41 +00001386 elementName = D->getNameAsCString();
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001387 buf += elementName;
1388 buf += ";\n\t";
1389 }
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001390 else {
1391 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
Chris Lattner86d7d912008-11-24 03:54:41 +00001392 elementName = DR->getDecl()->getNameAsCString();
Steve Naroff3ce3af22009-12-04 21:18:19 +00001393 ValueDecl *VD = cast<ValueDecl>(DR->getDecl());
1394 if (VD->getType()->isObjCQualifiedIdType() ||
1395 VD->getType()->isObjCQualifiedInterfaceType())
1396 // Simply use 'id' for all qualified types.
1397 elementTypeAsString = "id";
1398 else
1399 elementTypeAsString = VD->getType().getAsString();
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001400 }
Mike Stump11289f42009-09-09 15:08:12 +00001401
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001402 // struct __objcFastEnumerationState enumState = { 0 };
1403 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1404 // id items[16];
1405 buf += "id items[16];\n\t";
1406 // id l_collection = (id)
1407 buf += "id l_collection = (id)";
Fariborz Jahanian82ae0152008-01-10 00:24:29 +00001408 // Find start location of 'collection' the hard way!
1409 const char *startCollectionBuf = startBuf;
1410 startCollectionBuf += 3; // skip 'for'
1411 startCollectionBuf = strchr(startCollectionBuf, '(');
1412 startCollectionBuf++; // skip '('
1413 // find 'in' and skip it.
1414 while (*startCollectionBuf != ' ' ||
1415 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1416 (*(startCollectionBuf+3) != ' ' &&
1417 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1418 startCollectionBuf++;
1419 startCollectionBuf += 3;
Mike Stump11289f42009-09-09 15:08:12 +00001420
1421 // Replace: "for (type element in" with string constructed thus far.
Chris Lattner9cc55f52008-01-31 19:51:04 +00001422 ReplaceText(startLoc, startCollectionBuf - startBuf,
1423 buf.c_str(), buf.size());
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001424 // Replace ')' in for '(' type elem in collection ')' with ';'
Fariborz Jahanian82ae0152008-01-10 00:24:29 +00001425 SourceLocation rightParenLoc = S->getRParenLoc();
1426 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1427 SourceLocation lparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001428 buf = ";\n\t";
Mike Stump11289f42009-09-09 15:08:12 +00001429
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001430 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1431 // objects:items count:16];
1432 // which is synthesized into:
Mike Stump11289f42009-09-09 15:08:12 +00001433 // unsigned int limit =
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001434 // ((unsigned int (*)
1435 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump11289f42009-09-09 15:08:12 +00001436 // (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001437 // sel_registerName(
Mike Stump11289f42009-09-09 15:08:12 +00001438 // "countByEnumeratingWithState:objects:count:"),
1439 // (struct __objcFastEnumerationState *)&state,
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001440 // (id *)items, (unsigned int)16);
1441 buf += "unsigned long limit =\n\t\t";
1442 SynthCountByEnumWithState(buf);
1443 buf += ";\n\t";
1444 /// if (limit) {
1445 /// unsigned long startMutations = *enumState.mutationsPtr;
1446 /// do {
1447 /// unsigned long counter = 0;
1448 /// do {
Mike Stump11289f42009-09-09 15:08:12 +00001449 /// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001450 /// objc_enumerationMutation(l_collection);
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001451 /// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001452 buf += "if (limit) {\n\t";
1453 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1454 buf += "do {\n\t\t";
1455 buf += "unsigned long counter = 0;\n\t\t";
1456 buf += "do {\n\t\t\t";
1457 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1458 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1459 buf += elementName;
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001460 buf += " = (";
1461 buf += elementTypeAsString;
1462 buf += ")enumState.itemsPtr[counter++];";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001463 // Replace ')' in for '(' type elem in collection ')' with all of these.
Chris Lattner9cc55f52008-01-31 19:51:04 +00001464 ReplaceText(lparenLoc, 1, buf.c_str(), buf.size());
Mike Stump11289f42009-09-09 15:08:12 +00001465
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001466 /// __continue_label: ;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001467 /// } while (counter < limit);
Mike Stump11289f42009-09-09 15:08:12 +00001468 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001469 /// objects:items count:16]);
1470 /// elem = nil;
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001471 /// __break_label: ;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001472 /// }
1473 /// else
1474 /// elem = nil;
1475 /// }
Mike Stump11289f42009-09-09 15:08:12 +00001476 ///
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001477 buf = ";\n\t";
1478 buf += "__continue_label_";
1479 buf += utostr(ObjCBcLabelNo.back());
1480 buf += ": ;";
1481 buf += "\n\t\t";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001482 buf += "} while (counter < limit);\n\t";
1483 buf += "} while (limit = ";
1484 SynthCountByEnumWithState(buf);
1485 buf += ");\n\t";
1486 buf += elementName;
Fariborz Jahanian39d70942010-01-08 01:29:44 +00001487 buf += " = ((";
1488 buf += elementTypeAsString;
1489 buf += ")0);\n\t";
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001490 buf += "__break_label_";
1491 buf += utostr(ObjCBcLabelNo.back());
1492 buf += ": ;\n\t";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001493 buf += "}\n\t";
1494 buf += "else\n\t\t";
1495 buf += elementName;
Fariborz Jahanian39d70942010-01-08 01:29:44 +00001496 buf += " = ((";
1497 buf += elementTypeAsString;
1498 buf += ")0);\n\t";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001499 buf += "}\n";
Mike Stump11289f42009-09-09 15:08:12 +00001500
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001501 // Insert all these *after* the statement body.
Sebastian Redla7b98a72009-04-26 20:35:05 +00001502 // FIXME: If this should support Obj-C++, support CXXTryStmt
Steve Narofff0ff8792008-07-21 18:26:02 +00001503 if (isa<CompoundStmt>(S->getBody())) {
1504 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(1);
1505 InsertText(endBodyLoc, buf.c_str(), buf.size());
1506 } else {
1507 /* Need to treat single statements specially. For example:
1508 *
1509 * for (A *a in b) if (stuff()) break;
1510 * for (A *a in b) xxxyy;
1511 *
1512 * The following code simply scans ahead to the semi to find the actual end.
1513 */
1514 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1515 const char *semiBuf = strchr(stmtBuf, ';');
1516 assert(semiBuf && "Can't find ';'");
1517 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(semiBuf-stmtBuf+1);
1518 InsertText(endBodyLoc, buf.c_str(), buf.size());
1519 }
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001520 Stmts.pop_back();
1521 ObjCBcLabelNo.pop_back();
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001522 return 0;
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001523}
1524
Mike Stump11289f42009-09-09 15:08:12 +00001525/// RewriteObjCSynchronizedStmt -
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001526/// This routine rewrites @synchronized(expr) stmt;
1527/// into:
1528/// objc_sync_enter(expr);
1529/// @try stmt @finally { objc_sync_exit(expr); }
1530///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001531Stmt *RewriteObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001532 // Get the start location and compute the semi location.
1533 SourceLocation startLoc = S->getLocStart();
1534 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001535
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001536 assert((*startBuf == '@') && "bogus @synchronized location");
Mike Stump11289f42009-09-09 15:08:12 +00001537
1538 std::string buf;
Steve Naroffb2fc0522008-08-21 13:03:03 +00001539 buf = "objc_sync_enter((id)";
1540 const char *lparenBuf = startBuf;
1541 while (*lparenBuf != '(') lparenBuf++;
1542 ReplaceText(startLoc, lparenBuf-startBuf+1, buf.c_str(), buf.size());
Mike Stump11289f42009-09-09 15:08:12 +00001543 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1544 // the sync expression is typically a message expression that's already
Steve Naroffad7013b2008-08-19 13:04:19 +00001545 // been rewritten! (which implies the SourceLocation's are invalid).
1546 SourceLocation endLoc = S->getSynchBody()->getLocStart();
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001547 const char *endBuf = SM->getCharacterData(endLoc);
Steve Naroffad7013b2008-08-19 13:04:19 +00001548 while (*endBuf != ')') endBuf--;
1549 SourceLocation rparenLoc = startLoc.getFileLocWithOffset(endBuf-startBuf);
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001550 buf = ");\n";
1551 // declare a new scope with two variables, _stack and _rethrow.
1552 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1553 buf += "int buf[18/*32-bit i386*/];\n";
1554 buf += "char *pointers[4];} _stack;\n";
1555 buf += "id volatile _rethrow = 0;\n";
1556 buf += "objc_exception_try_enter(&_stack);\n";
1557 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Chris Lattner9cc55f52008-01-31 19:51:04 +00001558 ReplaceText(rparenLoc, 1, buf.c_str(), buf.size());
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001559 startLoc = S->getSynchBody()->getLocEnd();
1560 startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001561
Steve Naroffad7013b2008-08-19 13:04:19 +00001562 assert((*startBuf == '}') && "bogus @synchronized block");
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001563 SourceLocation lastCurlyLoc = startLoc;
1564 buf = "}\nelse {\n";
1565 buf += " _rethrow = objc_exception_extract(&_stack);\n";
Steve Naroffd9803712009-04-29 16:37:50 +00001566 buf += "}\n";
1567 buf += "{ /* implicit finally clause */\n";
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001568 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Steve Naroffec60b432009-12-05 21:43:12 +00001569
1570 std::string syncBuf;
1571 syncBuf += " objc_sync_exit(";
Mike Stump11289f42009-09-09 15:08:12 +00001572 Expr *syncExpr = new (Context) CStyleCastExpr(Context->getObjCIdType(),
Anders Carlssona2615922009-07-31 00:48:10 +00001573 CastExpr::CK_Unknown,
Mike Stump11289f42009-09-09 15:08:12 +00001574 S->getSynchExpr(),
Ted Kremenek5a201952009-02-07 01:47:29 +00001575 Context->getObjCIdType(),
1576 SourceLocation(),
1577 SourceLocation());
Ted Kremenek2d470fc2008-09-13 05:16:45 +00001578 std::string syncExprBufS;
1579 llvm::raw_string_ostream syncExprBuf(syncExprBufS);
Chris Lattnerc61089a2009-06-30 01:26:17 +00001580 syncExpr->printPretty(syncExprBuf, *Context, 0,
1581 PrintingPolicy(LangOpts));
Steve Naroffec60b432009-12-05 21:43:12 +00001582 syncBuf += syncExprBuf.str();
1583 syncBuf += ");";
1584
1585 buf += syncBuf;
1586 buf += "\n if (_rethrow) objc_exception_throw(_rethrow);\n";
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001587 buf += "}\n";
1588 buf += "}";
Mike Stump11289f42009-09-09 15:08:12 +00001589
Chris Lattner9cc55f52008-01-31 19:51:04 +00001590 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Steve Naroffec60b432009-12-05 21:43:12 +00001591
1592 bool hasReturns = false;
1593 HasReturnStmts(S->getSynchBody(), hasReturns);
1594 if (hasReturns)
1595 RewriteSyncReturnStmts(S->getSynchBody(), syncBuf);
1596
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001597 return 0;
1598}
1599
Steve Naroffec60b432009-12-05 21:43:12 +00001600void RewriteObjC::WarnAboutReturnGotoStmts(Stmt *S)
1601{
Steve Naroff6d6da252008-12-05 17:03:39 +00001602 // Perform a bottom up traversal of all children.
1603 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1604 CI != E; ++CI)
1605 if (*CI)
Steve Naroffec60b432009-12-05 21:43:12 +00001606 WarnAboutReturnGotoStmts(*CI);
Steve Naroff6d6da252008-12-05 17:03:39 +00001607
Steve Naroffec60b432009-12-05 21:43:12 +00001608 if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
Mike Stump11289f42009-09-09 15:08:12 +00001609 Diags.Report(Context->getFullLoc(S->getLocStart()),
Steve Naroff6d6da252008-12-05 17:03:39 +00001610 TryFinallyContainsReturnDiag);
1611 }
1612 return;
1613}
1614
Steve Naroffec60b432009-12-05 21:43:12 +00001615void RewriteObjC::HasReturnStmts(Stmt *S, bool &hasReturns)
1616{
1617 // Perform a bottom up traversal of all children.
1618 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1619 CI != E; ++CI)
1620 if (*CI)
1621 HasReturnStmts(*CI, hasReturns);
1622
1623 if (isa<ReturnStmt>(S))
1624 hasReturns = true;
1625 return;
1626}
1627
1628void RewriteObjC::RewriteTryReturnStmts(Stmt *S) {
1629 // Perform a bottom up traversal of all children.
1630 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1631 CI != E; ++CI)
1632 if (*CI) {
1633 RewriteTryReturnStmts(*CI);
1634 }
1635 if (isa<ReturnStmt>(S)) {
1636 SourceLocation startLoc = S->getLocStart();
1637 const char *startBuf = SM->getCharacterData(startLoc);
1638
1639 const char *semiBuf = strchr(startBuf, ';');
1640 assert((*semiBuf == ';') && "RewriteTryReturnStmts: can't find ';'");
1641 SourceLocation onePastSemiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
1642
1643 std::string buf;
1644 buf = "{ objc_exception_try_exit(&_stack); return";
1645
1646 ReplaceText(startLoc, 6, buf.c_str(), buf.size());
1647 InsertText(onePastSemiLoc, "}", 1);
1648 }
1649 return;
1650}
1651
1652void RewriteObjC::RewriteSyncReturnStmts(Stmt *S, std::string syncExitBuf) {
1653 // Perform a bottom up traversal of all children.
1654 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1655 CI != E; ++CI)
1656 if (*CI) {
1657 RewriteSyncReturnStmts(*CI, syncExitBuf);
1658 }
1659 if (isa<ReturnStmt>(S)) {
1660 SourceLocation startLoc = S->getLocStart();
1661 const char *startBuf = SM->getCharacterData(startLoc);
1662
1663 const char *semiBuf = strchr(startBuf, ';');
1664 assert((*semiBuf == ';') && "RewriteSyncReturnStmts: can't find ';'");
1665 SourceLocation onePastSemiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
1666
1667 std::string buf;
1668 buf = "{ objc_exception_try_exit(&_stack);";
1669 buf += syncExitBuf;
1670 buf += " return";
1671
1672 ReplaceText(startLoc, 6, buf.c_str(), buf.size());
1673 InsertText(onePastSemiLoc, "}", 1);
1674 }
1675 return;
1676}
1677
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001678Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Steve Naroffbf478ec2007-11-07 04:08:17 +00001679 // Get the start location and compute the semi location.
1680 SourceLocation startLoc = S->getLocStart();
1681 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001682
Steve Naroffbf478ec2007-11-07 04:08:17 +00001683 assert((*startBuf == '@') && "bogus @try location");
1684
1685 std::string buf;
1686 // declare a new scope with two variables, _stack and _rethrow.
1687 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1688 buf += "int buf[18/*32-bit i386*/];\n";
1689 buf += "char *pointers[4];} _stack;\n";
1690 buf += "id volatile _rethrow = 0;\n";
1691 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroff16018582007-11-07 18:43:40 +00001692 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroffbf478ec2007-11-07 04:08:17 +00001693
Chris Lattner9cc55f52008-01-31 19:51:04 +00001694 ReplaceText(startLoc, 4, buf.c_str(), buf.size());
Mike Stump11289f42009-09-09 15:08:12 +00001695
Steve Naroffbf478ec2007-11-07 04:08:17 +00001696 startLoc = S->getTryBody()->getLocEnd();
1697 startBuf = SM->getCharacterData(startLoc);
1698
1699 assert((*startBuf == '}') && "bogus @try block");
Mike Stump11289f42009-09-09 15:08:12 +00001700
Steve Naroffbf478ec2007-11-07 04:08:17 +00001701 SourceLocation lastCurlyLoc = startLoc;
Steve Naroffce2dca12008-07-16 15:31:30 +00001702 ObjCAtCatchStmt *catchList = S->getCatchStmts();
1703 if (catchList) {
1704 startLoc = startLoc.getFileLocWithOffset(1);
1705 buf = " /* @catch begin */ else {\n";
1706 buf += " id _caught = objc_exception_extract(&_stack);\n";
1707 buf += " objc_exception_try_enter (&_stack);\n";
1708 buf += " if (_setjmp(_stack.buf))\n";
1709 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1710 buf += " else { /* @catch continue */";
Mike Stump11289f42009-09-09 15:08:12 +00001711
Steve Naroffce2dca12008-07-16 15:31:30 +00001712 InsertText(startLoc, buf.c_str(), buf.size());
Steve Narofffac18fe2008-09-09 19:59:12 +00001713 } else { /* no catch list */
1714 buf = "}\nelse {\n";
1715 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1716 buf += "}";
1717 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Steve Naroffce2dca12008-07-16 15:31:30 +00001718 }
Steve Naroffbf478ec2007-11-07 04:08:17 +00001719 bool sawIdTypedCatch = false;
1720 Stmt *lastCatchBody = 0;
Steve Naroffbf478ec2007-11-07 04:08:17 +00001721 while (catchList) {
Steve Naroff371b8fb2009-03-03 19:52:17 +00001722 ParmVarDecl *catchDecl = catchList->getCatchParamDecl();
Steve Naroffbf478ec2007-11-07 04:08:17 +00001723
Mike Stump11289f42009-09-09 15:08:12 +00001724 if (catchList == S->getCatchStmts())
Steve Naroffbf478ec2007-11-07 04:08:17 +00001725 buf = "if ("; // we are generating code for the first catch clause
1726 else
1727 buf = "else if (";
1728 startLoc = catchList->getLocStart();
1729 startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001730
Steve Naroffbf478ec2007-11-07 04:08:17 +00001731 assert((*startBuf == '@') && "bogus @catch location");
Mike Stump11289f42009-09-09 15:08:12 +00001732
Steve Naroffbf478ec2007-11-07 04:08:17 +00001733 const char *lParenLoc = strchr(startBuf, '(');
1734
Steve Naroffe6b7ffd2008-02-01 22:08:12 +00001735 if (catchList->hasEllipsis()) {
Steve Naroffedb5bc62008-02-01 20:02:07 +00001736 // Now rewrite the body...
1737 lastCatchBody = catchList->getCatchBody();
Steve Naroffedb5bc62008-02-01 20:02:07 +00001738 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1739 const char *bodyBuf = SM->getCharacterData(bodyLoc);
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001740 assert(*SM->getCharacterData(catchList->getRParenLoc()) == ')' &&
1741 "bogus @catch paren location");
Steve Naroffedb5bc62008-02-01 20:02:07 +00001742 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump11289f42009-09-09 15:08:12 +00001743
Steve Naroffedb5bc62008-02-01 20:02:07 +00001744 buf += "1) { id _tmp = _caught;";
Daniel Dunbardec484a2009-08-19 19:10:30 +00001745 Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1, buf);
Steve Naroff371b8fb2009-03-03 19:52:17 +00001746 } else if (catchDecl) {
1747 QualType t = catchDecl->getType();
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001748 if (t == Context->getObjCIdType()) {
Steve Naroffbf478ec2007-11-07 04:08:17 +00001749 buf += "1) { ";
Chris Lattner9cc55f52008-01-31 19:51:04 +00001750 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroffbf478ec2007-11-07 04:08:17 +00001751 sawIdTypedCatch = true;
Mike Stump11289f42009-09-09 15:08:12 +00001752 } else if (const PointerType *pType = t->getAs<PointerType>()) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001753 ObjCInterfaceType *cls; // Should be a pointer to a class.
Mike Stump11289f42009-09-09 15:08:12 +00001754
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001755 cls = dyn_cast<ObjCInterfaceType>(pType->getPointeeType().getTypePtr());
Steve Naroffbf478ec2007-11-07 04:08:17 +00001756 if (cls) {
Steve Naroff16018582007-11-07 18:43:40 +00001757 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001758 buf += cls->getDecl()->getNameAsString();
Steve Naroff16018582007-11-07 18:43:40 +00001759 buf += "\"), (struct objc_object *)_caught)) { ";
Chris Lattner9cc55f52008-01-31 19:51:04 +00001760 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroffbf478ec2007-11-07 04:08:17 +00001761 }
1762 }
1763 // Now rewrite the body...
1764 lastCatchBody = catchList->getCatchBody();
1765 SourceLocation rParenLoc = catchList->getRParenLoc();
1766 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1767 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1768 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1769 assert((*rParenBuf == ')') && "bogus @catch paren location");
1770 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump11289f42009-09-09 15:08:12 +00001771
Steve Naroffbf478ec2007-11-07 04:08:17 +00001772 buf = " = _caught;";
Mike Stump11289f42009-09-09 15:08:12 +00001773 // Here we replace ") {" with "= _caught;" (which initializes and
Steve Naroffbf478ec2007-11-07 04:08:17 +00001774 // declares the @catch parameter).
Chris Lattner9cc55f52008-01-31 19:51:04 +00001775 ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, buf.c_str(), buf.size());
Steve Naroff371b8fb2009-03-03 19:52:17 +00001776 } else {
Steve Naroffbf478ec2007-11-07 04:08:17 +00001777 assert(false && "@catch rewrite bug");
Steve Naroffa733c7f2007-11-07 15:32:26 +00001778 }
Steve Naroffedb5bc62008-02-01 20:02:07 +00001779 // make sure all the catch bodies get rewritten!
Steve Naroffbf478ec2007-11-07 04:08:17 +00001780 catchList = catchList->getNextCatchStmt();
1781 }
1782 // Complete the catch list...
1783 if (lastCatchBody) {
1784 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001785 assert(*SM->getCharacterData(bodyLoc) == '}' &&
1786 "bogus @catch body location");
Mike Stump11289f42009-09-09 15:08:12 +00001787
Steve Naroff4adbe312008-09-11 15:29:03 +00001788 // Insert the last (implicit) else clause *before* the right curly brace.
1789 bodyLoc = bodyLoc.getFileLocWithOffset(-1);
1790 buf = "} /* last catch end */\n";
1791 buf += "else {\n";
1792 buf += " _rethrow = _caught;\n";
1793 buf += " objc_exception_try_exit(&_stack);\n";
1794 buf += "} } /* @catch end */\n";
1795 if (!S->getFinallyStmt())
1796 buf += "}\n";
Chris Lattner1780a852008-01-31 19:42:41 +00001797 InsertText(bodyLoc, buf.c_str(), buf.size());
Mike Stump11289f42009-09-09 15:08:12 +00001798
Steve Naroffbf478ec2007-11-07 04:08:17 +00001799 // Set lastCurlyLoc
1800 lastCurlyLoc = lastCatchBody->getLocEnd();
1801 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001802 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
Steve Naroffbf478ec2007-11-07 04:08:17 +00001803 startLoc = finalStmt->getLocStart();
1804 startBuf = SM->getCharacterData(startLoc);
1805 assert((*startBuf == '@') && "bogus @finally start");
Mike Stump11289f42009-09-09 15:08:12 +00001806
Steve Naroffbf478ec2007-11-07 04:08:17 +00001807 buf = "/* @finally */";
Chris Lattner9cc55f52008-01-31 19:51:04 +00001808 ReplaceText(startLoc, 8, buf.c_str(), buf.size());
Mike Stump11289f42009-09-09 15:08:12 +00001809
Steve Naroffbf478ec2007-11-07 04:08:17 +00001810 Stmt *body = finalStmt->getFinallyBody();
1811 SourceLocation startLoc = body->getLocStart();
1812 SourceLocation endLoc = body->getLocEnd();
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001813 assert(*SM->getCharacterData(startLoc) == '{' &&
1814 "bogus @finally body location");
Mike Stump11289f42009-09-09 15:08:12 +00001815 assert(*SM->getCharacterData(endLoc) == '}' &&
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001816 "bogus @finally body location");
Mike Stump11289f42009-09-09 15:08:12 +00001817
Steve Naroffbf478ec2007-11-07 04:08:17 +00001818 startLoc = startLoc.getFileLocWithOffset(1);
1819 buf = " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Chris Lattner1780a852008-01-31 19:42:41 +00001820 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroffbf478ec2007-11-07 04:08:17 +00001821 endLoc = endLoc.getFileLocWithOffset(-1);
1822 buf = " if (_rethrow) objc_exception_throw(_rethrow);\n";
Chris Lattner1780a852008-01-31 19:42:41 +00001823 InsertText(endLoc, buf.c_str(), buf.size());
Mike Stump11289f42009-09-09 15:08:12 +00001824
Steve Naroffbf478ec2007-11-07 04:08:17 +00001825 // Set lastCurlyLoc
1826 lastCurlyLoc = body->getLocEnd();
Mike Stump11289f42009-09-09 15:08:12 +00001827
Steve Naroff6d6da252008-12-05 17:03:39 +00001828 // Now check for any return/continue/go statements within the @try.
Steve Naroffec60b432009-12-05 21:43:12 +00001829 WarnAboutReturnGotoStmts(S->getTryBody());
Steve Naroff4adbe312008-09-11 15:29:03 +00001830 } else { /* no finally clause - make sure we synthesize an implicit one */
1831 buf = "{ /* implicit finally clause */\n";
1832 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
1833 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1834 buf += "}";
1835 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Steve Naroffec60b432009-12-05 21:43:12 +00001836
1837 // Now check for any return/continue/go statements within the @try.
1838 // The implicit finally clause won't called if the @try contains any
1839 // jump statements.
1840 bool hasReturns = false;
1841 HasReturnStmts(S->getTryBody(), hasReturns);
1842 if (hasReturns)
1843 RewriteTryReturnStmts(S->getTryBody());
Steve Naroffbf478ec2007-11-07 04:08:17 +00001844 }
1845 // Now emit the final closing curly brace...
1846 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
1847 buf = " } /* @try scope end */\n";
Chris Lattner1780a852008-01-31 19:42:41 +00001848 InsertText(lastCurlyLoc, buf.c_str(), buf.size());
Fariborz Jahanian63ac80e2007-11-05 17:47:33 +00001849 return 0;
1850}
1851
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001852Stmt *RewriteObjC::RewriteObjCCatchStmt(ObjCAtCatchStmt *S) {
Fariborz Jahanian63ac80e2007-11-05 17:47:33 +00001853 return 0;
1854}
1855
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001856Stmt *RewriteObjC::RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S) {
Fariborz Jahanian63ac80e2007-11-05 17:47:33 +00001857 return 0;
1858}
1859
Mike Stump11289f42009-09-09 15:08:12 +00001860// This can't be done with ReplaceStmt(S, ThrowExpr), since
1861// the throw expression is typically a message expression that's already
Steve Naroffa733c7f2007-11-07 15:32:26 +00001862// been rewritten! (which implies the SourceLocation's are invalid).
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001863Stmt *RewriteObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
Steve Naroffa733c7f2007-11-07 15:32:26 +00001864 // Get the start location and compute the semi location.
1865 SourceLocation startLoc = S->getLocStart();
1866 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001867
Steve Naroffa733c7f2007-11-07 15:32:26 +00001868 assert((*startBuf == '@') && "bogus @throw location");
1869
1870 std::string buf;
1871 /* void objc_exception_throw(id) __attribute__((noreturn)); */
Steve Naroffc7d2df22008-01-19 00:42:38 +00001872 if (S->getThrowExpr())
1873 buf = "objc_exception_throw(";
1874 else // add an implicit argument
1875 buf = "objc_exception_throw(_caught";
Mike Stump11289f42009-09-09 15:08:12 +00001876
Steve Naroff29788342008-07-25 15:41:30 +00001877 // handle "@ throw" correctly.
1878 const char *wBuf = strchr(startBuf, 'w');
1879 assert((*wBuf == 'w') && "@throw: can't find 'w'");
1880 ReplaceText(startLoc, wBuf-startBuf+1, buf.c_str(), buf.size());
Mike Stump11289f42009-09-09 15:08:12 +00001881
Steve Naroffa733c7f2007-11-07 15:32:26 +00001882 const char *semiBuf = strchr(startBuf, ';');
1883 assert((*semiBuf == ';') && "@throw: can't find ';'");
1884 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
1885 buf = ");";
Chris Lattner9cc55f52008-01-31 19:51:04 +00001886 ReplaceText(semiLoc, 1, buf.c_str(), buf.size());
Steve Naroffa733c7f2007-11-07 15:32:26 +00001887 return 0;
1888}
Fariborz Jahanian63ac80e2007-11-05 17:47:33 +00001889
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001890Stmt *RewriteObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattnerc6d91c02007-10-17 22:35:30 +00001891 // Create a new string expression.
1892 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlssond8499822007-10-29 05:01:08 +00001893 std::string StrEncoding;
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00001894 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
Chris Lattnerf83b5af2009-02-18 06:40:38 +00001895 Expr *Replacement = StringLiteral::Create(*Context,StrEncoding.c_str(),
1896 StrEncoding.length(), false,StrType,
1897 SourceLocation());
Chris Lattner2e0d2602008-01-31 19:37:57 +00001898 ReplaceStmt(Exp, Replacement);
Mike Stump11289f42009-09-09 15:08:12 +00001899
Chris Lattner4431a1b2007-11-30 22:53:43 +00001900 // Replace this subexpr in the parent.
Steve Naroff22216db2008-12-04 23:50:32 +00001901 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Chris Lattner69534692007-10-24 16:57:36 +00001902 return Replacement;
Chris Lattnera7c19fe2007-10-16 22:36:42 +00001903}
1904
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001905Stmt *RewriteObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
Steve Naroff2654e182008-12-22 22:16:07 +00001906 if (!SelGetUidFunctionDecl)
1907 SynthSelGetUidFunctionDecl();
Steve Naroffe4f9b232007-11-05 14:50:49 +00001908 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
1909 // Create a call to sel_registerName("selName").
1910 llvm::SmallVector<Expr*, 8> SelExprs;
1911 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump11289f42009-09-09 15:08:12 +00001912 SelExprs.push_back(StringLiteral::Create(*Context,
Ted Kremenek6b7ecf62009-02-06 19:55:15 +00001913 Exp->getSelector().getAsString().c_str(),
Chris Lattnere4b95692008-11-24 03:33:13 +00001914 Exp->getSelector().getAsString().size(),
Chris Lattner630970d2009-02-18 05:49:11 +00001915 false, argType, SourceLocation()));
Steve Naroffe4f9b232007-11-05 14:50:49 +00001916 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1917 &SelExprs[0], SelExprs.size());
Chris Lattner2e0d2602008-01-31 19:37:57 +00001918 ReplaceStmt(Exp, SelExp);
Steve Naroff22216db2008-12-04 23:50:32 +00001919 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroffe4f9b232007-11-05 14:50:49 +00001920 return SelExp;
1921}
1922
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001923CallExpr *RewriteObjC::SynthesizeCallToFunctionDecl(
Steve Naroff574440f2007-10-24 22:48:43 +00001924 FunctionDecl *FD, Expr **args, unsigned nargs) {
Steve Naroffdb1ab1c2007-10-23 23:50:29 +00001925 // Get the type, we will need to reference it in a couple spots.
Steve Naroff574440f2007-10-24 22:48:43 +00001926 QualType msgSendType = FD->getType();
Mike Stump11289f42009-09-09 15:08:12 +00001927
Steve Naroffdb1ab1c2007-10-23 23:50:29 +00001928 // Create a reference to the objc_msgSend() declaration.
Ted Kremenek5a201952009-02-07 01:47:29 +00001929 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, msgSendType, SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00001930
Steve Naroffdb1ab1c2007-10-23 23:50:29 +00001931 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattner3c799d72007-10-24 17:06:59 +00001932 QualType pToFunc = Context->getPointerType(msgSendType);
Mike Stump11289f42009-09-09 15:08:12 +00001933 ImplicitCastExpr *ICE = new (Context) ImplicitCastExpr(pToFunc,
Anders Carlssona2615922009-07-31 00:48:10 +00001934 CastExpr::CK_Unknown,
Mike Stump11289f42009-09-09 15:08:12 +00001935 DRE,
Douglas Gregora11693b2008-11-12 17:17:38 +00001936 /*isLvalue=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00001937
John McCall9dd450b2009-09-21 23:43:11 +00001938 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Mike Stump11289f42009-09-09 15:08:12 +00001939
Ted Kremenekd7b4f402009-02-09 20:51:47 +00001940 return new (Context) CallExpr(*Context, ICE, args, nargs, FT->getResultType(),
1941 SourceLocation());
Steve Naroff574440f2007-10-24 22:48:43 +00001942}
1943
Steve Naroff50d42052007-11-01 13:24:47 +00001944static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
1945 const char *&startRef, const char *&endRef) {
1946 while (startBuf < endBuf) {
1947 if (*startBuf == '<')
1948 startRef = startBuf; // mark the start.
1949 if (*startBuf == '>') {
Steve Naroff1b232132007-11-09 12:50:28 +00001950 if (startRef && *startRef == '<') {
1951 endRef = startBuf; // mark the end.
1952 return true;
1953 }
1954 return false;
Steve Naroff50d42052007-11-01 13:24:47 +00001955 }
1956 startBuf++;
1957 }
1958 return false;
1959}
1960
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00001961static void scanToNextArgument(const char *&argRef) {
1962 int angle = 0;
1963 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
1964 if (*argRef == '<')
1965 angle++;
1966 else if (*argRef == '>')
1967 angle--;
1968 argRef++;
1969 }
1970 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
1971}
Fariborz Jahanian16e703a2007-12-11 23:04:08 +00001972
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001973bool RewriteObjC::needToScanForQualifiers(QualType T) {
Steve Naroffc277ad12009-07-18 15:33:26 +00001974 return T->isObjCQualifiedIdType() || T->isObjCQualifiedInterfaceType();
Steve Naroff50d42052007-11-01 13:24:47 +00001975}
1976
Steve Naroff873bd842008-07-29 18:15:38 +00001977void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
1978 QualType Type = E->getType();
1979 if (needToScanForQualifiers(Type)) {
Steve Naroffdbfc6932008-11-19 21:15:47 +00001980 SourceLocation Loc, EndLoc;
Mike Stump11289f42009-09-09 15:08:12 +00001981
Steve Naroffdbfc6932008-11-19 21:15:47 +00001982 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
1983 Loc = ECE->getLParenLoc();
1984 EndLoc = ECE->getRParenLoc();
1985 } else {
1986 Loc = E->getLocStart();
1987 EndLoc = E->getLocEnd();
1988 }
1989 // This will defend against trying to rewrite synthesized expressions.
1990 if (Loc.isInvalid() || EndLoc.isInvalid())
1991 return;
1992
Steve Naroff873bd842008-07-29 18:15:38 +00001993 const char *startBuf = SM->getCharacterData(Loc);
Steve Naroffdbfc6932008-11-19 21:15:47 +00001994 const char *endBuf = SM->getCharacterData(EndLoc);
Steve Naroff873bd842008-07-29 18:15:38 +00001995 const char *startRef = 0, *endRef = 0;
1996 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1997 // Get the locations of the startRef, endRef.
1998 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-startBuf);
1999 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-startBuf+1);
2000 // Comment out the protocol references.
2001 InsertText(LessLoc, "/*", 2);
2002 InsertText(GreaterLoc, "*/", 2);
2003 }
2004 }
2005}
2006
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002007void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002008 SourceLocation Loc;
2009 QualType Type;
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002010 const FunctionProtoType *proto = 0;
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002011 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
2012 Loc = VD->getLocation();
2013 Type = VD->getType();
2014 }
2015 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
2016 Loc = FD->getLocation();
2017 // Check for ObjC 'id' and class types that have been adorned with protocol
2018 // information (id<p>, C<p>*). The protocol references need to be rewritten!
John McCall9dd450b2009-09-21 23:43:11 +00002019 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002020 assert(funcType && "missing function type");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002021 proto = dyn_cast<FunctionProtoType>(funcType);
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002022 if (!proto)
2023 return;
2024 Type = proto->getResultType();
2025 }
Steve Naroffe70a52a2009-12-05 15:55:59 +00002026 else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
2027 Loc = FD->getLocation();
2028 Type = FD->getType();
2029 }
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002030 else
2031 return;
Mike Stump11289f42009-09-09 15:08:12 +00002032
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002033 if (needToScanForQualifiers(Type)) {
Steve Naroff50d42052007-11-01 13:24:47 +00002034 // Since types are unique, we need to scan the buffer.
Mike Stump11289f42009-09-09 15:08:12 +00002035
Steve Naroff50d42052007-11-01 13:24:47 +00002036 const char *endBuf = SM->getCharacterData(Loc);
2037 const char *startBuf = endBuf;
Steve Naroff930e0992008-05-31 05:02:17 +00002038 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
Steve Naroff50d42052007-11-01 13:24:47 +00002039 startBuf--; // scan backward (from the decl location) for return type.
2040 const char *startRef = 0, *endRef = 0;
2041 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2042 // Get the locations of the startRef, endRef.
2043 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
2044 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
2045 // Comment out the protocol references.
Chris Lattner1780a852008-01-31 19:42:41 +00002046 InsertText(LessLoc, "/*", 2);
2047 InsertText(GreaterLoc, "*/", 2);
Steve Naroff37e011c2007-10-31 04:38:33 +00002048 }
2049 }
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002050 if (!proto)
2051 return; // most likely, was a variable
Steve Naroff50d42052007-11-01 13:24:47 +00002052 // Now check arguments.
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002053 const char *startBuf = SM->getCharacterData(Loc);
2054 const char *startFuncBuf = startBuf;
Steve Naroff50d42052007-11-01 13:24:47 +00002055 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
2056 if (needToScanForQualifiers(proto->getArgType(i))) {
2057 // Since types are unique, we need to scan the buffer.
Mike Stump11289f42009-09-09 15:08:12 +00002058
Steve Naroff50d42052007-11-01 13:24:47 +00002059 const char *endBuf = startBuf;
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002060 // scan forward (from the decl location) for argument types.
2061 scanToNextArgument(endBuf);
Steve Naroff50d42052007-11-01 13:24:47 +00002062 const char *startRef = 0, *endRef = 0;
2063 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2064 // Get the locations of the startRef, endRef.
Mike Stump11289f42009-09-09 15:08:12 +00002065 SourceLocation LessLoc =
Fariborz Jahanian16e703a2007-12-11 23:04:08 +00002066 Loc.getFileLocWithOffset(startRef-startFuncBuf);
Mike Stump11289f42009-09-09 15:08:12 +00002067 SourceLocation GreaterLoc =
Fariborz Jahanian16e703a2007-12-11 23:04:08 +00002068 Loc.getFileLocWithOffset(endRef-startFuncBuf+1);
Steve Naroff50d42052007-11-01 13:24:47 +00002069 // Comment out the protocol references.
Chris Lattner1780a852008-01-31 19:42:41 +00002070 InsertText(LessLoc, "/*", 2);
2071 InsertText(GreaterLoc, "*/", 2);
Steve Naroff50d42052007-11-01 13:24:47 +00002072 }
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002073 startBuf = ++endBuf;
2074 }
2075 else {
Steve Naroffc884aa82008-08-06 15:58:23 +00002076 // If the function name is derived from a macro expansion, then the
2077 // argument buffer will not follow the name. Need to speak with Chris.
2078 while (*startBuf && *startBuf != ')' && *startBuf != ',')
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002079 startBuf++; // scan forward (from the decl location) for argument types.
2080 startBuf++;
2081 }
Steve Naroff50d42052007-11-01 13:24:47 +00002082 }
Steve Naroff37e011c2007-10-31 04:38:33 +00002083}
2084
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002085// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002086void RewriteObjC::SynthSelGetUidFunctionDecl() {
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002087 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
2088 llvm::SmallVector<QualType, 16> ArgTys;
John McCall8ccfcb52009-09-24 19:53:00 +00002089 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002090 QualType getFuncType = Context->getFunctionType(Context->getObjCSelType(),
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002091 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002092 false /*isVariadic*/, 0);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002093 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002094 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002095 SelGetUidIdent, getFuncType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002096 FunctionDecl::Extern, false);
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002097}
2098
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002099void RewriteObjC::RewriteFunctionDecl(FunctionDecl *FD) {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002100 // declared in <objc/objc.h>
Douglas Gregor1e21c192009-01-09 01:47:02 +00002101 if (FD->getIdentifier() &&
2102 strcmp(FD->getNameAsCString(), "sel_registerName") == 0) {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002103 SelGetUidFunctionDecl = FD;
Steve Naroff37e011c2007-10-31 04:38:33 +00002104 return;
2105 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002106 RewriteObjCQualifiedInterfaceTypes(FD);
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002107}
2108
Steve Naroff17978c42008-03-11 17:37:02 +00002109// SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002110void RewriteObjC::SynthSuperContructorFunctionDecl() {
Steve Naroff17978c42008-03-11 17:37:02 +00002111 if (SuperContructorFunctionDecl)
2112 return;
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002113 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
Steve Naroff17978c42008-03-11 17:37:02 +00002114 llvm::SmallVector<QualType, 16> ArgTys;
2115 QualType argT = Context->getObjCIdType();
2116 assert(!argT.isNull() && "Can't find 'id' type");
2117 ArgTys.push_back(argT);
2118 ArgTys.push_back(argT);
2119 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
2120 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002121 false, 0);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002122 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002123 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002124 msgSendIdent, msgSendType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002125 FunctionDecl::Extern, false);
Steve Naroff17978c42008-03-11 17:37:02 +00002126}
2127
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002128// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002129void RewriteObjC::SynthMsgSendFunctionDecl() {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002130 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
2131 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002132 QualType argT = Context->getObjCIdType();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002133 assert(!argT.isNull() && "Can't find 'id' type");
2134 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002135 argT = Context->getObjCSelType();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002136 assert(!argT.isNull() && "Can't find 'SEL' type");
2137 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002138 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002139 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002140 true /*isVariadic*/, 0);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002141 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnerc5ffed42008-04-04 06:12:32 +00002142 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002143 msgSendIdent, msgSendType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002144 FunctionDecl::Extern, false);
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002145}
2146
Steve Naroff7fa2f042007-11-15 10:28:18 +00002147// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002148void RewriteObjC::SynthMsgSendSuperFunctionDecl() {
Steve Naroff7fa2f042007-11-15 10:28:18 +00002149 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
2150 llvm::SmallVector<QualType, 16> ArgTys;
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00002151 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattnerc5ffed42008-04-04 06:12:32 +00002152 SourceLocation(),
Ted Kremenek47923c72008-09-05 01:34:33 +00002153 &Context->Idents.get("objc_super"));
Steve Naroff7fa2f042007-11-15 10:28:18 +00002154 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2155 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2156 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002157 argT = Context->getObjCSelType();
Steve Naroff7fa2f042007-11-15 10:28:18 +00002158 assert(!argT.isNull() && "Can't find 'SEL' type");
2159 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002160 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff7fa2f042007-11-15 10:28:18 +00002161 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002162 true /*isVariadic*/, 0);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002163 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002164 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002165 msgSendIdent, msgSendType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002166 FunctionDecl::Extern, false);
Steve Naroff7fa2f042007-11-15 10:28:18 +00002167}
2168
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002169// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002170void RewriteObjC::SynthMsgSendStretFunctionDecl() {
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002171 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
2172 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002173 QualType argT = Context->getObjCIdType();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002174 assert(!argT.isNull() && "Can't find 'id' type");
2175 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002176 argT = Context->getObjCSelType();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002177 assert(!argT.isNull() && "Can't find 'SEL' type");
2178 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002179 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002180 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002181 true /*isVariadic*/, 0);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002182 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002183 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002184 msgSendIdent, msgSendType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002185 FunctionDecl::Extern, false);
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002186}
2187
Mike Stump11289f42009-09-09 15:08:12 +00002188// SynthMsgSendSuperStretFunctionDecl -
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002189// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002190void RewriteObjC::SynthMsgSendSuperStretFunctionDecl() {
Mike Stump11289f42009-09-09 15:08:12 +00002191 IdentifierInfo *msgSendIdent =
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002192 &Context->Idents.get("objc_msgSendSuper_stret");
2193 llvm::SmallVector<QualType, 16> ArgTys;
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00002194 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattnerc5ffed42008-04-04 06:12:32 +00002195 SourceLocation(),
Ted Kremenek47923c72008-09-05 01:34:33 +00002196 &Context->Idents.get("objc_super"));
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002197 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2198 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2199 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002200 argT = Context->getObjCSelType();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002201 assert(!argT.isNull() && "Can't find 'SEL' type");
2202 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002203 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002204 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002205 true /*isVariadic*/, 0);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002206 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002207 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002208 msgSendIdent, msgSendType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002209 FunctionDecl::Extern, false);
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002210}
2211
Steve Naroff2e4e3852008-05-08 22:02:18 +00002212// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002213void RewriteObjC::SynthMsgSendFpretFunctionDecl() {
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002214 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
2215 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002216 QualType argT = Context->getObjCIdType();
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002217 assert(!argT.isNull() && "Can't find 'id' type");
2218 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002219 argT = Context->getObjCSelType();
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002220 assert(!argT.isNull() && "Can't find 'SEL' type");
2221 ArgTys.push_back(argT);
Steve Naroff2e4e3852008-05-08 22:02:18 +00002222 QualType msgSendType = Context->getFunctionType(Context->DoubleTy,
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002223 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002224 true /*isVariadic*/, 0);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002225 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002226 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002227 msgSendIdent, msgSendType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002228 FunctionDecl::Extern, false);
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002229}
2230
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002231// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002232void RewriteObjC::SynthGetClassFunctionDecl() {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002233 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
2234 llvm::SmallVector<QualType, 16> ArgTys;
John McCall8ccfcb52009-09-24 19:53:00 +00002235 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002236 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002237 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002238 false /*isVariadic*/, 0);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002239 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002240 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002241 getClassIdent, getClassType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002242 FunctionDecl::Extern, false);
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002243}
2244
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002245// SynthGetMetaClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002246void RewriteObjC::SynthGetMetaClassFunctionDecl() {
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002247 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
2248 llvm::SmallVector<QualType, 16> ArgTys;
John McCall8ccfcb52009-09-24 19:53:00 +00002249 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002250 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002251 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002252 false /*isVariadic*/, 0);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002253 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002254 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002255 getClassIdent, getClassType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002256 FunctionDecl::Extern, false);
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002257}
2258
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002259Stmt *RewriteObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroffce8e8862008-03-15 00:55:56 +00002260 QualType strType = getConstantStringStructType();
2261
2262 std::string S = "__NSConstantStringImpl_";
Steve Naroffa6141f02008-05-31 03:35:42 +00002263
2264 std::string tmpName = InFileName;
2265 unsigned i;
2266 for (i=0; i < tmpName.length(); i++) {
2267 char c = tmpName.at(i);
2268 // replace any non alphanumeric characters with '_'.
2269 if (!isalpha(c) && (c < '0' || c > '9'))
2270 tmpName[i] = '_';
2271 }
2272 S += tmpName;
2273 S += "_";
Steve Naroffce8e8862008-03-15 00:55:56 +00002274 S += utostr(NumObjCStringLiterals++);
2275
Steve Naroff00a31762008-03-27 22:29:16 +00002276 Preamble += "static __NSConstantStringImpl " + S;
2277 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2278 Preamble += "0x000007c8,"; // utf8_str
Steve Naroffce8e8862008-03-15 00:55:56 +00002279 // The pretty printer for StringLiteral handles escape characters properly.
Ted Kremenek2d470fc2008-09-13 05:16:45 +00002280 std::string prettyBufS;
2281 llvm::raw_string_ostream prettyBuf(prettyBufS);
Chris Lattnerc61089a2009-06-30 01:26:17 +00002282 Exp->getString()->printPretty(prettyBuf, *Context, 0,
2283 PrintingPolicy(LangOpts));
Steve Naroff00a31762008-03-27 22:29:16 +00002284 Preamble += prettyBuf.str();
2285 Preamble += ",";
Steve Naroff94ed6dc2009-12-06 01:48:44 +00002286 Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00002287
2288 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
2289 &Context->Idents.get(S.c_str()), strType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002290 VarDecl::Static);
Ted Kremenek5a201952009-02-07 01:47:29 +00002291 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, strType, SourceLocation());
2292 Expr *Unop = new (Context) UnaryOperator(DRE, UnaryOperator::AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00002293 Context->getPointerType(DRE->getType()),
Steve Naroffce8e8862008-03-15 00:55:56 +00002294 SourceLocation());
Steve Naroff265a6b92007-11-08 14:30:50 +00002295 // cast to NSConstantString *
Mike Stump11289f42009-09-09 15:08:12 +00002296 CastExpr *cast = new (Context) CStyleCastExpr(Exp->getType(),
Anders Carlssona2615922009-07-31 00:48:10 +00002297 CastExpr::CK_Unknown,
Mike Stump11289f42009-09-09 15:08:12 +00002298 Unop, Exp->getType(),
2299 SourceLocation(),
Anders Carlssona2615922009-07-31 00:48:10 +00002300 SourceLocation());
Chris Lattner2e0d2602008-01-31 19:37:57 +00002301 ReplaceStmt(Exp, cast);
Steve Naroff22216db2008-12-04 23:50:32 +00002302 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroff265a6b92007-11-08 14:30:50 +00002303 return cast;
Steve Naroffa397efd2007-11-03 11:27:19 +00002304}
2305
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002306ObjCInterfaceDecl *RewriteObjC::isSuperReceiver(Expr *recExpr) {
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002307 // check if we are sending a message to 'super'
Douglas Gregorffca3a22009-01-09 17:18:27 +00002308 if (!CurMethodDef || !CurMethodDef->isInstanceMethod()) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00002309
Douglas Gregor8ea1f532008-11-04 14:56:14 +00002310 if (ObjCSuperExpr *Super = dyn_cast<ObjCSuperExpr>(recExpr)) {
Mike Stump11289f42009-09-09 15:08:12 +00002311 const ObjCObjectPointerType *OPT =
John McCall9dd450b2009-09-21 23:43:11 +00002312 Super->getType()->getAs<ObjCObjectPointerType>();
Steve Naroff7cae42b2009-07-10 23:34:53 +00002313 assert(OPT);
2314 const ObjCInterfaceType *IT = OPT->getInterfaceType();
Chris Lattnera9b3cae2008-06-21 18:04:54 +00002315 return IT->getDecl();
2316 }
2317 return 0;
Steve Naroff7fa2f042007-11-15 10:28:18 +00002318}
2319
2320// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002321QualType RewriteObjC::getSuperStructType() {
Steve Naroff7fa2f042007-11-15 10:28:18 +00002322 if (!SuperStructDecl) {
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00002323 SuperStructDecl = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002324 SourceLocation(),
Ted Kremenek47923c72008-09-05 01:34:33 +00002325 &Context->Idents.get("objc_super"));
Steve Naroff7fa2f042007-11-15 10:28:18 +00002326 QualType FieldTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00002327
Steve Naroff7fa2f042007-11-15 10:28:18 +00002328 // struct objc_object *receiver;
Mike Stump11289f42009-09-09 15:08:12 +00002329 FieldTypes[0] = Context->getObjCIdType();
Steve Naroff7fa2f042007-11-15 10:28:18 +00002330 // struct objc_class *super;
Mike Stump11289f42009-09-09 15:08:12 +00002331 FieldTypes[1] = Context->getObjCClassType();
Douglas Gregor91f84212008-12-11 16:49:14 +00002332
Steve Naroff7fa2f042007-11-15 10:28:18 +00002333 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00002334 for (unsigned i = 0; i < 2; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00002335 SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
2336 SourceLocation(), 0,
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002337 FieldTypes[i], 0,
2338 /*BitWidth=*/0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002339 /*Mutable=*/false));
Douglas Gregor91f84212008-12-11 16:49:14 +00002340 }
Mike Stump11289f42009-09-09 15:08:12 +00002341
Douglas Gregor91f84212008-12-11 16:49:14 +00002342 SuperStructDecl->completeDefinition(*Context);
Steve Naroff7fa2f042007-11-15 10:28:18 +00002343 }
2344 return Context->getTagDeclType(SuperStructDecl);
2345}
2346
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002347QualType RewriteObjC::getConstantStringStructType() {
Steve Naroffce8e8862008-03-15 00:55:56 +00002348 if (!ConstantStringDecl) {
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00002349 ConstantStringDecl = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002350 SourceLocation(),
Ted Kremenek47923c72008-09-05 01:34:33 +00002351 &Context->Idents.get("__NSConstantStringImpl"));
Steve Naroffce8e8862008-03-15 00:55:56 +00002352 QualType FieldTypes[4];
Mike Stump11289f42009-09-09 15:08:12 +00002353
Steve Naroffce8e8862008-03-15 00:55:56 +00002354 // struct objc_object *receiver;
Mike Stump11289f42009-09-09 15:08:12 +00002355 FieldTypes[0] = Context->getObjCIdType();
Steve Naroffce8e8862008-03-15 00:55:56 +00002356 // int flags;
Mike Stump11289f42009-09-09 15:08:12 +00002357 FieldTypes[1] = Context->IntTy;
Steve Naroffce8e8862008-03-15 00:55:56 +00002358 // char *str;
Mike Stump11289f42009-09-09 15:08:12 +00002359 FieldTypes[2] = Context->getPointerType(Context->CharTy);
Steve Naroffce8e8862008-03-15 00:55:56 +00002360 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00002361 FieldTypes[3] = Context->LongTy;
Douglas Gregor91f84212008-12-11 16:49:14 +00002362
Steve Naroffce8e8862008-03-15 00:55:56 +00002363 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00002364 for (unsigned i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00002365 ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
2366 ConstantStringDecl,
Douglas Gregor91f84212008-12-11 16:49:14 +00002367 SourceLocation(), 0,
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002368 FieldTypes[i], 0,
Douglas Gregor91f84212008-12-11 16:49:14 +00002369 /*BitWidth=*/0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002370 /*Mutable=*/true));
Douglas Gregor91f84212008-12-11 16:49:14 +00002371 }
2372
2373 ConstantStringDecl->completeDefinition(*Context);
Steve Naroffce8e8862008-03-15 00:55:56 +00002374 }
2375 return Context->getTagDeclType(ConstantStringDecl);
2376}
2377
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002378Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002379 if (!SelGetUidFunctionDecl)
2380 SynthSelGetUidFunctionDecl();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002381 if (!MsgSendFunctionDecl)
2382 SynthMsgSendFunctionDecl();
Steve Naroff7fa2f042007-11-15 10:28:18 +00002383 if (!MsgSendSuperFunctionDecl)
2384 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002385 if (!MsgSendStretFunctionDecl)
2386 SynthMsgSendStretFunctionDecl();
2387 if (!MsgSendSuperStretFunctionDecl)
2388 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002389 if (!MsgSendFpretFunctionDecl)
2390 SynthMsgSendFpretFunctionDecl();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002391 if (!GetClassFunctionDecl)
2392 SynthGetClassFunctionDecl();
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002393 if (!GetMetaClassFunctionDecl)
2394 SynthGetMetaClassFunctionDecl();
Mike Stump11289f42009-09-09 15:08:12 +00002395
Steve Naroff7fa2f042007-11-15 10:28:18 +00002396 // default to objc_msgSend().
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002397 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2398 // May need to use objc_msgSend_stret() as well.
2399 FunctionDecl *MsgSendStretFlavor = 0;
Steve Naroffd9803712009-04-29 16:37:50 +00002400 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
2401 QualType resultType = mDecl->getResultType();
Chris Lattner3f6cd0b2008-07-26 22:36:27 +00002402 if (resultType->isStructureType() || resultType->isUnionType())
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002403 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Chris Lattner3f6cd0b2008-07-26 22:36:27 +00002404 else if (resultType->isRealFloatingType())
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002405 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002406 }
Mike Stump11289f42009-09-09 15:08:12 +00002407
Steve Naroff574440f2007-10-24 22:48:43 +00002408 // Synthesize a call to objc_msgSend().
2409 llvm::SmallVector<Expr*, 8> MsgExprs;
2410 IdentifierInfo *clsName = Exp->getClassName();
Mike Stump11289f42009-09-09 15:08:12 +00002411
Steve Naroff574440f2007-10-24 22:48:43 +00002412 // Derive/push the receiver/selector, 2 implicit arguments to objc_msgSend().
2413 if (clsName) { // class message.
Steve Naroff6c79f972008-07-24 19:44:33 +00002414 // FIXME: We need to fix Sema (and the AST for ObjCMessageExpr) to handle
2415 // the 'super' idiom within a class method.
Daniel Dunbar07d07852009-10-18 21:17:35 +00002416 if (clsName->getName() == "super") {
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002417 MsgSendFlavor = MsgSendSuperFunctionDecl;
2418 if (MsgSendStretFlavor)
2419 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2420 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
Mike Stump11289f42009-09-09 15:08:12 +00002421
2422 ObjCInterfaceDecl *SuperDecl =
Steve Naroff677ab3a2008-10-27 17:20:55 +00002423 CurMethodDef->getClassInterface()->getSuperClass();
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002424
2425 llvm::SmallVector<Expr*, 4> InitExprs;
Mike Stump11289f42009-09-09 15:08:12 +00002426
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002427 // set the receiver to self, the first argument to all methods.
Steve Naroffd9803712009-04-29 16:37:50 +00002428 InitExprs.push_back(
Mike Stump11289f42009-09-09 15:08:12 +00002429 new (Context) CStyleCastExpr(Context->getObjCIdType(),
Anders Carlssona2615922009-07-31 00:48:10 +00002430 CastExpr::CK_Unknown,
Mike Stump11289f42009-09-09 15:08:12 +00002431 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
Steve Naroffd9803712009-04-29 16:37:50 +00002432 Context->getObjCIdType(),
2433 SourceLocation()),
2434 Context->getObjCIdType(),
2435 SourceLocation(), SourceLocation())); // set the 'receiver'.
2436
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002437 llvm::SmallVector<Expr*, 8> ClsExprs;
2438 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattnerf83b5af2009-02-18 06:40:38 +00002439 ClsExprs.push_back(StringLiteral::Create(*Context,
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00002440 SuperDecl->getIdentifier()->getNameStart(),
2441 SuperDecl->getIdentifier()->getLength(),
2442 false, argType, SourceLocation()));
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002443 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002444 &ClsExprs[0],
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002445 ClsExprs.size());
2446 // To turn off a warning, type-cast to 'id'
Douglas Gregore200adc2008-10-27 19:41:14 +00002447 InitExprs.push_back( // set 'super class', using objc_getClass().
Mike Stump11289f42009-09-09 15:08:12 +00002448 new (Context) CStyleCastExpr(Context->getObjCIdType(),
Anders Carlssona2615922009-07-31 00:48:10 +00002449 CastExpr::CK_Unknown,
Douglas Gregore200adc2008-10-27 19:41:14 +00002450 Cls, Context->getObjCIdType(),
Mike Stump11289f42009-09-09 15:08:12 +00002451 SourceLocation(), SourceLocation()));
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002452 // struct objc_super
2453 QualType superType = getSuperStructType();
Steve Naroff0b844f02008-03-11 18:14:26 +00002454 Expr *SuperRep;
Mike Stump11289f42009-09-09 15:08:12 +00002455
Steve Naroff0b844f02008-03-11 18:14:26 +00002456 if (LangOpts.Microsoft) {
2457 SynthSuperContructorFunctionDecl();
2458 // Simulate a contructor call...
Mike Stump11289f42009-09-09 15:08:12 +00002459 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
Steve Naroff0b844f02008-03-11 18:14:26 +00002460 superType, SourceLocation());
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002461 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
Mike Stump11289f42009-09-09 15:08:12 +00002462 InitExprs.size(),
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002463 superType, SourceLocation());
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002464 // The code for super is a little tricky to prevent collision with
2465 // the structure definition in the header. The rewriter has it's own
2466 // internal definition (__rw_objc_super) that is uses. This is why
2467 // we need the cast below. For example:
2468 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2469 //
Ted Kremenek5a201952009-02-07 01:47:29 +00002470 SuperRep = new (Context) UnaryOperator(SuperRep, UnaryOperator::AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00002471 Context->getPointerType(SuperRep->getType()),
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002472 SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002473 SuperRep = new (Context) CStyleCastExpr(Context->getPointerType(superType),
2474 CastExpr::CK_Unknown, SuperRep,
Anders Carlssona2615922009-07-31 00:48:10 +00002475 Context->getPointerType(superType),
Mike Stump11289f42009-09-09 15:08:12 +00002476 SourceLocation(), SourceLocation());
2477 } else {
Steve Naroff0b844f02008-03-11 18:14:26 +00002478 // (struct objc_super) { <exprs from above> }
Mike Stump11289f42009-09-09 15:08:12 +00002479 InitListExpr *ILE = new (Context) InitListExpr(SourceLocation(),
2480 &InitExprs[0], InitExprs.size(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002481 SourceLocation());
Ted Kremenek5a201952009-02-07 01:47:29 +00002482 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superType, ILE,
Chris Lattner07d754a2008-10-26 23:43:26 +00002483 false);
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002484 // struct objc_super *
Ted Kremenek5a201952009-02-07 01:47:29 +00002485 SuperRep = new (Context) UnaryOperator(SuperRep, UnaryOperator::AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00002486 Context->getPointerType(SuperRep->getType()),
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002487 SourceLocation());
Steve Naroff0b844f02008-03-11 18:14:26 +00002488 }
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002489 MsgExprs.push_back(SuperRep);
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002490 } else {
2491 llvm::SmallVector<Expr*, 8> ClsExprs;
2492 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattnerf83b5af2009-02-18 06:40:38 +00002493 ClsExprs.push_back(StringLiteral::Create(*Context,
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00002494 clsName->getNameStart(),
Chris Lattnerf83b5af2009-02-18 06:40:38 +00002495 clsName->getLength(),
2496 false, argType,
2497 SourceLocation()));
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002498 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002499 &ClsExprs[0],
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002500 ClsExprs.size());
2501 MsgExprs.push_back(Cls);
2502 }
Steve Naroffe7f18192007-11-14 23:54:14 +00002503 } else { // instance message.
2504 Expr *recExpr = Exp->getReceiver();
Steve Naroff7fa2f042007-11-15 10:28:18 +00002505
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002506 if (ObjCInterfaceDecl *SuperDecl = isSuperReceiver(recExpr)) {
Steve Naroff7fa2f042007-11-15 10:28:18 +00002507 MsgSendFlavor = MsgSendSuperFunctionDecl;
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002508 if (MsgSendStretFlavor)
2509 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
Steve Naroff7fa2f042007-11-15 10:28:18 +00002510 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
Mike Stump11289f42009-09-09 15:08:12 +00002511
Steve Naroff7fa2f042007-11-15 10:28:18 +00002512 llvm::SmallVector<Expr*, 4> InitExprs;
Mike Stump11289f42009-09-09 15:08:12 +00002513
Fariborz Jahanian1e34ce12007-12-04 22:32:58 +00002514 InitExprs.push_back(
Mike Stump11289f42009-09-09 15:08:12 +00002515 new (Context) CStyleCastExpr(Context->getObjCIdType(),
Anders Carlssona2615922009-07-31 00:48:10 +00002516 CastExpr::CK_Unknown,
Mike Stump11289f42009-09-09 15:08:12 +00002517 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
Steve Naroff97adf602008-07-16 22:35:27 +00002518 Context->getObjCIdType(),
Douglas Gregore200adc2008-10-27 19:41:14 +00002519 SourceLocation()),
2520 Context->getObjCIdType(),
Steve Naroffc989a7b2008-11-03 23:29:32 +00002521 SourceLocation(), SourceLocation())); // set the 'receiver'.
Mike Stump11289f42009-09-09 15:08:12 +00002522
Steve Naroff7fa2f042007-11-15 10:28:18 +00002523 llvm::SmallVector<Expr*, 8> ClsExprs;
2524 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump11289f42009-09-09 15:08:12 +00002525 ClsExprs.push_back(StringLiteral::Create(*Context,
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00002526 SuperDecl->getIdentifier()->getNameStart(),
2527 SuperDecl->getIdentifier()->getLength(),
2528 false, argType, SourceLocation()));
Steve Naroff7fa2f042007-11-15 10:28:18 +00002529 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002530 &ClsExprs[0],
Fariborz Jahanian1e34ce12007-12-04 22:32:58 +00002531 ClsExprs.size());
Fariborz Jahaniand5db92b2007-12-05 17:29:46 +00002532 // To turn off a warning, type-cast to 'id'
Fariborz Jahanian1e34ce12007-12-04 22:32:58 +00002533 InitExprs.push_back(
Douglas Gregore200adc2008-10-27 19:41:14 +00002534 // set 'super class', using objc_getClass().
Mike Stump11289f42009-09-09 15:08:12 +00002535 new (Context) CStyleCastExpr(Context->getObjCIdType(),
Anders Carlssona2615922009-07-31 00:48:10 +00002536 CastExpr::CK_Unknown,
Mike Stump11289f42009-09-09 15:08:12 +00002537 Cls, Context->getObjCIdType(), SourceLocation(), SourceLocation()));
Steve Naroff7fa2f042007-11-15 10:28:18 +00002538 // struct objc_super
2539 QualType superType = getSuperStructType();
Steve Naroff17978c42008-03-11 17:37:02 +00002540 Expr *SuperRep;
Mike Stump11289f42009-09-09 15:08:12 +00002541
Steve Naroff17978c42008-03-11 17:37:02 +00002542 if (LangOpts.Microsoft) {
2543 SynthSuperContructorFunctionDecl();
2544 // Simulate a contructor call...
Mike Stump11289f42009-09-09 15:08:12 +00002545 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
Steve Naroff17978c42008-03-11 17:37:02 +00002546 superType, SourceLocation());
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002547 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
Mike Stump11289f42009-09-09 15:08:12 +00002548 InitExprs.size(),
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002549 superType, SourceLocation());
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002550 // The code for super is a little tricky to prevent collision with
2551 // the structure definition in the header. The rewriter has it's own
2552 // internal definition (__rw_objc_super) that is uses. This is why
2553 // we need the cast below. For example:
2554 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2555 //
Ted Kremenek5a201952009-02-07 01:47:29 +00002556 SuperRep = new (Context) UnaryOperator(SuperRep, UnaryOperator::AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00002557 Context->getPointerType(SuperRep->getType()),
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002558 SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002559 SuperRep = new (Context) CStyleCastExpr(Context->getPointerType(superType),
Anders Carlssona2615922009-07-31 00:48:10 +00002560 CastExpr::CK_Unknown,
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002561 SuperRep, Context->getPointerType(superType),
Mike Stump11289f42009-09-09 15:08:12 +00002562 SourceLocation(), SourceLocation());
Steve Naroff17978c42008-03-11 17:37:02 +00002563 } else {
2564 // (struct objc_super) { <exprs from above> }
Mike Stump11289f42009-09-09 15:08:12 +00002565 InitListExpr *ILE = new (Context) InitListExpr(SourceLocation(),
2566 &InitExprs[0], InitExprs.size(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002567 SourceLocation());
Ted Kremenek5a201952009-02-07 01:47:29 +00002568 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superType, ILE, false);
Steve Naroff17978c42008-03-11 17:37:02 +00002569 }
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002570 MsgExprs.push_back(SuperRep);
Steve Naroff7fa2f042007-11-15 10:28:18 +00002571 } else {
Fariborz Jahanianff6a4552007-12-07 21:21:21 +00002572 // Remove all type-casts because it may contain objc-style types; e.g.
2573 // Foo<Proto> *.
Douglas Gregorf19b2312008-10-28 15:36:24 +00002574 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
Fariborz Jahanianff6a4552007-12-07 21:21:21 +00002575 recExpr = CE->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00002576 recExpr = new (Context) CStyleCastExpr(Context->getObjCIdType(),
Anders Carlssona2615922009-07-31 00:48:10 +00002577 CastExpr::CK_Unknown, recExpr,
Mike Stump11289f42009-09-09 15:08:12 +00002578 Context->getObjCIdType(),
Steve Naroffc989a7b2008-11-03 23:29:32 +00002579 SourceLocation(), SourceLocation());
Steve Naroff7fa2f042007-11-15 10:28:18 +00002580 MsgExprs.push_back(recExpr);
2581 }
Steve Naroffe7f18192007-11-14 23:54:14 +00002582 }
Steve Naroffa397efd2007-11-03 11:27:19 +00002583 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff574440f2007-10-24 22:48:43 +00002584 llvm::SmallVector<Expr*, 8> SelExprs;
2585 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump11289f42009-09-09 15:08:12 +00002586 SelExprs.push_back(StringLiteral::Create(*Context,
Ted Kremenek6b7ecf62009-02-06 19:55:15 +00002587 Exp->getSelector().getAsString().c_str(),
Chris Lattnere4b95692008-11-24 03:33:13 +00002588 Exp->getSelector().getAsString().size(),
Chris Lattner630970d2009-02-18 05:49:11 +00002589 false, argType, SourceLocation()));
Steve Naroff574440f2007-10-24 22:48:43 +00002590 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2591 &SelExprs[0], SelExprs.size());
2592 MsgExprs.push_back(SelExp);
Mike Stump11289f42009-09-09 15:08:12 +00002593
Steve Naroff574440f2007-10-24 22:48:43 +00002594 // Now push any user supplied arguments.
2595 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroffe7f18192007-11-14 23:54:14 +00002596 Expr *userExpr = Exp->getArg(i);
Steve Narofff60782b2007-11-15 02:58:25 +00002597 // Make all implicit casts explicit...ICE comes in handy:-)
2598 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
2599 // Reuse the ICE type, it is exactly what the doctor ordered.
Douglas Gregore200adc2008-10-27 19:41:14 +00002600 QualType type = ICE->getType()->isObjCQualifiedIdType()
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002601 ? Context->getObjCIdType()
Douglas Gregore200adc2008-10-27 19:41:14 +00002602 : ICE->getType();
Anders Carlssona2615922009-07-31 00:48:10 +00002603 userExpr = new (Context) CStyleCastExpr(type, CastExpr::CK_Unknown,
Mike Stump11289f42009-09-09 15:08:12 +00002604 userExpr, type, SourceLocation(),
Anders Carlssona2615922009-07-31 00:48:10 +00002605 SourceLocation());
Fariborz Jahanian9f0e3102007-12-18 21:33:44 +00002606 }
2607 // Make id<P...> cast into an 'id' cast.
Douglas Gregorf19b2312008-10-28 15:36:24 +00002608 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002609 if (CE->getType()->isObjCQualifiedIdType()) {
Douglas Gregorf19b2312008-10-28 15:36:24 +00002610 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
Fariborz Jahanian9f0e3102007-12-18 21:33:44 +00002611 userExpr = CE->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00002612 userExpr = new (Context) CStyleCastExpr(Context->getObjCIdType(),
Anders Carlssona2615922009-07-31 00:48:10 +00002613 CastExpr::CK_Unknown,
Mike Stump11289f42009-09-09 15:08:12 +00002614 userExpr, Context->getObjCIdType(),
Steve Naroffc989a7b2008-11-03 23:29:32 +00002615 SourceLocation(), SourceLocation());
Fariborz Jahanian9f0e3102007-12-18 21:33:44 +00002616 }
Mike Stump11289f42009-09-09 15:08:12 +00002617 }
Steve Naroffe7f18192007-11-14 23:54:14 +00002618 MsgExprs.push_back(userExpr);
Steve Naroffd9803712009-04-29 16:37:50 +00002619 // We've transferred the ownership to MsgExprs. For now, we *don't* null
2620 // out the argument in the original expression (since we aren't deleting
2621 // the ObjCMessageExpr). See RewritePropertySetter() usage for more info.
2622 //Exp->setArg(i, 0);
Steve Naroff574440f2007-10-24 22:48:43 +00002623 }
Steve Narofff36987c2007-11-04 22:37:50 +00002624 // Generate the funky cast.
2625 CastExpr *cast;
2626 llvm::SmallVector<QualType, 8> ArgTypes;
2627 QualType returnType;
Mike Stump11289f42009-09-09 15:08:12 +00002628
Steve Narofff36987c2007-11-04 22:37:50 +00002629 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroff44864e42007-11-15 10:43:57 +00002630 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
2631 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
2632 else
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002633 ArgTypes.push_back(Context->getObjCIdType());
2634 ArgTypes.push_back(Context->getObjCSelType());
Chris Lattnera4997152009-02-20 18:43:26 +00002635 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
Steve Narofff36987c2007-11-04 22:37:50 +00002636 // Push any user argument types.
Chris Lattnera4997152009-02-20 18:43:26 +00002637 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
2638 E = OMD->param_end(); PI != E; ++PI) {
2639 QualType t = (*PI)->getType()->isObjCQualifiedIdType()
Mike Stump11289f42009-09-09 15:08:12 +00002640 ? Context->getObjCIdType()
Chris Lattnera4997152009-02-20 18:43:26 +00002641 : (*PI)->getType();
Steve Naroff52c65fa2008-10-29 14:49:46 +00002642 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Steve Naroffa5c0db82008-12-11 21:05:33 +00002643 if (isTopLevelBlockPointerType(t)) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002644 const BlockPointerType *BPT = t->getAs<BlockPointerType>();
Steve Naroff52c65fa2008-10-29 14:49:46 +00002645 t = Context->getPointerType(BPT->getPointeeType());
2646 }
Steve Naroff98eb8d12007-11-05 14:36:37 +00002647 ArgTypes.push_back(t);
2648 }
Chris Lattnera4997152009-02-20 18:43:26 +00002649 returnType = OMD->getResultType()->isObjCQualifiedIdType()
2650 ? Context->getObjCIdType() : OMD->getResultType();
Steve Narofff36987c2007-11-04 22:37:50 +00002651 } else {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002652 returnType = Context->getObjCIdType();
Steve Narofff36987c2007-11-04 22:37:50 +00002653 }
2654 // Get the type, we will need to reference it in a couple spots.
Steve Naroff7fa2f042007-11-15 10:28:18 +00002655 QualType msgSendType = MsgSendFlavor->getType();
Mike Stump11289f42009-09-09 15:08:12 +00002656
Steve Narofff36987c2007-11-04 22:37:50 +00002657 // Create a reference to the objc_msgSend() declaration.
Mike Stump11289f42009-09-09 15:08:12 +00002658 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, msgSendType,
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002659 SourceLocation());
Steve Narofff36987c2007-11-04 22:37:50 +00002660
Mike Stump11289f42009-09-09 15:08:12 +00002661 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
Steve Narofff36987c2007-11-04 22:37:50 +00002662 // If we don't do this cast, we get the following bizarre warning/note:
2663 // xx.m:13: warning: function called through a non-compatible type
2664 // xx.m:13: note: if this code is reached, the program will abort
Mike Stump11289f42009-09-09 15:08:12 +00002665 cast = new (Context) CStyleCastExpr(Context->getPointerType(Context->VoidTy),
2666 CastExpr::CK_Unknown, DRE,
Douglas Gregore200adc2008-10-27 19:41:14 +00002667 Context->getPointerType(Context->VoidTy),
Steve Naroffc989a7b2008-11-03 23:29:32 +00002668 SourceLocation(), SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002669
Steve Narofff36987c2007-11-04 22:37:50 +00002670 // Now do the "normal" pointer to function cast.
Mike Stump11289f42009-09-09 15:08:12 +00002671 QualType castType = Context->getFunctionType(returnType,
Fariborz Jahanian227c0d12007-12-06 19:49:56 +00002672 &ArgTypes[0], ArgTypes.size(),
Steve Naroff327f0f42008-03-18 02:02:04 +00002673 // If we don't have a method decl, force a variadic cast.
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002674 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true, 0);
Steve Narofff36987c2007-11-04 22:37:50 +00002675 castType = Context->getPointerType(castType);
Mike Stump11289f42009-09-09 15:08:12 +00002676 cast = new (Context) CStyleCastExpr(castType, CastExpr::CK_Unknown, cast,
2677 castType, SourceLocation(),
Anders Carlssona2615922009-07-31 00:48:10 +00002678 SourceLocation());
Steve Narofff36987c2007-11-04 22:37:50 +00002679
2680 // Don't forget the parens to enforce the proper binding.
Ted Kremenek5a201952009-02-07 01:47:29 +00002681 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
Mike Stump11289f42009-09-09 15:08:12 +00002682
John McCall9dd450b2009-09-21 23:43:11 +00002683 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002684 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
Mike Stump11289f42009-09-09 15:08:12 +00002685 MsgExprs.size(),
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002686 FT->getResultType(), SourceLocation());
Fariborz Jahanian965a8962008-01-08 22:06:28 +00002687 Stmt *ReplacingStmt = CE;
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002688 if (MsgSendStretFlavor) {
2689 // We have the method which returns a struct/union. Must also generate
2690 // call to objc_msgSend_stret and hang both varieties on a conditional
2691 // expression which dictate which one to envoke depending on size of
2692 // method's return type.
Mike Stump11289f42009-09-09 15:08:12 +00002693
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002694 // Create a reference to the objc_msgSend_stret() declaration.
Mike Stump11289f42009-09-09 15:08:12 +00002695 DeclRefExpr *STDRE = new (Context) DeclRefExpr(MsgSendStretFlavor, msgSendType,
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002696 SourceLocation());
2697 // Need to cast objc_msgSend_stret to "void *" (see above comment).
Mike Stump11289f42009-09-09 15:08:12 +00002698 cast = new (Context) CStyleCastExpr(Context->getPointerType(Context->VoidTy),
2699 CastExpr::CK_Unknown, STDRE,
Douglas Gregore200adc2008-10-27 19:41:14 +00002700 Context->getPointerType(Context->VoidTy),
Steve Naroffc989a7b2008-11-03 23:29:32 +00002701 SourceLocation(), SourceLocation());
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002702 // Now do the "normal" pointer to function cast.
Mike Stump11289f42009-09-09 15:08:12 +00002703 castType = Context->getFunctionType(returnType,
Fariborz Jahanian227c0d12007-12-06 19:49:56 +00002704 &ArgTypes[0], ArgTypes.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002705 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false, 0);
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002706 castType = Context->getPointerType(castType);
Anders Carlssona2615922009-07-31 00:48:10 +00002707 cast = new (Context) CStyleCastExpr(castType, CastExpr::CK_Unknown,
2708 cast, castType, SourceLocation(), SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002709
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002710 // Don't forget the parens to enforce the proper binding.
Ted Kremenek5a201952009-02-07 01:47:29 +00002711 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
Mike Stump11289f42009-09-09 15:08:12 +00002712
John McCall9dd450b2009-09-21 23:43:11 +00002713 FT = msgSendType->getAs<FunctionType>();
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002714 CallExpr *STCE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
Mike Stump11289f42009-09-09 15:08:12 +00002715 MsgExprs.size(),
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002716 FT->getResultType(), SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002717
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002718 // Build sizeof(returnType)
Mike Stump11289f42009-09-09 15:08:12 +00002719 SizeOfAlignOfExpr *sizeofExpr = new (Context) SizeOfAlignOfExpr(true,
John McCallbcd03502009-12-07 02:54:59 +00002720 Context->getTrivialTypeSourceInfo(returnType),
Sebastian Redl6f282892008-11-11 17:56:53 +00002721 Context->getSizeType(),
2722 SourceLocation(), SourceLocation());
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002723 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2724 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
2725 // For X86 it is more complicated and some kind of target specific routine
2726 // is needed to decide what to do.
Mike Stump11289f42009-09-09 15:08:12 +00002727 unsigned IntSize =
Chris Lattner37e05872008-03-05 18:54:05 +00002728 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Mike Stump11289f42009-09-09 15:08:12 +00002729 IntegerLiteral *limit = new (Context) IntegerLiteral(llvm::APInt(IntSize, 8),
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002730 Context->IntTy,
2731 SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002732 BinaryOperator *lessThanExpr = new (Context) BinaryOperator(sizeofExpr, limit,
2733 BinaryOperator::LE,
2734 Context->IntTy,
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002735 SourceLocation());
2736 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
Mike Stump11289f42009-09-09 15:08:12 +00002737 ConditionalOperator *CondExpr =
Douglas Gregor7e112b02009-08-26 14:37:04 +00002738 new (Context) ConditionalOperator(lessThanExpr,
2739 SourceLocation(), CE,
2740 SourceLocation(), STCE, returnType);
Ted Kremenek5a201952009-02-07 01:47:29 +00002741 ReplacingStmt = new (Context) ParenExpr(SourceLocation(), SourceLocation(), CondExpr);
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002742 }
Mike Stump11289f42009-09-09 15:08:12 +00002743 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Fariborz Jahanian965a8962008-01-08 22:06:28 +00002744 return ReplacingStmt;
2745}
2746
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002747Stmt *RewriteObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanian965a8962008-01-08 22:06:28 +00002748 Stmt *ReplacingStmt = SynthMessageExpr(Exp);
Mike Stump11289f42009-09-09 15:08:12 +00002749
Steve Naroff574440f2007-10-24 22:48:43 +00002750 // Now do the actual rewrite.
Chris Lattner2e0d2602008-01-31 19:37:57 +00002751 ReplaceStmt(Exp, ReplacingStmt);
Mike Stump11289f42009-09-09 15:08:12 +00002752
2753 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Fariborz Jahanian965a8962008-01-08 22:06:28 +00002754 return ReplacingStmt;
Steve Naroffdb1ab1c2007-10-23 23:50:29 +00002755}
2756
Steve Naroffd9803712009-04-29 16:37:50 +00002757// typedef struct objc_object Protocol;
2758QualType RewriteObjC::getProtocolType() {
2759 if (!ProtocolTypeDecl) {
John McCallbcd03502009-12-07 02:54:59 +00002760 TypeSourceInfo *TInfo
2761 = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
Steve Naroffd9803712009-04-29 16:37:50 +00002762 ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002763 SourceLocation(),
Steve Naroffd9803712009-04-29 16:37:50 +00002764 &Context->Idents.get("Protocol"),
John McCallbcd03502009-12-07 02:54:59 +00002765 TInfo);
Steve Naroffd9803712009-04-29 16:37:50 +00002766 }
2767 return Context->getTypeDeclType(ProtocolTypeDecl);
2768}
2769
Fariborz Jahanian33c0e812007-12-07 18:47:10 +00002770/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
Steve Naroffd9803712009-04-29 16:37:50 +00002771/// a synthesized/forward data reference (to the protocol's metadata).
2772/// The forward references (and metadata) are generated in
2773/// RewriteObjC::HandleTranslationUnit().
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002774Stmt *RewriteObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Steve Naroffd9803712009-04-29 16:37:50 +00002775 std::string Name = "_OBJC_PROTOCOL_" + Exp->getProtocol()->getNameAsString();
2776 IdentifierInfo *ID = &Context->Idents.get(Name);
Mike Stump11289f42009-09-09 15:08:12 +00002777 VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Douglas Gregored6c7442009-11-23 11:41:28 +00002778 ID, getProtocolType(), 0, VarDecl::Extern);
Steve Naroffd9803712009-04-29 16:37:50 +00002779 DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, getProtocolType(), SourceLocation());
2780 Expr *DerefExpr = new (Context) UnaryOperator(DRE, UnaryOperator::AddrOf,
2781 Context->getPointerType(DRE->getType()),
2782 SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002783 CastExpr *castExpr = new (Context) CStyleCastExpr(DerefExpr->getType(),
2784 CastExpr::CK_Unknown,
2785 DerefExpr, DerefExpr->getType(),
Steve Naroffd9803712009-04-29 16:37:50 +00002786 SourceLocation(), SourceLocation());
2787 ReplaceStmt(Exp, castExpr);
2788 ProtocolExprDecls.insert(Exp->getProtocol());
Mike Stump11289f42009-09-09 15:08:12 +00002789 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroffd9803712009-04-29 16:37:50 +00002790 return castExpr;
Mike Stump11289f42009-09-09 15:08:12 +00002791
Fariborz Jahanian33c0e812007-12-07 18:47:10 +00002792}
2793
Mike Stump11289f42009-09-09 15:08:12 +00002794bool RewriteObjC::BufferContainsPPDirectives(const char *startBuf,
Steve Naroffcd92aeb2008-05-31 14:15:04 +00002795 const char *endBuf) {
2796 while (startBuf < endBuf) {
2797 if (*startBuf == '#') {
2798 // Skip whitespace.
2799 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
2800 ;
2801 if (!strncmp(startBuf, "if", strlen("if")) ||
2802 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
2803 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
2804 !strncmp(startBuf, "define", strlen("define")) ||
2805 !strncmp(startBuf, "undef", strlen("undef")) ||
2806 !strncmp(startBuf, "else", strlen("else")) ||
2807 !strncmp(startBuf, "elif", strlen("elif")) ||
2808 !strncmp(startBuf, "endif", strlen("endif")) ||
2809 !strncmp(startBuf, "pragma", strlen("pragma")) ||
2810 !strncmp(startBuf, "include", strlen("include")) ||
2811 !strncmp(startBuf, "import", strlen("import")) ||
2812 !strncmp(startBuf, "include_next", strlen("include_next")))
2813 return true;
2814 }
2815 startBuf++;
2816 }
2817 return false;
2818}
2819
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002820/// SynthesizeObjCInternalStruct - Rewrite one internal struct corresponding to
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00002821/// an objective-c class with ivars.
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002822void RewriteObjC::SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00002823 std::string &Result) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002824 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
Mike Stump11289f42009-09-09 15:08:12 +00002825 assert(CDecl->getNameAsCString() &&
Douglas Gregor77324f32008-11-17 14:58:09 +00002826 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanianc3cda762007-10-31 23:08:24 +00002827 // Do not synthesize more than once.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002828 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanianc3cda762007-10-31 23:08:24 +00002829 return;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002830 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Chris Lattner8d1c04f2008-03-16 21:08:55 +00002831 int NumIvars = CDecl->ivar_size();
Steve Naroffdde78982007-11-14 19:25:57 +00002832 SourceLocation LocStart = CDecl->getLocStart();
2833 SourceLocation LocEnd = CDecl->getLocEnd();
Mike Stump11289f42009-09-09 15:08:12 +00002834
Steve Naroffdde78982007-11-14 19:25:57 +00002835 const char *startBuf = SM->getCharacterData(LocStart);
2836 const char *endBuf = SM->getCharacterData(LocEnd);
Mike Stump11289f42009-09-09 15:08:12 +00002837
Fariborz Jahaniana883d6e2007-11-26 19:52:57 +00002838 // If no ivars and no root or if its root, directly or indirectly,
2839 // have no ivars (thus not synthesized) then no need to synthesize this class.
Chris Lattner8d1c04f2008-03-16 21:08:55 +00002840 if ((CDecl->isForwardDecl() || NumIvars == 0) &&
2841 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Chris Lattner184e65d2009-04-14 23:22:57 +00002842 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Chris Lattner9cc55f52008-01-31 19:51:04 +00002843 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahaniana883d6e2007-11-26 19:52:57 +00002844 return;
2845 }
Mike Stump11289f42009-09-09 15:08:12 +00002846
2847 // FIXME: This has potential of causing problem. If
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002848 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahaniana883d6e2007-11-26 19:52:57 +00002849 Result += "\nstruct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002850 Result += CDecl->getNameAsString();
Steve Naroffa1e115e2008-03-10 23:16:54 +00002851 if (LangOpts.Microsoft)
2852 Result += "_IMPL";
Steve Naroffdc5b6b22008-03-12 00:25:36 +00002853
Fariborz Jahanianaff228df2007-10-31 17:29:28 +00002854 if (NumIvars > 0) {
Steve Naroffdde78982007-11-14 19:25:57 +00002855 const char *cursor = strchr(startBuf, '{');
Mike Stump11289f42009-09-09 15:08:12 +00002856 assert((cursor && endBuf)
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002857 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Naroffcd92aeb2008-05-31 14:15:04 +00002858 // If the buffer contains preprocessor directives, we do more fine-grained
2859 // rewrites. This is intended to fix code that looks like (which occurs in
2860 // NSURL.h, for example):
2861 //
2862 // #ifdef XYZ
2863 // @interface Foo : NSObject
2864 // #else
2865 // @interface FooBar : NSObject
2866 // #endif
2867 // {
2868 // int i;
2869 // }
2870 // @end
2871 //
2872 // This clause is segregated to avoid breaking the common case.
2873 if (BufferContainsPPDirectives(startBuf, cursor)) {
Mike Stump11289f42009-09-09 15:08:12 +00002874 SourceLocation L = RCDecl ? CDecl->getSuperClassLoc() :
Steve Naroffcd92aeb2008-05-31 14:15:04 +00002875 CDecl->getClassLoc();
2876 const char *endHeader = SM->getCharacterData(L);
Chris Lattner184e65d2009-04-14 23:22:57 +00002877 endHeader += Lexer::MeasureTokenLength(L, *SM, LangOpts);
Steve Naroffcd92aeb2008-05-31 14:15:04 +00002878
Chris Lattnerf5b77512009-02-20 18:18:36 +00002879 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroffcd92aeb2008-05-31 14:15:04 +00002880 // advance to the end of the referenced protocols.
2881 while (endHeader < cursor && *endHeader != '>') endHeader++;
2882 endHeader++;
2883 }
2884 // rewrite the original header
2885 ReplaceText(LocStart, endHeader-startBuf, Result.c_str(), Result.size());
2886 } else {
2887 // rewrite the original header *without* disturbing the '{'
Steve Naroffb0e33902009-12-04 21:36:32 +00002888 ReplaceText(LocStart, cursor-startBuf, Result.c_str(), Result.size());
Steve Naroffcd92aeb2008-05-31 14:15:04 +00002889 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002890 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Naroffdde78982007-11-14 19:25:57 +00002891 Result = "\n struct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002892 Result += RCDecl->getNameAsString();
Steve Naroff9f33bd22008-03-12 21:09:20 +00002893 Result += "_IMPL ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002894 Result += RCDecl->getNameAsString();
Steve Naroffffb5f9a2008-03-12 21:22:52 +00002895 Result += "_IVARS;\n";
Mike Stump11289f42009-09-09 15:08:12 +00002896
Steve Naroffdde78982007-11-14 19:25:57 +00002897 // insert the super class structure definition.
Chris Lattner1780a852008-01-31 19:42:41 +00002898 SourceLocation OnePastCurly =
2899 LocStart.getFileLocWithOffset(cursor-startBuf+1);
2900 InsertText(OnePastCurly, Result.c_str(), Result.size());
Steve Naroffdde78982007-11-14 19:25:57 +00002901 }
2902 cursor++; // past '{'
Mike Stump11289f42009-09-09 15:08:12 +00002903
Steve Naroffdde78982007-11-14 19:25:57 +00002904 // Now comment out any visibility specifiers.
2905 while (cursor < endBuf) {
2906 if (*cursor == '@') {
2907 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattner174a8252007-11-14 22:57:51 +00002908 // Skip whitespace.
2909 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
2910 /*scan*/;
2911
Fariborz Jahanianaff228df2007-10-31 17:29:28 +00002912 // FIXME: presence of @public, etc. inside comment results in
2913 // this transformation as well, which is still correct c-code.
Steve Naroffdde78982007-11-14 19:25:57 +00002914 if (!strncmp(cursor, "public", strlen("public")) ||
2915 !strncmp(cursor, "private", strlen("private")) ||
Steve Naroffaf91b9a2008-04-04 22:34:24 +00002916 !strncmp(cursor, "package", strlen("package")) ||
Fariborz Jahanianc6225532007-11-14 22:26:25 +00002917 !strncmp(cursor, "protected", strlen("protected")))
Chris Lattner1780a852008-01-31 19:42:41 +00002918 InsertText(atLoc, "// ", 3);
Fariborz Jahanianaff228df2007-10-31 17:29:28 +00002919 }
Fariborz Jahanianc6225532007-11-14 22:26:25 +00002920 // FIXME: If there are cases where '<' is used in ivar declaration part
2921 // of user code, then scan the ivar list and use needToScanForQualifiers
2922 // for type checking.
2923 else if (*cursor == '<') {
2924 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattner1780a852008-01-31 19:42:41 +00002925 InsertText(atLoc, "/* ", 3);
Fariborz Jahanianc6225532007-11-14 22:26:25 +00002926 cursor = strchr(cursor, '>');
2927 cursor++;
2928 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattner1780a852008-01-31 19:42:41 +00002929 InsertText(atLoc, " */", 3);
Steve Naroff295570a2008-10-30 12:09:33 +00002930 } else if (*cursor == '^') { // rewrite block specifier.
2931 SourceLocation caretLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
2932 ReplaceText(caretLoc, 1, "*", 1);
Fariborz Jahanianc6225532007-11-14 22:26:25 +00002933 }
Steve Naroffdde78982007-11-14 19:25:57 +00002934 cursor++;
Fariborz Jahanianaff228df2007-10-31 17:29:28 +00002935 }
Steve Naroffdde78982007-11-14 19:25:57 +00002936 // Don't forget to add a ';'!!
Chris Lattner1780a852008-01-31 19:42:41 +00002937 InsertText(LocEnd.getFileLocWithOffset(1), ";", 1);
Steve Naroffdde78982007-11-14 19:25:57 +00002938 } else { // we don't have any instance variables - insert super struct.
Chris Lattner184e65d2009-04-14 23:22:57 +00002939 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Steve Naroffdde78982007-11-14 19:25:57 +00002940 Result += " {\n struct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002941 Result += RCDecl->getNameAsString();
Steve Naroff9f33bd22008-03-12 21:09:20 +00002942 Result += "_IMPL ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002943 Result += RCDecl->getNameAsString();
Steve Naroffffb5f9a2008-03-12 21:22:52 +00002944 Result += "_IVARS;\n};\n";
Chris Lattner9cc55f52008-01-31 19:51:04 +00002945 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00002946 }
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00002947 // Mark this struct as having been generated.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002948 if (!ObjCSynthesizedStructs.insert(CDecl))
Steve Naroff13e74872008-05-06 18:26:51 +00002949 assert(false && "struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00002950}
2951
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002952// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00002953/// class methods.
Douglas Gregor29bd76f2009-04-23 01:02:12 +00002954template<typename MethodIterator>
2955void RewriteObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
2956 MethodIterator MethodEnd,
Fariborz Jahanian3df412a2007-10-25 00:14:44 +00002957 bool IsInstanceMethod,
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00002958 const char *prefix,
Chris Lattner211f8b82007-10-25 17:07:24 +00002959 const char *ClassName,
2960 std::string &Result) {
Chris Lattner31bc07e2007-12-12 07:46:12 +00002961 if (MethodBegin == MethodEnd) return;
Mike Stump11289f42009-09-09 15:08:12 +00002962
Chris Lattner31bc07e2007-12-12 07:46:12 +00002963 if (!objc_impl_method) {
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00002964 /* struct _objc_method {
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00002965 SEL _cmd;
2966 char *method_types;
2967 void *_imp;
2968 }
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00002969 */
Chris Lattner211f8b82007-10-25 17:07:24 +00002970 Result += "\nstruct _objc_method {\n";
2971 Result += "\tSEL _cmd;\n";
2972 Result += "\tchar *method_types;\n";
2973 Result += "\tvoid *_imp;\n";
2974 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00002975
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00002976 objc_impl_method = true;
Fariborz Jahanian74a1cfa2007-10-19 00:36:46 +00002977 }
Mike Stump11289f42009-09-09 15:08:12 +00002978
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00002979 // Build _objc_method_list for class's methods if needed
Mike Stump11289f42009-09-09 15:08:12 +00002980
Steve Naroffc5b9cc72008-03-11 00:12:29 +00002981 /* struct {
2982 struct _objc_method_list *next_method;
2983 int method_count;
2984 struct _objc_method method_list[];
2985 }
2986 */
Douglas Gregor29bd76f2009-04-23 01:02:12 +00002987 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
Steve Naroffc5b9cc72008-03-11 00:12:29 +00002988 Result += "\nstatic struct {\n";
2989 Result += "\tstruct _objc_method_list *next_method;\n";
2990 Result += "\tint method_count;\n";
2991 Result += "\tstruct _objc_method method_list[";
Douglas Gregor29bd76f2009-04-23 01:02:12 +00002992 Result += utostr(NumMethods);
Steve Naroffc5b9cc72008-03-11 00:12:29 +00002993 Result += "];\n} _OBJC_";
Chris Lattner31bc07e2007-12-12 07:46:12 +00002994 Result += prefix;
2995 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
2996 Result += "_METHODS_";
2997 Result += ClassName;
Steve Naroffb327e492008-03-12 17:18:30 +00002998 Result += " __attribute__ ((used, section (\"__OBJC, __";
Chris Lattner31bc07e2007-12-12 07:46:12 +00002999 Result += IsInstanceMethod ? "inst" : "cls";
3000 Result += "_meth\")))= ";
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003001 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003002
Chris Lattner31bc07e2007-12-12 07:46:12 +00003003 Result += "\t,{{(SEL)\"";
Chris Lattnere4b95692008-11-24 03:33:13 +00003004 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Chris Lattner31bc07e2007-12-12 07:46:12 +00003005 std::string MethodTypeString;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003006 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Chris Lattner31bc07e2007-12-12 07:46:12 +00003007 Result += "\", \"";
3008 Result += MethodTypeString;
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003009 Result += "\", (void *)";
Chris Lattner31bc07e2007-12-12 07:46:12 +00003010 Result += MethodInternalNames[*MethodBegin];
3011 Result += "}\n";
3012 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
3013 Result += "\t ,{(SEL)\"";
Chris Lattnere4b95692008-11-24 03:33:13 +00003014 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003015 std::string MethodTypeString;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003016 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003017 Result += "\", \"";
3018 Result += MethodTypeString;
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003019 Result += "\", (void *)";
Chris Lattner31bc07e2007-12-12 07:46:12 +00003020 Result += MethodInternalNames[*MethodBegin];
Fariborz Jahanian56338352007-11-13 21:02:00 +00003021 Result += "}\n";
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00003022 }
Chris Lattner31bc07e2007-12-12 07:46:12 +00003023 Result += "\t }\n};\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003024}
3025
Steve Naroffd9803712009-04-29 16:37:50 +00003026/// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
Chris Lattner390d39a2008-07-21 21:32:27 +00003027void RewriteObjC::
Steve Naroffd9803712009-04-29 16:37:50 +00003028RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl, const char *prefix,
3029 const char *ClassName, std::string &Result) {
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00003030 static bool objc_protocol_methods = false;
Steve Naroffd9803712009-04-29 16:37:50 +00003031
3032 // Output struct protocol_methods holder of method selector and type.
3033 if (!objc_protocol_methods && !PDecl->isForwardDecl()) {
3034 /* struct protocol_methods {
3035 SEL _cmd;
3036 char *method_types;
3037 }
3038 */
3039 Result += "\nstruct _protocol_methods {\n";
3040 Result += "\tstruct objc_selector *_cmd;\n";
3041 Result += "\tchar *method_types;\n";
3042 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003043
Steve Naroffd9803712009-04-29 16:37:50 +00003044 objc_protocol_methods = true;
3045 }
3046 // Do not synthesize the protocol more than once.
3047 if (ObjCSynthesizedProtocols.count(PDecl))
3048 return;
Mike Stump11289f42009-09-09 15:08:12 +00003049
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003050 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
3051 unsigned NumMethods = std::distance(PDecl->instmeth_begin(),
3052 PDecl->instmeth_end());
Steve Naroffd9803712009-04-29 16:37:50 +00003053 /* struct _objc_protocol_method_list {
3054 int protocol_method_count;
3055 struct protocol_methods protocols[];
3056 }
Steve Naroff251084d2008-03-12 01:06:30 +00003057 */
Steve Naroffd9803712009-04-29 16:37:50 +00003058 Result += "\nstatic struct {\n";
3059 Result += "\tint protocol_method_count;\n";
3060 Result += "\tstruct _protocol_methods protocol_methods[";
3061 Result += utostr(NumMethods);
3062 Result += "];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_";
3063 Result += PDecl->getNameAsString();
3064 Result += " __attribute__ ((used, section (\"__OBJC, __cat_inst_meth\")))= "
3065 "{\n\t" + utostr(NumMethods) + "\n";
Mike Stump11289f42009-09-09 15:08:12 +00003066
Steve Naroffd9803712009-04-29 16:37:50 +00003067 // Output instance methods declared in this protocol.
Mike Stump11289f42009-09-09 15:08:12 +00003068 for (ObjCProtocolDecl::instmeth_iterator
3069 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
Steve Naroffd9803712009-04-29 16:37:50 +00003070 I != E; ++I) {
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003071 if (I == PDecl->instmeth_begin())
Steve Naroffd9803712009-04-29 16:37:50 +00003072 Result += "\t ,{{(struct objc_selector *)\"";
3073 else
3074 Result += "\t ,{(struct objc_selector *)\"";
3075 Result += (*I)->getSelector().getAsString().c_str();
3076 std::string MethodTypeString;
3077 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
3078 Result += "\", \"";
3079 Result += MethodTypeString;
3080 Result += "\"}\n";
Chris Lattner388f6e92008-07-21 21:33:21 +00003081 }
Steve Naroffd9803712009-04-29 16:37:50 +00003082 Result += "\t }\n};\n";
3083 }
Mike Stump11289f42009-09-09 15:08:12 +00003084
Steve Naroffd9803712009-04-29 16:37:50 +00003085 // Output class methods declared in this protocol.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003086 unsigned NumMethods = std::distance(PDecl->classmeth_begin(),
3087 PDecl->classmeth_end());
Steve Naroffd9803712009-04-29 16:37:50 +00003088 if (NumMethods > 0) {
3089 /* struct _objc_protocol_method_list {
3090 int protocol_method_count;
3091 struct protocol_methods protocols[];
3092 }
3093 */
3094 Result += "\nstatic struct {\n";
3095 Result += "\tint protocol_method_count;\n";
3096 Result += "\tstruct _protocol_methods protocol_methods[";
3097 Result += utostr(NumMethods);
3098 Result += "];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
3099 Result += PDecl->getNameAsString();
3100 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
3101 "{\n\t";
3102 Result += utostr(NumMethods);
3103 Result += "\n";
Mike Stump11289f42009-09-09 15:08:12 +00003104
Steve Naroffd9803712009-04-29 16:37:50 +00003105 // Output instance methods declared in this protocol.
Mike Stump11289f42009-09-09 15:08:12 +00003106 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003107 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
Steve Naroffd9803712009-04-29 16:37:50 +00003108 I != E; ++I) {
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003109 if (I == PDecl->classmeth_begin())
Steve Naroffd9803712009-04-29 16:37:50 +00003110 Result += "\t ,{{(struct objc_selector *)\"";
3111 else
3112 Result += "\t ,{(struct objc_selector *)\"";
3113 Result += (*I)->getSelector().getAsString().c_str();
3114 std::string MethodTypeString;
3115 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
3116 Result += "\", \"";
3117 Result += MethodTypeString;
3118 Result += "\"}\n";
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00003119 }
Steve Naroffd9803712009-04-29 16:37:50 +00003120 Result += "\t }\n};\n";
3121 }
3122
3123 // Output:
3124 /* struct _objc_protocol {
3125 // Objective-C 1.0 extensions
3126 struct _objc_protocol_extension *isa;
3127 char *protocol_name;
3128 struct _objc_protocol **protocol_list;
3129 struct _objc_protocol_method_list *instance_methods;
3130 struct _objc_protocol_method_list *class_methods;
Mike Stump11289f42009-09-09 15:08:12 +00003131 };
Steve Naroffd9803712009-04-29 16:37:50 +00003132 */
3133 static bool objc_protocol = false;
3134 if (!objc_protocol) {
3135 Result += "\nstruct _objc_protocol {\n";
3136 Result += "\tstruct _objc_protocol_extension *isa;\n";
3137 Result += "\tchar *protocol_name;\n";
3138 Result += "\tstruct _objc_protocol **protocol_list;\n";
3139 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
3140 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
Chris Lattner388f6e92008-07-21 21:33:21 +00003141 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003142
Steve Naroffd9803712009-04-29 16:37:50 +00003143 objc_protocol = true;
Chris Lattner388f6e92008-07-21 21:33:21 +00003144 }
Mike Stump11289f42009-09-09 15:08:12 +00003145
Steve Naroffd9803712009-04-29 16:37:50 +00003146 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
3147 Result += PDecl->getNameAsString();
3148 Result += " __attribute__ ((used, section (\"__OBJC, __protocol\")))= "
3149 "{\n\t0, \"";
3150 Result += PDecl->getNameAsString();
3151 Result += "\", 0, ";
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003152 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
Steve Naroffd9803712009-04-29 16:37:50 +00003153 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
3154 Result += PDecl->getNameAsString();
3155 Result += ", ";
3156 }
3157 else
3158 Result += "0, ";
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003159 if (PDecl->classmeth_begin() != PDecl->classmeth_end()) {
Steve Naroffd9803712009-04-29 16:37:50 +00003160 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLASS_METHODS_";
3161 Result += PDecl->getNameAsString();
3162 Result += "\n";
3163 }
3164 else
3165 Result += "0\n";
3166 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003167
Steve Naroffd9803712009-04-29 16:37:50 +00003168 // Mark this protocol as having been generated.
3169 if (!ObjCSynthesizedProtocols.insert(PDecl))
3170 assert(false && "protocol already synthesized");
3171
3172}
3173
3174void RewriteObjC::
3175RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> &Protocols,
3176 const char *prefix, const char *ClassName,
3177 std::string &Result) {
3178 if (Protocols.empty()) return;
Mike Stump11289f42009-09-09 15:08:12 +00003179
Steve Naroffd9803712009-04-29 16:37:50 +00003180 for (unsigned i = 0; i != Protocols.size(); i++)
3181 RewriteObjCProtocolMetaData(Protocols[i], prefix, ClassName, Result);
3182
Chris Lattner388f6e92008-07-21 21:33:21 +00003183 // Output the top lovel protocol meta-data for the class.
3184 /* struct _objc_protocol_list {
3185 struct _objc_protocol_list *next;
3186 int protocol_count;
3187 struct _objc_protocol *class_protocols[];
3188 }
3189 */
3190 Result += "\nstatic struct {\n";
3191 Result += "\tstruct _objc_protocol_list *next;\n";
3192 Result += "\tint protocol_count;\n";
3193 Result += "\tstruct _objc_protocol *class_protocols[";
3194 Result += utostr(Protocols.size());
3195 Result += "];\n} _OBJC_";
3196 Result += prefix;
3197 Result += "_PROTOCOLS_";
3198 Result += ClassName;
3199 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
3200 "{\n\t0, ";
3201 Result += utostr(Protocols.size());
3202 Result += "\n";
Mike Stump11289f42009-09-09 15:08:12 +00003203
Chris Lattner388f6e92008-07-21 21:33:21 +00003204 Result += "\t,{&_OBJC_PROTOCOL_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003205 Result += Protocols[0]->getNameAsString();
Chris Lattner388f6e92008-07-21 21:33:21 +00003206 Result += " \n";
Mike Stump11289f42009-09-09 15:08:12 +00003207
Chris Lattner388f6e92008-07-21 21:33:21 +00003208 for (unsigned i = 1; i != Protocols.size(); i++) {
3209 Result += "\t ,&_OBJC_PROTOCOL_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003210 Result += Protocols[i]->getNameAsString();
Chris Lattner388f6e92008-07-21 21:33:21 +00003211 Result += "\n";
3212 }
3213 Result += "\t }\n};\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003214}
3215
Steve Naroffd9803712009-04-29 16:37:50 +00003216
Mike Stump11289f42009-09-09 15:08:12 +00003217/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003218/// implementation.
Steve Naroff1dc53ef2008-04-14 22:03:09 +00003219void RewriteObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003220 std::string &Result) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003221 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003222 // Find category declaration for this implementation.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003223 ObjCCategoryDecl *CDecl;
Mike Stump11289f42009-09-09 15:08:12 +00003224 for (CDecl = ClassDecl->getCategoryList(); CDecl;
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003225 CDecl = CDecl->getNextClassCategory())
3226 if (CDecl->getIdentifier() == IDecl->getIdentifier())
3227 break;
Mike Stump11289f42009-09-09 15:08:12 +00003228
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003229 std::string FullCategoryName = ClassDecl->getNameAsString();
Chris Lattnerb907c3f2007-12-23 01:40:15 +00003230 FullCategoryName += '_';
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003231 FullCategoryName += IDecl->getNameAsString();
Mike Stump11289f42009-09-09 15:08:12 +00003232
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003233 // Build _objc_method_list for class's instance methods if needed
Mike Stump11289f42009-09-09 15:08:12 +00003234 llvm::SmallVector<ObjCMethodDecl *, 32>
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003235 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003236
3237 // If any of our property implementations have associated getters or
3238 // setters, produce metadata for them as well.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003239 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
3240 PropEnd = IDecl->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003241 Prop != PropEnd; ++Prop) {
3242 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
3243 continue;
3244 if (!(*Prop)->getPropertyIvarDecl())
3245 continue;
3246 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
3247 if (!PD)
3248 continue;
3249 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
3250 InstanceMethods.push_back(Getter);
3251 if (PD->isReadOnly())
3252 continue;
3253 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
3254 InstanceMethods.push_back(Setter);
3255 }
3256 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
Chris Lattnerb907c3f2007-12-23 01:40:15 +00003257 true, "CATEGORY_", FullCategoryName.c_str(),
3258 Result);
Mike Stump11289f42009-09-09 15:08:12 +00003259
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003260 // Build _objc_method_list for class's class methods if needed
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003261 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnerb907c3f2007-12-23 01:40:15 +00003262 false, "CATEGORY_", FullCategoryName.c_str(),
3263 Result);
Mike Stump11289f42009-09-09 15:08:12 +00003264
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003265 // Protocols referenced in class declaration?
Fariborz Jahanian989e0392007-11-13 22:09:49 +00003266 // Null CDecl is case of a category implementation with no category interface
3267 if (CDecl)
Steve Naroffd9803712009-04-29 16:37:50 +00003268 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(), "CATEGORY",
3269 FullCategoryName.c_str(), Result);
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003270 /* struct _objc_category {
3271 char *category_name;
3272 char *class_name;
3273 struct _objc_method_list *instance_methods;
3274 struct _objc_method_list *class_methods;
3275 struct _objc_protocol_list *protocols;
3276 // Objective-C 1.0 extensions
3277 uint32_t size; // sizeof (struct _objc_category)
Mike Stump11289f42009-09-09 15:08:12 +00003278 struct _objc_property_list *instance_properties; // category's own
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003279 // @property decl.
Mike Stump11289f42009-09-09 15:08:12 +00003280 };
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003281 */
Mike Stump11289f42009-09-09 15:08:12 +00003282
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003283 static bool objc_category = false;
3284 if (!objc_category) {
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003285 Result += "\nstruct _objc_category {\n";
3286 Result += "\tchar *category_name;\n";
3287 Result += "\tchar *class_name;\n";
3288 Result += "\tstruct _objc_method_list *instance_methods;\n";
3289 Result += "\tstruct _objc_method_list *class_methods;\n";
3290 Result += "\tstruct _objc_protocol_list *protocols;\n";
Mike Stump11289f42009-09-09 15:08:12 +00003291 Result += "\tunsigned int size;\n";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003292 Result += "\tstruct _objc_property_list *instance_properties;\n";
3293 Result += "};\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003294 objc_category = true;
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00003295 }
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003296 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
3297 Result += FullCategoryName;
Steve Naroffb327e492008-03-12 17:18:30 +00003298 Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003299 Result += IDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003300 Result += "\"\n\t, \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003301 Result += ClassDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003302 Result += "\"\n";
Mike Stump11289f42009-09-09 15:08:12 +00003303
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003304 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003305 Result += "\t, (struct _objc_method_list *)"
3306 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
3307 Result += FullCategoryName;
3308 Result += "\n";
3309 }
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003310 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003311 Result += "\t, 0\n";
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003312 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003313 Result += "\t, (struct _objc_method_list *)"
3314 "&_OBJC_CATEGORY_CLASS_METHODS_";
3315 Result += FullCategoryName;
3316 Result += "\n";
3317 }
3318 else
3319 Result += "\t, 0\n";
Mike Stump11289f42009-09-09 15:08:12 +00003320
Chris Lattnerf5b77512009-02-20 18:18:36 +00003321 if (CDecl && CDecl->protocol_begin() != CDecl->protocol_end()) {
Mike Stump11289f42009-09-09 15:08:12 +00003322 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003323 Result += FullCategoryName;
3324 Result += "\n";
3325 }
3326 else
3327 Result += "\t, 0\n";
3328 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003329}
3330
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003331/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
3332/// ivar offset.
Mike Stump11289f42009-09-09 15:08:12 +00003333void RewriteObjC::SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
3334 ObjCIvarDecl *ivar,
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003335 std::string &Result) {
Steve Naroffde7d0f62008-07-16 18:22:22 +00003336 if (ivar->isBitField()) {
3337 // FIXME: The hack below doesn't work for bitfields. For now, we simply
3338 // place all bitfields at offset 0.
3339 Result += "0";
3340 } else {
3341 Result += "__OFFSETOFIVAR__(struct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003342 Result += IDecl->getNameAsString();
Steve Naroffde7d0f62008-07-16 18:22:22 +00003343 if (LangOpts.Microsoft)
3344 Result += "_IMPL";
3345 Result += ", ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003346 Result += ivar->getNameAsString();
Steve Naroffde7d0f62008-07-16 18:22:22 +00003347 Result += ")";
3348 }
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003349}
3350
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003351//===----------------------------------------------------------------------===//
3352// Meta Data Emission
3353//===----------------------------------------------------------------------===//
3354
Steve Naroff1dc53ef2008-04-14 22:03:09 +00003355void RewriteObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003356 std::string &Result) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003357 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
Mike Stump11289f42009-09-09 15:08:12 +00003358
Fariborz Jahanian96502af2007-11-26 20:59:57 +00003359 // Explictly declared @interface's are already synthesized.
Steve Naroffaac654a2009-04-20 20:09:33 +00003360 if (CDecl->isImplicitInterfaceDecl()) {
Mike Stump11289f42009-09-09 15:08:12 +00003361 // FIXME: Implementation of a class with no @interface (legacy) doese not
Fariborz Jahanian96502af2007-11-26 20:59:57 +00003362 // produce correct synthesis as yet.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003363 SynthesizeObjCInternalStruct(CDecl, Result);
Fariborz Jahanian96502af2007-11-26 20:59:57 +00003364 }
Mike Stump11289f42009-09-09 15:08:12 +00003365
Chris Lattner30d23e82007-12-12 07:56:42 +00003366 // Build _objc_ivar_list metadata for classes ivars if needed
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003367 unsigned NumIvars = !IDecl->ivar_empty()
Mike Stump11289f42009-09-09 15:08:12 +00003368 ? IDecl->ivar_size()
Chris Lattner8d1c04f2008-03-16 21:08:55 +00003369 : (CDecl ? CDecl->ivar_size() : 0);
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003370 if (NumIvars > 0) {
3371 static bool objc_ivar = false;
3372 if (!objc_ivar) {
3373 /* struct _objc_ivar {
3374 char *ivar_name;
3375 char *ivar_type;
3376 int ivar_offset;
Mike Stump11289f42009-09-09 15:08:12 +00003377 };
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003378 */
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003379 Result += "\nstruct _objc_ivar {\n";
3380 Result += "\tchar *ivar_name;\n";
3381 Result += "\tchar *ivar_type;\n";
3382 Result += "\tint ivar_offset;\n";
3383 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003384
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003385 objc_ivar = true;
3386 }
3387
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003388 /* struct {
3389 int ivar_count;
3390 struct _objc_ivar ivar_list[nIvars];
Mike Stump11289f42009-09-09 15:08:12 +00003391 };
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003392 */
Mike Stump11289f42009-09-09 15:08:12 +00003393 Result += "\nstatic struct {\n";
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003394 Result += "\tint ivar_count;\n";
3395 Result += "\tstruct _objc_ivar ivar_list[";
3396 Result += utostr(NumIvars);
3397 Result += "];\n} _OBJC_INSTANCE_VARIABLES_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003398 Result += IDecl->getNameAsString();
Steve Naroffb327e492008-03-12 17:18:30 +00003399 Result += " __attribute__ ((used, section (\"__OBJC, __instance_vars\")))= "
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003400 "{\n\t";
3401 Result += utostr(NumIvars);
3402 Result += "\n";
Mike Stump11289f42009-09-09 15:08:12 +00003403
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003404 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
Douglas Gregor5f662052009-04-23 03:23:08 +00003405 llvm::SmallVector<ObjCIvarDecl *, 8> IVars;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003406 if (!IDecl->ivar_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00003407 for (ObjCImplementationDecl::ivar_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003408 IV = IDecl->ivar_begin(), IVEnd = IDecl->ivar_end();
Douglas Gregor5f662052009-04-23 03:23:08 +00003409 IV != IVEnd; ++IV)
3410 IVars.push_back(*IV);
3411 IVI = IVars.begin();
3412 IVE = IVars.end();
Chris Lattner30d23e82007-12-12 07:56:42 +00003413 } else {
3414 IVI = CDecl->ivar_begin();
3415 IVE = CDecl->ivar_end();
3416 }
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003417 Result += "\t,{{\"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003418 Result += (*IVI)->getNameAsString();
Fariborz Jahanianbc275932007-10-29 17:16:25 +00003419 Result += "\", \"";
Steve Naroffd9803712009-04-29 16:37:50 +00003420 std::string TmpString, StrEncoding;
3421 Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
3422 QuoteDoublequotes(TmpString, StrEncoding);
Fariborz Jahanianbc275932007-10-29 17:16:25 +00003423 Result += StrEncoding;
3424 Result += "\", ";
Chris Lattner30d23e82007-12-12 07:56:42 +00003425 SynthesizeIvarOffsetComputation(IDecl, *IVI, Result);
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003426 Result += "}\n";
Chris Lattner30d23e82007-12-12 07:56:42 +00003427 for (++IVI; IVI != IVE; ++IVI) {
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003428 Result += "\t ,{\"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003429 Result += (*IVI)->getNameAsString();
Fariborz Jahanianbc275932007-10-29 17:16:25 +00003430 Result += "\", \"";
Steve Naroffd9803712009-04-29 16:37:50 +00003431 std::string TmpString, StrEncoding;
3432 Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
3433 QuoteDoublequotes(TmpString, StrEncoding);
Fariborz Jahanianbc275932007-10-29 17:16:25 +00003434 Result += StrEncoding;
3435 Result += "\", ";
Chris Lattner30d23e82007-12-12 07:56:42 +00003436 SynthesizeIvarOffsetComputation(IDecl, (*IVI), Result);
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003437 Result += "}\n";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003438 }
Mike Stump11289f42009-09-09 15:08:12 +00003439
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003440 Result += "\t }\n};\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003441 }
Mike Stump11289f42009-09-09 15:08:12 +00003442
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003443 // Build _objc_method_list for class's instance methods if needed
Mike Stump11289f42009-09-09 15:08:12 +00003444 llvm::SmallVector<ObjCMethodDecl *, 32>
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003445 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003446
3447 // If any of our property implementations have associated getters or
3448 // setters, produce metadata for them as well.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003449 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
3450 PropEnd = IDecl->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003451 Prop != PropEnd; ++Prop) {
3452 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
3453 continue;
3454 if (!(*Prop)->getPropertyIvarDecl())
3455 continue;
3456 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
3457 if (!PD)
3458 continue;
3459 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
3460 InstanceMethods.push_back(Getter);
3461 if (PD->isReadOnly())
3462 continue;
3463 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
3464 InstanceMethods.push_back(Setter);
3465 }
3466 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
Chris Lattner86d7d912008-11-24 03:54:41 +00003467 true, "", IDecl->getNameAsCString(), Result);
Mike Stump11289f42009-09-09 15:08:12 +00003468
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003469 // Build _objc_method_list for class's class methods if needed
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003470 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattner86d7d912008-11-24 03:54:41 +00003471 false, "", IDecl->getNameAsCString(), Result);
Mike Stump11289f42009-09-09 15:08:12 +00003472
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003473 // Protocols referenced in class declaration?
Steve Naroffd9803712009-04-29 16:37:50 +00003474 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(),
3475 "CLASS", CDecl->getNameAsCString(), Result);
Mike Stump11289f42009-09-09 15:08:12 +00003476
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003477 // Declaration of class/meta-class metadata
3478 /* struct _objc_class {
3479 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003480 const char *super_class_name;
3481 char *name;
3482 long version;
3483 long info;
3484 long instance_size;
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003485 struct _objc_ivar_list *ivars;
3486 struct _objc_method_list *methods;
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003487 struct objc_cache *cache;
3488 struct objc_protocol_list *protocols;
3489 const char *ivar_layout;
3490 struct _objc_class_ext *ext;
Mike Stump11289f42009-09-09 15:08:12 +00003491 };
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003492 */
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003493 static bool objc_class = false;
3494 if (!objc_class) {
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003495 Result += "\nstruct _objc_class {\n";
3496 Result += "\tstruct _objc_class *isa;\n";
3497 Result += "\tconst char *super_class_name;\n";
3498 Result += "\tchar *name;\n";
3499 Result += "\tlong version;\n";
3500 Result += "\tlong info;\n";
3501 Result += "\tlong instance_size;\n";
3502 Result += "\tstruct _objc_ivar_list *ivars;\n";
3503 Result += "\tstruct _objc_method_list *methods;\n";
3504 Result += "\tstruct objc_cache *cache;\n";
3505 Result += "\tstruct _objc_protocol_list *protocols;\n";
3506 Result += "\tconst char *ivar_layout;\n";
3507 Result += "\tstruct _objc_class_ext *ext;\n";
3508 Result += "};\n";
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003509 objc_class = true;
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003510 }
Mike Stump11289f42009-09-09 15:08:12 +00003511
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003512 // Meta-class metadata generation.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003513 ObjCInterfaceDecl *RootClass = 0;
3514 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003515 while (SuperClass) {
3516 RootClass = SuperClass;
3517 SuperClass = SuperClass->getSuperClass();
3518 }
3519 SuperClass = CDecl->getSuperClass();
Mike Stump11289f42009-09-09 15:08:12 +00003520
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003521 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003522 Result += CDecl->getNameAsString();
Steve Naroffb327e492008-03-12 17:18:30 +00003523 Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= "
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003524 "{\n\t(struct _objc_class *)\"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003525 Result += (RootClass ? RootClass->getNameAsString() : CDecl->getNameAsString());
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003526 Result += "\"";
3527
3528 if (SuperClass) {
3529 Result += ", \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003530 Result += SuperClass->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003531 Result += "\", \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003532 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003533 Result += "\"";
3534 }
3535 else {
3536 Result += ", 0, \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003537 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003538 Result += "\"";
3539 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003540 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003541 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003542 Result += ", 0,2, sizeof(struct _objc_class), 0";
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003543 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
Steve Naroff0b844f02008-03-11 18:14:26 +00003544 Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003545 Result += IDecl->getNameAsString();
Mike Stump11289f42009-09-09 15:08:12 +00003546 Result += "\n";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003547 }
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003548 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003549 Result += ", 0\n";
Chris Lattnerf5b77512009-02-20 18:18:36 +00003550 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroff251084d2008-03-12 01:06:30 +00003551 Result += "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003552 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003553 Result += ",0,0\n";
3554 }
Fariborz Jahanian486f7182007-10-24 20:54:23 +00003555 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003556 Result += "\t,0,0,0,0\n";
3557 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003558
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003559 // class metadata generation.
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003560 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003561 Result += CDecl->getNameAsString();
Steve Naroffb327e492008-03-12 17:18:30 +00003562 Result += " __attribute__ ((used, section (\"__OBJC, __class\")))= "
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003563 "{\n\t&_OBJC_METACLASS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003564 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003565 if (SuperClass) {
3566 Result += ", \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003567 Result += SuperClass->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003568 Result += "\", \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003569 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003570 Result += "\"";
3571 }
3572 else {
3573 Result += ", 0, \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003574 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003575 Result += "\"";
3576 }
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003577 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanian801b6352007-10-26 23:09:28 +00003578 Result += ", 0,1";
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003579 if (!ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian801b6352007-10-26 23:09:28 +00003580 Result += ",0";
3581 else {
3582 // class has size. Must synthesize its size.
Fariborz Jahanian63ac80e2007-11-05 17:47:33 +00003583 Result += ",sizeof(struct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003584 Result += CDecl->getNameAsString();
Steve Naroff14a07462008-03-10 23:33:22 +00003585 if (LangOpts.Microsoft)
3586 Result += "_IMPL";
Fariborz Jahanian801b6352007-10-26 23:09:28 +00003587 Result += ")";
3588 }
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003589 if (NumIvars > 0) {
Steve Naroff17978c42008-03-11 17:37:02 +00003590 Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003591 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003592 Result += "\n\t";
3593 }
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003594 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003595 Result += ",0";
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003596 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003597 Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003598 Result += CDecl->getNameAsString();
Mike Stump11289f42009-09-09 15:08:12 +00003599 Result += ", 0\n\t";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003600 }
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003601 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003602 Result += ",0,0";
Chris Lattnerf5b77512009-02-20 18:18:36 +00003603 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroff251084d2008-03-12 01:06:30 +00003604 Result += ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003605 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003606 Result += ", 0,0\n";
3607 }
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003608 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003609 Result += ",0,0,0\n";
3610 Result += "};\n";
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003611}
Fariborz Jahanianc34409c2007-10-18 22:09:03 +00003612
Fariborz Jahanian98ba6cd2007-11-13 19:21:13 +00003613/// RewriteImplementations - This routine rewrites all method implementations
3614/// and emits meta-data.
3615
Steve Narofff8cfd162008-11-13 20:07:04 +00003616void RewriteObjC::RewriteImplementations() {
Fariborz Jahanian93191af2007-10-18 19:23:00 +00003617 int ClsDefCount = ClassImplementation.size();
3618 int CatDefCount = CategoryImplementation.size();
Mike Stump11289f42009-09-09 15:08:12 +00003619
Fariborz Jahanian98ba6cd2007-11-13 19:21:13 +00003620 // Rewrite implemented methods
3621 for (int i = 0; i < ClsDefCount; i++)
3622 RewriteImplementationDecl(ClassImplementation[i]);
Mike Stump11289f42009-09-09 15:08:12 +00003623
Fariborz Jahanianc54d8462007-11-13 20:04:28 +00003624 for (int i = 0; i < CatDefCount; i++)
3625 RewriteImplementationDecl(CategoryImplementation[i]);
Steve Narofff8cfd162008-11-13 20:07:04 +00003626}
Mike Stump11289f42009-09-09 15:08:12 +00003627
Steve Narofff8cfd162008-11-13 20:07:04 +00003628void RewriteObjC::SynthesizeMetaDataIntoBuffer(std::string &Result) {
3629 int ClsDefCount = ClassImplementation.size();
3630 int CatDefCount = CategoryImplementation.size();
3631
Steve Naroff30ac2222008-05-07 21:23:49 +00003632 // This is needed for determining instance variable offsets.
Fariborz Jahanian9ab63492010-01-07 18:31:42 +00003633 Result += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long) &((TYPE *)0)->MEMBER)\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003634 // For each implemented class, write out all its meta data.
Fariborz Jahanianc34409c2007-10-18 22:09:03 +00003635 for (int i = 0; i < ClsDefCount; i++)
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003636 RewriteObjCClassMetaData(ClassImplementation[i], Result);
Mike Stump11289f42009-09-09 15:08:12 +00003637
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003638 // For each implemented category, write out all its meta data.
3639 for (int i = 0; i < CatDefCount; i++)
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003640 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
Steve Naroffd9803712009-04-29 16:37:50 +00003641
Fariborz Jahanian93191af2007-10-18 19:23:00 +00003642 // Write objc_symtab metadata
3643 /*
3644 struct _objc_symtab
3645 {
3646 long sel_ref_cnt;
3647 SEL *refs;
3648 short cls_def_cnt;
3649 short cat_def_cnt;
3650 void *defs[cls_def_cnt + cat_def_cnt];
Mike Stump11289f42009-09-09 15:08:12 +00003651 };
Fariborz Jahanian93191af2007-10-18 19:23:00 +00003652 */
Mike Stump11289f42009-09-09 15:08:12 +00003653
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003654 Result += "\nstruct _objc_symtab {\n";
3655 Result += "\tlong sel_ref_cnt;\n";
3656 Result += "\tSEL *refs;\n";
3657 Result += "\tshort cls_def_cnt;\n";
3658 Result += "\tshort cat_def_cnt;\n";
3659 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
3660 Result += "};\n\n";
Mike Stump11289f42009-09-09 15:08:12 +00003661
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003662 Result += "static struct _objc_symtab "
Steve Naroffb327e492008-03-12 17:18:30 +00003663 "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
Mike Stump11289f42009-09-09 15:08:12 +00003664 Result += "\t0, 0, " + utostr(ClsDefCount)
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003665 + ", " + utostr(CatDefCount) + "\n";
3666 for (int i = 0; i < ClsDefCount; i++) {
3667 Result += "\t,&_OBJC_CLASS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003668 Result += ClassImplementation[i]->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003669 Result += "\n";
3670 }
Mike Stump11289f42009-09-09 15:08:12 +00003671
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003672 for (int i = 0; i < CatDefCount; i++) {
3673 Result += "\t,&_OBJC_CATEGORY_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003674 Result += CategoryImplementation[i]->getClassInterface()->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003675 Result += "_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003676 Result += CategoryImplementation[i]->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003677 Result += "\n";
3678 }
Mike Stump11289f42009-09-09 15:08:12 +00003679
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003680 Result += "};\n\n";
Mike Stump11289f42009-09-09 15:08:12 +00003681
Fariborz Jahanian93191af2007-10-18 19:23:00 +00003682 // Write objc_module metadata
Mike Stump11289f42009-09-09 15:08:12 +00003683
Fariborz Jahanian93191af2007-10-18 19:23:00 +00003684 /*
3685 struct _objc_module {
3686 long version;
3687 long size;
3688 const char *name;
3689 struct _objc_symtab *symtab;
3690 }
3691 */
Mike Stump11289f42009-09-09 15:08:12 +00003692
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003693 Result += "\nstruct _objc_module {\n";
3694 Result += "\tlong version;\n";
3695 Result += "\tlong size;\n";
3696 Result += "\tconst char *name;\n";
3697 Result += "\tstruct _objc_symtab *symtab;\n";
3698 Result += "};\n\n";
3699 Result += "static struct _objc_module "
Steve Naroffb327e492008-03-12 17:18:30 +00003700 "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
Mike Stump11289f42009-09-09 15:08:12 +00003701 Result += "\t" + utostr(OBJC_ABI_VERSION) +
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003702 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003703 Result += "};\n\n";
Steve Naroff945a3b12008-03-10 20:43:59 +00003704
3705 if (LangOpts.Microsoft) {
Steve Naroffd9803712009-04-29 16:37:50 +00003706 if (ProtocolExprDecls.size()) {
3707 Result += "#pragma section(\".objc_protocol$B\",long,read,write)\n";
3708 Result += "#pragma data_seg(push, \".objc_protocol$B\")\n";
Mike Stump11289f42009-09-09 15:08:12 +00003709 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Steve Naroffd9803712009-04-29 16:37:50 +00003710 E = ProtocolExprDecls.end(); I != E; ++I) {
3711 Result += "static struct _objc_protocol *_POINTER_OBJC_PROTOCOL_";
3712 Result += (*I)->getNameAsString();
3713 Result += " = &_OBJC_PROTOCOL_";
3714 Result += (*I)->getNameAsString();
3715 Result += ";\n";
3716 }
3717 Result += "#pragma data_seg(pop)\n\n";
3718 }
Steve Naroff945a3b12008-03-10 20:43:59 +00003719 Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
Steve Naroffcab93d52008-05-07 00:06:16 +00003720 Result += "#pragma data_seg(push, \".objc_module_info$B\")\n";
Steve Naroff945a3b12008-03-10 20:43:59 +00003721 Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
3722 Result += "&_OBJC_MODULES;\n";
3723 Result += "#pragma data_seg(pop)\n\n";
3724 }
Fariborz Jahanian93191af2007-10-18 19:23:00 +00003725}
Chris Lattnera7c19fe2007-10-16 22:36:42 +00003726
Steve Naroff677ab3a2008-10-27 17:20:55 +00003727std::string RewriteObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
3728 const char *funcName,
3729 std::string Tag) {
3730 const FunctionType *AFT = CE->getFunctionType();
3731 QualType RT = AFT->getResultType();
3732 std::string StructRef = "struct " + Tag;
3733 std::string S = "static " + RT.getAsString() + " __" +
3734 funcName + "_" + "block_func_" + utostr(i);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00003735
Steve Naroff677ab3a2008-10-27 17:20:55 +00003736 BlockDecl *BD = CE->getBlockDecl();
Mike Stump11289f42009-09-09 15:08:12 +00003737
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003738 if (isa<FunctionNoProtoType>(AFT)) {
Mike Stump11289f42009-09-09 15:08:12 +00003739 // No user-supplied arguments. Still need to pass in a pointer to the
Steve Narofff26a1d42009-02-02 17:19:26 +00003740 // block (to reference imported block decl refs).
3741 S += "(" + StructRef + " *__cself)";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003742 } else if (BD->param_empty()) {
3743 S += "(" + StructRef + " *__cself)";
3744 } else {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003745 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
Steve Naroff677ab3a2008-10-27 17:20:55 +00003746 assert(FT && "SynthesizeBlockFunc: No function proto");
3747 S += '(';
3748 // first add the implicit argument.
3749 S += StructRef + " *__cself, ";
3750 std::string ParamStr;
3751 for (BlockDecl::param_iterator AI = BD->param_begin(),
3752 E = BD->param_end(); AI != E; ++AI) {
3753 if (AI != BD->param_begin()) S += ", ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003754 ParamStr = (*AI)->getNameAsString();
Douglas Gregor7de59662009-05-29 20:38:28 +00003755 (*AI)->getType().getAsStringInternal(ParamStr, Context->PrintingPolicy);
Steve Naroff677ab3a2008-10-27 17:20:55 +00003756 S += ParamStr;
3757 }
3758 if (FT->isVariadic()) {
3759 if (!BD->param_empty()) S += ", ";
3760 S += "...";
3761 }
3762 S += ')';
3763 }
3764 S += " {\n";
Mike Stump11289f42009-09-09 15:08:12 +00003765
Steve Naroff677ab3a2008-10-27 17:20:55 +00003766 // Create local declarations to avoid rewriting all closure decl ref exprs.
3767 // First, emit a declaration for all "by ref" decls.
Mike Stump11289f42009-09-09 15:08:12 +00003768 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003769 E = BlockByRefDecls.end(); I != E; ++I) {
3770 S += " ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003771 std::string Name = (*I)->getNameAsString();
Fariborz Jahanian02e07732009-12-23 02:07:37 +00003772 std::string TypeString = "struct __Block_byref_" + Name + " *";
3773 Name = TypeString + Name;
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003774 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
Mike Stump11289f42009-09-09 15:08:12 +00003775 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00003776 // Next, emit a declaration for all "by copy" declarations.
Mike Stump11289f42009-09-09 15:08:12 +00003777 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003778 E = BlockByCopyDecls.end(); I != E; ++I) {
3779 S += " ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003780 std::string Name = (*I)->getNameAsString();
Steve Naroff677ab3a2008-10-27 17:20:55 +00003781 // Handle nested closure invocation. For example:
3782 //
3783 // void (^myImportedClosure)(void);
3784 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
Mike Stump11289f42009-09-09 15:08:12 +00003785 //
Steve Naroff677ab3a2008-10-27 17:20:55 +00003786 // void (^anotherClosure)(void);
3787 // anotherClosure = ^(void) {
3788 // myImportedClosure(); // import and invoke the closure
3789 // };
3790 //
Steve Naroffa5c0db82008-12-11 21:05:33 +00003791 if (isTopLevelBlockPointerType((*I)->getType()))
Steve Naroff677ab3a2008-10-27 17:20:55 +00003792 S += "struct __block_impl *";
3793 else
Douglas Gregor7de59662009-05-29 20:38:28 +00003794 (*I)->getType().getAsStringInternal(Name, Context->PrintingPolicy);
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003795 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003796 }
3797 std::string RewrittenStr = RewrittenBlockExprs[CE];
3798 const char *cstr = RewrittenStr.c_str();
3799 while (*cstr++ != '{') ;
3800 S += cstr;
3801 S += "\n";
3802 return S;
3803}
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00003804
Steve Naroff677ab3a2008-10-27 17:20:55 +00003805std::string RewriteObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
3806 const char *funcName,
3807 std::string Tag) {
3808 std::string StructRef = "struct " + Tag;
3809 std::string S = "static void __";
Mike Stump11289f42009-09-09 15:08:12 +00003810
Steve Naroff677ab3a2008-10-27 17:20:55 +00003811 S += funcName;
3812 S += "_block_copy_" + utostr(i);
3813 S += "(" + StructRef;
3814 S += "*dst, " + StructRef;
3815 S += "*src) {";
Mike Stump11289f42009-09-09 15:08:12 +00003816 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003817 E = ImportedBlockDecls.end(); I != E; ++I) {
Steve Naroff61d879e2008-12-16 15:50:30 +00003818 S += "_Block_object_assign((void*)&dst->";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003819 S += (*I)->getNameAsString();
Steve Naroff5ac4eac2008-12-11 20:51:38 +00003820 S += ", (void*)src->";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003821 S += (*I)->getNameAsString();
Fariborz Jahaniancbdcfe82009-12-23 20:32:38 +00003822 if (BlockByRefDecls.count((*I)))
Fariborz Jahanian4bf727d2009-12-23 21:18:41 +00003823 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
Fariborz Jahaniancbdcfe82009-12-23 20:32:38 +00003824 else
Fariborz Jahanian4bf727d2009-12-23 21:18:41 +00003825 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003826 }
Fariborz Jahaniancbdcfe82009-12-23 20:32:38 +00003827 S += "}\n";
3828
Steve Naroff677ab3a2008-10-27 17:20:55 +00003829 S += "\nstatic void __";
3830 S += funcName;
3831 S += "_block_dispose_" + utostr(i);
3832 S += "(" + StructRef;
3833 S += "*src) {";
Mike Stump11289f42009-09-09 15:08:12 +00003834 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003835 E = ImportedBlockDecls.end(); I != E; ++I) {
Steve Naroff61d879e2008-12-16 15:50:30 +00003836 S += "_Block_object_dispose((void*)src->";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003837 S += (*I)->getNameAsString();
Fariborz Jahaniancbdcfe82009-12-23 20:32:38 +00003838 if (BlockByRefDecls.count((*I)))
Fariborz Jahanian4bf727d2009-12-23 21:18:41 +00003839 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
Fariborz Jahaniancbdcfe82009-12-23 20:32:38 +00003840 else
Fariborz Jahanian4bf727d2009-12-23 21:18:41 +00003841 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003842 }
Mike Stump11289f42009-09-09 15:08:12 +00003843 S += "}\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003844 return S;
3845}
3846
Steve Naroff30484702009-12-06 21:14:13 +00003847std::string RewriteObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
3848 std::string Desc) {
Steve Naroff295570a2008-10-30 12:09:33 +00003849 std::string S = "\nstruct " + Tag;
Steve Naroff677ab3a2008-10-27 17:20:55 +00003850 std::string Constructor = " " + Tag;
Mike Stump11289f42009-09-09 15:08:12 +00003851
Steve Naroff677ab3a2008-10-27 17:20:55 +00003852 S += " {\n struct __block_impl impl;\n";
Steve Naroff30484702009-12-06 21:14:13 +00003853 S += " struct " + Desc;
3854 S += "* Desc;\n";
Mike Stump11289f42009-09-09 15:08:12 +00003855
Steve Naroff30484702009-12-06 21:14:13 +00003856 Constructor += "(void *fp, "; // Invoke function pointer.
3857 Constructor += "struct " + Desc; // Descriptor pointer.
3858 Constructor += " *desc";
Mike Stump11289f42009-09-09 15:08:12 +00003859
Steve Naroff677ab3a2008-10-27 17:20:55 +00003860 if (BlockDeclRefs.size()) {
3861 // Output all "by copy" declarations.
Mike Stump11289f42009-09-09 15:08:12 +00003862 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003863 E = BlockByCopyDecls.end(); I != E; ++I) {
3864 S += " ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003865 std::string FieldName = (*I)->getNameAsString();
Steve Naroff677ab3a2008-10-27 17:20:55 +00003866 std::string ArgName = "_" + FieldName;
3867 // Handle nested closure invocation. For example:
3868 //
3869 // void (^myImportedBlock)(void);
3870 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
Mike Stump11289f42009-09-09 15:08:12 +00003871 //
Steve Naroff677ab3a2008-10-27 17:20:55 +00003872 // void (^anotherBlock)(void);
3873 // anotherBlock = ^(void) {
3874 // myImportedBlock(); // import and invoke the closure
3875 // };
3876 //
Steve Naroffa5c0db82008-12-11 21:05:33 +00003877 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00003878 S += "struct __block_impl *";
3879 Constructor += ", void *" + ArgName;
3880 } else {
Douglas Gregor7de59662009-05-29 20:38:28 +00003881 (*I)->getType().getAsStringInternal(FieldName, Context->PrintingPolicy);
3882 (*I)->getType().getAsStringInternal(ArgName, Context->PrintingPolicy);
Steve Naroff677ab3a2008-10-27 17:20:55 +00003883 Constructor += ", " + ArgName;
3884 }
3885 S += FieldName + ";\n";
3886 }
3887 // Output all "by ref" declarations.
Mike Stump11289f42009-09-09 15:08:12 +00003888 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003889 E = BlockByRefDecls.end(); I != E; ++I) {
3890 S += " ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003891 std::string FieldName = (*I)->getNameAsString();
Steve Naroff677ab3a2008-10-27 17:20:55 +00003892 std::string ArgName = "_" + FieldName;
3893 // Handle nested closure invocation. For example:
3894 //
3895 // void (^myImportedBlock)(void);
3896 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
Mike Stump11289f42009-09-09 15:08:12 +00003897 //
Steve Naroff677ab3a2008-10-27 17:20:55 +00003898 // void (^anotherBlock)(void);
3899 // anotherBlock = ^(void) {
3900 // myImportedBlock(); // import and invoke the closure
3901 // };
3902 //
Steve Naroffa5c0db82008-12-11 21:05:33 +00003903 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00003904 S += "struct __block_impl *";
3905 Constructor += ", void *" + ArgName;
3906 } else {
Fariborz Jahanian02e07732009-12-23 02:07:37 +00003907 std::string TypeString = "struct __Block_byref_" + FieldName;
3908 TypeString += " *";
3909 FieldName = TypeString + FieldName;
3910 ArgName = TypeString + ArgName;
Steve Naroff677ab3a2008-10-27 17:20:55 +00003911 Constructor += ", " + ArgName;
3912 }
3913 S += FieldName + "; // by ref\n";
3914 }
3915 // Finish writing the constructor.
Steve Naroff677ab3a2008-10-27 17:20:55 +00003916 Constructor += ", int flags=0) {\n";
Steve Naroffd9803712009-04-29 16:37:50 +00003917 if (GlobalVarDecl)
3918 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
3919 else
3920 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Steve Naroff30484702009-12-06 21:14:13 +00003921 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
Mike Stump11289f42009-09-09 15:08:12 +00003922
Steve Naroff30484702009-12-06 21:14:13 +00003923 Constructor += " Desc = desc;\n";
Mike Stump11289f42009-09-09 15:08:12 +00003924
Steve Naroff677ab3a2008-10-27 17:20:55 +00003925 // Initialize all "by copy" arguments.
Mike Stump11289f42009-09-09 15:08:12 +00003926 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003927 E = BlockByCopyDecls.end(); I != E; ++I) {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003928 std::string Name = (*I)->getNameAsString();
Steve Naroff677ab3a2008-10-27 17:20:55 +00003929 Constructor += " ";
Steve Naroffa5c0db82008-12-11 21:05:33 +00003930 if (isTopLevelBlockPointerType((*I)->getType()))
Steve Naroff677ab3a2008-10-27 17:20:55 +00003931 Constructor += Name + " = (struct __block_impl *)_";
3932 else
3933 Constructor += Name + " = _";
3934 Constructor += Name + ";\n";
3935 }
3936 // Initialize all "by ref" arguments.
Mike Stump11289f42009-09-09 15:08:12 +00003937 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003938 E = BlockByRefDecls.end(); I != E; ++I) {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003939 std::string Name = (*I)->getNameAsString();
Steve Naroff677ab3a2008-10-27 17:20:55 +00003940 Constructor += " ";
Steve Naroffa5c0db82008-12-11 21:05:33 +00003941 if (isTopLevelBlockPointerType((*I)->getType()))
Steve Naroff677ab3a2008-10-27 17:20:55 +00003942 Constructor += Name + " = (struct __block_impl *)_";
3943 else
3944 Constructor += Name + " = _";
Fariborz Jahanian02e07732009-12-23 02:07:37 +00003945 Constructor += Name + "->__forwarding;\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003946 }
3947 } else {
3948 // Finish writing the constructor.
Steve Naroff677ab3a2008-10-27 17:20:55 +00003949 Constructor += ", int flags=0) {\n";
Steve Naroffd9803712009-04-29 16:37:50 +00003950 if (GlobalVarDecl)
3951 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
3952 else
3953 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Steve Naroff30484702009-12-06 21:14:13 +00003954 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3955 Constructor += " Desc = desc;\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003956 }
3957 Constructor += " ";
3958 Constructor += "}\n";
3959 S += Constructor;
3960 S += "};\n";
3961 return S;
3962}
3963
Steve Naroff30484702009-12-06 21:14:13 +00003964std::string RewriteObjC::SynthesizeBlockDescriptor(std::string DescTag,
3965 std::string ImplTag, int i,
3966 const char *FunName,
3967 unsigned hasCopy) {
3968 std::string S = "\nstatic struct " + DescTag;
3969
3970 S += " {\n unsigned long reserved;\n";
3971 S += " unsigned long Block_size;\n";
3972 if (hasCopy) {
Fariborz Jahaniane175eeb2009-12-21 23:31:42 +00003973 S += " void (*copy)(struct ";
3974 S += ImplTag; S += "*, struct ";
3975 S += ImplTag; S += "*);\n";
3976
3977 S += " void (*dispose)(struct ";
3978 S += ImplTag; S += "*);\n";
Steve Naroff30484702009-12-06 21:14:13 +00003979 }
3980 S += "} ";
3981
3982 S += DescTag + "_DATA = { 0, sizeof(struct ";
3983 S += ImplTag + ")";
3984 if (hasCopy) {
3985 S += ", __" + std::string(FunName) + "_block_copy_" + utostr(i);
3986 S += ", __" + std::string(FunName) + "_block_dispose_" + utostr(i);
3987 }
3988 S += "};\n";
3989 return S;
3990}
3991
Steve Naroff677ab3a2008-10-27 17:20:55 +00003992void RewriteObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
3993 const char *FunName) {
3994 // Insert closures that were part of the function.
3995 for (unsigned i = 0; i < Blocks.size(); i++) {
3996
3997 CollectBlockDeclRefInfo(Blocks[i]);
3998
Steve Naroff30484702009-12-06 21:14:13 +00003999 std::string ImplTag = "__" + std::string(FunName) + "_block_impl_" + utostr(i);
4000 std::string DescTag = "__" + std::string(FunName) + "_block_desc_" + utostr(i);
Mike Stump11289f42009-09-09 15:08:12 +00004001
Steve Naroff30484702009-12-06 21:14:13 +00004002 std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004003
4004 InsertText(FunLocStart, CI.c_str(), CI.size());
4005
Steve Naroff30484702009-12-06 21:14:13 +00004006 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
Mike Stump11289f42009-09-09 15:08:12 +00004007
Steve Naroff677ab3a2008-10-27 17:20:55 +00004008 InsertText(FunLocStart, CF.c_str(), CF.size());
4009
4010 if (ImportedBlockDecls.size()) {
Steve Naroff30484702009-12-06 21:14:13 +00004011 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004012 InsertText(FunLocStart, HF.c_str(), HF.size());
4013 }
Steve Naroff30484702009-12-06 21:14:13 +00004014 std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
4015 ImportedBlockDecls.size() > 0);
4016 InsertText(FunLocStart, BD.c_str(), BD.size());
Mike Stump11289f42009-09-09 15:08:12 +00004017
Steve Naroff677ab3a2008-10-27 17:20:55 +00004018 BlockDeclRefs.clear();
4019 BlockByRefDecls.clear();
4020 BlockByCopyDecls.clear();
4021 BlockCallExprs.clear();
4022 ImportedBlockDecls.clear();
4023 }
4024 Blocks.clear();
4025 RewrittenBlockExprs.clear();
4026}
4027
4028void RewriteObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
4029 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
Chris Lattner86d7d912008-11-24 03:54:41 +00004030 const char *FuncName = FD->getNameAsCString();
Mike Stump11289f42009-09-09 15:08:12 +00004031
Steve Naroff677ab3a2008-10-27 17:20:55 +00004032 SynthesizeBlockLiterals(FunLocStart, FuncName);
4033}
4034
4035void RewriteObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
Steve Naroff295570a2008-10-30 12:09:33 +00004036 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
4037 //SourceLocation FunLocStart = MD->getLocStart();
4038 // FIXME: This hack works around a bug in Rewrite.InsertText().
4039 SourceLocation FunLocStart = MD->getLocStart().getFileLocWithOffset(-1);
Chris Lattnere4b95692008-11-24 03:33:13 +00004040 std::string FuncName = MD->getSelector().getAsString();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004041 // Convert colons to underscores.
4042 std::string::size_type loc = 0;
4043 while ((loc = FuncName.find(":", loc)) != std::string::npos)
4044 FuncName.replace(loc, 1, "_");
Mike Stump11289f42009-09-09 15:08:12 +00004045
Steve Naroff677ab3a2008-10-27 17:20:55 +00004046 SynthesizeBlockLiterals(FunLocStart, FuncName.c_str());
4047}
4048
4049void RewriteObjC::GetBlockDeclRefExprs(Stmt *S) {
4050 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4051 CI != E; ++CI)
4052 if (*CI) {
4053 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
4054 GetBlockDeclRefExprs(CBE->getBody());
4055 else
4056 GetBlockDeclRefExprs(*CI);
4057 }
4058 // Handle specific things.
4059 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S))
4060 // FIXME: Handle enums.
4061 if (!isa<FunctionDecl>(CDRE->getDecl()))
4062 BlockDeclRefs.push_back(CDRE);
4063 return;
4064}
4065
4066void RewriteObjC::GetBlockCallExprs(Stmt *S) {
4067 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4068 CI != E; ++CI)
4069 if (*CI) {
4070 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
4071 GetBlockCallExprs(CBE->getBody());
4072 else
4073 GetBlockCallExprs(*CI);
4074 }
Mike Stump11289f42009-09-09 15:08:12 +00004075
Steve Naroff677ab3a2008-10-27 17:20:55 +00004076 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
4077 if (CE->getCallee()->getType()->isBlockPointerType()) {
4078 BlockCallExprs[dyn_cast<BlockDeclRefExpr>(CE->getCallee())] = CE;
4079 }
4080 }
4081 return;
4082}
4083
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004084Stmt *RewriteObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00004085 // Navigate to relevant type information.
Steve Naroff677ab3a2008-10-27 17:20:55 +00004086 const BlockPointerType *CPT = 0;
Mike Stump11289f42009-09-09 15:08:12 +00004087
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004088 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004089 CPT = DRE->getType()->getAs<BlockPointerType>();
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004090 } else if (const BlockDeclRefExpr *CDRE =
4091 dyn_cast<BlockDeclRefExpr>(BlockExp)) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004092 CPT = CDRE->getType()->getAs<BlockPointerType>();
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004093 } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004094 CPT = MExpr->getType()->getAs<BlockPointerType>();
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004095 }
4096 else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
4097 return SynthesizeBlockCall(Exp, PRE->getSubExpr());
4098 }
4099 else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
4100 CPT = IEXPR->getType()->getAs<BlockPointerType>();
4101 else if (const ConditionalOperator *CEXPR =
4102 dyn_cast<ConditionalOperator>(BlockExp)) {
4103 Expr *LHSExp = CEXPR->getLHS();
4104 Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
4105 Expr *RHSExp = CEXPR->getRHS();
4106 Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
4107 Expr *CONDExp = CEXPR->getCond();
4108 ConditionalOperator *CondExpr =
4109 new (Context) ConditionalOperator(CONDExp,
4110 SourceLocation(), cast<Expr>(LHSStmt),
4111 SourceLocation(), cast<Expr>(RHSStmt),
4112 Exp->getType());
4113 return CondExpr;
Fariborz Jahanian6ab7ed42009-12-18 01:15:21 +00004114 } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
4115 CPT = IRE->getType()->getAs<BlockPointerType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004116 } else {
4117 assert(1 && "RewriteBlockClass: Bad type");
4118 }
4119 assert(CPT && "RewriteBlockClass: Bad type");
John McCall9dd450b2009-09-21 23:43:11 +00004120 const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004121 assert(FT && "RewriteBlockClass: Bad type");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004122 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004123 // FTP will be null for closures that don't take arguments.
Mike Stump11289f42009-09-09 15:08:12 +00004124
Steve Naroff350b6652008-10-30 10:07:53 +00004125 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
4126 SourceLocation(),
4127 &Context->Idents.get("__block_impl"));
4128 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
Steve Naroff677ab3a2008-10-27 17:20:55 +00004129
Steve Naroff350b6652008-10-30 10:07:53 +00004130 // Generate a funky cast.
4131 llvm::SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00004132
Steve Naroff350b6652008-10-30 10:07:53 +00004133 // Push the block argument type.
4134 ArgTypes.push_back(PtrBlock);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004135 if (FTP) {
Mike Stump11289f42009-09-09 15:08:12 +00004136 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroff350b6652008-10-30 10:07:53 +00004137 E = FTP->arg_type_end(); I && (I != E); ++I) {
4138 QualType t = *I;
4139 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Steve Naroffa5c0db82008-12-11 21:05:33 +00004140 if (isTopLevelBlockPointerType(t)) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004141 const BlockPointerType *BPT = t->getAs<BlockPointerType>();
Steve Naroff350b6652008-10-30 10:07:53 +00004142 t = Context->getPointerType(BPT->getPointeeType());
4143 }
4144 ArgTypes.push_back(t);
4145 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00004146 }
Steve Naroff350b6652008-10-30 10:07:53 +00004147 // Now do the pointer to function cast.
Mike Stump11289f42009-09-09 15:08:12 +00004148 QualType PtrToFuncCastType = Context->getFunctionType(Exp->getType(),
Steve Naroff350b6652008-10-30 10:07:53 +00004149 &ArgTypes[0], ArgTypes.size(), false/*no variadic*/, 0);
Mike Stump11289f42009-09-09 15:08:12 +00004150
Steve Naroff350b6652008-10-30 10:07:53 +00004151 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
Mike Stump11289f42009-09-09 15:08:12 +00004152
4153 CastExpr *BlkCast = new (Context) CStyleCastExpr(PtrBlock,
Anders Carlssona2615922009-07-31 00:48:10 +00004154 CastExpr::CK_Unknown,
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004155 const_cast<Expr*>(BlockExp),
Ted Kremenek5a201952009-02-07 01:47:29 +00004156 PtrBlock, SourceLocation(),
4157 SourceLocation());
Steve Naroff350b6652008-10-30 10:07:53 +00004158 // Don't forget the parens to enforce the proper binding.
Ted Kremenek5a201952009-02-07 01:47:29 +00004159 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4160 BlkCast);
Steve Naroff350b6652008-10-30 10:07:53 +00004161 //PE->dump();
Mike Stump11289f42009-09-09 15:08:12 +00004162
Douglas Gregor91f84212008-12-11 16:49:14 +00004163 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00004164 &Context->Idents.get("FuncPtr"), Context->VoidPtrTy, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00004165 /*BitWidth=*/0, /*Mutable=*/true);
Ted Kremenek5a201952009-02-07 01:47:29 +00004166 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
4167 FD->getType());
Mike Stump11289f42009-09-09 15:08:12 +00004168
Anders Carlssona2615922009-07-31 00:48:10 +00004169 CastExpr *FunkCast = new (Context) CStyleCastExpr(PtrToFuncCastType,
4170 CastExpr::CK_Unknown, ME,
Ted Kremenek5a201952009-02-07 01:47:29 +00004171 PtrToFuncCastType,
4172 SourceLocation(),
4173 SourceLocation());
4174 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
Mike Stump11289f42009-09-09 15:08:12 +00004175
Steve Naroff350b6652008-10-30 10:07:53 +00004176 llvm::SmallVector<Expr*, 8> BlkExprs;
4177 // Add the implicit argument.
4178 BlkExprs.push_back(BlkCast);
4179 // Add the user arguments.
Mike Stump11289f42009-09-09 15:08:12 +00004180 for (CallExpr::arg_iterator I = Exp->arg_begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00004181 E = Exp->arg_end(); I != E; ++I) {
Steve Naroff350b6652008-10-30 10:07:53 +00004182 BlkExprs.push_back(*I);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004183 }
Ted Kremenekd7b4f402009-02-09 20:51:47 +00004184 CallExpr *CE = new (Context) CallExpr(*Context, PE, &BlkExprs[0],
4185 BlkExprs.size(),
Ted Kremenek5a201952009-02-07 01:47:29 +00004186 Exp->getType(), SourceLocation());
Steve Naroff350b6652008-10-30 10:07:53 +00004187 return CE;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004188}
4189
4190void RewriteObjC::RewriteBlockCall(CallExpr *Exp) {
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004191 Stmt *BlockCall = SynthesizeBlockCall(Exp, Exp->getCallee());
Steve Naroff350b6652008-10-30 10:07:53 +00004192 ReplaceStmt(Exp, BlockCall);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004193}
4194
Steve Naroffd9803712009-04-29 16:37:50 +00004195// We need to return the rewritten expression to handle cases where the
4196// BlockDeclRefExpr is embedded in another expression being rewritten.
4197// For example:
4198//
4199// int main() {
4200// __block Foo *f;
4201// __block int i;
Mike Stump11289f42009-09-09 15:08:12 +00004202//
Steve Naroffd9803712009-04-29 16:37:50 +00004203// void (^myblock)() = ^() {
4204// [f test]; // f is a BlockDeclRefExpr embedded in a message (which is being rewritten).
4205// i = 77;
4206// };
4207//}
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004208Stmt *RewriteObjC::RewriteBlockDeclRefExpr(Expr *DeclRefExp) {
Fariborz Jahanian25c07fa2009-12-23 19:26:34 +00004209 // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004210 // for each DeclRefExp where BYREFVAR is name of the variable.
4211 ValueDecl *VD;
4212 bool isArrow = true;
4213 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(DeclRefExp))
4214 VD = BDRE->getDecl();
4215 else {
4216 VD = cast<DeclRefExpr>(DeclRefExp)->getDecl();
4217 isArrow = false;
4218 }
4219
Fariborz Jahanian7df39802009-12-23 19:22:33 +00004220 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4221 &Context->Idents.get("__forwarding"),
4222 Context->VoidPtrTy, 0,
4223 /*BitWidth=*/0, /*Mutable=*/true);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004224 MemberExpr *ME = new (Context) MemberExpr(DeclRefExp, isArrow,
4225 FD, SourceLocation(),
Fariborz Jahanian7df39802009-12-23 19:22:33 +00004226 FD->getType());
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004227
4228 const char *Name = VD->getNameAsCString();
Fariborz Jahanian7df39802009-12-23 19:22:33 +00004229 FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4230 &Context->Idents.get(Name),
4231 Context->VoidPtrTy, 0,
4232 /*BitWidth=*/0, /*Mutable=*/true);
4233 ME = new (Context) MemberExpr(ME, true, FD, SourceLocation(),
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004234 DeclRefExp->getType());
Fariborz Jahanian7df39802009-12-23 19:22:33 +00004235
4236
4237
Steve Narofff26a1d42009-02-02 17:19:26 +00004238 // Need parens to enforce precedence.
Fariborz Jahanian7df39802009-12-23 19:22:33 +00004239 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4240 ME);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004241 ReplaceStmt(DeclRefExp, PE);
Steve Naroffd9803712009-04-29 16:37:50 +00004242 return PE;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004243}
4244
Steve Naroffc989a7b2008-11-03 23:29:32 +00004245void RewriteObjC::RewriteCastExpr(CStyleCastExpr *CE) {
4246 SourceLocation LocStart = CE->getLParenLoc();
4247 SourceLocation LocEnd = CE->getRParenLoc();
Steve Narofff4b992a2008-10-28 20:29:00 +00004248
4249 // Need to avoid trying to rewrite synthesized casts.
4250 if (LocStart.isInvalid())
4251 return;
Steve Naroff3e7ced12008-11-03 11:20:24 +00004252 // Need to avoid trying to rewrite casts contained in macros.
4253 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
4254 return;
Mike Stump11289f42009-09-09 15:08:12 +00004255
Steve Naroff677ab3a2008-10-27 17:20:55 +00004256 const char *startBuf = SM->getCharacterData(LocStart);
4257 const char *endBuf = SM->getCharacterData(LocEnd);
Mike Stump11289f42009-09-09 15:08:12 +00004258
Steve Naroff677ab3a2008-10-27 17:20:55 +00004259 // advance the location to startArgList.
4260 const char *argPtr = startBuf;
Mike Stump11289f42009-09-09 15:08:12 +00004261
Steve Naroff677ab3a2008-10-27 17:20:55 +00004262 while (*argPtr++ && (argPtr < endBuf)) {
4263 switch (*argPtr) {
Mike Stump11289f42009-09-09 15:08:12 +00004264 case '^':
Steve Naroff677ab3a2008-10-27 17:20:55 +00004265 // Replace the '^' with '*'.
4266 LocStart = LocStart.getFileLocWithOffset(argPtr-startBuf);
4267 ReplaceText(LocStart, 1, "*", 1);
4268 break;
4269 }
4270 }
4271 return;
4272}
4273
4274void RewriteObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
4275 SourceLocation DeclLoc = FD->getLocation();
4276 unsigned parenCount = 0;
Mike Stump11289f42009-09-09 15:08:12 +00004277
Steve Naroff677ab3a2008-10-27 17:20:55 +00004278 // We have 1 or more arguments that have closure pointers.
4279 const char *startBuf = SM->getCharacterData(DeclLoc);
4280 const char *startArgList = strchr(startBuf, '(');
Mike Stump11289f42009-09-09 15:08:12 +00004281
Steve Naroff677ab3a2008-10-27 17:20:55 +00004282 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
Mike Stump11289f42009-09-09 15:08:12 +00004283
Steve Naroff677ab3a2008-10-27 17:20:55 +00004284 parenCount++;
4285 // advance the location to startArgList.
4286 DeclLoc = DeclLoc.getFileLocWithOffset(startArgList-startBuf);
4287 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
Mike Stump11289f42009-09-09 15:08:12 +00004288
Steve Naroff677ab3a2008-10-27 17:20:55 +00004289 const char *argPtr = startArgList;
Mike Stump11289f42009-09-09 15:08:12 +00004290
Steve Naroff677ab3a2008-10-27 17:20:55 +00004291 while (*argPtr++ && parenCount) {
4292 switch (*argPtr) {
Mike Stump11289f42009-09-09 15:08:12 +00004293 case '^':
Steve Naroff677ab3a2008-10-27 17:20:55 +00004294 // Replace the '^' with '*'.
4295 DeclLoc = DeclLoc.getFileLocWithOffset(argPtr-startArgList);
4296 ReplaceText(DeclLoc, 1, "*", 1);
4297 break;
Mike Stump11289f42009-09-09 15:08:12 +00004298 case '(':
4299 parenCount++;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004300 break;
Mike Stump11289f42009-09-09 15:08:12 +00004301 case ')':
Steve Naroff677ab3a2008-10-27 17:20:55 +00004302 parenCount--;
4303 break;
4304 }
4305 }
4306 return;
4307}
4308
4309bool RewriteObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004310 const FunctionProtoType *FTP;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004311 const PointerType *PT = QT->getAs<PointerType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004312 if (PT) {
John McCall9dd450b2009-09-21 23:43:11 +00004313 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004314 } else {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004315 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004316 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
John McCall9dd450b2009-09-21 23:43:11 +00004317 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004318 }
4319 if (FTP) {
Mike Stump11289f42009-09-09 15:08:12 +00004320 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00004321 E = FTP->arg_type_end(); I != E; ++I)
Steve Naroffa5c0db82008-12-11 21:05:33 +00004322 if (isTopLevelBlockPointerType(*I))
Steve Naroff677ab3a2008-10-27 17:20:55 +00004323 return true;
4324 }
4325 return false;
4326}
4327
Ted Kremenek5a201952009-02-07 01:47:29 +00004328void RewriteObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
4329 const char *&RParen) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00004330 const char *argPtr = strchr(Name, '(');
4331 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
Mike Stump11289f42009-09-09 15:08:12 +00004332
Steve Naroff677ab3a2008-10-27 17:20:55 +00004333 LParen = argPtr; // output the start.
4334 argPtr++; // skip past the left paren.
4335 unsigned parenCount = 1;
Mike Stump11289f42009-09-09 15:08:12 +00004336
Steve Naroff677ab3a2008-10-27 17:20:55 +00004337 while (*argPtr && parenCount) {
4338 switch (*argPtr) {
4339 case '(': parenCount++; break;
4340 case ')': parenCount--; break;
4341 default: break;
4342 }
4343 if (parenCount) argPtr++;
4344 }
4345 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
4346 RParen = argPtr; // output the end
4347}
4348
4349void RewriteObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
4350 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4351 RewriteBlockPointerFunctionArgs(FD);
4352 return;
Mike Stump11289f42009-09-09 15:08:12 +00004353 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00004354 // Handle Variables and Typedefs.
4355 SourceLocation DeclLoc = ND->getLocation();
4356 QualType DeclT;
4357 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
4358 DeclT = VD->getType();
4359 else if (TypedefDecl *TDD = dyn_cast<TypedefDecl>(ND))
4360 DeclT = TDD->getUnderlyingType();
4361 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
4362 DeclT = FD->getType();
Mike Stump11289f42009-09-09 15:08:12 +00004363 else
Steve Naroff677ab3a2008-10-27 17:20:55 +00004364 assert(0 && "RewriteBlockPointerDecl(): Decl type not yet handled");
Mike Stump11289f42009-09-09 15:08:12 +00004365
Steve Naroff677ab3a2008-10-27 17:20:55 +00004366 const char *startBuf = SM->getCharacterData(DeclLoc);
4367 const char *endBuf = startBuf;
4368 // scan backward (from the decl location) for the end of the previous decl.
4369 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
4370 startBuf--;
Mike Stump11289f42009-09-09 15:08:12 +00004371
Steve Naroff677ab3a2008-10-27 17:20:55 +00004372 // *startBuf != '^' if we are dealing with a pointer to function that
4373 // may take block argument types (which will be handled below).
4374 if (*startBuf == '^') {
4375 // Replace the '^' with '*', computing a negative offset.
4376 DeclLoc = DeclLoc.getFileLocWithOffset(startBuf-endBuf);
4377 ReplaceText(DeclLoc, 1, "*", 1);
4378 }
4379 if (PointerTypeTakesAnyBlockArguments(DeclT)) {
4380 // Replace the '^' with '*' for arguments.
4381 DeclLoc = ND->getLocation();
4382 startBuf = SM->getCharacterData(DeclLoc);
4383 const char *argListBegin, *argListEnd;
4384 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
4385 while (argListBegin < argListEnd) {
4386 if (*argListBegin == '^') {
4387 SourceLocation CaretLoc = DeclLoc.getFileLocWithOffset(argListBegin-startBuf);
4388 ReplaceText(CaretLoc, 1, "*", 1);
4389 }
4390 argListBegin++;
4391 }
4392 }
4393 return;
4394}
4395
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004396
4397/// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
4398/// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
4399/// struct Block_byref_id_object *src) {
4400/// _Block_object_assign (&_dest->object, _src->object,
4401/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4402/// [|BLOCK_FIELD_IS_WEAK]) // object
4403/// _Block_object_assign(&_dest->object, _src->object,
4404/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4405/// [|BLOCK_FIELD_IS_WEAK]) // block
4406/// }
4407/// And:
4408/// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
4409/// _Block_object_dispose(_src->object,
4410/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4411/// [|BLOCK_FIELD_IS_WEAK]) // object
4412/// _Block_object_dispose(_src->object,
4413/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4414/// [|BLOCK_FIELD_IS_WEAK]) // block
4415/// }
4416
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004417std::string RewriteObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
4418 int flag) {
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004419 std::string S;
Benjamin Kramere056cea2010-01-10 19:57:50 +00004420 if (CopyDestroyCache.count(flag))
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004421 return S;
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004422 CopyDestroyCache.insert(flag);
4423 S = "static void __Block_byref_id_object_copy_";
4424 S += utostr(flag);
4425 S += "(void *dst, void *src) {\n";
4426
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004427 // offset into the object pointer is computed as:
4428 // void * + void* + int + int + void* + void *
4429 unsigned IntSize =
4430 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
4431 unsigned VoidPtrSize =
4432 static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
4433
4434 unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/8;
4435 S += " _Block_object_assign((char*)dst + ";
4436 S += utostr(offset);
4437 S += ", *(void * *) ((char*)src + ";
4438 S += utostr(offset);
4439 S += "), ";
4440 S += utostr(flag);
4441 S += ");\n}\n";
4442
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004443 S += "static void __Block_byref_id_object_dispose_";
4444 S += utostr(flag);
4445 S += "(void *src) {\n";
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004446 S += " _Block_object_dispose(*(void * *) ((char*)src + ";
4447 S += utostr(offset);
4448 S += "), ";
4449 S += utostr(flag);
4450 S += ");\n}\n";
4451 return S;
4452}
4453
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004454/// RewriteByRefVar - For each __block typex ND variable this routine transforms
4455/// the declaration into:
4456/// struct __Block_byref_ND {
4457/// void *__isa; // NULL for everything except __weak pointers
4458/// struct __Block_byref_ND *__forwarding;
4459/// int32_t __flags;
4460/// int32_t __size;
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004461/// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
4462/// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004463/// typex ND;
4464/// };
4465///
4466/// It then replaces declaration of ND variable with:
4467/// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
4468/// __size=sizeof(struct __Block_byref_ND),
4469/// ND=initializer-if-any};
4470///
4471///
4472void RewriteObjC::RewriteByRefVar(VarDecl *ND) {
Fariborz Jahanian7fac6552010-01-05 19:21:35 +00004473 int flag = 0;
4474 int isa = 0;
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004475 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
4476 const char *startBuf = SM->getCharacterData(DeclLoc);
Fariborz Jahanian92368a12009-12-30 20:38:08 +00004477 SourceLocation X = ND->getLocEnd();
4478 X = SM->getInstantiationLoc(X);
4479 const char *endBuf = SM->getCharacterData(X);
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004480 std::string Name(ND->getNameAsString());
4481 std::string ByrefType = "struct __Block_byref_";
4482 ByrefType += Name;
4483 ByrefType += " {\n";
4484 ByrefType += " void *__isa;\n";
4485 ByrefType += " struct __Block_byref_" + Name + " *__forwarding;\n";
4486 ByrefType += " int __flags;\n";
4487 ByrefType += " int __size;\n";
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004488 // Add void *__Block_byref_id_object_copy;
4489 // void *__Block_byref_id_object_dispose; if needed.
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004490 QualType Ty = ND->getType();
4491 bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty);
4492 if (HasCopyAndDispose) {
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004493 ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
4494 ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004495 }
4496
4497 Ty.getAsStringInternal(Name, Context->PrintingPolicy);
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004498 ByrefType += " " + Name + ";\n";
4499 ByrefType += "};\n";
4500 // Insert this type in global scope. It is needed by helper function.
4501 assert(CurFunctionDef && "RewriteByRefVar - CurFunctionDef is null");
4502 SourceLocation FunLocStart = CurFunctionDef->getTypeSpecStartLoc();
4503 InsertText(FunLocStart, ByrefType.c_str(), ByrefType.size());
Fariborz Jahanian7fac6552010-01-05 19:21:35 +00004504 if (Ty.isObjCGCWeak()) {
4505 flag |= BLOCK_FIELD_IS_WEAK;
4506 isa = 1;
4507 }
4508
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004509 if (HasCopyAndDispose) {
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004510 flag = BLOCK_BYREF_CALLER;
4511 QualType Ty = ND->getType();
4512 // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
4513 if (Ty->isBlockPointerType())
4514 flag |= BLOCK_FIELD_IS_BLOCK;
4515 else
4516 flag |= BLOCK_FIELD_IS_OBJECT;
4517 std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004518 if (!HF.empty())
4519 InsertText(FunLocStart, HF.c_str(), HF.size());
4520 }
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004521
4522 // struct __Block_byref_ND ND =
4523 // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
4524 // initializer-if-any};
4525 bool hasInit = (ND->getInit() != 0);
Fariborz Jahanianf7945432010-01-05 18:15:57 +00004526 unsigned flags = 0;
4527 if (HasCopyAndDispose)
4528 flags |= BLOCK_HAS_COPY_DISPOSE;
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004529 Name = ND->getNameAsString();
4530 ByrefType = "struct __Block_byref_" + Name;
4531 if (!hasInit) {
Fariborz Jahanian7fac6552010-01-05 19:21:35 +00004532 ByrefType += " " + Name + " = {(void*)";
4533 ByrefType += utostr(isa);
4534 ByrefType += ", &" + Name + ", ";
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004535 ByrefType += utostr(flags);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004536 ByrefType += ", ";
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004537 ByrefType += "sizeof(struct __Block_byref_" + Name + ")";
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004538 if (HasCopyAndDispose) {
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004539 ByrefType += ", __Block_byref_id_object_copy_";
4540 ByrefType += utostr(flag);
4541 ByrefType += ", __Block_byref_id_object_dispose_";
4542 ByrefType += utostr(flag);
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004543 }
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004544 ByrefType += "};\n";
4545 ReplaceText(DeclLoc, endBuf-startBuf+Name.size(),
4546 ByrefType.c_str(), ByrefType.size());
4547 }
4548 else {
4549 SourceLocation startLoc = ND->getInit()->getLocStart();
Fariborz Jahanianb8646ed2010-01-05 23:06:29 +00004550 startLoc = SM->getInstantiationLoc(startLoc);
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004551 ByrefType += " " + Name;
4552 ReplaceText(DeclLoc, endBuf-startBuf,
4553 ByrefType.c_str(), ByrefType.size());
Fariborz Jahanian7fac6552010-01-05 19:21:35 +00004554 ByrefType = " = {(void*)";
4555 ByrefType += utostr(isa);
4556 ByrefType += ", &" + Name + ", ";
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004557 ByrefType += utostr(flags);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004558 ByrefType += ", ";
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004559 ByrefType += "sizeof(struct __Block_byref_" + Name + "), ";
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004560 if (HasCopyAndDispose) {
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004561 ByrefType += "__Block_byref_id_object_copy_";
4562 ByrefType += utostr(flag);
4563 ByrefType += ", __Block_byref_id_object_dispose_";
4564 ByrefType += utostr(flag);
4565 ByrefType += ", ";
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004566 }
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004567 InsertText(startLoc, ByrefType.c_str(), ByrefType.size());
Steve Naroff13468372009-12-23 17:24:33 +00004568
4569 // Complete the newly synthesized compound expression by inserting a right
4570 // curly brace before the end of the declaration.
4571 // FIXME: This approach avoids rewriting the initializer expression. It
4572 // also assumes there is only one declarator. For example, the following
4573 // isn't currently supported by this routine (in general):
4574 //
4575 // double __block BYREFVAR = 1.34, BYREFVAR2 = 1.37;
4576 //
4577 const char *startBuf = SM->getCharacterData(startLoc);
4578 const char *semiBuf = strchr(startBuf, ';');
4579 assert((*semiBuf == ';') && "RewriteByRefVar: can't find ';'");
4580 SourceLocation semiLoc =
4581 startLoc.getFileLocWithOffset(semiBuf-startBuf);
4582
4583 InsertText(semiLoc, "}", 1);
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004584 }
Fariborz Jahanian81203462009-12-22 00:48:54 +00004585 return;
4586}
4587
Mike Stump11289f42009-09-09 15:08:12 +00004588void RewriteObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00004589 // Add initializers for any closure decl refs.
4590 GetBlockDeclRefExprs(Exp->getBody());
4591 if (BlockDeclRefs.size()) {
4592 // Unique all "by copy" declarations.
4593 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
4594 if (!BlockDeclRefs[i]->isByRef())
4595 BlockByCopyDecls.insert(BlockDeclRefs[i]->getDecl());
4596 // Unique all "by ref" declarations.
4597 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
4598 if (BlockDeclRefs[i]->isByRef()) {
4599 BlockByRefDecls.insert(BlockDeclRefs[i]->getDecl());
4600 }
4601 // Find any imported blocks...they will need special attention.
4602 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
Fariborz Jahaniane175eeb2009-12-21 23:31:42 +00004603 if (BlockDeclRefs[i]->isByRef() ||
4604 BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
4605 BlockDeclRefs[i]->getType()->isBlockPointerType()) {
Steve Naroff832d8902008-11-13 17:40:07 +00004606 GetBlockCallExprs(BlockDeclRefs[i]);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004607 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
4608 }
4609 }
4610}
4611
Steve Narofff4b992a2008-10-28 20:29:00 +00004612FunctionDecl *RewriteObjC::SynthBlockInitFunctionDecl(const char *name) {
4613 IdentifierInfo *ID = &Context->Idents.get(name);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004614 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
Mike Stump11289f42009-09-09 15:08:12 +00004615 return FunctionDecl::Create(*Context, TUDecl,SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00004616 ID, FType, 0, FunctionDecl::Extern, false,
Douglas Gregor739ef0c2009-02-25 16:33:18 +00004617 false);
Steve Narofff4b992a2008-10-28 20:29:00 +00004618}
4619
Steve Naroffd8907b72008-10-29 18:15:37 +00004620Stmt *RewriteObjC::SynthBlockInitExpr(BlockExpr *Exp) {
Steve Narofff4b992a2008-10-28 20:29:00 +00004621 Blocks.push_back(Exp);
4622
4623 CollectBlockDeclRefInfo(Exp);
4624 std::string FuncName;
Mike Stump11289f42009-09-09 15:08:12 +00004625
Steve Narofff4b992a2008-10-28 20:29:00 +00004626 if (CurFunctionDef)
Chris Lattnere4b95692008-11-24 03:33:13 +00004627 FuncName = CurFunctionDef->getNameAsString();
Steve Narofff4b992a2008-10-28 20:29:00 +00004628 else if (CurMethodDef) {
Chris Lattnere4b95692008-11-24 03:33:13 +00004629 FuncName = CurMethodDef->getSelector().getAsString();
Steve Narofff4b992a2008-10-28 20:29:00 +00004630 // Convert colons to underscores.
4631 std::string::size_type loc = 0;
4632 while ((loc = FuncName.find(":", loc)) != std::string::npos)
4633 FuncName.replace(loc, 1, "_");
Steve Naroffd8907b72008-10-29 18:15:37 +00004634 } else if (GlobalVarDecl)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004635 FuncName = std::string(GlobalVarDecl->getNameAsString());
Mike Stump11289f42009-09-09 15:08:12 +00004636
Steve Narofff4b992a2008-10-28 20:29:00 +00004637 std::string BlockNumber = utostr(Blocks.size()-1);
Mike Stump11289f42009-09-09 15:08:12 +00004638
Steve Narofff4b992a2008-10-28 20:29:00 +00004639 std::string Tag = "__" + FuncName + "_block_impl_" + BlockNumber;
4640 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
Mike Stump11289f42009-09-09 15:08:12 +00004641
Steve Narofff4b992a2008-10-28 20:29:00 +00004642 // Get a pointer to the function type so we can cast appropriately.
4643 QualType FType = Context->getPointerType(QualType(Exp->getFunctionType(),0));
4644
4645 FunctionDecl *FD;
4646 Expr *NewRep;
Mike Stump11289f42009-09-09 15:08:12 +00004647
Steve Narofff4b992a2008-10-28 20:29:00 +00004648 // Simulate a contructor call...
4649 FD = SynthBlockInitFunctionDecl(Tag.c_str());
Ted Kremenek5a201952009-02-07 01:47:29 +00004650 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, FType, SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00004651
Steve Narofff4b992a2008-10-28 20:29:00 +00004652 llvm::SmallVector<Expr*, 4> InitExprs;
Mike Stump11289f42009-09-09 15:08:12 +00004653
Steve Naroffe2514232008-10-29 21:23:59 +00004654 // Initialize the block function.
Steve Narofff4b992a2008-10-28 20:29:00 +00004655 FD = SynthBlockInitFunctionDecl(Func.c_str());
Ted Kremenek5a201952009-02-07 01:47:29 +00004656 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, FD->getType(),
4657 SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00004658 CastExpr *castExpr = new (Context) CStyleCastExpr(Context->VoidPtrTy,
4659 CastExpr::CK_Unknown, Arg,
Ted Kremenek5a201952009-02-07 01:47:29 +00004660 Context->VoidPtrTy, SourceLocation(),
4661 SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00004662 InitExprs.push_back(castExpr);
4663
Steve Naroff30484702009-12-06 21:14:13 +00004664 // Initialize the block descriptor.
4665 std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
Mike Stump11289f42009-09-09 15:08:12 +00004666
Steve Naroff30484702009-12-06 21:14:13 +00004667 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
4668 &Context->Idents.get(DescData.c_str()),
4669 Context->VoidPtrTy, 0,
4670 VarDecl::Static);
4671 UnaryOperator *DescRefExpr = new (Context) UnaryOperator(
4672 new (Context) DeclRefExpr(NewVD,
4673 Context->VoidPtrTy, SourceLocation()),
4674 UnaryOperator::AddrOf,
4675 Context->getPointerType(Context->VoidPtrTy),
4676 SourceLocation());
4677 InitExprs.push_back(DescRefExpr);
4678
Steve Narofff4b992a2008-10-28 20:29:00 +00004679 // Add initializers for any closure decl refs.
4680 if (BlockDeclRefs.size()) {
Steve Naroffe2514232008-10-29 21:23:59 +00004681 Expr *Exp;
Steve Narofff4b992a2008-10-28 20:29:00 +00004682 // Output all "by copy" declarations.
Mike Stump11289f42009-09-09 15:08:12 +00004683 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Narofff4b992a2008-10-28 20:29:00 +00004684 E = BlockByCopyDecls.end(); I != E; ++I) {
Steve Narofff4b992a2008-10-28 20:29:00 +00004685 if (isObjCType((*I)->getType())) {
Steve Naroffe2514232008-10-29 21:23:59 +00004686 // FIXME: Conform to ABI ([[obj retain] autorelease]).
Chris Lattner86d7d912008-11-24 03:54:41 +00004687 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek5a201952009-02-07 01:47:29 +00004688 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
Steve Naroffa5c0db82008-12-11 21:05:33 +00004689 } else if (isTopLevelBlockPointerType((*I)->getType())) {
Chris Lattner86d7d912008-11-24 03:54:41 +00004690 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek5a201952009-02-07 01:47:29 +00004691 Arg = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00004692 Exp = new (Context) CStyleCastExpr(Context->VoidPtrTy,
4693 CastExpr::CK_Unknown, Arg,
4694 Context->VoidPtrTy,
Anders Carlssona2615922009-07-31 00:48:10 +00004695 SourceLocation(),
Ted Kremenek5a201952009-02-07 01:47:29 +00004696 SourceLocation());
Steve Narofff4b992a2008-10-28 20:29:00 +00004697 } else {
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());
Steve Narofff4b992a2008-10-28 20:29:00 +00004700 }
Mike Stump11289f42009-09-09 15:08:12 +00004701 InitExprs.push_back(Exp);
Steve Narofff4b992a2008-10-28 20:29:00 +00004702 }
4703 // Output all "by ref" declarations.
Mike Stump11289f42009-09-09 15:08:12 +00004704 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Narofff4b992a2008-10-28 20:29:00 +00004705 E = BlockByRefDecls.end(); I != E; ++I) {
Chris Lattner86d7d912008-11-24 03:54:41 +00004706 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek5a201952009-02-07 01:47:29 +00004707 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
4708 Exp = new (Context) UnaryOperator(Exp, UnaryOperator::AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00004709 Context->getPointerType(Exp->getType()),
Steve Naroffe2514232008-10-29 21:23:59 +00004710 SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00004711 InitExprs.push_back(Exp);
Steve Narofff4b992a2008-10-28 20:29:00 +00004712 }
4713 }
Fariborz Jahanian65e6bd62009-12-23 21:52:32 +00004714 if (ImportedBlockDecls.size()) {
4715 // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
4716 int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
Steve Naroff30484702009-12-06 21:14:13 +00004717 unsigned IntSize =
4718 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Fariborz Jahanian65e6bd62009-12-23 21:52:32 +00004719 Expr *FlagExp = new (Context) IntegerLiteral(llvm::APInt(IntSize, flag),
4720 Context->IntTy, SourceLocation());
4721 InitExprs.push_back(FlagExp);
Steve Naroff30484702009-12-06 21:14:13 +00004722 }
Ted Kremenekd7b4f402009-02-09 20:51:47 +00004723 NewRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0], InitExprs.size(),
4724 FType, SourceLocation());
Ted Kremenek5a201952009-02-07 01:47:29 +00004725 NewRep = new (Context) UnaryOperator(NewRep, UnaryOperator::AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00004726 Context->getPointerType(NewRep->getType()),
Steve Narofff4b992a2008-10-28 20:29:00 +00004727 SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00004728 NewRep = new (Context) CStyleCastExpr(FType, CastExpr::CK_Unknown, NewRep,
Anders Carlssona2615922009-07-31 00:48:10 +00004729 FType, SourceLocation(),
Ted Kremenek5a201952009-02-07 01:47:29 +00004730 SourceLocation());
Steve Narofff4b992a2008-10-28 20:29:00 +00004731 BlockDeclRefs.clear();
4732 BlockByRefDecls.clear();
4733 BlockByCopyDecls.clear();
4734 ImportedBlockDecls.clear();
4735 return NewRep;
4736}
4737
4738//===----------------------------------------------------------------------===//
4739// Function Body / Expression rewriting
4740//===----------------------------------------------------------------------===//
4741
Steve Naroff4588d0f2008-12-04 16:24:46 +00004742// This is run as a first "pass" prior to RewriteFunctionBodyOrGlobalInitializer().
4743// The allows the main rewrite loop to associate all ObjCPropertyRefExprs with
4744// their respective BinaryOperator. Without this knowledge, we'd need to rewrite
4745// the ObjCPropertyRefExpr twice (once as a getter, and later as a setter).
4746// Since the rewriter isn't capable of rewriting rewritten code, it's important
4747// we get this right.
4748void RewriteObjC::CollectPropertySetters(Stmt *S) {
4749 // Perform a bottom up traversal of all children.
4750 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4751 CI != E; ++CI)
4752 if (*CI)
4753 CollectPropertySetters(*CI);
4754
4755 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(S)) {
4756 if (BinOp->isAssignmentOp()) {
4757 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(BinOp->getLHS()))
4758 PropSetters[PRE] = BinOp;
4759 }
4760 }
4761}
4762
Steve Narofff4b992a2008-10-28 20:29:00 +00004763Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
Mike Stump11289f42009-09-09 15:08:12 +00004764 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofff4b992a2008-10-28 20:29:00 +00004765 isa<DoStmt>(S) || isa<ForStmt>(S))
4766 Stmts.push_back(S);
4767 else if (isa<ObjCForCollectionStmt>(S)) {
4768 Stmts.push_back(S);
Chris Lattnerb71980f2010-01-09 21:45:57 +00004769 ObjCBcLabelNo.push_back(++BcLabelCount);
Steve Narofff4b992a2008-10-28 20:29:00 +00004770 }
Mike Stump11289f42009-09-09 15:08:12 +00004771
Steve Narofff4b992a2008-10-28 20:29:00 +00004772 SourceRange OrigStmtRange = S->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00004773
Steve Narofff4b992a2008-10-28 20:29:00 +00004774 // Perform a bottom up rewrite of all children.
4775 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4776 CI != E; ++CI)
4777 if (*CI) {
4778 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(*CI);
Mike Stump11289f42009-09-09 15:08:12 +00004779 if (newStmt)
Steve Narofff4b992a2008-10-28 20:29:00 +00004780 *CI = newStmt;
4781 }
Mike Stump11289f42009-09-09 15:08:12 +00004782
Steve Narofff4b992a2008-10-28 20:29:00 +00004783 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
4784 // Rewrite the block body in place.
4785 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
Mike Stump11289f42009-09-09 15:08:12 +00004786
Steve Narofff4b992a2008-10-28 20:29:00 +00004787 // Now we snarf the rewritten text and stash it away for later use.
Ted Kremenekdb2ef372010-01-07 18:00:35 +00004788 std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
Steve Naroffd8907b72008-10-29 18:15:37 +00004789 RewrittenBlockExprs[BE] = Str;
Mike Stump11289f42009-09-09 15:08:12 +00004790
Steve Narofff4b992a2008-10-28 20:29:00 +00004791 Stmt *blockTranscribed = SynthBlockInitExpr(BE);
4792 //blockTranscribed->dump();
Steve Naroffd8907b72008-10-29 18:15:37 +00004793 ReplaceStmt(S, blockTranscribed);
Steve Narofff4b992a2008-10-28 20:29:00 +00004794 return blockTranscribed;
4795 }
4796 // Handle specific things.
4797 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
4798 return RewriteAtEncode(AtEncode);
Mike Stump11289f42009-09-09 15:08:12 +00004799
Steve Narofff4b992a2008-10-28 20:29:00 +00004800 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S))
4801 return RewriteObjCIvarRefExpr(IvarRefExpr, OrigStmtRange.getBegin());
4802
Steve Naroff4588d0f2008-12-04 16:24:46 +00004803 if (ObjCPropertyRefExpr *PropRefExpr = dyn_cast<ObjCPropertyRefExpr>(S)) {
4804 BinaryOperator *BinOp = PropSetters[PropRefExpr];
4805 if (BinOp) {
4806 // Because the rewriter doesn't allow us to rewrite rewritten code,
4807 // we need to rewrite the right hand side prior to rewriting the setter.
Steve Naroff08628db2008-12-09 12:56:34 +00004808 DisableReplaceStmt = true;
4809 // Save the source range. Even if we disable the replacement, the
4810 // rewritten node will have been inserted into the tree. If the synthesized
4811 // node is at the 'end', the rewriter will fail. Consider this:
Mike Stump11289f42009-09-09 15:08:12 +00004812 // self.errorHandler = handler ? handler :
Steve Naroff08628db2008-12-09 12:56:34 +00004813 // ^(NSURL *errorURL, NSError *error) { return (BOOL)1; };
4814 SourceRange SrcRange = BinOp->getSourceRange();
Steve Naroff4588d0f2008-12-04 16:24:46 +00004815 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(BinOp->getRHS());
Steve Naroff08628db2008-12-09 12:56:34 +00004816 DisableReplaceStmt = false;
Steve Naroff22216db2008-12-04 23:50:32 +00004817 //
4818 // Unlike the main iterator, we explicily avoid changing 'BinOp'. If
4819 // we changed the RHS of BinOp, the rewriter would fail (since it needs
4820 // to see the original expression). Consider this example:
4821 //
4822 // Foo *obj1, *obj2;
4823 //
4824 // obj1.i = [obj2 rrrr];
4825 //
4826 // 'BinOp' for the previous expression looks like:
4827 //
4828 // (BinaryOperator 0x231ccf0 'int' '='
4829 // (ObjCPropertyRefExpr 0x231cc70 'int' Kind=PropertyRef Property="i"
4830 // (DeclRefExpr 0x231cc50 'Foo *' Var='obj1' 0x231cbb0))
4831 // (ObjCMessageExpr 0x231ccb0 'int' selector=rrrr
4832 // (DeclRefExpr 0x231cc90 'Foo *' Var='obj2' 0x231cbe0)))
4833 //
4834 // 'newStmt' represents the rewritten message expression. For example:
4835 //
4836 // (CallExpr 0x231d300 'id':'struct objc_object *'
4837 // (ParenExpr 0x231d2e0 'int (*)(id, SEL)'
4838 // (CStyleCastExpr 0x231d2c0 'int (*)(id, SEL)'
4839 // (CStyleCastExpr 0x231d220 'void *'
4840 // (DeclRefExpr 0x231d200 'id (id, SEL, ...)' FunctionDecl='objc_msgSend' 0x231cdc0))))
4841 //
4842 // Note that 'newStmt' is passed to RewritePropertySetter so that it
4843 // can be used as the setter argument. ReplaceStmt() will still 'see'
4844 // the original RHS (since we haven't altered BinOp).
4845 //
Mike Stump11289f42009-09-09 15:08:12 +00004846 // This implies the Rewrite* routines can no longer delete the original
Steve Naroff22216db2008-12-04 23:50:32 +00004847 // node. As a result, we now leak the original AST nodes.
4848 //
Steve Naroff08628db2008-12-09 12:56:34 +00004849 return RewritePropertySetter(BinOp, dyn_cast<Expr>(newStmt), SrcRange);
Steve Naroff4588d0f2008-12-04 16:24:46 +00004850 } else {
4851 return RewritePropertyGetter(PropRefExpr);
Steve Narofff326f402008-12-03 00:56:33 +00004852 }
4853 }
Steve Narofff4b992a2008-10-28 20:29:00 +00004854 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
4855 return RewriteAtSelector(AtSelector);
Mike Stump11289f42009-09-09 15:08:12 +00004856
Steve Narofff4b992a2008-10-28 20:29:00 +00004857 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
4858 return RewriteObjCStringLiteral(AtString);
Mike Stump11289f42009-09-09 15:08:12 +00004859
Steve Narofff4b992a2008-10-28 20:29:00 +00004860 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
Steve Naroff4588d0f2008-12-04 16:24:46 +00004861#if 0
Steve Narofff4b992a2008-10-28 20:29:00 +00004862 // Before we rewrite it, put the original message expression in a comment.
4863 SourceLocation startLoc = MessExpr->getLocStart();
4864 SourceLocation endLoc = MessExpr->getLocEnd();
Mike Stump11289f42009-09-09 15:08:12 +00004865
Steve Narofff4b992a2008-10-28 20:29:00 +00004866 const char *startBuf = SM->getCharacterData(startLoc);
4867 const char *endBuf = SM->getCharacterData(endLoc);
Mike Stump11289f42009-09-09 15:08:12 +00004868
Steve Narofff4b992a2008-10-28 20:29:00 +00004869 std::string messString;
4870 messString += "// ";
4871 messString.append(startBuf, endBuf-startBuf+1);
4872 messString += "\n";
Mike Stump11289f42009-09-09 15:08:12 +00004873
4874 // FIXME: Missing definition of
Steve Narofff4b992a2008-10-28 20:29:00 +00004875 // InsertText(clang::SourceLocation, char const*, unsigned int).
4876 // InsertText(startLoc, messString.c_str(), messString.size());
4877 // Tried this, but it didn't work either...
4878 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroff4588d0f2008-12-04 16:24:46 +00004879#endif
Steve Narofff4b992a2008-10-28 20:29:00 +00004880 return RewriteMessageExpr(MessExpr);
4881 }
Mike Stump11289f42009-09-09 15:08:12 +00004882
Steve Narofff4b992a2008-10-28 20:29:00 +00004883 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
4884 return RewriteObjCTryStmt(StmtTry);
4885
4886 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
4887 return RewriteObjCSynchronizedStmt(StmtTry);
4888
4889 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
4890 return RewriteObjCThrowStmt(StmtThrow);
Mike Stump11289f42009-09-09 15:08:12 +00004891
Steve Narofff4b992a2008-10-28 20:29:00 +00004892 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
4893 return RewriteObjCProtocolExpr(ProtocolExp);
Mike Stump11289f42009-09-09 15:08:12 +00004894
4895 if (ObjCForCollectionStmt *StmtForCollection =
Steve Narofff4b992a2008-10-28 20:29:00 +00004896 dyn_cast<ObjCForCollectionStmt>(S))
Mike Stump11289f42009-09-09 15:08:12 +00004897 return RewriteObjCForCollectionStmt(StmtForCollection,
Steve Narofff4b992a2008-10-28 20:29:00 +00004898 OrigStmtRange.getEnd());
4899 if (BreakStmt *StmtBreakStmt =
4900 dyn_cast<BreakStmt>(S))
4901 return RewriteBreakStmt(StmtBreakStmt);
4902 if (ContinueStmt *StmtContinueStmt =
4903 dyn_cast<ContinueStmt>(S))
4904 return RewriteContinueStmt(StmtContinueStmt);
Mike Stump11289f42009-09-09 15:08:12 +00004905
4906 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
Steve Narofff4b992a2008-10-28 20:29:00 +00004907 // and cast exprs.
4908 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
4909 // FIXME: What we're doing here is modifying the type-specifier that
4910 // precedes the first Decl. In the future the DeclGroup should have
Mike Stump11289f42009-09-09 15:08:12 +00004911 // a separate type-specifier that we can rewrite.
Steve Naroffe70a52a2009-12-05 15:55:59 +00004912 // NOTE: We need to avoid rewriting the DeclStmt if it is within
4913 // the context of an ObjCForCollectionStmt. For example:
4914 // NSArray *someArray;
4915 // for (id <FooProtocol> index in someArray) ;
4916 // This is because RewriteObjCForCollectionStmt() does textual rewriting
4917 // and it depends on the original text locations/positions.
Benjamin Krameracc5fa12009-12-05 22:16:51 +00004918 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
Steve Naroffe70a52a2009-12-05 15:55:59 +00004919 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
Mike Stump11289f42009-09-09 15:08:12 +00004920
Steve Narofff4b992a2008-10-28 20:29:00 +00004921 // Blocks rewrite rules.
4922 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
4923 DI != DE; ++DI) {
Douglas Gregor6e6ad602009-01-20 01:17:11 +00004924 Decl *SD = *DI;
Steve Narofff4b992a2008-10-28 20:29:00 +00004925 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
Steve Naroffa5c0db82008-12-11 21:05:33 +00004926 if (isTopLevelBlockPointerType(ND->getType()))
Steve Narofff4b992a2008-10-28 20:29:00 +00004927 RewriteBlockPointerDecl(ND);
Mike Stump11289f42009-09-09 15:08:12 +00004928 else if (ND->getType()->isFunctionPointerType())
Steve Narofff4b992a2008-10-28 20:29:00 +00004929 CheckFunctionPointerDecl(ND->getType(), ND);
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004930 if (VarDecl *VD = dyn_cast<VarDecl>(SD))
4931 if (VD->hasAttr<BlocksAttr>())
4932 RewriteByRefVar(VD);
Steve Narofff4b992a2008-10-28 20:29:00 +00004933 }
4934 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(SD)) {
Steve Naroffa5c0db82008-12-11 21:05:33 +00004935 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofff4b992a2008-10-28 20:29:00 +00004936 RewriteBlockPointerDecl(TD);
Mike Stump11289f42009-09-09 15:08:12 +00004937 else if (TD->getUnderlyingType()->isFunctionPointerType())
Steve Narofff4b992a2008-10-28 20:29:00 +00004938 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
4939 }
4940 }
4941 }
Mike Stump11289f42009-09-09 15:08:12 +00004942
Steve Narofff4b992a2008-10-28 20:29:00 +00004943 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
4944 RewriteObjCQualifiedInterfaceTypes(CE);
Mike Stump11289f42009-09-09 15:08:12 +00004945
4946 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofff4b992a2008-10-28 20:29:00 +00004947 isa<DoStmt>(S) || isa<ForStmt>(S)) {
4948 assert(!Stmts.empty() && "Statement stack is empty");
Mike Stump11289f42009-09-09 15:08:12 +00004949 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
4950 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
Steve Narofff4b992a2008-10-28 20:29:00 +00004951 && "Statement stack mismatch");
4952 Stmts.pop_back();
4953 }
4954 // Handle blocks rewriting.
4955 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(S)) {
4956 if (BDRE->isByRef())
Steve Naroffd9803712009-04-29 16:37:50 +00004957 return RewriteBlockDeclRefExpr(BDRE);
Steve Narofff4b992a2008-10-28 20:29:00 +00004958 }
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004959 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4960 ValueDecl *VD = DRE->getDecl();
4961 if (VD->hasAttr<BlocksAttr>())
4962 return RewriteBlockDeclRefExpr(DRE);
4963 }
4964
Steve Narofff4b992a2008-10-28 20:29:00 +00004965 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
Steve Naroff350b6652008-10-30 10:07:53 +00004966 if (CE->getCallee()->getType()->isBlockPointerType()) {
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004967 Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
Steve Naroff350b6652008-10-30 10:07:53 +00004968 ReplaceStmt(S, BlockCall);
4969 return BlockCall;
4970 }
Steve Narofff4b992a2008-10-28 20:29:00 +00004971 }
Steve Naroffc989a7b2008-11-03 23:29:32 +00004972 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
Steve Narofff4b992a2008-10-28 20:29:00 +00004973 RewriteCastExpr(CE);
4974 }
4975#if 0
4976 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
Ted Kremenek5a201952009-02-07 01:47:29 +00004977 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(), ICE->getSubExpr(), SourceLocation());
Steve Narofff4b992a2008-10-28 20:29:00 +00004978 // Get the new text.
4979 std::string SStr;
4980 llvm::raw_string_ostream Buf(SStr);
Eli Friedman0905f142009-05-30 05:19:26 +00004981 Replacement->printPretty(Buf, *Context);
Steve Narofff4b992a2008-10-28 20:29:00 +00004982 const std::string &Str = Buf.str();
4983
4984 printf("CAST = %s\n", &Str[0]);
4985 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
4986 delete S;
4987 return Replacement;
4988 }
4989#endif
4990 // Return this stmt unmodified.
4991 return S;
4992}
4993
Steve Naroffe70a52a2009-12-05 15:55:59 +00004994void RewriteObjC::RewriteRecordBody(RecordDecl *RD) {
4995 for (RecordDecl::field_iterator i = RD->field_begin(),
4996 e = RD->field_end(); i != e; ++i) {
4997 FieldDecl *FD = *i;
4998 if (isTopLevelBlockPointerType(FD->getType()))
4999 RewriteBlockPointerDecl(FD);
5000 if (FD->getType()->isObjCQualifiedIdType() ||
5001 FD->getType()->isObjCQualifiedInterfaceType())
5002 RewriteObjCQualifiedInterfaceTypes(FD);
5003 }
5004}
5005
Steve Narofff4b992a2008-10-28 20:29:00 +00005006/// HandleDeclInMainFile - This is called for each top-level decl defined in the
5007/// main file of the input.
5008void RewriteObjC::HandleDeclInMainFile(Decl *D) {
5009 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroffb1368882008-12-17 00:20:22 +00005010 if (FD->isOverloadedOperator())
5011 return;
Mike Stump11289f42009-09-09 15:08:12 +00005012
Steve Narofff4b992a2008-10-28 20:29:00 +00005013 // Since function prototypes don't have ParmDecl's, we check the function
5014 // prototype. This enables us to rewrite function declarations and
5015 // definitions using the same code.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005016 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
Steve Narofff4b992a2008-10-28 20:29:00 +00005017
Sebastian Redla7b98a72009-04-26 20:35:05 +00005018 // FIXME: If this should support Obj-C++, support CXXTryStmt
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00005019 if (CompoundStmt *Body = FD->getCompoundBody()) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005020 CurFunctionDef = FD;
Steve Naroff4588d0f2008-12-04 16:24:46 +00005021 CollectPropertySetters(Body);
Steve Naroff1042ff32008-12-08 16:43:47 +00005022 CurrentBody = Body;
Ted Kremenek73980592009-03-12 18:33:24 +00005023 Body =
5024 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5025 FD->setBody(Body);
Steve Naroff1042ff32008-12-08 16:43:47 +00005026 CurrentBody = 0;
5027 if (PropParentMap) {
5028 delete PropParentMap;
5029 PropParentMap = 0;
5030 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005031 // This synthesizes and inserts the block "impl" struct, invoke function,
5032 // and any copy/dispose helper functions.
5033 InsertBlockLiteralsWithinFunction(FD);
5034 CurFunctionDef = 0;
Mike Stump11289f42009-09-09 15:08:12 +00005035 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005036 return;
5037 }
5038 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00005039 if (CompoundStmt *Body = MD->getCompoundBody()) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005040 CurMethodDef = MD;
Steve Naroff4588d0f2008-12-04 16:24:46 +00005041 CollectPropertySetters(Body);
Steve Naroff1042ff32008-12-08 16:43:47 +00005042 CurrentBody = Body;
Ted Kremenek73980592009-03-12 18:33:24 +00005043 Body =
5044 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5045 MD->setBody(Body);
Steve Naroff1042ff32008-12-08 16:43:47 +00005046 CurrentBody = 0;
5047 if (PropParentMap) {
5048 delete PropParentMap;
5049 PropParentMap = 0;
5050 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005051 InsertBlockLiteralsWithinMethod(MD);
5052 CurMethodDef = 0;
5053 }
5054 }
5055 if (ObjCImplementationDecl *CI = dyn_cast<ObjCImplementationDecl>(D))
5056 ClassImplementation.push_back(CI);
5057 else if (ObjCCategoryImplDecl *CI = dyn_cast<ObjCCategoryImplDecl>(D))
5058 CategoryImplementation.push_back(CI);
5059 else if (ObjCClassDecl *CD = dyn_cast<ObjCClassDecl>(D))
5060 RewriteForwardClassDecl(CD);
5061 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
5062 RewriteObjCQualifiedInterfaceTypes(VD);
Steve Naroffa5c0db82008-12-11 21:05:33 +00005063 if (isTopLevelBlockPointerType(VD->getType()))
Steve Narofff4b992a2008-10-28 20:29:00 +00005064 RewriteBlockPointerDecl(VD);
Steve Naroffd8907b72008-10-29 18:15:37 +00005065 else if (VD->getType()->isFunctionPointerType()) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005066 CheckFunctionPointerDecl(VD->getType(), VD);
5067 if (VD->getInit()) {
Steve Naroffc989a7b2008-11-03 23:29:32 +00005068 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005069 RewriteCastExpr(CE);
5070 }
5071 }
Steve Naroffe70a52a2009-12-05 15:55:59 +00005072 } else if (VD->getType()->isRecordType()) {
5073 RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
5074 if (RD->isDefinition())
5075 RewriteRecordBody(RD);
Steve Narofff4b992a2008-10-28 20:29:00 +00005076 }
Steve Naroffd8907b72008-10-29 18:15:37 +00005077 if (VD->getInit()) {
5078 GlobalVarDecl = VD;
Steve Naroff4588d0f2008-12-04 16:24:46 +00005079 CollectPropertySetters(VD->getInit());
Steve Naroff1042ff32008-12-08 16:43:47 +00005080 CurrentBody = VD->getInit();
Steve Naroffd8907b72008-10-29 18:15:37 +00005081 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
Steve Naroff1042ff32008-12-08 16:43:47 +00005082 CurrentBody = 0;
5083 if (PropParentMap) {
5084 delete PropParentMap;
5085 PropParentMap = 0;
5086 }
Mike Stump11289f42009-09-09 15:08:12 +00005087 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(),
Chris Lattner86d7d912008-11-24 03:54:41 +00005088 VD->getNameAsCString());
Steve Naroffd8907b72008-10-29 18:15:37 +00005089 GlobalVarDecl = 0;
5090
5091 // This is needed for blocks.
Steve Naroffc989a7b2008-11-03 23:29:32 +00005092 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Naroffd8907b72008-10-29 18:15:37 +00005093 RewriteCastExpr(CE);
5094 }
5095 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005096 return;
5097 }
5098 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(D)) {
Steve Naroffa5c0db82008-12-11 21:05:33 +00005099 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofff4b992a2008-10-28 20:29:00 +00005100 RewriteBlockPointerDecl(TD);
Mike Stump11289f42009-09-09 15:08:12 +00005101 else if (TD->getUnderlyingType()->isFunctionPointerType())
Steve Narofff4b992a2008-10-28 20:29:00 +00005102 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
Steve Naroffe70a52a2009-12-05 15:55:59 +00005103 else if (TD->getUnderlyingType()->isRecordType()) {
5104 RecordDecl *RD = TD->getUnderlyingType()->getAs<RecordType>()->getDecl();
5105 if (RD->isDefinition())
5106 RewriteRecordBody(RD);
5107 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005108 return;
5109 }
5110 if (RecordDecl *RD = dyn_cast<RecordDecl>(D)) {
Steve Naroffe70a52a2009-12-05 15:55:59 +00005111 if (RD->isDefinition())
5112 RewriteRecordBody(RD);
Steve Narofff4b992a2008-10-28 20:29:00 +00005113 return;
5114 }
5115 // Nothing yet.
5116}
5117
Chris Lattnercf169832009-03-28 04:11:33 +00005118void RewriteObjC::HandleTranslationUnit(ASTContext &C) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005119 // Get the top-level buffer that this corresponds to.
Mike Stump11289f42009-09-09 15:08:12 +00005120
Steve Narofff4b992a2008-10-28 20:29:00 +00005121 // Rewrite tabs if we care.
5122 //RewriteTabs();
Mike Stump11289f42009-09-09 15:08:12 +00005123
Steve Narofff4b992a2008-10-28 20:29:00 +00005124 if (Diags.hasErrorOccurred())
5125 return;
Mike Stump11289f42009-09-09 15:08:12 +00005126
Steve Narofff4b992a2008-10-28 20:29:00 +00005127 RewriteInclude();
Mike Stump11289f42009-09-09 15:08:12 +00005128
Steve Naroffd9803712009-04-29 16:37:50 +00005129 // Here's a great place to add any extra declarations that may be needed.
5130 // Write out meta data for each @protocol(<expr>).
Mike Stump11289f42009-09-09 15:08:12 +00005131 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Steve Naroffd9803712009-04-29 16:37:50 +00005132 E = ProtocolExprDecls.end(); I != E; ++I)
5133 RewriteObjCProtocolMetaData(*I, "", "", Preamble);
5134
Mike Stump11289f42009-09-09 15:08:12 +00005135 InsertText(SM->getLocForStartOfFile(MainFileID),
Steve Narofff4b992a2008-10-28 20:29:00 +00005136 Preamble.c_str(), Preamble.size(), false);
Steve Naroff2a2a41f2008-11-14 14:10:01 +00005137 if (ClassImplementation.size() || CategoryImplementation.size())
5138 RewriteImplementations();
Steve Naroffd9803712009-04-29 16:37:50 +00005139
Steve Narofff4b992a2008-10-28 20:29:00 +00005140 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
5141 // we are done.
Mike Stump11289f42009-09-09 15:08:12 +00005142 if (const RewriteBuffer *RewriteBuf =
Steve Narofff4b992a2008-10-28 20:29:00 +00005143 Rewrite.getRewriteBufferFor(MainFileID)) {
5144 //printf("Changed:\n");
5145 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
5146 } else {
5147 fprintf(stderr, "No changes\n");
5148 }
Steve Narofff8cfd162008-11-13 20:07:04 +00005149
Steve Naroffd9803712009-04-29 16:37:50 +00005150 if (ClassImplementation.size() || CategoryImplementation.size() ||
5151 ProtocolExprDecls.size()) {
Steve Naroff2a2a41f2008-11-14 14:10:01 +00005152 // Rewrite Objective-c meta data*
5153 std::string ResultStr;
5154 SynthesizeMetaDataIntoBuffer(ResultStr);
5155 // Emit metadata.
5156 *OutFile << ResultStr;
5157 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005158 OutFile->flush();
5159}
5160